All posts
System Design Mastermind · Part 27
  • System design
  • Interview prep
  • Kafka
  • Message queues
  • Platform

Kafka system design: a distributed log that never loses an acknowledged message

How to design a distributed message queue like Kafka in real interview order: bytes times replication and fan-out as the numbers that matter, a light API of produce, fetch, group heartbeat and commit, partitions, leaders, in-sync followers, controllers and consumer groups built in passes, one record walked from send() to a committed offset, a lab on acks, min.insync.replicas and who can become leader, a lab on partitions, hot keys and broker network and disk, a lab on consumer-group rebalances and duplicates, and what happens when each part fails.

25 Oct 2026 · 33 min read · interactive

Share

The 1-minute answer

Kafka is a partitioned, replicated, append-only log, not a queue that deletes on read. A topic is split into partitions spread over brokers; the producer hashes the key to pick one, so records with the same key stay in order. It batches and compresses records and sends them straight to the partition's leader, which appends them to a segment file through the OS page cache. Followers in other zones pull the new records; the leader acknowledges an acks=all write once every in-sync replica (ISR) has it, and with replication factor 3 and min.insync.replicas 2 it refuses writes rather than keep them on one copy. Consumers in a group split the partitions, one owner each, pull from an offset with long polls, and commit the next offset to an internal topic; another group reads the same data independently. A controller quorum (KRaft) holds metadata and moves leadership to an in-sync follower when a broker dies. Retention deletes whole old segments, compaction keeps the last value per key, and tiered storage keeps hours on brokers and months in object storage. The hard parts: never losing an acknowledged record, sizing partitions and brokers (hot keys, fan-out, disk), and consumer groups that rebalance without stalling.

How this page follows the interview

Each phase is a section below, in the order you'd present it. Click a phase for what to say, what to write, and the trap.

✅ Seen: said publicly (cited)🔶 Inferred❓ Unknown: state it as an assumption🧭 Interview choice

This page designs the log itself. When Kafka is just an arrow in someone else's design (why a queue, task queues vs logs, outboxes, dead-letter queues), Foundations F10 (queues and event streams) and F11 (idempotency and exactly-once) cover it; F09 covers leases and consensus.

Requirements and numbers

Agree what's promised, then size it. For a log, bytes per second times replication and fan-out decides the brokers; consumer speed decides the partitions. Change any input: each number comes with the decision it forces.

Functional

  • Producers append records to named topics
  • Many consumer groups, each reads everything
  • Order per key; replay from any offset
  • Keep records for days (or latest per key)
  • Create topics, add partitions, set retention

Non-functional

  • An acknowledged record is never lost
  • Survive a broker or a zone going down
  • Produce p99 in tens of ms
  • Hundreds of MB/s per topic, scale out
  • One noisy client can't slow the rest

Out of scope (say it)

Stream processing (windows, joins), schema registry internals, connectors, cross-region replication in depth.

Capacity calculator

Every input is an assumption 🔶: say it out loud. Anchors: a single partition can take "10s of MB/sec" from producers ✅ Confluent 2015; Kafka's default retention is 168 hours ✅ Kafka docs; LinkedIn ran 7 trillion messages a day on 4,000+ brokers in 2019 ✅ LinkedIn 2019. Network and disk per broker are teaching values.

Three rules for this estimate
  1. A day is 86,400 seconds; size network for the peak and disk for the average.
  2. Every byte moves many times: in once, to RF − 1 followers, out once per consumer group.
  3. Partitions = max(t/p, t/c): the slower of producing into and consuming from one partition decides.
They'll push on thisAnswer out loud, then open.

Core entities and the API

Kafka speaks a binary protocol over TCP; it's shown here as readable fields. What they listen for: clients talk straight to partition leaders, producers say how many copies to wait for, consumers pull from an offset and commit their own progress.

EntityKey fieldsNote
Request
Response

Where does a record live?

Two lookups an interviewer may ask you to do by hand: which partition a key goes to, and how a broker finds offset N without scanning a terabyte. Change the key, the partition count or the offset.

