System Building and Log-Centric Architecture

Why Do So Many Data Systems Exist?

Redis, Elasticsearch, Cassandra, Hive, OLAP cubes — they look like separate databases with separate truths. They're not. They are different query-optimized views of the same underlying data. The truth lives in the log; each system is just an index on top of it. Building one system that does all of this well has never happened — cutting scope to one query type is what makes each system feasible at all. The price: running many specialized systems creates an operational and data-integration burden.

Three Futures for Distributed Infrastructure

Given that every specialized data system (Redis, Elasticsearch, Cassandra…) is really just a query-optimized view of the same underlying data, three things could happen next:

  1. Status quo — stay separate, glue with a log. Each specialized system keeps doing its one job. An external log (Kafka) carries data between them and keeps them in sync. This is the world Kafka was actually built for.
  2. Re-consolidation — one system to rule them all. A single uber-database absorbs storage, search, analytics, everything. Considered unlikely: it's extremely hard to build, and specialized systems win on performance precisely because they cut scope.
  3. Unbundling — build databases from off-the-shelf parts. Every distributed database has to solve the same handful of problems internally: pick a leader, store data safely, find rows fast, talk over the network, turn objects into bytes. Today each of those problems has its own ready-made open-source tool. So instead of writing all of it from scratch, you pick the parts you need and wire them together.

Option 3 is already happening. Here are the jobs a database does inside itself, and the standalone tool that now does each job:

Job inside a databaseIn plain wordsNow a standalone tool
Coordination (leader election, config)"Which node is the boss right now? What are the current settings?"Zookeeper, Helix, Curator
Resource management (scheduling)"Which machine should this process run on, with how much CPU and memory?"Mesos, YARN
Indexing (fast lookups)"Find all rows matching X without scanning everything."Lucene, LevelDB
Communication (network I/O)"Send and receive requests between machines efficiently."Netty, Jetty, Finagle
Serialization (data format)"Turn an object into bytes to store or send, and back again."Avro, Protobuf, Thrift
Backing log (durable event stream)"Write every change down safely, in order, so anyone can replay it."Kafka, Bookkeeper

Example 1: Real systems are already built this way

Elasticsearch did not write its own search engine or networking layer. Its indexing is Lucene and its node-to-node networking is Netty. What Elasticsearch adds is the distributed layer on top: sharding, replication, and a REST API. Kafka itself used ZooKeeper for coordination (controller election, cluster metadata) for most of its life, instead of writing its own consensus. It replaced ZooKeeper with its built-in KRaft only once the team was ready to own that part.

Example 2: Building "search my orders" for an online store

Say users need to search their past orders by product name, date or price. Without unbundling, you would write a storage engine, a search index, replication and failover yourself, which takes years. With unbundling, you assemble it from parts:

  1. Backing log: Kafka. The order service writes every OrderPlaced / OrderCancelled event to an orders topic. This is the source of truth.
  2. Serialization: Avro or Protobuf. Each event has a defined schema, so the producer and every consumer agree on what an order looks like, even as fields get added.
  3. Indexing: Lucene. A small indexer service reads the topic and adds each order to a Lucene index, so "blue shoes under $50" is a fast lookup.
  4. Coordination: ZooKeeper. You run 3 indexer nodes. ZooKeeper decides which node owns which slice of the data and picks a replacement when one dies.
  5. Communication: Netty. The query API that serves search requests is built on Netty, so you don't write socket handling yourself.

The only code you write is the glue: the indexer loop and the query handler. If a node's index gets corrupted, you delete it and replay the Kafka topic from offset 0 to rebuild it. That's the log-as-source-of-truth idea from earlier in this part, now acting as your recovery mechanism.

Stack these together and you compose exactly what you need. Building a distributed system goes from years to weeks — and the pressure to consolidate into a monolith disappears. Kafka's role in this picture is the backing log: the shared, replayable record that ties all the other parts together.

Queue vs. Log — The Fundamental Distinction

