Skip to content

Apache Kafka in Practice

Intermediate 48 min read Part 15 of 18

Kafka in practice: brokers, partitions and ISR, producers and acks, consumer groups, why it is fast, retention and compaction, KRaft, sizing and pitfalls.

Summary#

Apache Kafka is a distributed, replicated, append-only log:

  • Producers append records to topics.
  • Each topic is split into partitions, and each partition is an ordered log stored on disk and replicated across brokers.
  • Consumers read by offset, at their own pace, in consumer groups that split the partitions between members.

Because records are retained for days or forever (not deleted on read), many independent consumers can read the same stream and replay history.

The append-only design, sequential disk I/O, the OS page cache, batching and zero-copy transfer let one broker move hundreds of MB/s. Partitioning and replication scale this to millions of messages per second with strong durability (acks=all, min.insync.replicas=2).

Ordering holds within a partition only, so the partition key is the central design decision. Kafka is the default backbone for event-driven systems, change data capture, stream processing, log and metrics pipelines, and asynchronous work between services.

Why It Exists#

In 2010 LinkedIn had a data plumbing problem. Dozens of systems produced activity data (page views, searches, profile updates), and dozens of systems consumed it: Hadoop for analytics, search indexers, monitoring, recommendation pipelines. Point-to-point pipelines between each producer and consumer were brittle and multiplied quadratically. Traditional message brokers (JMS-style queues such as ActiveMQ) kept per-message state, slowed down when consumers fell behind, and couldn't handle LinkedIn's billions of events per day.

Jay Kreps, Neha Narkhede and Jun Rao built Kafka around one idea: a log. They described it in "Kafka: a Distributed Messaging System for Log Processing" (NetDB workshop, 2011). Producers only append, and consumers only remember a number, the offset. The broker doesn't track who read what or delete on delivery. It keeps an immutable, ordered sequence on disk for a retention period. Kreps later argued, in the essay "The Log: What every software engineer should know about real-time data's unifying abstraction" (2013), that this structure is the natural integration point for a company's data. Every system publishes its changes to a log, and every other system subscribes. LinkedIn open-sourced Kafka in 2011, it became an Apache top-level project in 2012, and its creators founded Confluent in 2014.

That design solves problems that show up in almost every large system:

  • Decoupling. Producers don't know or care who consumes. Adding a fraud detector, a search indexer or a data-lake sink later means adding a consumer group, not changing producers.
  • Buffering and back pressure. A spike of 10 times normal traffic lands in the log. Consumers catch up at their own rate instead of collapsing.
  • Fan-out with replay. Ten consumer groups read the same topic independently. A new service can start from the beginning of retained history, and a buggy consumer can rewind and reprocess.
  • Ordering where it matters. All events for one key (an order, a user, a match) are strictly ordered.
  • Durability at high throughput. Replicated logs survive broker failures, without the per-message overhead of classic brokers.

How It Works#

A motivating example: live match statistics#

Picture a site showing real-time football statistics. Every goal, card and substitution is an event:

  1. A producer (the ingestion service) writes each event to a queue.
  2. A consumer reads events and updates the site.

With one queue server and one consumer, that's fine for one tournament. Scale it to 1,000 matches at once, and both the queue and the consumer are overwhelmed.

  • Add servers to the queue? If events are spread randomly, a goal might be processed before kick-off. So route by match ID: all events for a match go to the same queue shard, called a partition, and stay in order.
  • Add consumers? Make them a consumer group. Each partition is assigned to exactly one member, so each event is handled by one consumer, while the group as a whole processes all partitions in parallel.
  • Add basketball? Use separate topics (soccer-events, basketball-events), so each site subscribes only to what it needs.

Those three moves (partition by key, consumer groups, topics) are Kafka's core model.

Architecture: brokers, topics, partitions and replicas#

  • Broker: a Kafka server process that stores partitions on local disk and serves clients. A cluster has 3 to hundreds or more brokers.
  • Topic: a named, logical stream, such as orders or page-views. It's multi-producer and multi-consumer.
  • Partition: the unit of storage, ordering and parallelism. Each partition is an ordered, immutable sequence of records, appended at the end. Each record gets a sequential offset (0, 1, 2, ...). A topic with 12 partitions can be consumed by up to 12 consumers in parallel within one group. A topic is a logical grouping; partitions are physical, spread across brokers.
  • Replica: each partition is copied to replication.factor brokers (typically 3). One replica is the leader: it handles all writes and, by default, reads. The others are followers, which fetch from the leader continuously. Since Kafka 2.4 (KIP-392), consumers may read from a nearby follower, to save cross-AZ traffic.
  • ISR (in-sync replicas): the set of replicas caught up with the leader, meaning they've fetched up to the leader's log end within replica.lag.time.max.ms (30 s by default). Only ISR members are eligible to become leader under the default, safe settings.
  • Controller: the component that manages cluster metadata (topics, partition assignments, leaders, ISR changes) and performs leader elections. Historically this was a broker elected via ZooKeeper. In KRaft mode it's a Raft quorum of controller nodes. More below.

The data model: records, partitions, segments and offsets#

A record has four parts, all technically optional:

  1. A key, which decides the partition, and so the ordering scope and compaction identity.
  2. A value, the payload in bytes. Kafka doesn't interpret it. Typical encodings are JSON, Avro or Protobuf, with a schema registry.
  3. A timestamp, set at creation or ingestion. Ordering is by offset, not timestamp.
  4. Headers: key-value metadata such as trace IDs, schema version and event type.

On disk, each partition is a directory of segments, for example 00000000000004200000.log. These are files of a bounded size (segment.bytes, 1 GB by default), plus time-based rolling. Each has an offset index and a time index, which are sparse and memory-mapped, so a consumer seeking offset 4,200,517 binary-searches the index and scans forward a few KB. Only the newest (active) segment is written. Retention deletes or compacts whole closed segments.

Records travel and are stored as record batches. A producer groups records for one partition, compresses the batch once (with lz4, zstd, snappy or gzip), and the broker writes the batch to disk as is, without decompressing it. Consumers receive the same bytes and decompress them. That end-to-end batch format is a big part of why Kafka is efficient.

Two log positions matter:

  • the log end offset (LEO), the next offset to be written on a replica;
  • the high watermark (HW), the highest offset replicated to all ISR members.

Consumers can only read up to the high watermark. That prevents a consumer from seeing a record that might vanish if the leader fails before followers copy it.

Because the log is immutable, replication is just "copy bytes after offset X". Recovery is "truncate to a known point and refetch". Caching is trivial, because data never changes. Kafka is often called a distributed commit log for this reason.

Brokers, replicas and ISR, in depth#

Replication protocol. Followers send Fetch requests to the leader, like consumers do, saying "give me data from offset X". The leader learns each follower's position from those fetch offsets.

  • When all ISR members have fetched past offset N, the leader advances the high watermark to N and tells followers (in fetch responses), so they can advance theirs.
  • A follower that hasn't caught up to the leader's log end within replica.lag.time.max.ms is removed from the ISR. The controller records the change in metadata.
  • When it catches up, it's added back.

That makes the ISR a dynamic quorum. Kafka doesn't need a fixed majority of 3 for every write. It needs every currently in-sync replica, plus a floor set by min.insync.replicas.