Why it works this way

  • Key → partition. The client hashes the key and takes the remainder by the partition count; Kafka's Java client uses murmur2, computed exactly here. 🔶 client code
  • Segments are named by their first offset, 20 digits, so finding the file is a search over names. ✅ Strimzi 2021
  • The index is sparse: one entry per 4,096 bytes of records by default, offset → byte position. ✅ Strimzi 2021
  • Segments are 1 GiB by default, and retention deletes whole closed segments. ✅ Kafka docs

Changing the partition count is why teams over-partition up front: Confluent's guidance is to size for one or two years of growth. ✅ Confluent 2015

They'll push on thisAnswer out loud, then open.

High-level design

Build it in passes and say why each box exists. Click any box to see what it does, what it owns, what's inside it and what you'd watch. Every broker leads some partitions and follows others; the diagram shows one partition's view.

They'll push on thisAnswer out loud, then open.

Walk one record, box by box

The payments service publishes "order 7731 paid". Follow it from send() to a committed offset in the billing team's consumer group, then to object storage, then through a leader dying. Each step lights up the path and shows what goes over the wire, what's stored and how long it takes.

On the wire

Arrows show who calls whom, and the numbers give the order. Followers and consumers both call the leader: Kafka pulls, it doesn't push. Replies go back along the same line. Step 1 happens inside the app, so it has no arrow.

What the producer does before a byte leaves

