Key technologies
Kafka
A replayable log that most candidates describe as a queue. The difference is where the interesting follow-ups live.
Kafka comes up in almost every system design interview that involves more than one service, and it is the technology candidates most often get directionally right and mechanically wrong. “We’ll put it on a Kafka topic” passes the first pass. Then the interviewer asks what happens when the consumer crashes halfway through a batch, or how you add a second consumer without slowing the first, and the answer stops being about Kafka and starts being about whether you have run one.
This is the model you need to hold, in the order the follow-ups arrive.
What Kafka actually is
Kafka is a distributed, durable, replayable append-only log. That phrase is doing four separate jobs, and the one candidates drop is replayable.
A message queue — SQS, RabbitMQ, Celery on Redis — hands a message to a consumer and deletes it on acknowledgement. The queue’s job is to get work done once and forget it. Its depth tends toward zero, and reading is destructive.
Kafka does not delete on read. A producer appends records to the end of a log; consumers track their own position in that log. Reading is non-destructive, the data stays until a retention policy removes it, and two unrelated consumers can read the same records at their own speeds without knowing about each other.
Kafka is a log you can rewind, not a queue you drain. Nearly every design that is a good fit for Kafka is a good fit because of the rewind: a new service that needs the last 30 days of events, a cache you can rebuild from scratch, a bug fixed on Tuesday that has to be reapplied to Monday’s data.
The architectural consequence is that the broker is deliberately dumb. It does not track which consumer got what, it does not do per-message routing, and it does not retry on your behalf. It appends bytes to a file and serves ranges of that file. That is why a modest cluster moves hundreds of megabytes per second — sequential disk writes, batched reads, and no per-message bookkeeping — and also why so much of the complexity lands in your consumer code.
The data model: topic, partition, offset
Four nouns, and precision about them is most of the interview.
A topic is a named stream — orders, clicks, payments. It is purely logical.
A topic is split into partitions, and the partition is the real unit of everything: ordering, storage, parallelism and replication all happen per partition, never per topic. A partition is an ordered, immutable sequence of records stored as segment files on a broker’s disk.
Every record in a partition gets a monotonically increasing offset, assigned by the leader on append. Offsets are per-partition — offset 42 in P0 has nothing to do with offset 42 in P1 — and never reused.
A record is a key, a value, a timestamp and headers. All of them are opaque bytes to the broker; Kafka has no idea you are sending JSON.
topic: orders
├── partition 0 [0][1][2][3][4][5][6][7][8] → appends here
├── partition 1 [0][1][2][3] → appends here
└── partition 2 [0][1][2][3][4][5][6] → appends here
Notice that the partitions are different lengths. Nothing synchronises them, and there is no cluster-wide ordering of records across them. If you need a total order over a stream, you need one partition — which means one consumer, which means you have capped your throughput at what one machine can do. Interviewers ask this on purpose.
Ordering, and the one thing that destroys it
Kafka guarantees that records in a partition are delivered in offset order. It guarantees nothing about order across partitions. So the useful question is never “does Kafka preserve order” but “what decides which partition a record lands in?”
The record key. With a key set, the default partitioner computes hash(key) % partitionCount. Same
key, same partition, therefore same ordering guarantee. Key by the entity whose history must stay in
order: orderId, userId, accountId.
With a null key, the producer round-robins (in batches — the sticky partitioner fills one batch before moving on). Your records spread across partitions and the ordering guarantee is gone.
A null key does not give you “slightly weaker” ordering. It gives you none. PLACED, SHIPPED and
CANCELLED for the same order land on three partitions, get read by three consumers, and can be
processed in any order — including CANCELLED before PLACED. The bug shows up under load, days
later, as a handful of orders in an impossible state.
The second-order trap is that the partition count is effectively permanent. hash(key) % 3 and
hash(key) % 6 send the same key to different partitions, so adding partitions rehashes the
keyspace and breaks per-key ordering for every key that has records in flight. Kafka will let you
raise the count happily and silently. You cannot lower it at all.
Delete the key and watch ordering go
In kafka-lab, exercise 2 is one line: make the producer send with a null key, then re-run the
three-status lifecycle endpoint. The log prints the partition and offset of every consumed record,
so you can see the three statuses for one order split across partitions and arrive out of order.
Exercise 3 then resets a group to the earliest offset and replays the whole topic, with the second
group unaffected.
Consumer groups: a cursor, not a queue
A consumer sets a group.id. Within one group, each partition is assigned to exactly one
consumer — Kafka’s coordinator does the assignment, and partitions are handed out whole.
Three facts fall out of that, and they are worth being able to recite:
- Partition count is the ceiling on a group’s parallelism. Six partitions, nine consumers, three consumers idle. Scaling a consumer group past the partition count does nothing at all.
- Separate groups are independent. A
fulfilmentgroup and ananalyticsgroup both receive every record, each with its own committed offset. That is fan-out, and it is free. - A group’s position is server-side state. Committed offsets live in an internal Kafka topic,
__consumer_offsets, so a restarted consumer resumes where the group left off rather than where that process left off.
Rebalancing, and why people fear it
When a consumer joins, leaves, or stops sending heartbeats, the group rebalances and partitions are reassigned. The classic (“eager”) protocol does this stop-the-world: every consumer gives up every partition, then the group reassigns from scratch. On a large group with slow startup, that is seconds of a cold stop, and a rebalance that triggers another rebalance is the production incident people mean when they say rebalance storm.
Three mitigations are worth naming:
- Cooperative (incremental) rebalancing revokes only the partitions that actually have to move.
- Static membership (
group.instance.id) lets a consumer restart inside the session timeout and reclaim its own partitions without a rebalance, which makes rolling deploys cheap. - Kafka 4.x’s new consumer group protocol (KIP-848) moves assignment into the broker-side coordinator and removes the global synchronisation barrier altogether.
The most common self-inflicted rebalance has nothing to do with any of that: a handler that takes
longer than max.poll.interval.ms between polls. The coordinator decides the consumer is dead and
reassigns its partitions, the consumer wakes up and tries to commit an offset it no longer owns,
and the cycle repeats. Slow handler work belongs on a thread pool or in a smaller batch, not inside
the poll loop.
Strand a consumer, then replay a topic
Exercise 1: start a second app instance and watch three partitions split across two consumers; start a third and watch one sit idle. The ceiling stops being a sentence you memorised and becomes something you have seen in a consumer-group view.
Durability: replication, ISR and acks
Each partition has one leader and some number of followers; the replication factor is set per topic and is almost always 3 in production. All reads and writes go to the leader. Followers that are caught up form the in-sync replica set (ISR), and only an in-sync replica can be elected leader if the leader dies.
The producer’s acks setting decides when a send is considered successful:
acks |
Leader waits for | Loses data when |
|---|---|---|
0 |
nothing — fire and forget | anything at all goes wrong |
1 |
its own local write | the leader dies before a follower replicates |
all |
every in-sync replica | every in-sync replica dies |
acks=all on its own is not enough, and this is the detail that separates answers. If the ISR has
shrunk to just the leader — two followers lagging, or restarting — then “all in-sync replicas” means
one machine, and acks=all is quietly as weak as acks=1. The setting that fixes it lives on the
broker: min.insync.replicas=2 makes the leader reject a write when fewer than two replicas
are in sync, so you fail loudly rather than silently accepting data you cannot keep.
“Replication factor 3, acks=all, min.insync.replicas=2. That tolerates one broker failure with
no data loss and no write stall, and it fails writes rather than losing them if a second one goes.
I’d also leave unclean leader election disabled, so an out-of-sync replica can’t be promoted and
truncate committed records.”
Delivery semantics, honestly
Kafka’s default, in any normal setup, is at-least-once. A consumer reads a record, processes it, then commits the offset. If it crashes after processing and before committing, the record is delivered again on restart.
Flip the order — commit first, then process — and you get at-most-once: a crash loses the record. That is a legitimate choice for metrics and almost nothing else.
Two things improve the picture, and both are narrower than they sound.
The idempotent producer (enable.idempotence=true, the default since Kafka 3.0) stamps each
batch with a producer id and a sequence number per partition, so the broker can drop a batch it has
already appended. Without it, a retry after a transient failure can append a batch twice, or append
batches out of order. With it, producer retries are safe. It says nothing about your consumer.
Transactions (transactional.id plus consumers reading at read_committed) give you genuine
exactly-once semantics for read-from-Kafka, process, write-to-Kafka — the model Kafka Streams is
built on. They commit the output records and the input offsets atomically.
Transactions do not extend to the database write your consumer actually performs. The commit to Postgres and the commit to Kafka are two systems and there is no distributed transaction between them. If someone tells you they have exactly-once delivery into their own datastore, they have at-least-once delivery and an idempotent write, which is the correct answer — just not that name.
So the real answer to duplicates is to make the handler idempotent: a natural idempotency key
(orderId + status, a payment reference), a uniqueness constraint that makes the replay a no-op, or
an upsert whose second application changes nothing. Say that, and you have answered a question most
candidates deflect.
Make a replay a no-op
kafka-lab commits offsets after the handler returns, so exercise 3’s replay re-delivers every
record and you can watch the side effects happen twice. Exercise 6 is to add a dedup key and make
the second delivery do nothing — the only real fix.
Retention, compaction and replay
Records leave a partition for one of two reasons, and you choose which.
Time or size retention (cleanup.policy=delete, the default, typically seven days) drops whole
segments once they age or the partition exceeds a size cap. The retention window is your replay
window: it is how far back a new consumer can start, and therefore how long you have to notice a
bug before the data to reprocess is gone.
Log compaction (cleanup.policy=compact) keeps the most recent record per key and garbage
collects older values for that key. The partition stops being a history and becomes a snapshot you
can rebuild state from. This is what makes a topic usable as a changelog — the current value of
every account, bootstrappable from offset 0 without storing every change ever made.
Replay is the capability most worth bringing up unprompted, because it changes designs:
- A new service launches and needs history. Give it a new
group.idandauto.offset.reset=earliest. - A consumer wrote bad data for six hours. Fix it, reset the group’s offsets to a timestamp, reprocess.
- A cache or search index is corrupt. Rebuild it from the topic instead of from the source database.
One gotcha worth knowing: auto.offset.reset only applies when a group has no committed offset.
It is not “where to start reading”, it is “what to do when there is no cursor” — which is why a new
group set to latest appears to receive nothing at all.
Where it hurts in production
Naming the operational edges is what makes an answer sound like experience rather than reading.
Consumer lag is the metric. Latency and error rate tell you nothing about a consumer that quietly stopped committing. Lag — log end offset minus committed offset, per partition — is the alert that catches a stuck consumer, a hot partition and an under-scaled group alike.
Head-of-line blocking is the default failure mode. One record that always throws will block every later record on that partition forever, because the offset never advances. Scaling out does not help; the partition is stuck, and the ones behind it are fine. The fix is a retry policy with a bounded backoff and then a dead-letter topic — plus an owner for the DLT, because a dead-letter topic nobody drains is just a silent data-loss queue with extra steps.
Hot partitions follow from skewed keys. Key by tenantId and your largest customer is one
partition’s problem. The usual fix is a composite key (tenantId:bucket) that spreads the entity
across partitions, accepting weaker ordering within it.
Partitions are not free. Each one is open file handles, memory and replication traffic on its broker, and more partitions means longer leader-election and rebalance times. Thousands per broker is normal; tens of thousands needs thought. Size for the throughput you need, with headroom, and remember you cannot go down.
Small records are inefficient one at a time. linger.ms and batch.size trade a few
milliseconds of latency for much better throughput, and compression (lz4, zstd) typically gets
3–5× on JSON. This is the one tuning conversation worth having unprompted.
And the things Kafka simply does not do, which are the real reason to pick something else: no per-message acknowledgement, no per-message delay or TTL, no priority, no selective redelivery of one record out of a partition.
Block a partition on purpose
Exercise 4 throws for one orderId and leaves the partition wedged on restart — head-of-line
blocking, felt. Exercise 5 fixes it properly with a dead-letter topic and a bounded backoff, and
exercise 7 has you watch lag grow with kafka-consumer-groups.sh --describe while a producer runs.
Kafka versus the alternatives
The interviewer is usually testing whether you reach for Kafka reflexively.
| Model | Reach for it when | Avoid when | |
|---|---|---|---|
| Kafka | Replayable partitioned log, consumer-tracked offsets | High volume, several independent consumers, replay or backfill matters, ordering per entity, stream processing | You want a task queue with per-message retry, delay or priority |
| SQS | Managed queue, destructive read, per-message ack and visibility timeout | Task queues, decoupling work, per-message retry and DLQ for nearly free ops | You need replay, fan-out to many consumers, or high-throughput strict ordering |
| SNS + SQS | Pub/sub fan-out into independent queues | Fan-out with queue semantics per subscriber, on AWS, with no ops | You need history — a new subscriber starts empty |
| RabbitMQ | Broker-routed queues, rich routing, per-message ack | Complex routing, priorities, request/reply, RPC-ish patterns | Very high throughput, or replay of what already went through |
| Kinesis | Shard-based log, very Kafka-like | You want Kafka’s model fully managed on AWS and can live with shard limits | You need Kafka’s ecosystem, or finer control over partitioning |
| Redis Streams | In-memory log with consumer groups | Low latency, modest volume, Redis already in the stack | It must survive the loss of a node with no data loss |
The honest cost line, which earns credit: self-hosting Kafka is real operational work — brokers, rebalances, partition sizing, upgrades, capacity. On a small team you take MSK or Confluent Cloud and pay for it, or you use SQS and avoid the problem.
When to propose Kafka in an interview
Say Kafka when at least one of these is true:
- Several consumers need the same stream for different purposes, and you do not want the producer to know about any of them.
- Replay or backfill is part of the design — rebuilding a cache or index, onboarding a new service with history, reprocessing after a bug.
- Ordering per entity matters and you can key by that entity.
- Volume is high and sustained, and the write path must absorb spikes the consumers cannot.
- Stream processing, CDC or an outbox is in the picture: Kafka’s ecosystem is the reason to choose it, as much as the broker is.
Do not say Kafka when the thing you actually described is a task queue — one worker per job, per-message retries with backoff, scheduled or delayed delivery, priorities. Kafka can be bent into that shape and the result is worse than SQS at a fraction of the operational cost. Low volume with a single consumer is the same story.
“I’d put order events on a Kafka topic keyed by orderId — that gives me per-order ordering, and
fulfilment, analytics and the search indexer can each consume at their own pace as separate groups.
I want the replay: when the indexer schema changes I rebuild from the topic rather than backfill
from the orders database. If this were a worker queue for sending emails I’d use SQS instead — I’d
want per-message retry and a visibility timeout, not a log.”
Sizing it on the whiteboard
If you are asked to size a topic, this is the whole calculation. Say 50,000 events/second at ~1 KB:
- Write throughput: 50 MB/s in, ×3 for replication = 150 MB/s of cluster write traffic.
- Storage at 7 days: 50 MB/s × 604,800 s ≈ 30 TB raw, ~90 TB replicated, and roughly 20–25 TB on disk after 4:1 compression.
- Partitions: if one consumer instance handles ~5,000 records/second, you need at least 10 to keep up. Round up for headroom and future growth — 24 or 32 — because adding them later rehashes your keys.
- Consumers: no more than the partition count per group, so 32 partitions caps each group at 32 instances.
Then say the part that matters: those numbers are small for Kafka. A handful of brokers carries this. If the interviewer wanted a system that strains Kafka, they would have asked for a hundred times more.
The follow-ups, and the one-line answers
- “How do you guarantee ordering?” Per partition only. Key by the entity; ordering across entities is not guaranteed and usually not needed.
- “What if one consumer falls behind?” Watch lag. Scale the group up to the partition count, then either repartition or move slow work off the poll loop.
- “A message keeps failing — what happens?” It blocks its partition. Bounded retries, then a dead-letter topic with an owner.
- “Can you do exactly-once?” Within Kafka, with transactions. Into your database, no — so make the handler idempotent.
- “A broker dies?” An in-sync replica is elected leader; producers and consumers follow the
metadata to the new one. With RF 3 and
min.insync.replicas=2, no loss and no stall. - “How do you add a new consumer later?” New
group.id,auto.offset.reset=earliest. It reads history without touching the existing groups. - “How far back can you replay?” As far as retention. That window is a design decision, not a default to accept.
- “Why not SQS?” Replay and fan-out. If I needed neither, I would use SQS.