Durability, as a formula. A write with acks=all is acknowledged once all ISR members have it. With replication.factor=3 and min.insync.replicas=2:

  • if the ISR shrinks to 1 (two brokers down or lagging), producers using acks=all get NotEnoughReplicas errors, rather than writing data that only one disk holds;
  • an acknowledged record is on at least 2 brokers, so it survives any single broker failure.

That's the standard production setting: RF=3, min.insync.replicas=2, acks=all. You get availability through one broker failure, and no acknowledged-data loss through one failure.

Leader election. When a leader fails, the controller picks a new leader from the ISR. If no ISR member is alive, unclean.leader.election.enable decides. With false (the default since 0.11), the partition stays unavailable until an ISR member returns: consistency over availability. With true, an out-of-sync replica becomes leader, and acknowledged records it lacks are lost.

Leader epochs (KIP-101). Early Kafka used the high watermark to truncate logs after failover, which could lose or diverge data in rare double-failure scenarios. Since 0.11, each leadership term has an epoch number, recorded in the log with its start offset. A returning replica asks the new leader "where did epoch 7 end?", truncates exactly there, and refetches. That's the same idea as Raft terms (Consensus), and it closed those divergence holes.

Rack awareness. Set broker.rack to the availability zone, and Kafka spreads each partition's replicas across zones. One AZ outage then leaves at least two replicas (with RF=3 across 3 AZs) and the partition keeps accepting writes. See Replication for leader-follower trade-offs in general.

Is Kafka "CP" or "AP"? It's configurable per topic. With acks=all, min.insync.replicas=2 and unclean election disabled, Kafka chooses consistency: writes fail rather than risk loss. With acks=1 and unclean election enabled, it chooses availability. Engineers joke that "Kafka is always available, sometimes consistent", because a well-run cluster almost never goes fully down. In an interview, "what if Kafka goes down?" usually deserves a gentle push back toward the more realistic failure: a consumer goes down. See CAP Theorem and PACELC.

Producers: keys, partitioning, acks and batching#

A producer application calls send(topic, key, value). The client library does the rest:

  1. Serialise the key and value to bytes. Use a schema (Avro or Protobuf plus a schema registry) so consumers can evolve safely.
  2. Choose the partition.
    • With a key: partition = murmur2(key) mod numPartitions, so the same key always lands in the same partition, which is what preserves per-key ordering.
    • Without a key: modern clients use the sticky partitioner (KIP-480). They fill a batch for one partition, then switch to another, which gives large batches and an even spread over time.
    • A custom partitioner can route by any rule.
  3. Find the leader. The client caches cluster metadata (which broker leads each partition), and sends straight to that broker. There's no proxy and no extra hop.
  4. Batch. Records for the same partition accumulate in an in-memory buffer until the batch reaches batch.size (16 KB by default; often raised to 64 KB–1 MB for throughput), or until linger.ms passes. That's a small wait, often 5–20 ms, that trades a little latency for much bigger batches.
  5. Compress the whole batch (zstd or lz4 are the usual picks), and send.
  6. Wait for acknowledgment, according to acks.
acksBroker replies whenLatencyLoss risk
0Never; fire-and-forgetLowestAny network or broker failure loses records silently
1Leader has written it to its log (page cache)Low (about 1–5 ms)Lost if the leader dies before followers copy it
all (-1)All current ISR members have it, and the ISR is at least min.insync.replicasHigher (adds one follower fetch round, a few ms in-region)None for a single broker failure with RF=3 and min ISR 2

Since Kafka 3.0, producer defaults are acks=all and enable.idempotence=true. Older clients defaulted to acks=1, and many production incidents trace back to that.

Retries and idempotence. Transient errors (leader changes, timeouts, network blips) make the producer retry automatically, within delivery.timeout.ms (2 minutes by default). Retrying is dangerous on its own. If the first attempt actually succeeded but the response was lost, a retry writes a duplicate. The idempotent producer fixes this:

  • The broker assigns each producer a producer ID (PID).
  • The producer numbers each batch per partition with a sequence number.
  • The broker remembers the last sequence numbers per PID and partition, and drops duplicates.
  • It rejects gaps, so batches can't be reordered even with up to 5 requests in flight.

You get exactly one copy per partition, in order, without limiting throughput. Always enable it with retries.

Producer-side numbers. A single producer instance with good batching sends tens to hundreds of MB/s. Small, unbatched, acks=all sends of 100-byte records may reach only thousands per second per partition, because each request pays a full replication round trip. Batching is how Kafka turns "one fsync-and-replicate per message" into "one per thousand messages".

Keep messages small. message.max.bytes (about 1 MB by default) caps record batch size, and the right shape is records of a few hundred bytes to tens of KB. Don't put videos or files in Kafka. Upload the blob to object storage (S3), and publish a small event containing its location and metadata (Handling Large Blobs). A video pipeline should produce {videoId, s3://bucket/raw/123.mp4, size, uploader}, not the 2 GB file.

Producers, in depth: ordering under retries, and what can still go wrong#

Ordering with retries. Without idempotence, max.in.flight.requests.per.connection > 1 plus retries can reorder records. Batch 1 fails, batch 2 succeeds, then batch 1's retry lands after it. The old fix was max.in.flight=1, which killed throughput. With idempotence on, the broker enforces sequence order per partition, so up to 5 in-flight requests stay ordered.

Where producers lose data even with good settings:

  1. The application crashes with records still in the producer's memory buffer. send() is asynchronous. It returns a future, and the record isn't durable until the callback reports success. Code that writes to a database, calls send(), and then returns 200 to the user without awaiting the acknowledgment can lose the event. If the event must not be lost, either await it, or use the transactional outbox: write the event into the database in the same transaction, and let a relay (Debezium CDC, or a poller) publish it (Change Data Capture).
  2. The buffer fills (buffer.memory, 32 MB by default) while brokers are slow. send() blocks for up to max.block.ms, then throws. The application must handle that by retrying, spilling to disk, or shedding load.
  3. delivery.timeout.ms expires during a long broker outage. The record fails permanently, and your callback must log it, alert, or route it elsewhere.
  4. Dual writes. "Write to the database, then publish to Kafka" from application code isn't atomic. A crash between the two leaves them inconsistent. The outbox pattern, or making Kafka the source of truth (event sourcing; see Event Sourcing and CQRS), removes the dual write.

Choosing the key, the most important producer decision. The key determines:

  • the ordering scope: all events with one key are ordered;
  • the load distribution: hot keys make hot partitions;
  • the co-location for stateful consumers: all events of one user reach the same consumer instance, so it can keep per-user state locally;
  • the compaction identity for compacted topics.

