Scrivio Interview library

Kafka architecture and internals

40 questions in 9 subtopics.

About this topic

Kafka's internals explain why a cluster behaves the way it does under load and during failures. A Kafka 4.x cluster is a set of brokers that store partition logs and a small quorum of KRaft controllers that own the metadata. Each partition is an append-only log of segment files, copied to followers, with an in-sync replica set and a high watermark deciding what is safe to read. Most production incidents, from slow restarts to lost writes and runaway disk use, trace back to these mechanisms. The questions cover the controller quorum, the storage layout, replication and leader election, retention and compaction, the operating-system tricks behind Kafka's throughput, tiered storage, rack-aware placement and the request path from client to disk, at every level from first principles to platform strategy.

Brokers, controllers and KRaft

Since Kafka 4.0 every cluster runs in KRaft mode: a few nodes act as controllers that keep the cluster metadata in a replicated log, and brokers serve client traffic. Before answering, be clear on what the controllers decide, how brokers learn about changes, what a quorum majority means for availability, and how dedicated and combined roles differ in operation.

ConceptFoundations7 min read

In a Kafka 4.x cluster running in KRaft mode, three nodes have process.roles=controller and six have process.roles=broker.

Explain what each group does, where the cluster metadata lives, and how many controller failures the cluster can survive before metadata changes stop.
InternalsIntermediate7 min read

A broker in a KRaft cluster that leads 400 partitions is killed with kill -9 and does not come back.

Walk through what happens step by step from the controller's point of view and from a producer's point of view, and compare it with a controlled shutdown of the same broker.
DebuggingIntermediate7 min read

After a rolling restart of the three dedicated controllers, topic creation and partition reassignments start timing out, although producing and consuming still work.

kafka-metadata-quorum.sh describe --replication shows the leader at LogEndOffset 8,412,330 and both followers lagging by more than 2 million records, with LastCaughtUpTimestamp several minutes old. What is going on and how do you recover?
DesignAdvanced7 min read

You are designing the controller layer for a Kafka 4.x deployment with 60 brokers and about 40,000 partitions across three availability zones.

Decide between combined and dedicated controllers, three or five voters, and their placement, and explain how you would later add or replace a controller.
LeadershipPrincipal7 min read

Your company still runs six Kafka 3.x clusters in ZooKeeper mode, used by 200 services, and Kafka 4.0 removed ZooKeeper support.

Leadership asks for a plan and a risk assessment for moving to Kafka 4.x. How do you structure the programme?

Log segments, indexes and storage layout

Each partition is stored as a directory of segment files, each with an offset index, a time index and a few small state files. Understand how records are grouped into batches, how a broker finds an offset quickly, when a new segment is rolled, and why the number of segments affects open files, memory maps and broker recovery time.

ConceptFoundations7 min read

On a broker you list the directory /var/kafka/data/orders-3 and see files such as 00000000000005120000.log, .index, .timeindex and .snapshot, plus leader-epoch-checkpoint and partition.metadata.

What is each file for, and what does the long number in the file names mean?
InternalsFoundations6 min read

A producer sends 500 records of about 200 bytes each to one partition in a single lz4-compressed batch.

Describe how Kafka stores them in the v2 record batch format, and which batch fields support compression, idempotence and transactions.
InternalsIntermediate6 min read

A consumer fetches offset 48,213,907 from a partition with 300 segments.

Explain how the broker finds the bytes to return, why the offset index is sparse, and why the consumer can receive records with offsets lower than the one it asked for.
DebuggingIntermediate7 min read

After a data-centre power cut, one broker with 4,000 partition replicas on two disks takes 40 minutes to start; its log shows it loading and recovering log segments partition by partition while it stays out of every ISR.

Why does this take so long, and what would you change?
ScenarioAdvanced7 min read

To make one-hour retention precise, a team set segment.ms=60000 on topics totalling 6,000 partitions, on a cluster that already hosts 30,000 partition replicas. A week later brokers fail with 'Too many open files' and memory-map errors.

Explain the chain of cause and effect, and the platform guardrails you would put in place.

Replication, ISR and high watermark

Kafka copies every partition from a leader to followers, and the in-sync replica set records which copies are fully caught up. The high watermark marks how far records are safely replicated. Know how acks, min.insync.replicas and replica lag interact, why followers drop out of the ISR, and how leader epochs keep logs consistent after crashes.

ConceptFoundations6 min read

A partition has replication factor 3. The leader's log end offset is 1,050, follower A is at 1,040 and follower B at 1,046, and both are in the ISR.

What is the high watermark, which offsets can a consumer read, and why does Kafka hide the rest?
InternalsIntermediate6 min read

A follower restarts after a crash and must decide whether the end of its log matches the new leader's log.

