Kafka
Apache Kafka is an open-source, distributed event streaming platform. At its core it's a replicated, append-only log: producers write records to the end of it, the records stay there for a configured time, and any number of consumers read them in order, each at its own pace. It started at LinkedIn as the pipe that moved activity events and logs between systems, and it's now the default backbone for event-driven architectures at most large tech companies.
The properties that define it:
- A log, not a queue: reading a record doesn't remove it. Records are kept for a retention period (days, weeks or forever), so a new consumer can start from the beginning and a broken one can rewind and replay.
- Partitioned: each topic is split into partitions spread across many brokers. Partitions are the unit of parallelism, ordering and scaling.
- Replicated: each partition is copied to several brokers, usually three, so losing a machine loses no acknowledged data.
- Pull-based consumers: consumers fetch records and track their own position (the offset). The broker doesn't track per-message acknowledgements, which is a big reason it's so cheap to run at high volume.
- High throughput: sequential disk I/O, batching and compression let a modest cluster absorb millions of records per second.
Kafka shows up in a huge share of system design interviews. Any time you need to decouple producers from consumers, absorb a write burst, fan the same events out to several systems, or feed a stream processor, "put it on Kafka" is a reasonable move. Interviewers know that, so they follow up: how is it partitioned, what's the key, what happens when a broker dies, can you get duplicates, and what if one partition gets hot. This post covers those answers.
The Core Concepts
Record (message): the unit of data. A record has an optional key, a value (bytes; usually JSON, Avro or Protobuf), a timestamp and optional headers. Kafka doesn't care what's in the value. Records are usually small, from hundreds of bytes to a few KB, and the default maximum is about 1 MB.
Topic: a named stream of records, like orders or page-views. Producers write to topics and consumers subscribe to them.
Partition: a topic is split into a fixed number of partitions. Each partition is an ordered, append-only sequence of records stored on disk. A record's position in its partition is its offset, a 64-bit number that only goes up.
Broker: a Kafka server. A cluster has several to hundreds of brokers, and each one stores some of the partitions.
Consumer group: a set of consumers that share the work of reading a topic. Each partition is read by exactly one consumer in the group at a time, so the group processes each record once. Different groups are independent: an analytics group and a search-indexing group can both read every record of the same topic.
Creating a topic is a single command:
kafka-topics.sh --create --topic orders \
--partitions 48 --replication-factor 3 \
--config min.insync.replicas=2 \
--config retention.ms=604800000 # 7 days
The most important rule follows directly from the model: Kafka guarantees ordering only within a partition. Records in partition 3 are read in the order they were written. Records in partition 3 and partition 7 have no ordering relative to each other. So if you need all events for one order (or one user, or one chat) processed in order, they must land in the same partition, and that's what the key is for.
Architecture
A Kafka cluster is a set of brokers plus a small controller quorum that manages metadata.
- Brokers store partitions and serve reads and writes. For each partition, one broker is the leader and handles all produce requests (and, by default, all fetch requests). The other replicas are followers that copy the leader's log.
- The controller tracks which brokers are alive, which broker leads each partition, and topic configuration. When a broker fails, the controller picks new leaders for the partitions it led. Modern Kafka runs the controller as a KRaft quorum (usually 3 or 5 nodes using a Raft-based protocol), storing metadata in an internal log. Older clusters used ZooKeeper for this. Kafka 4.0 removed ZooKeeper support entirely.
- Clients are smart. A producer or consumer first fetches cluster metadata (which broker leads which partition) and then talks directly to the right brokers. There's no proxy or router in the middle.
Leadership is spread so that each broker leads roughly the same number of partitions. With 48 partitions and 6 brokers, each broker leads about 8 partitions and follows about 16 more (at replication factor 3).
How Writes Work
A producer decides which partition each record goes to:
- With a key: the default partitioner hashes the key (murmur2) modulo the partition count. Every record with key
order-123lands in the same partition, which gives you per-key ordering. - Without a key: records are spread across partitions. Modern clients use a "sticky" strategy that fills a batch for one partition before moving to the next, which keeps batches large.
- Explicitly: you can pick the partition yourself or plug in a custom partitioner.
The producer doesn't send records one at a time. It collects them into per-partition batches, waiting up to linger.ms or until batch.size is reached, compresses each batch (lz4, zstd, snappy or gzip), and sends batches to each partition's leader. Batching is where most of Kafka's throughput comes from: one network request and one disk append can carry thousands of records.
The producer's acks setting decides when a write counts as successful:
acks |
Leader responds when | Risk |
|---|---|---|
0 |
Never waits | Records can vanish silently |
1 |
Leader has written it | Lost if the leader dies before followers copy it |
all |
All in-sync replicas have it | Durable as long as one in-sync replica survives |
acks=all is the default in current clients, and it's the one to name in an interview for anything that matters. Combined with min.insync.replicas=2 and a replication factor of 3, a write succeeds only once at least two brokers have it, and the partition can lose one broker without losing data or stopping writes.
# producer settings for important data
acks=all
enable.idempotence=true # no duplicates from retries (default in modern clients)
linger.ms=10 # wait up to 10 ms to fill a batch
batch.size=65536
compression.type=lz4
But what is actually happening under the hood? On the broker, each partition is a directory of segment files. The active segment is a plain file that the broker appends to; when it reaches a size limit (1 GB by default) or age, it's closed and a new one starts. Each segment has a sparse offset index (offset to file position) and a time index (timestamp to offset), so finding offset 8,000,000 is a binary search in a small index followed by a short scan.
The broker writes to the operating system's page cache and doesn't call fsync on every write. Durability comes from replication across machines, not from flushing to disk on one machine. Because writes are always sequential appends, even spinning disks handle them well, and the page cache means consumers reading recent data are served from memory.
In an interview, the short version of "why is Kafka fast?" is: sequential appends instead of random writes, batching and compression on the wire and on disk, the OS page cache instead of an application cache, and zero-copy transfer to consumers. No per-message bookkeeping on the broker ties it together.
How Reads Work
Consumers pull. A consumer sends a fetch request saying "give me records from partition 3 starting at offset 41,200," and the broker returns a batch. Pulling lets each consumer go at its own speed, batch naturally, and fall behind without the broker having to buffer anything for it. A long-poll setting (fetch.max.wait.ms) keeps a caught-up consumer from spinning.
A consumer only sees records up to the partition's high watermark, the offset that every in-sync replica has copied. That's what stops a consumer from reading a record that might disappear if the leader fails.
But what is actually happening under the hood? When a consumer reads data that's still in the page cache, the broker uses the sendfile system call to copy bytes straight from the page cache to the network socket, without bringing them into the JVM. The batch format on disk is the same as on the wire, so the broker doesn't decompress or re-encode anything. That's why a broker can serve many consumers of the same topic for little extra cost.
Consumer Groups and Rebalancing
Within a consumer group, partitions are divided among consumers. With 12 partitions and 4 consumers, each consumer gets 3. Add a fifth consumer and the group rebalances so that partitions are spread again; remove one and its partitions move to the others.
Two consequences matter in interviews:
- Parallelism is capped by the partition count. With 12 partitions, a 13th consumer in the group sits idle. If you think you'll need 100 consumers at peak, you need at least 100 partitions.
- Rebalances pause work. The original protocol stopped every consumer in the group while partitions were reassigned. Cooperative rebalancing, and the newer broker-driven consumer protocol, move only the partitions that need to change, but a rebalance still causes a short hiccup for the moved partitions.
Each group has a group coordinator (one of the brokers) that tracks membership through heartbeats and stores the group's progress.
Offsets and Commits
A consumer's progress is the offset of the next record it will read in each partition. Consumers commit these offsets to an internal, compacted topic called __consumer_offsets. When a consumer restarts or a partition moves to another consumer, reading resumes from the last committed offset.
When you commit decides your delivery guarantee:
- Commit before processing: if the consumer crashes after committing but before finishing, those records are skipped. That's at-most-once.
- Commit after processing: if it crashes after processing but before committing, the next consumer reprocesses those records. That's at-least-once, and it's the normal choice.
while (running) {
ConsumerRecords<String, Order> records = consumer.poll(Duration.ofMillis(500));
for (ConsumerRecord<String, Order> r : records) {
process(r.value()); // must be idempotent: may run twice after a crash
}
consumer.commitSync(); // commit only after the batch is done
}
Most real designs pair at-least-once delivery with an idempotent consumer: use an event ID or the (partition, offset) pair as a deduplication key, or make the write naturally idempotent (an upsert, or a conditional update on a version). Saying this unprompted is one of the clearest signals that you've built on Kafka before.
Replication and Fault Tolerance
Each partition has a replication factor (RF), usually 3. One replica is the leader; the followers continuously fetch from it, exactly like consumers do.
The leader tracks the in-sync replica set (ISR): the replicas that have caught up to the leader within a time limit (replica.lag.time.max.ms, 30 seconds by default). A follower that falls behind, because it's slow or its broker is down, is dropped from the ISR and rejoins once it catches up.
The pieces fit together like this:
- A producer with
acks=allsends a batch to the leader of partition 3, which appends it at offsets 500 to 599. - The two followers fetch from the leader and append the same records.
- Once every replica in the ISR has offset 599, the leader advances the high watermark to 600 and acknowledges the producer. Consumers can now read those records.
- If the ISR shrinks below
min.insync.replicas, the leader rejectsacks=allwrites with an error instead of accepting writes it can't protect. Reads keep working.
When a broker dies, the controller notices (it stops getting heartbeats), and for each partition the dead broker led, it picks a new leader from the ISR. Clients refresh their metadata and carry on, usually within seconds. Because only ISR members can become leader, and every acknowledged record is on every ISR member, no acknowledged write is lost.
What if every in-sync replica is gone? Kafka then has a choice between waiting for one to come back (unavailable) or electing an out-of-sync replica and losing whatever it missed (unclean.leader.election.enable). The default is to wait, which favours consistency. That's a good, concrete example of the CAP trade-off to give if your interviewer asks.
But what is actually happening under the hood? Each leader change bumps the partition's leader epoch. When an old leader comes back, it uses the epoch history to find where its log diverged from the new leader's and truncates its uncommitted tail before following again. This replaced an older scheme based on the high watermark that could, in rare double-failure cases, lose or diverge data.
Brokers can also be rack-aware: with broker.rack set to the availability zone, Kafka places a partition's three replicas in three different zones, so a whole zone outage leaves two replicas alive. Consumers can be configured to fetch from a follower in their own zone, which cuts cross-zone network cost in the cloud.
Delivery Guarantees and Exactly-Once
Kafka offers three levels, and you should be precise about which one a design needs:
- At-most-once:
acks=0or commit-before-process. Fine for metrics you can afford to drop. - At-least-once:
acks=allwith retries, commit-after-process. The default for nearly everything, with idempotent consumers to absorb the duplicates. - Exactly-once: no duplicates and no losses, but only within Kafka.
Exactly-once is built from two features:
The idempotent producer. Each producer gets a producer ID, and each batch it sends to a partition carries a sequence number. If a network timeout makes the producer retry a batch the broker already wrote, the broker sees the duplicate sequence number and discards it. This also preserves ordering across retries, with up to five requests in flight. It's on by default in modern clients and costs almost nothing.
Transactions. A producer with a transactional.id can write to several partitions and commit consumer offsets as one atomic unit. Either all of the writes and the offset commit become visible, or none do. Consumers with isolation.level=read_committed skip records from aborted transactions. This is what makes a read-process-write loop (consume from topic A, transform, produce to topic B) exactly-once, and it's what Kafka Streams and Flink's Kafka sink use under the hood.
producer.initTransactions();
while (running) {
ConsumerRecords<String, Click> in = consumer.poll(Duration.ofMillis(200));
producer.beginTransaction();
for (var r : in) producer.send(new ProducerRecord<>("clicks-enriched", r.key(), enrich(r.value())));
producer.sendOffsetsToTransaction(nextOffsets(in), consumer.groupMetadata());
producer.commitTransaction(); // outputs and input offsets commit together
}
The common trap: "Kafka has exactly-once, so my consumer that charges a credit card runs exactly once." It doesn't. Kafka's guarantee covers records and offsets inside Kafka. The moment a consumer calls an external API or writes to a database, a crash between that side effect and the offset commit can repeat it. You still need idempotency keys, or you store the offset in the same database transaction as the result.
Retention, Compaction and Tiered Storage
Kafka keeps data according to a per-topic cleanup policy:
- Delete (time or size retention): segments older than
retention.ms(7 days by default) or beyondretention.bytesare deleted whole. Consumers that fall further behind than the retention window lose data, so set retention well above your worst expected outage. - Compact: Kafka keeps at least the latest record for every key and removes older ones in the background. A record with a null value (a tombstone) deletes the key. A compacted topic acts like a changelog of a table: replay it from the start and you rebuild the latest state for every key. Kafka uses this for
__consumer_offsets, and Kafka Streams uses it to back up its local state stores. - Both: compact, and also delete anything older than the retention period.
Retention is also where the sizing arithmetic usually lands. Suppose you ingest 1 million events per second at 1 KB each: that's 1 GB/s, or about 86 TB per day. Seven days of retention is about 600 TB, and with replication factor 3 the cluster has to hold about 1.8 PB on local disks. That's where tiered storage comes in. With it, brokers keep only recent segments locally (say, the last few hours) and move closed segments to object storage like S3. Consumers reading old data are served from the remote tier transparently. It decouples storage from compute, so you don't add brokers just to hold more history, and it makes broker replacement and rebalancing much faster because there's less local data to move.
Scaling Kafka
Choosing the Partition Count
Partitions are how Kafka scales, so the partition count is the main design decision for a topic. Size it from both throughput and consumer parallelism:
- If a single consumer can process about 5 MB/s of your records (say, because each record triggers a database write) and the topic peaks at 500 MB/s, you need at least 100 partitions just for consumers to keep up.
- If you need 60 consumers for CPU-heavy processing, you need at least 60 partitions.
Take the larger number and add headroom, since you can't easily change it later. A single partition can typically handle on the order of tens of MB/s of writes, and a broker on the order of hundreds of MB/s, but the consumer side usually sets the limit.
Why not just make 10,000 partitions? Each partition is a set of open files, replication traffic and metadata for the controller. Too many partitions slow leader elections and recovery, increase end-to-end latency (batches get smaller), and use more memory on clients. KRaft raised the practical ceiling considerably compared with ZooKeeper-era clusters, but it's still wise to keep partitions per broker in the low thousands.
You can add partitions to a topic, but you can't remove them, and adding them changes
hash(key) % partitions, so existing keys start landing in different partitions. Any consumer relying on per-key ordering or per-partition state sees a discontinuity. Over-provision partitions up front instead of planning to add them.
Hot Partitions
Keying by entity gives you ordering, but it also means a single huge key (one celebrity's activity, one giant tenant, one viral ad) sends all its traffic to one partition, one leader and one consumer. Options, from simplest:
- Pick a finer key if the ordering requirement allows it:
user_idinstead ofcountry,(ad_id, minute)instead ofad_id. - Salt hot keys: append a random suffix 0 to N-1 for keys known to be hot, spreading them across N partitions, and merge the partial results downstream. You give up strict per-key ordering for those keys.
- Dedicated handling: route known heavy hitters to their own topic with its own consumers.
This exact problem is the core of the ad click aggregator deep dive.
Consumer Lag
Consumer lag is the gap between the latest offset in a partition and the group's committed offset. It's the single most important Kafka metric, because it tells you whether consumers are keeping up. Autoscale consumers on lag (up to the partition count), alert when it grows steadily, and remember that lag in records means nothing without throughput: 1 million records of lag is 1 second at 1M/s or 3 hours at 100/s.
Multiple Clusters and Regions
A single cluster normally lives in one region, spread across availability zones. For multi-region designs, you replicate topics between clusters with MirrorMaker 2 (or a vendor tool like Confluent's Cluster Linking). Replication between regions is asynchronous, offsets differ between clusters, and failing over consumers requires translating their positions, so treat cross-region Kafka as disaster recovery or aggregation ("every region's events flow into a central analytics cluster"), not as one logical log.
The Ecosystem
Kafka rarely appears alone. Know these by name:
- Kafka Connect: a framework for moving data in and out of Kafka without writing consumers. Source connectors pull from databases (Debezium for change data capture from Postgres or MySQL binlogs), and sink connectors push into S3, Elasticsearch, Snowflake and others.
- Kafka Streams: a Java library for stream processing inside your own service, with local state stores backed by compacted changelog topics. Good for per-key aggregations and joins without running a separate cluster.
- Schema Registry: stores Avro, Protobuf or JSON schemas and enforces compatibility rules, so a producer can't ship a change that breaks every consumer. Most serious deployments use one.
- Managed offerings: Amazon MSK, Confluent Cloud and others run the brokers for you. In an interview, "a managed Kafka cluster" is a perfectly good answer to "who operates this?"
- Kafka-compatible systems: Redpanda and WarpStream speak the Kafka protocol with different internals. Pulsar and Kinesis solve the same problem with different architectures.
Kafka vs Other Messaging Systems
| Kafka | SQS | RabbitMQ | Kinesis | |
|---|---|---|---|---|
| Model | Partitioned log | Queue | Broker with exchanges and queues | Partitioned log (shards) |
| Replay | Yes, within retention | No | No (except streams) | Yes, within retention |
| Ordering | Per partition | None (FIFO queues: per group) | Per queue | Per shard |
| Per-message ack | No, offsets | Yes | Yes | No, checkpoints |
| Throughput | Very high | High, scales automatically | Moderate | High, per-shard limits |
| Operations | You or a managed service | Fully managed | You or a managed service | Fully managed |
The key distinction is log versus queue. A queue hands each message to one worker, tracks acknowledgements per message and deletes it when it's done. That's ideal for a pool of workers doing independent jobs, with retries and dead-letter queues for the failures. A log keeps everything in order, lets many independent readers replay it, and is ideal for event streams. You can use Kafka as a work queue, but per-message retries, delays and dead-lettering have to be built on top. Newer Kafka versions add share groups (queue-style consumption where many consumers can read one partition with per-record acknowledgement), but in an interview the classic log semantics are what people expect.
Kafka in an Interview
When to Use It
Reach for Kafka when:
- Several systems need the same events. Order placed → payments, inventory, email, analytics and search each read the same topic in their own group. Adding a consumer doesn't touch the producer.
- You need to absorb bursts. Writes land in Kafka at whatever rate they arrive, and consumers drain them at a sustainable rate. Spikes become lag instead of outages.
- You're building a streaming pipeline. Clickstreams, logs, metrics, IoT readings and CDC feeds flowing into Flink, Spark or a warehouse.
- Ordering per entity matters. Partition by
order_idand every event for that order is processed in sequence. - Replay is valuable. Rebuild a cache or search index, backfill a new service, or reprocess after fixing a bug by resetting a consumer group's offsets.
- Event sourcing or a durable change log is part of the design.
Knowing Its Limitations
- Ordering is per partition only. Global ordering means one partition, which means one consumer.
- Consumer parallelism is capped by partitions, and partition counts are hard to change.
- No per-message acknowledgements, delays or priorities. One slow or poisoned record blocks its partition for that group. Retries and dead-letter topics are application patterns, not built-in features.
- Not a database. You can't query by anything but offset or timestamp. Consumers materialize data into a store that can answer queries.
- Exactly-once stops at Kafka's edge. External side effects need idempotency.
- Operational weight. Self-managed Kafka is a serious system to run. For low-volume task queues, SQS or RabbitMQ is simpler and cheaper.
- Latency is good, not ultra-low. End-to-end latency is typically a few to tens of milliseconds. Trading systems that need microseconds use other tools.
Questions You Might Get
- "How do you guarantee order for a user's events?" Key by
user_idso they share a partition, use an idempotent producer so retries don't reorder, and process each partition with a single thread (or per-key queues within the consumer). - "A consumer crashes mid-batch. What happens?" Its partitions move to other consumers in the group, which resume from the last committed offset. Records processed after that commit are processed again, so processing must be idempotent.
- "A broker dies. Do we lose data?" Not with RF 3,
acks=allandmin.insync.replicas=2: a new leader is elected from the ISR, which has every acknowledged record. - "One record keeps failing. What do you do?" Retry a few times, then publish it to a retry topic (or a dead-letter topic) with the error, commit past it, and alert. Don't block the partition forever.
- "How many partitions?" Do the arithmetic from peak throughput and per-consumer throughput, take the larger of that and the consumer count you need, and add headroom.
Summary
Kafka is a partitioned, replicated, append-only log. Producers append batches to partition leaders, followers replicate them, and records become visible once the in-sync replicas have them. Consumers pull from offsets they track themselves, consumer groups split partitions among their members, and records stay on disk for a retention period so anything can be replayed.
In an interview, the details that matter are the key (it sets ordering and hot spots), the partition count (it caps parallelism), acks=all with min.insync.replicas=2 (durability), at-least-once delivery with idempotent consumers (correctness), and consumer lag (health). Get those right and Kafka becomes a reliable building block you can drop into almost any event-driven design.