PropertyTraditional QueueLog
Read is destructiveYes — deleted after consumeNo — offset advances, message stays
Multiple consumersCompete for the same messagesEach group has independent offset
ReplayImpossibleRewind to any offset
RetentionUntil consumedTime/size window, or compaction

A queue gives you delivery. A log gives you delivery plus a replayable record of what happened. The two roles are not separable.

Log-Centric Architecture

Serving nodes are your own services, not Kafka brokers. Each one is a Kafka consumer that reads the topic (fetching from the partition leader, like any consumer), applies every event to a local store, and answers end-user queries from that store. End users never query Kafka directly. A log only answers "give me events from offset X," not "what is user 42's name?"

Writes go into the log, a Kafka topic, where each gets an offset. Three serving nodes subscribe to the log and each applies the writes in offset order, so they reach identical state without talking to each other. Clients query the serving nodes through the client query API.
Put the order in the log, and the serving nodes stop needing to agree

The log handles all the hard distributed systems problems:

ProblemHow the log solves it
ConsistencyEvery write gets an offset. All serving nodes apply writes in offset order — no divergence.
ReplicationNodes don't talk to each other. They all subscribe to the log and independently reach identical state.
DurabilityThe log only acks after committed to enough replicas. Serving nodes inherit this.
External subscribersAny system subscribes at its own pace — one tap for all changes.
RecoveryA crashed node replays the log from its last snapshot. No peer-to-peer copy.
RebalancingA new consumer takes over a partition and resumes from the last committed offset — not from where the old consumer actually was. If the old consumer processed up to offset 500 but only committed up to 490, the new consumer re-reads 490–500. This is why Kafka is at-least-once by default, not exactly-once.

The serving layer is just a cache with a query API. It has no write path of its own.

Log Compaction

Data TypeRetention StrategyReasoning
Event data (activity, metrics)Time or size windowIndividual events have no "superseding" update
Keyed data (DB-like updates)Log compactionEach key has a current value; old values are obsolete

Enabled per-topic via cleanup.policy:

cleanup.policyBehavior
delete (default)Time/size-based deletion — the "event stream" case
compactKeep only the latest value per key, forever — the "keyed/changelog" case
compact,deleteBoth: compact by key, and still expire the result by time/size

This is exactly the mechanism Kafka Streams relies on for changelog topics backing state stores: the changelog only ever needs the latest aggregate per key (user_42 → count=1042), so compaction keeps it bounded instead of growing forever — replaying it from scratch still reconstructs current state.

Building a Scalable Log — The Five Design Pillars

1. Partitioning

Topic payments is split into three partitions by hashing the user ID. Partition 0 lives on broker 1 and holds user IDs hashing to 0, partition 1 on broker 2 for IDs hashing to 1, and partition 2 on broker 3 for IDs hashing to 2. Each partition is its own append-only file, ordered within itself; there is no global order across partitions.
A topic is three independent files, and the key decides which one Need strict ordering across everything? Use a single partition — and give up the parallelism this picture exists to buy.

Each partition is its own append-only file. No global ordering across partitions — if you need strict ordering, use a single partition (at the cost of throughput).

2. Batching at Every Layer

LayerWhat's batchedBenefit
Producer → partition leaderMessages accumulate in buffer before sendingOne network call per batch
Leader → disk (followers do the same)OS page cache groups writes into sequential flushesSequential I/O — orders of magnitude faster
Leader → followers (other brokers)Followers fetch in bulkReplication keeps up
Partition leader → consumerConsumer fetches configurable chunkProcesses locally, not one per round-trip

"Leader" here means the broker that currently leads the partition being written or read — e.g. Broker A for payments-0 in the table above. Each row happens separately for every partition, so a producer writing to 10 partitions sends batches to up to 10 different leader brokers at once.

3. Sequential Disk I/O

A spinning HDD has two mechanical costs per random write: seek (~5–10ms) + rotational latency (~2–4ms). At ~10ms per write, a random-write workload caps at ~100 writes/sec. Sequential writes eliminate both costs — the head is already in position. Sequential throughput on the same HDD: 100–200 MB/sec — 3–4 orders of magnitude faster in operations per second.

