Kafka Architecture
On this page
Kafka stores events as replayable partitioned logs. Understanding it can begin with two independent questions: where records are stored, and where readers have read to. The former is handled by the broker's log and replication mechanisms, while the latter is handled by the consumer's position and consumer groups.
This article uses the standard topics, replicated logs, and consumer groups from the Kafka 4.1 documentation as a baseline. Specific client default values and cluster features should be confirmed according to the deployment version; share groups do not belong to the partition-exclusive consumption model discussed here.
Why Logs Suit Multiple Independent Readers
Suppose an order service generates three events in sequence: Create, Pay, and Ship. The inventory service focuses on inventory, the statistics service focuses on transaction volume, and the audit service needs to retain the complete history. These three services may operate at different speeds and may restart independently.
If events were deleted once "a reader has read them," other readers would be unable to progress independently. The log model separates retention policies from consumption progress: events continue to remain in the log, and each reader maintains its own position. When a consumer recovers, it moves its cursor without requiring the producer to re-send the entire history.
An offset is a position identifier within a partition, not a global message ID, nor does it equal the "number of remaining messages." Factors such as log compaction and transaction control records can cause the offsets of visible business records to be discontinuous.
Division of Labor: Topic, Partition, Replica
| Concept | Responsibility | Boundary Not to Confuse |
|---|---|---|
| Topic | Names the event stream and configures policies like retention | A single topic can have multiple independently ordered partitions |
| Partition | The basic unit for appending and ordering | There is no natural total order between partitions |
| Replica | Stores a copy of a partition | Adding replicas primarily increases redundancy, not write sharding |
| Broker | Hosts multiple partition replicas and serves requests | A single broker usually acts as leader/follower for different partitions simultaneously |
| Controller | Manages cluster metadata and leadership changes | Metadata consensus in the control plane does not mean every business record is written to the controller log |
The number of partitions determines into how many write and consumption units data can be distributed; the number of replicas determines how many copies of the same data are stored. Both consume resources but solve different problems. The KRaft control plane is responsible for metadata management, while data partitions still have their own replication paths. See Kafka KRaft.
Write Path for a Record
Client batching can dilute network and protocol overhead, but waiting for batching also increases latency. Compression usually applies to batches; more partitions might split traffic into smaller batches. Therefore, "more partitions means faster" is not necessarily true; one must also consider hotspots, batch size, file handles, replication connections, and recovery costs.
For streams requiring ordered processing of the same business entity, order_id is often used as the key. Guarantees depend on the partitioner, key serialization, and consistent partition counts. After expanding partitions and changing the mapping, new and old records with the same key may land in different partitions, requiring separate consideration for order during migration.
How records without keys are assigned is determined by the client implementation and cannot be uniformly written as per-record round-robin; the Java client's batching and partitioning strategies should be checked in Producer Configs. Even with the same key, it only determines the partition for ordering: the business precedence between multiple independent producers needs to be established by the application itself.
Replication, ISR, and Acknowledgement Conditions
The leader accepts writes, and followers continuously pull. The ISR (In-Sync Replicas) is the set of replicas considered to be keeping up, including the leader; whether a replica stays in the set depends on its replication progress and related configurations.
| Configuration | When the Producer Receives Success | Cost to Understand |
|---|---|---|
acks=0 | Does not wait for broker acknowledgement | Send success does not prove the broker received it |
acks=1 | After the leader accepts the write | Data not yet replicated when the leader fails may be lost |
acks=all | Meets current ISR replication acknowledgement requirements | Acknowledgement wait is coupled with replica availability |
min.insync.replicas works with acks=all to set the minimum ISR condition for accepting writes. It does not mean "configured to 2, so it only waits for any two replicas." For example, with a replication factor of 3 and min.insync.replicas of 2: when the ISR is reduced to one replica, the system would rather reject such writes than disguise single-replica success as sufficient redundancy. See Kafka Replication for detailed semantics.
Also distinguish between "replicated to multiple nodes" and "each message has been fsynced to every disk." Acknowledgement strategies cannot be interpreted in isolation as absolute durability without considering log flushing, failure domains, power supply, and recovery policies. Recovery policies that allow lagging replicas to become leaders may also trade off lost acknowledged records for availability.
Three Positions: End, Replication Commit, and Transaction Visibility
Kafka's read and write positions are not the same number. The following uses "the position of the next record" as the boundary and makes conceptual simplifications:
- LEO (Log End Offset): The next position at the end of a replica's log. It may differ across replicas.
- HW (High Watermark): The replication commit boundary; normal reads cannot cross it to read uncommitted replication tail data.
- LSO (Last Stable Offset): The transaction stable boundary;
read_committedreads are also restricted by it, and aborted transactions are skipped.
This distinction explains a phenomenon: the disk log has grown, but the consumer temporarily cannot see records further back. The reason could be replication progress or unfinished transactions ahead. Simply looking at "whether this message exists in the file" cannot determine if it should be visible to the consumer.
Same HW, Why Different Records Read at Different Isolation Levels
Continuing with the positions in the figure: 10 and 11 are normal records, transaction T starts at 12, and 13 is another normal record. HW=14 indicates these positions have entered the replication commit range, but T is still unfinished. read_uncommitted can return 10, 11, 12, 13; read_committed can only return 10, 11. Although 13 does not belong to T, it cannot cross the preceding transaction stable boundary.
Below, we simulate visibility filtering using boundaries as inputs. Transaction status committed or aborted indicates that the completion marker has also reached stable conditions, not just that the producer has issued a commit request. The model omits broker replication and transaction coordination processes.
=
# transactions: Transaction ID -> (first offset, stable status)
=
=
=
return
assert ==
assert ==
assert ==
assert ==
assert ==
assert ==
The last two completion scenarios assume that offset 14 holds the transaction completion marker and HW has reached 15; the marker is not placed into the model as a business record. When T is aborted, 12 is filtered, and 13 becomes visible again, resulting in holes in the read results. These holes do not indicate that the consumer missed a record that needs processing.
Here, LSO uniformly adopts an exclusive upper bound: read records with offsets less than LSO; unfinished transactions start at 12, so the boundary is 12. endOffsets() under read_committed returns min(HW, earliest unfinished transaction start), see KafkaConsumer Transaction Reads and End Offset Definitions. It also explains why having zero lag relative to LSO alone does not prove that there is no backlog behind the replication log end blocked by transactions.
Records Already Replicated, Why Still Unread?
"Requesting to commit a transaction" and "the commit marker is already stable" must also be distinguished. Below, we compare three independent histories; the completion history has a marker at offset 14, but the transaction is only considered stably completed once HW reaches 15. All visibility boundaries are exclusive upper bounds; holes after abortion come from filtering and should not cause consumers to wait for an offset 12 that will never be delivered.
read_committed is restricted by the exclusive LSO. Unfinished transactions block subsequent normal records; after abortion, transaction records are filtered, and subsequent normal records can become visible.
Consumption Position and Committed Position
A single poll() returns several records, and the client's read position advances accordingly, but business processing may not be complete. The committed offset is the progress promise at fault recovery; the two should be separated.
In a standard consumer group, a partition is assigned to a single member at any given moment, while different groups can independently read the same partition. The client reads by offset, which does not automatically guarantee that asynchronous worker threads complete in the same order. See Consumer Groups and Collaboration for takeover processes and concurrent commit rules.
Retention and Log Compaction
Two cleanup methods correspond to two data usage patterns:
| Method | Focuses On | Suitable For Expressing |
|---|---|---|
| Deleting old log segments by time or size | How long history is preserved | Time-bound event replay |
| Compacting old versions by key | The latest state for each key | Rebuilding state from a changelog |
Compaction happens in the background; it does not guarantee that each key appears only once upon read, nor does it reorder or re-number remaining records. Deletion status is usually expressed using tombstones; after the corresponding retention period expires, even tombstones may be cleaned up. Readers that are too far behind may be unable to reconstruct the correct deletion history from the remaining log. Log Compaction details these guarantees.
Therefore, whether replay is possible depends on retention boundaries, and whether state can be rebuilt depends on compaction keys and deletion semantics. Event auditing and latest state synchronization cannot be treated as the same requirement simply because "they both exist in Kafka."
After Deletion Markers Disappear, Empty DB Reconstruction and Old Snapshot Continuation Are Not Equivalent
Suppose the log sequence is 0:A=1, 1:B=7, 2:A=2, 3:B=null. The last one deletes B. Below, we simulate the result of "all old versions have been cleaned," deliberately not simulating the actual asynchronous scheduling of the cleaner:
=
=
=
return
=
=
return
=
=
assert ==
assert == # offset remains 2
assert == ==
=
assert ==
assert ==
B in the old snapshot will not be automatically deleted just because "there is no B" in the log. The consumer cannot distinguish between "B was never changed" and "B was deleted, but the deletion evidence has expired." Therefore, the recovery protocol must agree on the offset corresponding to the snapshot, the available range of incremental logs, and the deletion retention range together; checking only whether it can connect to the broker is insufficient.
Here, empty DB reconstruction yields the correct result because the input is a fixed, complete post-compaction set. During real reconstruction, the cleaner is still running: if a reader reads the old value of B first but fails to read the tombstone that was subsequently cleaned up, it may similarly retain an incorrect state. Therefore, starting from an empty DB also requires satisfying read progress and deletion retention conditions; one cannot treat model equations as guarantees for infinite-time recovery. See Log Compaction Guarantees for relevant conditions.
Architecture Deduction: How Order Streams Divide Labor
A reasonable split is to partition by order ID, ensuring partition-internal order for events of the same order; the inventory group and statistics group commit their progress independently; audit requirements determine the history retention period; replication and acknowledgement strategies determine write promises during failures.
If a large customer generates half the traffic, its key may form a hotspot. Adding consumers cannot automatically split an exclusive partition. Using a finer-grained key can improve parallelism, but the business scope requiring order preservation must be redefined. Performance trade-offs therefore come from business relationships, not just tuning up configurations.
References
- Kafka 4.1: Design
- Kafka 4.1: Producer Configs
- Kafka 4.1: KRaft
- Message Semantics: Retries, Idempotency, and Transaction Boundaries
Keywords: Kafka, partition, replica, ISR, acks, offset, HW, LSO, retention, log compaction