DEV Community

NullPointer
NullPointer

Posted on Originally published at thelp.me

Apache Kafka Architecture in 5 Minutes: The Core Concepts

Unlike traditional message queues (like RabbitMQ) that delete records immediately after acknowledgment, Apache Kafka is an append-only distributed commit log. Messages are strictly ordered, immutable, and persisted to disk for a configurable retention window. This allows multiple decoupled consumer groups to read and replay data at their own pace.

If you are designing distributed systems or preparing for technical interviews, here is a quick, architectural breakdown of how Kafka works under the hood.


1. High-Level Architecture: Servers & Clients

Kafka separates compute and storage into two operational tiers communicating over an optimized binary TCP network protocol:

  • Storage Tier (Brokers & Connect): Kafka brokers persist partition commit logs directly to disk, manage replication across failure zones, and serve client requests. Kafka Connect clusters stream records between Kafka and external databases, object storage, and search indices without custom code.
  • Client Tier (Producers, Consumers & Streams): Microservices running outside the cluster. Producers publish records, consumers read partitions in coordinated groups, and Kafka Streams handles real-time stateful transformations.
[Producers] ────(Publish)───► [ Kafka Brokers (Storage) ] ◄───(Connectors)─── [External DBs]
                                      │
[Consumers] ◄───(Fetch)───────────────┘
Enter fullscreen mode Exit fullscreen mode

2. Topics, Partitions & Leadership

  • Topics & Partitions: A Topic is a logical feed name (e.g., orders). To scale horizontally, each topic is split into Partitions distributed across cluster brokers.
  • Offsets: Within a partition, each record receives a sequential 64-bit ID called an offset. Offsets are strictly partition-local (Partition 0's offset 100 has no connection to Partition 1's offset 100).
  • Leader vs. Followers: Every partition runs a single active Leader (which handles all client write traffic) and multiple Followers (In-Sync Replicas or ISR).
  • Pull-Based Replication: Follower brokers behave like consumers, continuously fetching byte batches from the leader. Once all qualifying ISR replicas acknowledge a batch, the leader advances the High Watermark (HW). Consumers can only read up to the High Watermark, guaranteeing zero dirty reads during unexpected leader failovers.

3. Why Kafka Is Blazingly Fast

Despite writing everything to disk, Kafka sustains millions of events per second with sub-millisecond latencies. Two OS-level optimizations make this possible:

  1. OS Page Cache: Kafka relies directly on kernel RAM instead of caching messages in JVM heap memory. Active consumers reading recent events are served straight from the OS page cache without touching physical disks or triggering JVM garbage collection pauses.
  2. Zero-Copy Transfers (sendfile): When streaming to network sockets, Kafka uses Linux sendfile system calls. This routes data directly from the OS page cache to the Network Interface Card (NIC), bypassing user-space memory copies entirely.
Traditional: Disk ──► OS Cache ──► JVM Heap ──► Socket Buffer ──► NIC Buffer (4 copies)
Zero-Copy:   Disk ──► OS Cache ────────────────────────────────► NIC Buffer (Direct DMA)
Enter fullscreen mode Exit fullscreen mode

4. How Producers Route Messages

A common misconception is that brokers route messages. In reality, partition routing decisions happen entirely on the client side:

  1. Bootstrap Discovery: The producer connects to any seed host in bootstrap.servers and issues a MetadataRequest to fetch the cluster topology. It then opens direct point-to-point TCP sockets to partition leaders (bootstrap brokers are never proxies).
  2. Partition Selection:
    • Explicit Partition: If specified, routes directly to that partition ID.
    • Message Key Present: Evaluates abs(MurmurHash2(key)) % total_partitions, guaranteeing that all messages with the same key (e.g., customerId) land on the exact same partition in strict chronological order.
    • No Key: Uses the Sticky Partitioner to fill batches per partition before rotating, maximizing compression ratios and reducing network round-trips.
  3. Buffering (RecordAccumulator): Records are staged in an in-memory buffer per partition and flushed in batches according to batch.size and linger.ms.

5. Consumer Progress & Offsets

Kafka brokers do not maintain per-message ACKs. Instead, consumers track their own progress:

  • Consumers maintain an internal Fetch Position in memory and periodically save their Committed Offset.
  • Checkpoints are written to an internal, compacted topic: __consumer_offsets.
  • If a worker crashes or a consumer group rebalances, the re-assigned worker fetches this checkpoint and resumes exactly where the previous instance stopped.
  • In production systems, disable enable.auto.commit and commit offsets manually (commitSync or commitAsync) only after downstream database writes or business transactions succeed.

6. Multi-Cluster Topologies (WAN)

Synchronous ISR replication works across local Availability Zones (<2ms latency), but spanning clusters over WAN (50–150ms) causes severe write latency and ISR flapping. Multi-region deployments use asynchronous replication via MirrorMaker 2 (MM2) or Cluster Linking:

  • Active-Passive: One region handles all reads and writes; the standby region is mirrored asynchronously for disaster recovery.
  • Active-Active: Both regions accept local traffic with prefixed topics (e.g., us.orders and eu.orders) to prevent infinite replication loops.

📖 Read the Full Deep-Dive

This post is a quick architecture reference. For detailed diagrams, KRaft consensus mechanics, and storage internals, check out the complete guide on thelp.me:

👉 Read the full deep-dive on thelp.me

Explore more hands-on developer tools and architecture guides at thelp.me.


Find More details on · thelp.me

Top comments (0)