Good keys have high cardinality and even traffic, and match the entity whose events must stay ordered: orderId for order lifecycle events, userId for per-user activity, accountId for ledger entries. Bad keys have low cardinality (country, event type, a boolean) or are dominated by a few values (a celebrity's user ID, a viral ad ID).

Consumers, consumer groups and offsets#

Consumers pull. A consumer calls poll() in a loop, and the broker returns batches of records after the consumer's current position, waiting up to fetch.max.wait.ms for at least fetch.min.bytes. The pull model was a deliberate design choice:

  • consumers set their own pace, so a slow consumer never gets overwhelmed by pushed data;
  • they fetch big batches efficiently;
  • they can rewind at will;
  • the broker stays simple, because it doesn't track per-message delivery state.

Consumer groups. Consumers sharing a group.id form a group. The group's partitions are divided among its members, and each partition is assigned to exactly one member of the group at a time. So:

  • Parallelism is capped by partition count. 12 partitions means at most 12 active consumers in a group. A 13th sits idle as a standby.
  • Different groups are independent. The analytics group and the fraud group each read every record, at their own offsets. That's how Kafka is both a queue (within a group, each record goes to one worker) and pub/sub (across groups, every group gets everything).

Offsets. Each group commits, per partition, the offset of the next record to read. Commits go to an internal compacted topic, __consumer_offsets, managed by a group coordinator broker. On restart, or after a rebalance, consumption resumes from the committed offset. Where no commit exists, auto.offset.reset decides: earliest (start of retained data) or latest (only new data).

When to commit defines the delivery guarantee:

  • Commit after processing: at-least-once. A crash after processing but before commit means the record is processed again on restart. This is the default stance. Make handlers idempotent with dedupe keys, upserts or conditional writes (Idempotency).
  • Commit before processing: at-most-once. A crash after commit but before processing skips the record.
  • Exactly-once processing needs either transactions (read-process-write inside Kafka), or storing the offset atomically with the result in the same database transaction. More in the Deep Dive.

enable.auto.commit=true (the default) commits the latest polled offsets every 5 s in the background. That can commit records you haven't finished processing, if processing is asynchronous. Production consumers usually disable auto-commit and commit explicitly after the work is durably done.

Commit after durable side effects. In a web crawler, the consumer that downloads a page must not commit the offset until the raw HTML is safely in blob storage. The more work a single consumer does per record, the more work is redone after a crash. So split pipelines into small stages, each consuming one topic and producing to the next: download, then parse, then index. Each stage then commits after a short, well-defined unit of work.

Rebalancing. When a member joins, leaves, crashes (no heartbeat within session.timeout.ms, 45 s by default in recent versions), or takes longer than max.poll.interval.ms (5 minutes by default) between polls, the group rebalances: partitions are reassigned. Rebalances used to be "stop-the-world" (eager): every member revoked every partition, then got new ones. Improvements since then:

  • Cooperative incremental rebalancing (KIP-429): only the partitions that move are revoked. Others keep processing.
  • Static membership (KIP-345): a member with a stable group.instance.id can restart within the session timeout without triggering a rebalance. Ideal for rolling deploys of stateful consumers.
  • The next-generation consumer group protocol (KIP-848, generally available in Kafka 4.0) moves assignment to the broker-side coordinator, making rebalances incremental and much faster at scale.

Consumer lag is the log end offset minus the committed offset, per partition. It's the health metric for consumers: growing lag means consumers can't keep up. Monitor it with Burrow, Kafka exporter, or the managed-service dashboards, and alert on both size and growth rate.

Why Kafka is fast#

People are surprised that a disk-based system outruns many in-memory brokers. Kafka's speed comes from designing around how hardware and operating systems actually behave:

  1. Sequential I/O only. Writes are appends to the end of the active segment. Reads are mostly sequential scans from an offset. Sequential disk throughput is enormous (hundreds of MB/s on HDDs, GB/s on NVMe SSDs), while random I/O on HDDs manages only about 100–200 seeks per second. The Kafka design docs make the point that sequential disk access can beat random memory access in some cases. By never updating in place, Kafka keeps the disk in its fast mode.
  2. The OS page cache instead of an application cache. Kafka writes to the file system and lets Linux cache recent data in free RAM. Most consumers read the tail of the log, which is still in the page cache, so they're served from memory without touching disk. Because the cache belongs to the OS, it survives broker process restarts, avoids JVM garbage-collection overhead for message data, and isn't duplicated in a heap. That's why Kafka brokers are deployed with modest heaps (around 6 GB) on machines with 64 GB+ of RAM.
  3. Zero-copy transfer. To send log data to a consumer, a naive server reads the file into user space and writes it to a socket: four copies and several context switches. Kafka uses sendfile() (Java FileChannel.transferTo), which tells the kernel to copy straight from the page cache to the socket buffer (or the NIC, with DMA). That removes user-space copies, so serving many consumers costs little CPU. Caveat: with TLS, data must be encrypted in user space, so true zero-copy is lost and CPU cost rises, though modern CPUs with AES-NI keep this manageable.
  4. Batching everywhere. Producers batch records per partition. Brokers append batches as single writes. Followers fetch batches. Consumers fetch batches. A thousand records cost about one request, one disk write and one network transfer.
  5. Compression on batches. Compressing a batch of similar JSON records with zstd or lz4 often shrinks them 3–10 times. The broker stores compressed batches untouched, saving disk, network and page cache.
  6. No per-message bookkeeping. The broker doesn't track per-message acknowledgments or delete on consumption. Consumers own their position as a single integer per partition. Delivery state is O(partitions), not O(messages).
  7. Partition parallelism. Each partition is an independent log with an independent leader. Spread across brokers and disks, throughput scales roughly linearly with partitions and brokers, until network or disk saturates.

Throughput numbers to plan with:

  • A well-configured broker on modern hardware sustains hundreds of MB/s of combined produce and consume traffic. Often 100–300 MB/s of produce, with consumer fan-out multiplying reads.
  • With small messages, that's on the order of 1 million messages per second per broker. A useful, hand-wavy interview number.
  • A broker typically stores several to tens of TB. Some interview guides use about 1 TB per broker as a conservative figure. Tiered storage removes most of this limit.
  • End-to-end latency (produce to consume) is usually a few to tens of milliseconds, dominated by linger.ms, the replication round for acks=all, and consumer poll intervals. That's not microseconds. For sub-millisecond, in-memory fan-out, see Redis pub/sub.

In public posts, LinkedIn has reported running Kafka at over 7 trillion messages per day (2019), and Uber has described deployments handling trillions of messages and petabytes per day. These figures are for very large multi-cluster fleets, not single clusters.

Retention and log compaction#

Kafka deletes data by policy, not consumption. cleanup.policy per topic is delete, compact, or both.

Time and size retention (delete).

  • retention.ms defaults to 7 days (log.retention.hours=168). retention.bytes caps size per partition.
  • Whole closed segments older than the limit are deleted. The active segment is never deleted. So with segment.bytes=1 GB on a slow topic, data can linger beyond the retention time, until the segment rolls (segment.ms forces rolling).
  • Retention can be hours (a buffer for high-volume metrics), weeks (replay window for reprocessing), or infinite (retention.ms=-1, for event-sourced systems of record).

Longer retention costs disk. A topic ingesting 50 MB/s keeps about 4.3 TB per day before replication, so 7 days at RF=3 is about 90 TB. Plan storage, or use tiered storage.

Log compaction (compact). Instead of age, Kafka keeps at least the latest record for each key. A background log cleaner thread rewrites closed segments, dropping older records whose key appears later. A record with a key and a null value is a tombstone: it marks the key deleted, and is itself removed after delete.retention.ms (24 h by default), giving consumers time to see the deletion.

What compaction guarantees:

  • consumers reading from the start eventually see the latest value for every key;
  • offsets never change (compacted logs have gaps);
  • the order of surviving records is preserved;
  • the uncompacted head of the log still holds every recent update.

Compacted topics are a changelog or table in log form. They're used for:

  • __consumer_offsets itself (the latest offset per group and partition);
  • Kafka Streams state-store changelogs, which rebuild local state after a crash;
  • CDC topics keyed by primary key, giving a replayable snapshot of a table (Change Data Capture);
  • configuration and reference data that new services bootstrap from.

The New York Times has described its publishing pipeline (2017) storing every published article in a Kafka log retained indefinitely, so new services build their own views by replaying it.

Tiered storage (KIP-405; early access in Kafka 3.6, and production-ready in later 3.x releases) moves closed segments to object storage (S3, GCS, Azure Blob), keeping only recent data on broker disks. Retention of months becomes cheap. Brokers become lighter, so rebalancing and replacing a broker no longer copy many TB. And historical replays read from object storage at somewhat higher latency. Confluent Cloud, Amazon MSK and others offer their own tiered or object-storage-based variants. Some newer Kafka-compatible systems (for example WarpStream, and the object-storage designs from several vendors) go further, writing directly to object storage with stateless brokers, trading latency for cost.

Ordering guarantees#

Kafka guarantees order within a partition: records appear to every consumer in offset order, which is the order the leader appended them. Across partitions, there's no global order. Partition 3's offset 900 may be newer or older than partition 7's offset 1200.

What that means in practice:

  • Per-entity ordering: key by the entity. All events for order:42 are ordered: created, then paid, then shipped. Events of different orders interleave freely, which is fine.
  • Global ordering (every event in one sequence) needs a single-partition topic, which caps throughput at one partition's speed (roughly 10–50 MB/s, depending on hardware and message size) and one consumer. Sometimes that's right, as with a low-volume ledger or a ticketing waiting-room queue that admits users strictly in arrival order. Usually it isn't.
  • Changing partition count breaks key-to-partition mapping. murmur2(key) mod 12 differs from mod 24, so after adding partitions, new events for a key may land on a different partition than its older events, and ordering across the change isn't guaranteed. Pre-provision partitions for growth (more below), or migrate to a new topic for strict cases.
  • Consumers can break ordering themselves. If one consumer processes records from a partition in a thread pool, concurrently, it loses partition order. Parallelise by key inside the consumer instead: hash the key to a worker thread. The Confluent Parallel Consumer library does this.
  • Retries break ordering if a failed record is sent to a retry topic while later records for the same key carry on. When order matters, pause the partition, or block on the key until the retry succeeds.
  • Producer ordering requires idempotence (or max.in.flight=1), as discussed earlier.

KRaft vs ZooKeeper#

From its beginning until version 3.x, Kafka stored cluster metadata (brokers, topics, partition assignments, ISR, configs, ACLs) in Apache ZooKeeper (ZooKeeper and etcd). One broker, elected through a ZooKeeper ephemeral node, acted as controller. That had real costs:

  • two distributed systems to deploy, secure, monitor and upgrade, with different configs and failure modes;
  • controller failover was slow at scale. A new controller had to read the entire metadata state from ZooKeeper, which for hundreds of thousands of partitions took tens of seconds to minutes, during which leader elections stalled;
  • partition count was limited to roughly a couple of hundred thousand per cluster in practice, by ZooKeeper write rates and controller loading time;
  • metadata propagated from the controller to brokers via RPCs, which could diverge.

KRaft (Kafka Raft, KIP-500) replaces ZooKeeper with an internal metadata log, replicated by a Raft-based quorum of controller nodes, typically 3 or 5. They can run as dedicated processes, or combined with brokers in small clusters.

  • The active controller is the Raft leader. It appends metadata changes ("partition 7 leader is now broker 3") as records to the __cluster_metadata topic.
  • Brokers replicate that log like any consumer, keeping an in-memory metadata image up to date by offset.
  • Controller failover is near-instant. Standby controllers already have the whole log in memory, so a new leader just continues.
  • Metadata becomes an event log, with snapshots. Brokers that restart catch up from their last offset, instead of reloading everything.
  • One system to operate. The goal was clusters with millions of partitions.

KRaft was marked production-ready in Kafka 3.3 (2022). ZooKeeper mode was deprecated, then removed in Kafka 4.0 (2025), so new clusters are KRaft-only. Migration tools move existing ZooKeeper clusters in place. In interviews: "Kafka uses an internal Raft quorum (KRaft) for metadata and controller election; older deployments used ZooKeeper."

Handling retries and errors#

Kafka itself is reliable, but getting records in and out can fail.

Producer side. Configure automatic retries with backoff (retries, retry.backoff.ms, and the overall delivery.timeout.ms), and always enable idempotence, so a retry after a lost acknowledgment doesn't duplicate. Handle final failures in the send callback: alert, write to a local fallback, or fail the user request.

Consumer side. Kafka has no built-in per-message retry or dead-letter queue. Amazon SQS has visibility timeouts and redrive policies, and RabbitMQ has nack plus dead-letter exchanges, but a Kafka consumer that fails on a record has three choices:

  1. Retry in place. Keep retrying the same record, with backoff. That's correct for transient errors (a database briefly down), and preserves ordering, but it blocks the whole partition. A poison message, one that will never succeed, stalls it forever.
  2. Retry topics. Publish the failed record to orders.retry.1m, and commit the original offset. A separate consumer reads the retry topic, waits until the record's due time (checking a header timestamp), and retries. After N failures, it moves to orders.retry.10m, then to orders.dlq. That unblocks the main partition, but sacrifices per-key ordering for that record.
  3. Dead-letter queue (DLQ). A topic holding records that exhausted their retries, with error metadata in headers, for human investigation and replay tooling.

Frameworks implement these patterns: Spring Kafka's retryable topics, Kafka Connect's errors.deadletterqueue.topic.name, and Kafka Streams' deserialisation exception handlers. If built-in redelivery, visibility timeouts and per-message acknowledgment matter more than replay and throughput, a queue such as SQS may simply fit better. A web crawler's URL frontier, for example, benefits from SQS's native retries and DLQ. Kafka is adding share groups ("Queues for Kafka", KIP-932, early access in 4.0), which give queue-style per-record acknowledgment and redelivery without the one-consumer-per-partition limit. Check version maturity before relying on them.

Scalability, partition sizing and hot partitions#

First, check whether you need to scale at all. Estimate the message rate, message size and retention. A system producing 20k messages per second at 1 KB is 20 MB/s, about 1.7 TB per day. That's a small cluster (3 brokers, mostly for redundancy). Scaling conversations start in the hundreds of MB/s, or with millions of messages per second.

Horizontal scaling. Add brokers, and spread partitions across them. A topic can only use as many brokers, disks and consumers in parallel as it has partitions. Adding brokers without enough partitions leaves the new brokers idle, so partition count is the real lever. In managed services (Confluent Cloud, Amazon MSK, Aiven, Azure Event Hubs with its Kafka API) broker scaling is largely automated, but partitioning remains your decision. Scale per topic: a 2 GB/s clickstream topic may need hundreds of partitions, while a 50-messages-per-second admin-events topic needs 3.

Sizing partitions. A widely used rule from Confluent's guidance:

partitions ≥ max(target throughput ÷ per-partition producer throughput, target throughput ÷ per-partition consumer throughput)

Measure per-partition throughput on your hardware. Producers often reach about 10–50 MB/s per partition, and consumers vary with processing cost. Worked example:

  • Target: 600 MB/s of click events.
  • Measured: a producer pushes 30 MB/s per partition, and a consumer processes 15 MB/s per partition (it does enrichment).
  • Partitions ≥ max(600 ÷ 30, 600 ÷ 15) = max(20, 40) = 40.
  • Round up for growth, to 64 or 96, because adding partitions later remaps keys. With 96 partitions you can run up to 96 consumers per group.

Don't over-partition. Each partition costs:

  • open file handles (segments and indexes);
  • memory for buffers;
  • replication fetch work;
  • controller metadata;
  • longer leader elections during failover;
  • longer rebalances.

Historical guidance for ZooKeeper-based clusters was a few thousand partitions per broker and roughly 200,000 per cluster. KRaft raises the cluster ceiling substantially. As a rule of thumb, tens to low hundreds of partitions per topic covers most systems. Very high counts need a reason.

Hot partitions. The classic interview follow-up. An ad-click aggregator keys clicks by adId, so each ad's clicks stay together for counting. Then a huge brand launches a celebrity campaign, and one ad gets 100 times normal traffic. Its partition, and the one consumer that owns it, are overwhelmed while others sit idle. Options:

FixHowCost
No keySticky or round-robin partitioningNo per-ad ordering or co-location; fine if order doesn't matter (counts are commutative)
SaltingKey = adId + ":" + random(0..N-1), or a time bucketEach ad's events split across N partitions; consumers or a downstream aggregation must merge N partial counts
Compound keyadId + region or adId + userId % 16Spreads by a second dimension; ordering only within the compound key
Adaptive saltingDetect heavy hitters (count-min sketch or top-k on the stream) and salt only those keysMore logic; keeps normal keys unsalted
Back pressureProducers slow down when lag on hot partitions growsHigher ingest latency; can't fix sustained hotness
Dedicated topicRoute known VIP keys to a separate, wider topicOperational complexity

The ad-click aggregator uses salting plus a Flink job that pre-aggregates per (adId, salt) and then merges (Ad Click Aggregator, Flink).

Detecting heavy hitters cheaply is a job for probabilistic sketches. A count-min sketch keeps approximate counts per key in fixed memory. Paired with a small heap, it yields the top-k hottest keys, in any stream (Probabilistic Data Structures). That's how you decide which keys to salt.

Hot keys are the same problem everywhere. A sharded post cache keyed by post ID suffers a hot shard when a post goes viral. The fix there is replicated cache instances behind a load balancer, so any instance can serve any post. That's the same "spread one hot key across many servers" idea, and it costs a few extra cache misses. The geographic flavour is the same too: a nearby-inventory service that partitions by region ID (say, the first 3 digits of a postal code) keeps each query on one or two partitions, which is great for locality, but a dense metro region can become a hot partition. Choose keys that align with access patterns, and check their skew.

Scalability, in depth: partition math, broker sizing and rebalancing data#

Storage per broker. Example:

  • Ingest 300 MB/s with RF=3 gives 900 MB/s of writes cluster-wide.
  • With 3 days of retention: 900 MB/s × 259,200 s ≈ 233 TB.
  • On 12 brokers, that's about 19 TB each, plus 20–30% headroom, so about 25 TB of disk per broker, as JBOD or a few large volumes.
  • Each broker writes about 75 MB/s, and serves consumer reads: if three consumer groups read everything, that's 300 MB/s × 3 ≈ 900 MB/s cluster-wide, about 75 MB/s per broker, mostly from the page cache.
  • Network per broker: about 75 MB/s in from producers (leader share), about 150 MB/s of follower replication traffic in and out, and about 75 MB/s to consumers. Comfortable on 10–25 Gbps NICs.

Page cache sizing. For consumers to stay in memory, the page cache should hold at least the last few minutes of writes per broker that consumers read. At 75 MB/s per broker, 30 s of lag tolerance is about 2.25 GB, and 10 minutes is 45 GB. Lagging consumers fall off the cache and hit disk, which raises I/O load. A massive replay (say, a new consumer reading 3 days of history) can evict the hot tail from the page cache, and slow everyone. Tiered storage, or dedicated replay clusters, isolate that.

Reassigning partitions. Adding brokers doesn't move existing partitions automatically. You run a reassignment: kafka-reassign-partitions, or Cruise Control, LinkedIn's open-source rebalancer, which optimises against goals such as disk, network and CPU balance. That copies whole partitions (potentially TBs) to new replicas, so throttle it (leader.replication.throttled.rate) to avoid starving production traffic. Tiered storage shrinks the local data to copy, so rebalances finish in minutes instead of hours.

Message size effects. Throughput in messages per second falls as message size rises, while MB/s rises until it saturates network or disk. Tiny messages (under 100 B) are dominated by per-record overhead, so batching and compression matter most. Big messages (100 KB+) increase memory pressure and fetch sizes, and replication catch-up stalls. Keep the payload lean, and put blobs in object storage.

When to Use It#

Kafka fits when you need a durable, ordered, replayable stream with high throughput and multiple independent consumers. It's used in two styles:

  • As a message queue: a consumer group shares the work, and each record is processed by one worker. Records remain in the log until retention, but the group's offsets move past them. Fits when:
    • Work can be asynchronous. A video upload makes the standard-definition version available quickly and publishes "transcode video 123 at s3://..." for workers to process when capacity allows (Video Streaming).
    • Order must be preserved. A ticketing virtual waiting room admits users in arrival order. Low volume, so even a single partition can work (Ticket Booking).
    • Producers and consumers must scale independently. One service shouldn't be able to overload another. Kafka absorbs bursts (Message Queues).
  • As an event stream: many groups read continuously, often with replay. Fits when:
    • Data must be processed continuously, in real time: click aggregation, fraud scoring, metrics (Batch and Stream Processing).
    • Many consumers need the same events: live comments fanned out to many servers (Live Comments), or order events feeding billing, email, analytics and search.
    • You want change data capture. Debezium streams database changes to Kafka, feeding caches, search indexes and warehouses (Change Data Capture).
    • Log and metrics pipelines: application logs and metrics go into Kafka, then out to Elasticsearch, object storage and time-series databases (Data Pipelines and Analytics, Metrics Monitoring).
    • Event sourcing, where the log is the system of record, with compaction or infinite retention (Event Sourcing and CQRS).

Page-view analytics show the batch and stream contrast. If daily hit counts are enough, a nightly MapReduce or Spark job over web-server logs works: the mapper emits ((month, url), 1) and the reducer sums. Kafka is the upgrade when you need counts in seconds. Stream page-view events into a topic, aggregate with Flink or Kafka Streams in windows, and also land the raw events in object storage for the batch job.

Pick something else instead when:

  • you need per-message acknowledgment, delays, priorities or built-in retries and DLQ, at modest volume: pick SQS, RabbitMQ, or a Redis-backed job queue;
  • you need sub-millisecond fan-out to connected clients, and losing a message is acceptable: pick Redis pub/sub;
  • you need long-running workflows with timers and compensation: pick Temporal;
  • you need queryable storage: Kafka isn't a database. Sink to Cassandra, PostgreSQL or Elasticsearch;
  • you need multi-tenant geo-replicated messaging with many topics (millions of small topics): consider Apache Pulsar, whose design separates serving from storage (BookKeeper) and is built for very high topic counts.

When NOT to Use It#

  • Low volume and simple needs. A few hundred jobs per minute between two services doesn't justify a Kafka cluster. Use SQS, or a database-backed queue (SELECT ... FOR UPDATE SKIP LOCKED).
  • Large payloads. Files, images and video belong in object storage. Kafka should carry the pointer.
  • Request-response or RPC. Kafka adds milliseconds and complexity to what should be a direct call. Use HTTP or gRPC.
  • Random access by key. Kafka can't look up "the latest event for order 42" efficiently, unless you build a materialised view (Kafka Streams state store, or a database).
  • Strict global ordering at high throughput. Impossible across partitions. Rethink whether you truly need it.
  • Per-message scheduling ("deliver this in 3 hours"). Kafka has no delayed delivery. Use a scheduler or a queue with delays (Job Scheduler).

How to Implement It#

  1. Model events first. Name topics by domain (orders.v1, payments.events). Decide the event schema (Avro or Protobuf with a schema registry), required headers (event ID, type, trace ID), and the key for each topic.
  2. Size partitions. Use partitions ≥ max(throughput ÷ producer per-partition rate, throughput ÷ consumer per-partition rate), rounded up for 2–3 years of growth. Avoid low-cardinality or skewed keys.
  3. Set durability per topic. Use replication.factor=3, min.insync.replicas=2 and unclean.leader.election.enable=false, with replicas spread across AZs (broker.rack).
  4. Configure producers: acks=all, enable.idempotence=true, linger.ms of 5–20 ms, batch.size of 64–256 KB, compression.type=zstd or lz4. Await or handle every send callback. Use the outbox pattern for database-plus-event atomicity.
  5. Configure consumers:
    • disable auto-commit, and commit after side effects are durable;
    • use idempotent handlers;
    • choose the cooperative or new consumer protocol, and static membership for stateful consumers;
    • tune max.poll.records and max.poll.interval.ms to your processing time.
  6. Plan retries and DLQs: retry topics with backoff, a DLQ with error headers, and a replay tool.
  7. Set retention and compaction: delete with a replay window (often 3–7 days) for event streams, compact for changelogs and entity state, and tiered storage for long retention.
  8. Monitor:
    • consumer lag per group and partition;
    • under-replicated and offline partitions (alert at above 0);
    • ISR shrink and expand rates;
    • request latency percentiles (produce and fetch);
    • broker disk, network and page-cache hit ratio;
    • controller health and active-controller count (it must be 1).
  9. Secure it: TLS in transit, SASL (SCRAM or OAuth) or mTLS authentication, ACLs per topic and group, quotas per client to stop noisy neighbours.
  10. Operate: use KRaft, rolling upgrades, Cruise Control for balance, throttled reassignments, and capacity reviews against lag and disk trends.

A TypeScript (kafkajs) producer and consumer with the key settings:

import { Kafka, CompressionTypes } from "kafkajs";
 
const kafka = new Kafka({ clientId: "orders-svc", brokers: ["b1:9092", "b2:9092", "b3:9092"] });
 
// Producer: idempotent, acks=all, batched and compressed
const producer = kafka.producer({ idempotent: true, maxInFlightRequests: 5 });
await producer.connect();
await producer.send({
  topic: "orders.v1",
  acks: -1,                                  // all in-sync replicas
  compression: CompressionTypes.GZIP,        // zstd/lz4 via codec plugins
  messages: [{ key: order.id, value: JSON.stringify(order), headers: { eventId: evtId } }],
});                                          // await: not durable until acked
 
// Consumer: manual commit after durable side effects (at-least-once)
const consumer = kafka.consumer({ groupId: "billing", sessionTimeout: 45000 });
await consumer.connect();
await consumer.subscribe({ topic: "orders.v1", fromBeginning: false });
await consumer.run({
  autoCommit: false,
  eachMessage: async ({ topic, partition, message }) => {
    const evtId = message.headers?.eventId?.toString();
    await billing.applyOnce(evtId, JSON.parse(message.value!.toString())); // idempotent upsert
    await consumer.commitOffsets([
      { topic, partition, offset: (BigInt(message.offset) + 1n).toString() }, // next offset
    ]);
  },
});
TechnologyFits when
Apache Kafka (self-managed, KRaft)You have platform engineers and want full control, large scale, and the lowest unit cost
Confluent Cloud, Amazon MSK (provisioned or serverless), Aiven, InstaclustrManaged Kafka; you want Kafka semantics without running brokers
Azure Event Hubs (Kafka endpoint)Azure shops wanting a Kafka-compatible managed ingestion service
RedpandaA Kafka-API compatible C++ engine (thread-per-core, no JVM, Raft per partition), for lower tail latency and simpler ops
Amazon Kinesis Data StreamsAWS-native streaming with per-shard limits (about 1 MB/s or 1,000 records/s in, about 2 MB/s out per shard), simpler but less flexible
Apache PulsarVery many topics, built-in multi-tenancy and geo-replication, separated compute and storage
Kafka Connect + DebeziumMoving data in and out (databases via CDC, S3, Elasticsearch, warehouses) without custom code
Kafka Streams, ksqlDB, Apache FlinkStream processing: Kafka Streams as a library inside services; Flink for large stateful jobs with event time
Schema Registry (Confluent, Apicurio)Enforcing schema compatibility (backward or forward) across producers and consumers
MirrorMaker 2, Cluster Linking, ReplicatorCross-cluster and cross-region replication

Trade-offs#

OptionProsConsPick when
acks=all + min ISR 2No acknowledged loss through one broker failureA few ms more latency; writes fail if ISR shrinksBusiness events, payments, orders, CDC
acks=1Lower latency, higher throughputLoss on leader failure before replicationMetrics and logs where tiny loss is fine
Keyed partitioningPer-key order, consumer co-locationHot partitions on skewed keysEntity-centric events
No key (sticky)Even load, best batchingNo ordering or co-locationLogs, metrics, commutative aggregates
Many partitionsMore parallelismMore overhead, slower failover and rebalances, more filesProven high throughput needs
Few partitionsSimple, efficientCaps consumer parallelism; hard to increase later without remappingLow-volume topics
Long retention or tiered storageReplay, new consumers bootstrap from historyStorage cost; replays can disturb the page cacheEvent sourcing, reprocessing, audit
Kafka vs SQS or RabbitMQKafka: throughput, replay, fan-out, orderingKafka: no per-message retry, delay or priority; more opsHigh-volume streams vs simple task queues
Kafka vs Redis StreamsKafka: disk retention, durability, scaleKafka: higher latency, heavier opsDurable streams vs lightweight in-memory queues

Common Pitfalls#

  • Bad partition key. Low cardinality or skewed keys create hot partitions, and you can't easily change keys later. Analyse key distribution before launch.
  • Under-partitioning. You can't scale consumers past the partition count, and adding partitions later breaks key ordering across the change.
  • Over-partitioning. Tens of thousands of partitions for small topics slow failover, rebalances and metadata.
  • Assuming exactly-once by default. The default is at-least-once. Consumers will see duplicates after crashes and rebalances. Make handlers idempotent.
  • Auto-commit with asynchronous processing: offsets get committed for records still being processed, and are lost on a crash.
  • Not awaiting sends (or ignoring callbacks), plus dual writes to the database and Kafka, causing silent loss and inconsistency. Use the outbox pattern.
  • RF=3 but min.insync.replicas=1, which makes acks=all meaningless when the ISR shrinks to the leader alone.
  • Unclean leader election enabled on critical topics: it trades acknowledged data for availability.
  • Long processing inside poll(), which exceeds max.poll.interval.ms, triggers rebalance storms, and reprocesses work. Bound the batch size, or hand off to workers while pausing the partition.
  • Poison messages blocking a partition. Add retry topics and a DLQ with alerting.
  • Big messages. Multi-MB records hurt the page cache, memory and replication. Store blobs elsewhere.
  • No schema discipline. One producer changes a field type and every consumer breaks. Use a schema registry with compatibility rules.
  • Ignoring consumer lag until users notice stale data. Alert on lag growth.
  • Treating Kafka as a database: querying by key or scanning topics for lookups. Build materialised views instead.

Real-World Examples#

  • LinkedIn created Kafka for activity tracking and operational metrics, and has reported running it at over 7 trillion messages per day (2019) across many clusters, with tooling like Cruise Control and Burrow (lag monitoring) open-sourced from that experience.
  • Uber has written about Kafka as the backbone of its real-time platform: trip events, driver locations and logs feeding stream processing and its data lake, at trillions of messages per day.
  • Netflix's Keystone data pipeline used Kafka as the routing layer for event data (playback events, logs), into stream processing and storage.
  • The New York Times (2017) described storing all published content in a Kafka log retained indefinitely, as the source for building search and personalisation views by replay.
  • Change data capture with Debezium plus Kafka is widely used to sync operational databases into search indexes, caches and warehouses.

Case studies that use this pattern#

In the Interview#

Deep Dive: Exactly-once semantics, idempotence and transactionsShow

"Exactly-once" in Kafka means a specific, provable thing: the effects of processing each input record appear exactly once in Kafka output topics and committed offsets, even with retries, crashes and rebalances. It arrived in Kafka 0.11 (2017, KIP-98), and has two building blocks.

1. The idempotent producer (described above) removes duplicates caused by producer retries, per partition and per producer session, using a producer ID and per-partition sequence numbers. On its own, it doesn't survive a producer restart: a new process gets a new producer ID.

2. Transactions make a group of writes atomic across partitions and topics, including the consumer offset commit. A typical consume-transform-produce loop:

  1. The producer is configured with a stable transactional.id, such as billing-processor-7. On initTransactions(), the transaction coordinator (a broker chosen by hashing the transactional ID onto the internal __transaction_state topic) bumps the producer epoch for that ID. Any older "zombie" instance with the same ID, for example one that paused and was replaced, is fenced: its writes are rejected with ProducerFenced.
  2. beginTransaction(), then read records from input partitions and produce results to output partitions. The producer registers each new partition with the coordinator (AddPartitionsToTxn).
  3. sendOffsetsToTransaction(offsets, groupMetadata) adds the consumer's input offsets to the same transaction.
  4. commitTransaction(). The coordinator writes PREPARE_COMMIT to its log, then writes commit markers (control records) into every involved partition, including __consumer_offsets, then COMPLETE. This is a two-phase commit coordinated inside Kafka (Distributed Transactions). An abort writes abort markers instead.
  5. Downstream consumers use isolation.level=read_committed. They read only up to the last stable offset (LSO), the first offset of any still-open transaction, and skip records from aborted transactions. With read_uncommitted (the default), consumers see everything immediately, including records later aborted.

What exactly-once does not cover. Side effects outside Kafka: sending an email, charging a card, writing to Postgres. If a processor writes to a database and then crashes before committing its Kafka transaction, the input is reprocessed and the database write repeats. For external sinks you need one of:

  • idempotent writes keyed by event ID, or by a deterministic (topic, partition, offset). INSERT ... ON CONFLICT DO NOTHING or upserts make reprocessing harmless;
  • storing the offset in the same database transaction as the result. On startup, the consumer seeks to the offset stored in the database, ignoring Kafka's committed offset. This is how many exactly-once sinks work (Kafka Connect sinks for JDBC can use upserts; Flink two-phase-commit sinks coordinate with checkpoints);
  • a transactional outbox on the producing side, so database state and emitted events stay consistent.

So the honest summary for interviews is: "effectively-once = at-least-once delivery + idempotent processing". See Delivery Semantics.

Costs. Transactions add coordinator round trips and commit markers. Throughput overhead is modest with reasonably large transactions (commit every 100 ms–1 s, or every few thousand records), but latency for read_committed consumers rises to roughly the transaction commit interval. Kafka Streams wraps all of this behind processing.guarantee=exactly_once_v2 (KIP-447 made it scale by fencing per consumer group generation instead of per input partition). Flink's Kafka sink uses Kafka transactions tied to Flink checkpoints, so output becomes visible when a checkpoint completes.

Transaction pitfalls.

  • Long-open transactions block read_committed consumers at the LSO. A hung producer stalls downstream until transaction.timeout.ms (1 minute by default) aborts it.
  • Each transactional.id must map to one logical processor instance, consistently, or fencing won't protect you.
  • Exactly-once doesn't fix non-deterministic processing. If reprocessing gives a different answer (reading the wall clock, calling external services), outputs differ across retries, even though only one version is committed.
Deep Dive: Can Kafka lose messages? Walking every loss pathShow

Kafka can be configured to lose nothing you were told was written, but every layer has a way to lose data if it's misconfigured. Here they are, end to end.

Producer layer.

  • acks=0: no acknowledgment at all. Any error is invisible.
  • acks=1, then the leader dies before followers fetch the batch. The new leader (from the ISR) doesn't have it, and when the old leader returns it truncates its log to match the new leader's epoch boundary. The record is gone, though the producer saw success.
  • Unawaited sends, buffer overflow, or delivery timeout: records die in client memory.
  • Dual-write gaps: the database commits, and the process dies before publishing.

Fixes: acks=all, idempotence, handling callbacks, the outbox pattern.

Broker layer.

  • Low min.insync.replicas. With RF=3 and min ISR 1, if two followers lag out of the ISR, acks=all means "the leader alone". A leader disk failure then loses data. Set min ISR to 2.
  • Unclean leader election. If all ISR members are down and an out-of-sync replica is allowed to lead, the records it lacks are discarded. Keep it disabled for important topics.
  • No fsync per write. Kafka acknowledges once data is in the page cache of the ISR replicas. It doesn't fsync each message by default (flush.messages and flush.ms default to effectively infinite), relying on replication across machines rather than disk sync for durability. A single broker's crash is fine: the other replicas have the data. But a correlated failure, such as all replicas losing power at once in one rack or AZ before the OS flushes (typically within about 30 s), could lose acknowledged data. Mitigate with rack- and AZ-aware replica placement, so a single power domain can't hold every replica. You can force fsync settings, at a heavy throughput cost, but most deployments rely on replica diversity.
  • Retention too short. A consumer down for longer than retention finds its offset deleted. auto.offset.reset=latest then silently skips the gap, while earliest jumps to the oldest data still retained. Monitor lag against retention, and alert well before the gap.
  • Disk-full brokers go offline. With RF=3 and min ISR 2, two full brokers make partitions unwritable rather than lossy. Better unavailable than wrong, but still an outage.

Consumer layer.

  • Auto-commit before processing finishes, then a crash: those records are skipped.
  • Committing offsets for a batch when some records in it failed and were dropped, not sent to a DLQ.
  • Offset reset misconfiguration on a new group or after expiry (the offset retention for empty groups defaults to 7 days, offsets.retention.minutes). A group that was idle longer than that loses its committed offsets, and restarts at latest, skipping data.

Duplicates, the flip side. With everything configured for no loss, duplicates happen:

  • producer retries without idempotence;
  • consumer crashes after processing and before commit;
  • rebalances that reassign a partition while the old owner is mid-batch, beyond its poll interval;
  • upstream replays.

Expect them, and design consumers to be idempotent: dedupe on an event ID within a retention window (for example a Redis SET evt:{id} 1 NX EX 86400), use conditional or upsert writes, or store offsets atomically with the results.

Verifying durability. Chaos-test the config. Kill leaders under load with acks=all, and verify that the count of acknowledged records equals the count consumed. Tools such as Jepsen have historically found bugs in Kafka's earlier replication protocol (Kyle Kingsbury's 2013 analysis) that motivated designs like leader epochs. Kafka's guarantees today are well documented, but only hold under the documented settings.