4. OS Page Cache

Kafka writes directly to the OS page cache and lets the OS flush to disk in the background. Writes return in microseconds. A consumer reading recently-produced messages reads from page cache — no disk I/O at all.

5. Producer Batching Internals

The application thread, your for loop, calls send, which only drops the record into the RecordAccumulator: a 32 MB in-memory buffer holding one batch per partition. A batch ships when it reaches batch.size, 16 KB by default, or when linger.ms expires. The sender thread does the network I/O to the broker. When the 32 MB buffer is full, send blocks, slowing the application down.
send() only fills a buffer — a separate thread decides when bytes leave
ConfigDefaultMeaning
batch.size16 KBFlush when the batch reaches this size
linger.ms0 msFlush after waiting this long, even if batch isn't full

With linger.ms=0: flushes immediately — fine for latency, bad for throughput. With linger.ms=5: waits up to 5ms; under high traffic, batch.size fires first anyway. Backpressure: once the buffer is full, producer.send() blocks — your app slows down gracefully.

Consumer Groups

A consumer group is a set of consumers that collectively read from a topic, where each partition is assigned to exactly one consumer in the group at a time.

Topic orders has four partitions, P0 to P3. Group A has two consumers: A1 reads P0 and P1, A2 reads P2 and P3. Group B has one consumer, B1, which reads all four partitions. Both groups receive every message independently; within a group each partition goes to exactly one consumer.
Groups share nothing with each other; consumers inside a group split the partitions

Group A and Group B both receive all messages independently. Within each group, each message is processed by exactly one consumer. This is what makes consumer groups the primitive for scalable, load-balanced consumption.

Throughput Limits: Partitions, Brokers and Fan-Out

Two questions come up as soon as consumer groups are in the picture: if many groups read the same topic, do they share the broker's capacity? And what actually caps throughput — the partition, the broker, or something else?

What N consumer groups cost a broker

Each group reads every partition on its own, with its own offsets. So the leader of each partition sends every message out once per group. Example: a topic takes in 80 MB/s across 8 partitions (10 MB/s each), rf=3, with 10 consumer groups. The leader broker for one partition handles:

TrafficAmount
In from producers10 MB/s
Out to 2 followers (replication)20 MB/s
Out to 10 consumer groups100 MB/s

Writes are paid once; reads are paid once per group. Consumer fan-out is usually the largest outbound traffic on a broker.

What caps throughput: partition, broker, topic

One partition is capped by its leader broker. All writes to a partition go to its single leader, which appends to a single log. Adding machines cannot make one partition accept writes faster. In practice a partition handles roughly tens of MB/s of writes (a common planning number is ~10 MB/s) — well below a broker's total capacity, because a single log append plus replication has its own limit.

The resource that runs out first on the broker is usually not CPU or RAM:

ResourceRoleUsually the bottleneck?
Network cardProducer traffic in; replication + consumer traffic outMost often
DiskSequential writes; reads for lagging consumersSometimes — especially with lagging consumers
RAMPage cache that keeps recent data hot for readersIndirectly — too little RAM turns reads into disk reads
CPUCompression, TLS, checksumsOnly with heavy TLS or compression

A broker is not dedicated to one partition. It leads several partitions and follows others, and all of them share its NIC, disk and RAM. "One partition's ceiling" and "one broker's capacity" are different numbers — a broker might do 500 MB/s+ in total, spread over 20 partitions.

A topic is not capped by one broker. Leaders are spread across brokers, so 8 partitions can use 8 brokers' worth of capacity:

topic throughput ≈ number of partitions × per-partition throughput

The limit people hit first: consumers

Within one group, one partition is read by exactly one consumer. If your consumer processes 5 MB/s (DB writes, API calls), that partition is consumed at 5 MB/s no matter how fast the broker is. So partition count must cover both sides:

