Core Concepts
Kafka
Follow an order event through Kafka's partitioned log, consumer replay, and replication.
Kafka stores events in logs that can be read again. A producer appends an event such as OrderPaid. Fulfillment and audit can read that same event independently, each at its own pace.
Reading a Kafka record leaves it in the log. Each application can save where it stopped and pick up from there while the records are still retained. That makes Kafka useful when more than one service needs the same history or when a service needs to replay it.
Append an event and find it again
A topic names a stream of records. A Kafka server is called a broker. Brokers store a topic as one or more partitions, each an ordered log that new records are appended to. Different partitions can accept writes and serve reads in parallel.
The payments service sends a record to orders.events. The key tells Kafka's producer where to route it. The value says what happened and carries a stable event ID that downstream services can use during retries.
Producer record (decoded example)
{
"topic": "orders.events",
"key": "order-622",
"value": {
"eventId": "evt-622-paid",
"type": "OrderPaid",
"orderId": "order-622"
}
}The producer routes the record to partition 1. Kafka appends it and assigns an offset, a numeric position within that partition.
Successful send result (illustrative metadata)
topic: orders.events
partition: 1
offset: 42The offset belongs to a topic and partition. Partition 0 can have its own offset 42. The application assigned evt-622-paid to identify the payment event even if the application sends it again and Kafka assigns the new copy a different offset.
The figure follows the record into partition 1 and shows how fulfillment and audit can keep separate read positions over the same log.
With time or size retention, Kafka removes old log segments even if a consumer has yet to read their records. Replay reaches as far back as the topic still holds data. Log compaction can clean up older values for a key while keeping its latest value. It fits a topic that rebuilds the latest state per order. For orders.events, keep the full history over the required replay window if consumers need both OrderCreated and OrderPaid. Kafka design and compaction
Choose what must stay in order
The earlier OrderCreated also uses order-622 as its key. With the Java producer's built-in routing, a keyed record usually goes to the partition selected by a hash of its serialized key. Keep the key bytes, routing rule, and partition count stable and the two records go to the same log.
Excerpt from orders.events, partition 1
offset key event
41 order-622 OrderCreated
42 order-622 OrderPaidKafka orders records by append position inside a partition. If the producer sends events in the wrong business order, or a consumer dispatches each event concurrently and the later one finishes first, the application can still apply changes out of order. For a handler that needs creation before payment, process those effects in sequence.
A hot key concentrates all of its writes and ordered work on one partition. Adding partitions gives other keys more room but cannot spread that key across different partitions while preserving its single log order. Changing the partition count can also send new records for an existing key to a different partition while its older records stay where they were. Plan from the expected traffic per partition and account for skew and ordering during a capacity change. Kafka producer partitioning
Share the work and recover from a crash
A consumer group is a set of workers that use the same group ID and save progress together. When those workers subscribe to the same topic, Kafka assigns each partition to at most one worker in the group at a time. Three partitions can keep up to three workers busy on this topic. The audit group has its own workers and read positions, so it can still read 41 even when fulfillment has reached 42.
The read position and the saved position can differ
Worker A in fulfillment reads OrderPaid at offset 42. The worker's local reading position can advance to 43 immediately. The group's committed offset, the saved position that a replacement can use, still points at 42 until the handler finishes and saves its progress.
State after worker A fetches offset 42
group: fulfillment
partition: orders.events / 1
worker's next position: 43
group's committed next offset: 42Suppose worker A creates a fulfillment job in the database and crashes before committing offset 43. When a worker joins, leaves, or times out, Kafka redistributes partitions. That reassignment is a rebalance. Once worker B gets partition 1, it resumes from the committed offset and receives the same event again.
Record delivered after reassignment (decoded excerpt)
partition: orders.events / 1
offset: 42
key: order-622
value.eventId: evt-622-paid
value.type: OrderPaidThe handler can make this replay safe by inserting evt-622-paid into a processed-events table with a unique key and creating the job in the same database transaction. Worker B finds that the event already has a processed marker, so it commits 43 without creating a second job. That is idempotency at the job-creation boundary.
State after the replay succeeds
fulfillment jobs for evt-622-paid: 1
fulfillment / orders.events / 1 committed next offset: 43Saving progress after the effect gives at-least-once processing when retained records can be retried. Saving progress before the effect can skip work if the worker crashes between those steps. Disable automatic commits for this example and advance progress only past finished work. A worker that loses a partition should stop work on it, and its handler must tolerate any work already in flight. Kafka consumer positions and groups
Decide how many copies a write needs
A partition can have several copies on different brokers. One copy is the leader, which receives writes. Follower replicas copy its log. The in-sync replica set (ISR) contains the leader and followers that Kafka considers caught up enough. A topic's replication factor counts all configured copies, including followers that are currently behind.
Compare attempts to write the same record at offset 42. Partition 1 has three copies. Broker B1 is the leader, B2 is in sync, and B3 is behind. For the stronger acknowledgment use the following settings.
topic replication factor: 3
topic min.insync.replicas: 2
producer acks: all
current ISR: B1, B2- With
acks=1, B1 can report a successful send as soon as it appends 42. If B1 fails before B2 copies it and B2 takes over, the acknowledged record is missing from the new leader. This comparison uses leader-only acknowledgment without producer idempotence. - With
acks=all, both B1 and B2 must have the record before the producer gets success. If B1 then fails, B2 can become leader with 42 already in its log. If B3 is also in the ISR at write time, Kafka waits for all three. If the ISR has only B1, the minimum of two prevents the send from succeeding.
An acks=1 success confirms the leader's append. Replication limits reads to offsets below the partition's high watermark, the next offset after the records Kafka has made available through replication. With B1 and B2 still in sync, B2 must copy 42 before the high watermark can pass it. The minimum is a floor for accepting acks=all writes, and the producer waits for the current ISR. This trades write availability and latency for a smaller loss window. Kafka topic settings
Spread replicas across independent failure domains, and avoid unclean leader election, which can promote a lagging copy. Kafka 4.0 introduced Eligible Leader Replicas as an optional feature to extend safe failover below the ISR floor. It is enabled by default on new clusters starting in 4.1. The examples here compare failovers to a replica already in the ISR. Eligible Leader Replicas
Deduplicate retries from the producer
If the broker appends 42 but the reply gets lost, the producer may retry the same send. Kafka's idempotent producer attaches a producer ID and sequence numbers so the broker can recognize the retry and keep one log record for that send. The Apache Kafka Java producer enables it by default from Kafka 3.0 when the other settings are compatible. It requires acks=all, retries enabled, and at most five requests in flight per connection. Kafka 3.0 producer defaults
A new application send of evt-622-paid gets a new sequence and can append another record. The producer's retry guarantee applies within a producer session. Keep the stable event ID and apply the business deduplication rule where the effect happens. Kafka producer API · Producer configuration
Commit a Kafka output and its input position together
Now give the fulfillment worker a different job. Instead of writing directly to a database, it reads offset 42 and publishes a command that another service will handle. If it publishes the command and crashes before saving offset 43, a replacement can publish the command again from the same input.
Output record (decoded example)
{
"topic": "fulfillment.commands",
"key": "order-622",
"value": {
"type": "StartFulfillment",
"orderId": "order-622",
"sourceEventId": "evt-622-paid"
}
}A Kafka transaction can commit the output and the input position together. The worker stages StartFulfillment and adds the group's next input offset, 43, to that same transaction.
In the Java client, give the producer a transactional.id and call initTransactions before starting work. Call beginTransaction before sending the command, then sendOffsetsToTransaction with offset 43 for partition 1 and the consumer's current group metadata. Disable the input consumer's automatic commits with enable.auto.commit=false and save its offsets only through commitTransaction. A downstream consumer using read_committed sees transactional records only after commit and skips aborted records. KafkaProducer transactions
Outcome for this event after abort versus commit
transaction group next offset read_committed output
aborted 42 none
committed 43 StartFulfillmentAfter an abort, a replacement can read 42 again. After commit, the command is visible to the downstream group, and fulfillment's saved position is 43.
This is the exactly-once effect of a Kafka-to-Kafka consume, transform, and produce operation. A consumer using read_uncommitted can see even aborted records. A long open transaction can also hold back later records in its output partition for read_committed consumers until the transaction finishes. If the downstream handler calls an external warehouse API, the warehouse still needs its own idempotency key or another mechanism to prevent the same shipment from starting twice. Kafka transactions · Consumer isolation levels
How to use in a system design
Use Kafka for order events when fulfillment and audit need the same history independently, or they need to rebuild from retained records. Key by order ID and give each application its own group. Use a transactional outbox if the payment is saved in a database and the event must represent a committed payment. The payment handler can return after the database commit if a relay will publish its outbox event as a separate step.
Use direct RPC when checkout needs an immediate answer from another service. A work queue is a simpler starting point if one worker pool just needs to run independent jobs with retries. Keep searchable order state in a database. The Kafka log carries the transitions that other services need to act on or replay.
In an interview, name the event and the ordering key, then estimate the throughput of one partition and check for a hot key. Choose how long the topic must keep events so a stopped consumer can catch up. Explain what can be lost after a successful write and what happens when too few replicas are available. For each group, state when it saves its position and how it will handle a repeat or a record it cannot process. If moving a failed record aside breaks the order of later effects for that order, decide whether to pause that work or let later events proceed.
See also
- Idempotency - keeps replayed consumer side effects from appearing twice.
- Data Replication - frames leaders, followers, quorums, lag, and failover.
- Flink - processes Kafka streams with event-time state and checkpoint recovery.
- Messaging and Work Queues - separates work sharing, fan-out, retention, and replay.
- Transactional Outbox - publishes database changes without a dual-write gap.
- Change Data Capture - turns database log changes into an event stream.
- Event-Driven Architecture - defines which service owns a business fact and where its subscribers recover.
Used in
- URL Shortener - sends click events to a durable stream so the redirect can finish before analytics processing.
- Batched Inference Service - separates admission from batch assembly and result processing.
- Collaborative Coding Interview Platform - dispatches code runs through per-language topics to isolated runner pools.
Done reading? Mark it so it sticks in your dashboard.