Deep Dive: Multi-region Kafka, stream processing internals, and the ecosystemShow

Multi-region topologies. A Kafka cluster is designed for one region (low-latency replication between AZs). Across regions:

  • Active-passive (DR). MirrorMaker 2 (built on Kafka Connect), Confluent Replicator, or Cluster Linking copies topics from the primary region to a standby cluster asynchronously. On disaster, producers and consumers fail over to the standby. Records not yet mirrored (seconds of lag, typically) are lost or delayed, matching an RPO of a few seconds (Disaster Recovery).
  • Offsets differ between clusters, because mirrored partitions get their own offsets. MirrorMaker 2 emits checkpoints that translate consumer group offsets (source offset to target offset), and can sync them, so consumers resume near the right position after failover. Expect some reprocessing, so idempotent consumers matter again.
  • Active-active. Each region produces locally to its own cluster, and MirrorMaker 2 replicates each region's topics to the others, prefixed by source cluster (us-east.orders in eu-west), to avoid replication loops. Consumers read local plus remote topics. Conflicts (the same entity updated in two regions) must be resolved by the application, and global ordering doesn't exist (Multi-Region Data).
  • Stretch clusters spread one cluster's brokers across 3 nearby regions, with synchronous replication via acks=all. That's only viable with low inter-region latency (roughly under 50–100 ms). It gives zero-RPO failover, at a latency cost on every write.