Explain how leader epochs and the leader-epoch-checkpoint file prevent the lost or divergent records that truncating to the high watermark could cause.
DebuggingIntermediate7 min read

Every night during a bulk load, UnderReplicatedPartitions jumps from 0 to about 120 and IsrShrinksPerSec and IsrExpandsPerSec spike together, and some producers using acks=all with min.insync.replicas=2 log NotEnoughReplicasException.

Explain what is happening and how you would fix it.
DesignAdvanced7 min read

Payment events must survive broker and zone failures, and in a cluster spread over three availability zones every replica that crosses a zone also adds network cost.

Choose replication settings for a payments topic in a cluster spread over three availability zones: replication factor, min.insync.replicas, producer acks and leader election settings. Explain exactly which failures lose data, which block writes, and what the cross-zone cost is.
LeadershipPrincipal6 min read

A risk committee member points out that Kafka acknowledges writes before they are fsynced to disk and asks you to mandate flush.messages=1 on all topics.

How do you decide the durability policy for the platform and explain it to the committee?

Leader election and unclean leader election

Each partition has one leader that handles reads and writes, and the controller picks a new one when a broker fails or shuts down. Understand preferred leaders and rebalancing, what clients see during a leader change, and the choice between staying offline and electing an out-of-sync replica, which trades availability against lost data.

ConceptFoundations6 min read

A broker is restarted with a controlled shutdown while producers and consumers are active.

Describe what the clients experience during the leader change, and explain why a producer using acks=1 can lose records in an unplanned leader failure while acks=all does not.
ConceptFoundations6 min read

After a rolling restart, one broker of six leads 40 percent of all partitions and its CPU is twice that of the others.

Explain what the preferred replica is, how Kafka moves leadership back automatically, and how you trigger it by hand.
ScenarioIntermediate7 min read

A broker holding the only in-sync replica of a partition has a failed disk. The other live replica was removed from the ISR an hour ago and is about 30,000 records behind.

The topic has unclean.leader.election.enable=false. What happens now, what are your options, and what are the consequences of each?
DesignAdvanced7 min read

Your platform has 800 topics: metrics and logs, CDC streams from databases, compacted reference data, and payment events.

Define a policy per class for unclean leader election and the related replication settings, and the runbook for an offline partition.

Retention and log compaction

Kafka removes old data in one of two ways: deleting whole segments after a time or size limit, or compacting a topic so that only the latest record per key remains. Know how retention works at segment level, how the log cleaner chooses and rewrites segments, how tombstones disappear, and what this means for consumers that rebuild state.

DebuggingFoundations6 min read

A low-traffic topic has retention.ms=86400000 (one day), but kafka-dump-log.sh shows records three days old still on disk.

Why are they not deleted, and how do you fix it?
InternalsIntermediate7 min read

Log compaction is the alternative to time-based deletion: instead of dropping old segments, Kafka keeps the latest record for each key, and the work happens in the background on every broker.

Explain how the log cleaner compacts a topic with cleanup.policy=compact: how it chooses what to clean, how cleaning works, and what a consumer reading from offset 0 is guaranteed to see. Name the settings that control the timing.
DebuggingIntermediate7 min read

A compacted topic holding customer state has grown from 40 GB to 220 GB over three weeks while the number of distinct keys stays near 5 million.

The broker's max-dirty-percent metric is at 95 and time-since-last-run-ms keeps growing. What do you check and how do you fix it?
ScenarioAdvanced7 min read

Twelve services build local stores by reading a compacted topic of 50 million customer profiles from the beginning.

A new service takes 30 hours to bootstrap, and after going live it still serves profiles that were deleted weeks ago. delete.retention.ms is at its default. Explain the cause and the design changes you would make.
LeadershipPrincipal7 min read

Legal requires that a customer's personal data in the event platform be deletable within 30 days of a request.

Today some delete-policy topics keep data for a year, some compacted topics hold customer state, and tiered storage keeps old segments in object storage. How do you set the long-term retention and deletion policy?

Page cache, zero-copy and sequential I/O

Kafka gets much of its throughput from the operating system rather than the JVM: it writes and reads files sequentially, leaves caching to the page cache, and can send file data to sockets without copying it through the application. Understand when these tricks apply, what defeats them, and how memory, disks and encryption change broker performance.

ConceptFoundations7 min read

Kafka brokers often run with a 6 GB JVM heap on machines with 64 GB of RAM and still serve hundreds of MB per second.

Explain the design choices that make this work.
InternalsIntermediate6 min read

After enabling TLS between clients and brokers, broker CPU rose from 25 to 60 percent and the maximum fetch throughput per broker dropped by about a third.

Explain why, and what you can do about it.
DebuggingIntermediate7 min read