Most of Kafka's speed and safety is decided in the client library. Six things it does:

    Data and storage choices

    There's no database here: the log is the storage. Records live in segment files, offsets in an internal topic, metadata in a replicated log of its own.

    DataPickConsideredWhy not those

    The one rule to know: ack only what every in-sync copy has

    # A partition leader handling one Produce.
    # Illustrative, not Kafka's code.
    def on_produce(batch, acks):
        if acks == "all" and len(isr) < min_insync:
            return NOT_ENOUGH_REPLICAS          # refuse, don't weaken
        if dup_of_last_batches(batch.pid, batch.seq):
            return OK(previous_offset)          # idempotent retry
        base = log.append(batch)                # page cache, no fsync
        if acks == "0" or acks == "1":
            return OK(base)                     # leader only
        wait_until(high_watermark > base + batch.count - 1)
        return OK(base)                         # every ISR copy has it
    
    # On each follower Fetch(from_offset):
    def on_follower_fetch(f, offset):
        f.end = offset                          # it has everything below
        isr = [r for r in replicas if caught_up_recently(r)]
        high_watermark = min(r.end for r in isr)

    Illustrative. The order is the point: refuse below min ISR, drop retried duplicates, append, then wait for the high watermark. 🧭

    Why a log on disk is fast

    1. Appends only. Linear writes ran ~600 MB/s vs ~100 KB/s for random writes on the disks Kafka's design notes describe. ✅ Kafka docs
    2. The page cache, not the heap. Recent data stays in OS memory; "a cache of up to 28-30GB on a 32GB machine". ✅ Kafka docs
    3. sendfile. Bytes go from page cache to socket without a copy through the app (not with TLS). ✅ Kafka docs
    4. Batches end to end. Compressed once by the producer, stored and sent as-is. ✅ Kafka docs

    More storage questions

    They'll push on thisAnswer out loud, then open.

    Deep dive: replication, acks and who can become leader

    The leader's broker dies. Which acknowledged records survive depends on four settings: replication factor, acks, min.insync.replicas and unclean leader election, plus whether a follower had quietly fallen behind. Pick a preset, then change one setting at a time.

    Bars: how far each copy's log reached when the leader died (not to scale). Dashed line: what producers were told is saved. Red: acknowledged records the new leader doesn't have. 🧭

    The rules this lab teaches

    1. acks=all waits for the ISR, not for every replica; a shrunken ISR weakens it. ✅ Kafka docs
    2. min.insync.replicas refuses writes below the minimum, and "only takes effect if the producer uses acks=all". ✅ Kafka docs
    3. Only ISR members can be elected, unless unclean election is on (off by default since 0.11). ✅ Confluent docs
    4. f + 1 copies tolerate f failures in the ISR model; a majority quorum needs 3 copies for 1. ✅ Confluent docs

    Numbers to quote

    A follower is dropped from the ISR after replica.lag.time.max.ms: 30 s since Kafka 2.5 (was 10 s). ✅ KIP-537

    fsync per write "can reduce performance by two to three orders of magnitude", so Kafka relies on copies, not flushes. ✅ Confluent docs

    Kafka 4.0 previews Eligible Leader Replicas: replicas guaranteed to have everything up to the high watermark, a safer pool to elect from. ✅ Kafka 4.0

    They'll push on thisAnswer out loud, then open.

    Deep dive: partitions, hot keys and brokers

    Partitions set how many consumers can work in parallel; brokers set how many bytes can move. Too few partitions and consumers can't keep up; one hot key and no partition count helps; long retention fills disks; fan-out fills networks. Pick a preset, then change the inputs.

    What the platform builds

    1. Size partitions from consumers, max(t/p, t/c), then for two years of growth. ✅ Confluent 2015
    2. Key by the thing whose order matters, and only that: a coarse key makes hot partitions. 🧭
    3. Place replicas one per zone (rack-aware), and spread leaders evenly. 🧭
    4. Tiered storage for long retention: local hours, remote days to months. ✅ Uber 2024

    Numbers to quote

    LinkedIn (2019): 100+ clusters, 4,000+ brokers, 100,000+ topics, 7 million partitions, 7 trillion messages a day. ✅ LinkedIn 2019

    Partition limits (2015, ZooKeeper era): 2,000–4,000 per broker; ~5 ms per leader election, so 1,000 leaders take ~5 s to move. ✅ Confluent 2015

    KRaft: 2 million partitions in Confluent's test, 10× the old bound. ✅ Confluent 2021

    They'll push on thisAnswer out loud, then open.

    Deep dive: consumer groups, rebalances and duplicates

    Each partition has one owner in a group, so moving partitions between consumers pauses them, and a consumer that dies after processing but before committing makes its replacement read those records again. Pick a preset, then change the protocol or the timings.

    The rules this lab teaches

    1. Eager stops the world: every member gives up every partition each round. ✅ Confluent 2019
    2. Incremental pauses only what moves: the KIP-848 protocol is server-side and has no global sync step. ✅ KIP-848 docs
    3. A rolling restart means two rebalances per consumer with dynamic membership; static ids avoid them. ✅ Confluent 2023
    4. At least once by default: make the side effect idempotent, or commit offsets inside the same transaction. ✅ Kafka docs

    Numbers to quote

    Eager vs incremental (Kafka Connect, 900 tasks): ~14 minutes to settle vs about one minute. ✅ Confluent 2019

    Auto-commit runs every 5 s by default, so a crash re-reads up to 5 s of records. ✅ Kafka docs

    KIP-848 is generally available in Kafka 4.0; clients opt in with group.protocol=consumer. Share groups (queue-style) are production-ready in 4.2. ✅ Kafka 4.0 · 4.2

    They'll push on thisAnswer out loud, then open.

    A partition's lifecycle

    From the platform team's view, a partition is healthy, under-replicated, below its minimum, offline, or moving. Click events to move it; ones that can't happen from the current state are disabled. Each event shows what fires across the cluster.

    NormalSomething went wrongGreyed out: not possible from the current state.

    States are named for teaching; Kafka exposes them as metrics (under-replicated, under-min-ISR and offline partition counts). 🔶

    Edge cases interviewers love

    They'll push on thisAnswer out loud, then open.

    Failure, monitoring and recovery

    Kafka is built to lose brokers. What hurts is the slow failures: a follower that's sick but alive, a consumer that quietly stopped, a replay that empties the page cache. Click a box to take it down: red is the failed part, amber is its blast radius. Each answer covers impact, degraded mode, the alert, automatic and manual recovery, and how you'd trace it.

    Tracing it back: a normal write vs a slow follower

    Time from send() to the consumer committing. In the slow trace the follower is alive but its disk is failing, so acks=all waits until it's dropped from the ISR.

    How one failure becomes three

    What you'd alert on (SLOs)

    SignalTargetAlert

    Incident playbook

      The toolkit

      Name the technique, then say where it goes in this design.

      They'll push on thisAnswer out loud, then open.

      Making it fast, and who owns what

      A healthy write takes milliseconds; failover, a slow follower and rebalances are measured in seconds, and those are what users notice. Bars are sizing estimates, not measured figures.

      TeamOwnsPaged when…

      Senior follow-ups beyond the happy path

      Interviewers pick from these themes once the design is on the board. Have one concrete answer per theme, tied to this design.

      Practice ladder

      Real interviews go level by level. Answer out loud before opening each one. Levels 6–7 are where Senior becomes Staff.

      Sources

      Checked October 2026. Mechanisms and defaults come from Apache Kafka's docs (the 4.2 design and consumer-rebalance-protocol pages; producer defaults from the 3.2 docs; broker defaults from the 0.10 docs; consumer defaults from the 1.0 docs), KIP-537 (replica.lag.time.max.ms 30 s since 2.5), the 3.9 (Nov 2024), 4.0 (Mar 2025) and 4.2 (Feb 2026) release announcements, and Confluent's docs and blog posts (replication; partitions, 2015; KRaft, 2021; incremental rebalancing, 2019; static membership, 2023). Company figures are as published: LinkedIn (Oct 2019) and Uber's tiered storage post (Jul 2024). The 2015 partition limits predate KRaft and are labelled that way. Older version docs are used where newer pages couldn't be fetched; defaults change between releases (Kafka 4.0's KIP-1030 changed several), so check the docs for your version. The labs use rounded teaching values. techinterview.org is a third-party prep site, used only to cross-check what interviewers expect.

      System Design Mastermind · Platform & Infra

      Series home

      All of Platform & Infra

      5 published · 7 comingWhat Senior platform loops lean on.

      19

      Distributed job scheduler system design: on time, at least once, never lost

      Jobs in a sharded store with a precomputed next_run_at → one scheduler per shard (lease + fencing token) claims due jobs every second: insert run (unique job_id + time) and advance next_run_at in one transaction → durable queue with deliver-at, enqueued a little early → workers lease runs, heartbeat, call the target with the run id as idempotency key → backoff, then a DLQ. At-least-once, made safe by idempotency.

      32 min · interactive Preview
      24

      Metrics and logging system design (Datadog-style): series, roll-ups and alerts you can trust

      Agents add up metrics for 10 s and batch them with logs → intake checks key and quotas, appends to a durable log, then 202 → writers map tags to series ids in an inverted index and store compressed points with roll-ups → logs: index a slice, archive all → monitors evaluate a window that ends in the past, and the whole stack is watched from outside.

      32 min · interactive Preview
      27

      Kafka system design: a distributed log that never loses an acknowledged message

      Topics split into partitions; the producer hashes the key, batches and sends to the partition leader → the leader appends to the page cache, followers in other zones pull, acks=all waits for every in-sync copy (RF 3, min ISR 2) → consumer groups pull from offsets and commit them → KRaft controllers move leaders; tiered storage keeps history.

      You're reading this Preview
      30

      Ad click aggregator system design: exactly-once counts, late clicks and hot ads

      Signed click URL → click service appends to Kafka and 302s → Flink dedupes by click id, counts per ad in 1-minute event-time windows, upserts (ad, minute) rows into an OLAP store → a per-click counter paces budgets → a nightly recount from raw clicks is what billing reads.

      32 min · interactive Preview
      33

      Payment system design (Stripe): idempotency, unknown outcomes, the ledger and reconciliation

      Card → vault → token; confirm with an Idempotency-Key → attempt row written before the bank call → gateway with timeouts and breakers → result + outbox in one commit → event log → append-only double-entry ledger and signed webhooks → a timeout is 'unknown', resolved by status check and the next day's settlement file → payouts from balances.

      33 min · interactive Preview
      ··

      Web crawler

      Coming next
      ··

      File sync (Dropbox)

      Coming next

      More posts