Kafka Streams internals. Kafka Streams is a Java library, not a cluster. Your service instances form a consumer group, and each processes a share of the input partitions as tasks.

  • State (counts, joins, windows) lives in local state stores, RocksDB by default, backed by compacted changelog topics. On failure or rebalance, a new instance rebuilds the store by replaying the changelog. Standby replicas (num.standby.replicas) keep warm copies on other instances, for fast failover.
  • Re-keying (groupBy a different field) writes to an internal repartition topic, so records with the new key end up co-partitioned with the right task. That's a shuffle through Kafka.
  • KTable and KStream duality. A stream of updates is a table's changelog, and a table is the latest value per key, the same idea as log compaction.
  • Interactive queries let instances serve their local state over RPC, effectively embedding a materialised view in the service.

Flink vs Kafka Streams. Flink is a separate cluster runtime with event-time windows, watermarks, large managed state with distributed snapshots (Chandy-Lamport-style checkpoints), and connectors beyond Kafka. Kafka Streams is lighter, and embedded in your service. Choose Kafka Streams for Kafka-in, Kafka-out microservice logic, and Flink for large, complex, multi-source stateful jobs.

Kafka Connect is a distributed framework for source connectors (databases via Debezium CDC, files, SaaS APIs) and sink connectors (S3, Elasticsearch, Snowflake, JDBC). Workers share tasks, store their config, offsets and status in Kafka topics, and support single message transforms and DLQs. It replaces mountains of bespoke ETL code with configuration (Data Pipelines and Analytics).