Producer p99 latency on a cluster jumps from 8 ms to 450 ms whenever an analytics job starts re-reading five days of history from a busy topic.

Disk read IOPS on the brokers rise from almost zero to their limit. Explain the mechanism and your options.
DesignAdvanced7 min read

A team is planning hardware for a new high-throughput Kafka cluster and needs figures it can defend rather than guesses.

Size the brokers for a cluster that must accept 400 MB/s of produce traffic with replication factor 3, where most consumers stay within ten minutes of the head and a few batch jobs read up to a day back. How much memory, disk and network do you plan, and which OS settings matter?

Tiered storage

Tiered storage lets a topic keep recent segments on broker disks and move older ones to remote object storage, so retention is no longer limited by local disk size. Learn how local and total retention interact, what changes for reads of old data, which topics can use it, and how it affects broker replacement, reassignment and cost.

ConceptFoundations6 min read

Tiered storage lets a Kafka topic keep recent segments on broker disks and older segments in remote object storage, so long retention no longer means large local disks.

What is Kafka tiered storage, which settings turn it on for a cluster and for a topic, and how do retention.ms and local.retention.ms work together? Which topics cannot use it?
ScenarioIntermediate6 min read

On a topic with tiered storage, a consumer replaying 30-day-old data sees fetch latencies of 1 to 3 seconds and only 15 MB/s per partition, while consumers near the head get single-digit milliseconds.

Explain why and what you would tune.
DesignAdvanced7 min read

A cluster keeps 14 days of data on broker disks, 900 TB in total with replication factor 3, and teams want 90 days.

Design the move to tiered storage: which topics, what local retention, what changes for broker replacement and partition reassignment, and what can go wrong.
LeadershipPrincipal6 min read

Vendors now offer Kafka-compatible systems that write directly to object storage, with no broker disks and no cross-zone replication, trading higher latency for much lower cost, and similar ideas are being discussed for Apache Kafka itself.

How would you decide whether to adopt such a system for your event platform?

Rack awareness and replica placement

Kafka can spread the replicas of each partition across racks or availability zones and let consumers read from a nearby replica. Understand how broker.rack drives placement when topics are created, how follower fetching works, what cross-zone traffic costs, and why clusters stretched over long distances behave differently from clusters inside one region.

ConceptFoundations5 min read

Kafka clusters often span several racks or availability zones, and both replica placement and client reads can take that physical layout into account.

What does broker.rack do in Kafka? Explain how it affects replica placement when a topic is created, and how client.rack together with replica.selector.class lets consumers read from a replica in their own zone.
ScenarioIntermediate6 min read

A cluster spans three zones with replication factor 3 and one replica per zone. Producers in all zones write 300 MB/s, leaders are spread evenly, and four consumer groups read everything.

Estimate the cross-zone traffic per second, and show how much rack-aware settings can remove.
ScenarioAdvanced6 min read

A 40-broker cluster grew up in two data halls without broker.rack set and is now moving to three availability zones. Many partitions have two of their three replicas in the same hall.

Plan the change so each partition ends up with one replica per zone without hurting production traffic.
LeadershipPrincipal5 min read

Leaders want a single Kafka cluster stretched across three cloud regions so that losing a region loses no data and needs no failover.

Round-trip times between regions are 30 to 70 ms. How do you evaluate this request, and what would you recommend?

Request flow, metadata and the Kafka protocol

Clients discover the cluster through bootstrap servers and metadata requests, then talk directly to partition leaders over Kafka's binary protocol. Understand how a broker handles a request through its network threads, request queue and handler threads, which metrics show where time is spent, and how protocol versions decide which client and broker versions can work together.

ConceptFoundations5 min read

A producer starts with bootstrap.servers listing three of twelve brokers.

Explain how it learns where to send records for each partition, and what happens when a partition leader moves to another broker.
DebuggingIntermediate6 min read

Produce p99 latency on one broker is 1.2 seconds. Request metrics show a RequestQueueTimeMs p99 of 900 ms, LocalTimeMs of 20 ms and RemoteTimeMs of 40 ms; RequestHandlerAvgIdlePercent is 0.03 and NetworkProcessorAvgIdlePercent is 0.6.

Walk through the broker request pipeline and explain what these numbers say and what you do.
ScenarioAdvanced6 min read

Before upgrading brokers to Kafka 4.x you learn that about 300 client applications in Java, Go, Python and Node.js connect to the cluster, some built years ago.

How do you find which clients would break against 4.x brokers and run the upgrade without outages?
LeadershipPrincipal5 min read

Teams across five languages use different Kafka clients, some reach Kafka through an HTTP proxy, and every incident review finds different defaults and versions.

Should the company standardise on particular client libraries, build its own wrapper, or move non-JVM teams to a proxy? How do you decide?