Kafka Ordering, Durability, and Exactly-Once Processing
System DesignModel answerLast updated
Describe how Kafka's partitioned, replicated log and consumer groups shape ordering, scale, and resilience, and how to get effectively-once results from a pipeline.
You are reviewing the messaging layer of a platform in which a stream of order events flows through Apache Kafka into a downstream service that updates account balances.
Answer the following in a structured way:
- Describe how topics, partitions, replicas, and consumer groups work in Kafka.
- Explain how these mechanisms influence message ordering, horizontal scalability, and fault tolerance.
- Contrast at-most-once, at-least-once, and exactly-once delivery. State what failure each one tolerates and what it costs.
- Lay out how you would build a pipeline that produces exactly-once effects end to end, including the part that writes to an external system outside Kafka.
State your assumptions (replication factor, partition count, key choice) and point out where the guarantees stop.
Hints
Hint 1
Start from the smallest unit: a partition is an ordered log with offsets. Ask what that implies for ordering, and for how many consumers in one group can be busy at once.
Hint 2
For fault tolerance, think about leader and followers, the in-sync replica set, and how the producer ack level combined with a minimum in-sync replica count decides whether an acknowledged write can be lost.
Hint 3
Delivery semantics depend on the order of 'do the work' and 'record progress'. Kafka transactions cover work that stays inside Kafka; for an external database you need the write to be safe to repeat, or to commit the offset in the same atomic step as the data.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Framing
This is a conceptual question. A strong answer builds a clean model (log, partition, replica, offset), ties each piece to ordering, scale, and failure behavior, and is honest that "exactly-once" has boundaries. I'll use the running example of order events keyed by account ID and consumed by a balance service.
Core model
- A topic is divided into partitions. Each partition is an append-only log, and each record has a monotonically increasing offset within that partition.
- The producer picks the partition. With a key, the default partitioner hashes it (murmur2) modulo the partition count, so one key always maps to one partition. Without a key, records are spread in batches across partitions.
Ordering. Order is guaranteed only inside a single partition. There is no global order across a topic. Keying by account ID gives per-account ordering, which is what a balance service needs. Total order would require a single partition and would cap throughput.
Scalability. Partitions are the unit of parallelism: they distribute storage and I/O across brokers, and within a consumer group each partition is read by exactly one member. Twelve partitions means at most twelve useful consumers per group. Choose the partition count for peak consumer parallelism with headroom. Increasing it later changes the key-to-partition mapping and breaks per-key ordering across the change.
Hot keys. One very busy account overloads a single partition. Options: a finer-grained key, or salting the key if per-key order can be relaxed or restored downstream.
Replication and fault tolerance
- Each partition has a replication factor (commonly 3): one leader serving reads and writes and followers that replicate from it.
- The ISR is the set of replicas that are caught up. The high watermark is the offset replicated to all ISR members. Consumers read only up to it, so they never see data that could vanish on failover.
- If a leader dies, the controller elects a new one from the ISR.
- Durability settings that matter:
acks=allwithmin.insync.replicas=2and RF=3: a write is acknowledged only once two replicas hold it. One broker can fail with no loss and writes continue. If the ISR drops below 2, writes are rejected rather than silently weakened.unclean.leader.election.enable=false: never promote an out-of-sync replica. This favors durability over availability.acks=1risks loss if the leader fails before followers copy the record.acks=0is fire-and-forget.
- Place replicas across racks or zones (
broker.rack) so a zone failure does not take out all copies.
Consumer groups
- Members of a group split the partitions; each partition belongs to one member. Separate groups each receive the full stream.
- Progress is stored as committed offsets in the internal
__consumer_offsetstopic. After a restart or rebalance, the new owner resumes from the last committed offset. - Rebalances occur when members join, leave, or miss heartbeats or
max.poll.interval.ms. To limit disruption, use the cooperative-sticky assignor and static membership (group.instance.id). - Because resumption follows the committed offset, the order of processing versus committing defines delivery semantics.
Delivery semantics
| Semantics | Pattern | Failure outcome | Cost |
|---|---|---|---|
| At-most-once | Commit, then process | Crash after commit loses records | Possible data loss; cheapest |
| At-least-once | Process, then commit | Crash before commit replays records | Duplicates must be tolerated |
| Exactly-once | Atomic output and offset, or repeat-safe effects | Each record's effect applied once | Extra latency and complexity |
On the producer side, a retry after a lost ack can duplicate a record, and with several in-flight requests a retry can also reorder records.
Default recommendation: at-least-once plus idempotent processing. Use at-most-once only for loss-tolerant data such as metrics.
Exactly-once inside Kafka
Two building blocks:
- Idempotent producer (
enable.idempotence=true, default in recent versions). The broker tracks a producer ID and per-partition sequence numbers, discarding duplicates and rejecting gaps. This removes retry duplicates and preserves order with up to 5 in-flight requests. Scope: one producer session, per partition. - Transactions (
transactional.id). A producer writes to several partitions and commits the consumer's offsets in the same atomic transaction. Consumers usingisolation.level=read_committedsee only committed records. The transactional ID carries an epoch, so a restarted instance fences out a stalled "zombie" predecessor.
Together they give exactly-once for consume, transform, produce loops that stay within Kafka. Kafka Streams enables this with processing.guarantee=exactly_once_v2.
consumer = Consumer({"group.id": "balances", "enable.auto.commit": False,
"isolation.level": "read_committed", ...})
producer = Producer({"transactional.id": "balances-svc-0",
"enable.idempotence": True, "acks": "all", ...})
producer.init_transactions()
consumer.subscribe(["orders"])
while True:
msgs = consumer.consume(500, 1.0)
if not msgs:
continue
producer.begin_transaction()
try:
for m in msgs:
producer.produce("balances", key=m.key(), value=apply(m.value()))
producer.send_offsets_to_transaction(
consumer.position(consumer.assignment()),
consumer.consumer_group_metadata())
producer.commit_transaction()
except KafkaException:
producer.abort_transaction()
# rewind consumer to committed offsets; shut down on fatal/fenced errors
End to end, including an external sink
Kafka transactions cannot span an external database. Two reliable patterns:
- Idempotent sink (most common). Run at-least-once and make the write safe to repeat:
- Give every event a stable unique ID (or use topic, partition, offset).
- Use an upsert or a unique constraint, e.g.
INSERT ... ON CONFLICT DO NOTHING, or a version check such as "apply only if event_version > stored_version". - Replays then change nothing.
- Offsets stored with the data. Write the business change and the consumed offset in the same database transaction, and on startup
seekto the stored offset. This gives atomicity without relying on Kafka commits.
For the opposite direction (a database change that must become an event), use the transactional outbox: write the event to an outbox table in the same transaction as the state change, and have a relay or CDC publish it to Kafka, with consumers deduplicating.
Trade-offs and common mistakes
- Transactions add latency (commit markers,
read_committedwaits on open transactions); size batches accordingly. - Claiming Kafka gives end-to-end exactly-once. It does not once an external side effect (email, payment API, database) is involved.
- Committing offsets before processing, then calling it at-least-once.
- Forgetting that adding partitions changes key placement.
- Setting
acks=allbut leavingmin.insync.replicas=1, which gives no real durability benefit. - Ignoring zombie instances and rebalances, which cause duplicate processing without fencing or idempotent writes.
- Long processing between polls exceeding
max.poll.interval.ms, triggering needless rebalances.
Summary: partitions give ordering per key and parallelism; replication with acks=all and a minimum ISR gives durability; consumer groups give scale-out; and effectively-once results come from at-least-once delivery combined with idempotent or atomically committed effects at the sink.