Schema evolution. A schema registry stores versioned Avro, Protobuf or JSON schemas per subject (usually per topic). Producers embed a small schema ID in each record. Consumers fetch the schema to deserialise. Compatibility modes enforce safe evolution:

  • backward: new consumers can read old data, for example by adding fields with defaults;
  • forward: old consumers can read new data;
  • full: both.

This prevents the classic outage where one producer's field rename breaks ten consumers.

How Kafka compares architecturally.

  • Pulsar separates stateless brokers from storage in Apache BookKeeper (ledgers spread across bookies). That makes broker scaling instant, and supports millions of topics and built-in geo-replication, at the price of more components.
  • Kinesis offers shards with fixed per-shard limits, managed entirely by AWS.
  • Redpanda reimplements the Kafka protocol in C++ with per-partition Raft and a thread-per-core design, aiming for lower tail latency.
  • Object-storage-native Kafka-compatible systems write segments straight to S3, eliminating cross-AZ replication traffic and its cost, but add produce latency (often hundreds of ms).

Kafka's core strengths remain the de facto protocol and ecosystem, the mature tooling, and predictable high throughput.

Key Takeaways#

  • Kafka is a replicated, partitioned, append-only log. Producers append, consumers pull by offset, and records are retained by time, size or compaction, not deleted on read, so many groups can read and replay independently.
  • Partitions are the unit of order, parallelism and scale. Order holds only within a partition, and consumer parallelism per group is capped at the partition count. The key decides partition placement, so choose it for ordering scope and even load.
  • Durability: RF=3, min.insync.replicas=2, acks=all, idempotent producer, unclean leader election off, and replicas spread across AZs.
  • Consumers commit offsets after durable processing (at-least-once), with idempotent handlers. Transactions give exactly-once within Kafka. External effects need idempotence or offsets stored with the results.
  • It's fast because of sequential I/O, the OS page cache, zero-copy sendfile, batching, batch compression, and no per-message broker state. Plan on hundreds of MB/s (about 1 million small messages per second) per broker, with messages under 1 MB.
  • KRaft replaced ZooKeeper (production-ready in 3.3, ZooKeeper removed in 4.0), giving faster controller failover and higher partition limits.
  • Hot partitions: drop the key, salt, use compound keys, detect heavy hitters, apply back pressure. Size partitions as max(throughput ÷ producer rate, throughput ÷ consumer rate), with growth headroom.
  • Kafka isn't a database, a blob store, an RPC layer or a delayed-job queue. Pair it with object storage, materialised views, and queues or workflow engines where those fit better.