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.

One partitioned log, multiple independent consumption positions 100 Create 101 Pay 102 Ship 103 End Position Stats Group Inventory Group Audit Group Commit progress does not delete records; whether logs are retained is determined by cleanup policies.

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

ConceptResponsibilityBoundary Not to Confuse
TopicNames the event stream and configures policies like retentionA single topic can have multiple independently ordered partitions
PartitionThe basic unit for appending and orderingThere is no natural total order between partitions
ReplicaStores a copy of a partitionAdding replicas primarily increases redundancy, not write sharding
BrokerHosts multiple partition replicas and serves requestsA single broker usually acts as leader/follower for different partitions simultaneously
ControllerManages cluster metadata and leadership changesMetadata 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

Record Write: Partitioning, Batching, Replication, and Acknowledgement Serialize and Select Partition Key encoding and partitioning strategy determine the mapping 1 Batch by Partition Batch buffering dilutes network and compression costs 2 Send to Partition Leader Leader appends records, followers pull to replicate 3 Return Write Result Acknowledgement conditions are determined by acks and replica status 4 The meaning of an application receiving success must be interpreted in conjunction with replication and durability boundaries.

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.

ConfigurationWhen the Producer Receives SuccessCost to Understand
acks=0Does not wait for broker acknowledgementSend success does not prove the broker received it
acks=1After the leader accepts the writeData not yet replicated when the leader fails may be lost
acks=allMeets current ISR replication acknowledgement requirementsAcknowledgement 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:

Three Log Boundaries: LEO, HW, and LSO 10 11 12 13 14 15 LSO = 12 Transaction Stable Boundary HW = 14 Replication Commit Boundary LEO = 16 Next Append Position Stable Records With Unfinished Transactions Replication Tail The figure is a simplified example: read_committed also skips records from aborted transactions.
  • 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_committed reads 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.

records = [(10, None), (11, None), (12, "T"), (13, None)]

def visible(records, hw, transactions, committed_only):
    # transactions: Transaction ID -> (first offset, stable status)
    first_open = [first for first, status in transactions.values()
                  if status == "open"]
    lso = min([hw] + first_open)
    boundary = lso if committed_only else hw
    return [offset for offset, tx in records
            if offset < boundary
            and (not committed_only or tx is None
                 or transactions[tx][1] == "committed")]

assert visible(records, 14, {"T": (12, "open")}, False) == [10, 11, 12, 13]
assert visible(records, 14, {"T": (12, "open")}, True) == [10, 11]
assert visible(records, 15, {"T": (12, "committed")}, True) == [10, 11, 12, 13]
assert visible(records, 15, {"T": (12, "aborted")}, True) == [10, 11, 13]
assert visible(records, 11, {"T": (12, "open")}, True) == [10]
assert visible([], 0, {}, True) == []

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.

Preparing the visual
Records Already Replicated, Why Still Unread?

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.

Fetch Position and Processing Completion Position Differ 100 Completed 101 Completed 102 Incomplete 103 Incomplete Next Safely Committable Position: 102 Only when all preceding records are complete can the continuous commit watermark advance to the right.

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:

MethodFocuses OnSuitable For Expressing
Deleting old log segments by time or sizeHow long history is preservedTime-bound event replay
Compacting old versions by keyThe latest state for each keyRebuilding state from a changelog
Key Compaction: Retain Latest State, Offsets Not Re-numbered offset 0 A=1 offset 1 B=7 offset 2 A=2 Background cleanup of old versions Old values can be removed offset 1: B=7 offset 2: A=2 Cleanup is an asynchronous process; readers may still read multiple versions that have not yet been cleaned.

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:

log = [(0, "A", 1), (1, "B", 7), (2, "A", 2), (3, "B", None)]

def compact_snapshot(records, keep_tombstones):
    latest = {}
    for record in records:
        latest[record[1]] = record
    return sorted((record for record in latest.values()
                   if keep_tombstones or record[2] is not None),
                  key=lambda record: record[0])

def replay(initial, records):
    state = dict(initial)
    for _, key, value in records:
        if value is None:
            state.pop(key, None)
        else:
            state[key] = value
    return state

with_delete = compact_snapshot(log, True)
without_delete = compact_snapshot(log, False)
assert with_delete == [(2, "A", 2), (3, "B", None)]
assert without_delete == [(2, "A", 2)]  # offset remains 2
assert replay({}, log) == replay({}, without_delete) == {"A": 2}
stale_snapshot = {"A": 1, "B": 7}
assert replay(stale_snapshot, with_delete) == {"A": 2}
assert replay(stale_snapshot, without_delete) == {"A": 2, "B": 7}

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

Keywords: Kafka, partition, replica, ISR, acks, offset, HW, LSO, retention, log compaction