partitions = max( target ÷ per-partition write speed , target ÷ per-consumer processing speed )

Example: target 200 MB/s, a partition handles 20 MB/s of writes, a consumer processes 5 MB/s → max(10, 40) = 40 partitions. The consumer side decides the number, not the broker.

Scaling levers

ProblemLeverCatch
Group needs more parallelismAdd partitions (max active consumers per group = partition count; a 9th consumer on 8 partitions sits idle)Changes key → partition mapping, so per-key ordering breaks across the change
Brokers overloadedAdd brokers and reassign partitions (kafka-reassign-partitions or Cruise Control)New brokers start empty — nothing moves until you reassign
One noisy groupPer-client byte-rate quotasThat group gets throttled
Lagging readers hit diskTiered storage — old data served from object storage (S3)Higher latency for cold reads
Heavy batch / analytics readersMirror the topic to a separate cluster (MirrorMaker 2)Second cluster to run; replication lag
Read load on leaders / cross-AZ costFollower fetching (below)Slightly later visibility

Can consumers read from followers?

Yes, since Kafka 2.4 (KIP-392, "follower fetching"). By default every read goes to the leader. With rack awareness configured, a consumer reads from a replica in its own rack / availability zone:

# broker
broker.rack=us-east-1a
replica.selector.class=org.apache.kafka.common.replica.RackAwareReplicaSelector

# consumer
client.rack=us-east-1a
  • Main purpose: avoiding cross-AZ network charges in the cloud, often a big part of the bill. Spreading read load across all rf replicas is a side benefit — so read capacity for one partition can exceed one broker.
  • Catch: a follower only serves data up to the high watermark (messages every ISR member already has), so consumers on followers see new messages slightly later than consumers on the leader.
  • Writes always go to the leader. Only reads can be moved.

Multiple Systems, One Log

One log, a Kafka topic, feeds three subscribers that each build their own index from the same ordered feed: a search index in Elasticsearch, a key-value store in Cassandra, and an OLAP cube in Druid. Adding a new query system means adding one more subscriber, not a new pipeline.
Every query system is just another reader of the same feed

Each system reads the same ordered feed and builds whatever index it needs. Adding a new query system = adding one new subscriber. Not a new pipeline.

Read-Your-Write Consistency

A client that writes and then immediately reads can miss its own write, because serving nodes build their state asynchronously and each lags the log by a different amount. The fix: the client carries its write's offset into the read, and the serving node waits until it has applied at least that offset.

LayerWhoRoleLeader?
LogPartition leader brokerTakes producer writes, assigns offsets, serves consumer fetchesYes, elected by the controller
LogISR followersCopy the leader; used only for durability and failoverCandidates if the leader dies
ServingYour consumer services (e.g. profile-service, an Elasticsearch indexer)Consume from the leader, build a queryable view, answer end-user readsNo
  1. Write. The client produces {user:42, name:"Sam"}. The partition leader appends it at offset 1057 and returns that offset.
  2. Read with the offset. The client calls a serving node: GET /user/42?min_offset=1057.
  3. Wait if behind. Node B has applied only up to 1031. It holds the request (no reject, no redirect) until its consumer reaches 1057.
  4. Answer. Any node with applied_offset ≥ 1057 answers immediately, and the answer is guaranteed to include the write.

Storage Cost

Keeping the same data in Kafka and in every serving system looks like paying for storage twice. In practice it's cheap, for three reasons:

ReasonWhy it keeps cost down
Kafka runs on cheap disksKafka only appends to the end of a file and reads it front to back. Ordinary large hard drives handle that well, so you don't need expensive SSDs. LinkedIn kept about 75 TB per datacenter in Kafka this way.
Serving systems need fast storage anywayThey answer lookups like "get user 42", which jump around the data. That needs SSDs or memory whether Kafka exists or not, so Kafka adds no cost there.
One log feeds many systemsSearch, cache and analytics all read the same Kafka copy. Each extra serving system makes the log's cost per system smaller.