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:
- 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.
- 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.
- 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 database | In plain words | Now 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:
- Backing log: Kafka. The order service writes every
OrderPlaced/OrderCancelledevent to anorderstopic. This is the source of truth. - 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.
- 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.
- Coordination: ZooKeeper. You run 3 indexer nodes. ZooKeeper decides which node owns which slice of the data and picks a replacement when one dies.
- 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
| Property | Traditional Queue | Log |
|---|---|---|
| Read is destructive | Yes — deleted after consume | No — offset advances, message stays |
| Multiple consumers | Compete for the same messages | Each group has independent offset |
| Replay | Impossible | Rewind to any offset |
| Retention | Until consumed | Time/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?"
The log handles all the hard distributed systems problems:
| Problem | How the log solves it |
|---|---|
| Consistency | Every write gets an offset. All serving nodes apply writes in offset order — no divergence. |
| Replication | Nodes don't talk to each other. They all subscribe to the log and independently reach identical state. |
| Durability | The log only acks after committed to enough replicas. Serving nodes inherit this. |
| External subscribers | Any system subscribes at its own pace — one tap for all changes. |
| Recovery | A crashed node replays the log from its last snapshot. No peer-to-peer copy. |
| Rebalancing | A 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 Type | Retention Strategy | Reasoning |
|---|---|---|
| Event data (activity, metrics) | Time or size window | Individual events have no "superseding" update |
| Keyed data (DB-like updates) | Log compaction | Each key has a current value; old values are obsolete |
Enabled per-topic via cleanup.policy:
cleanup.policy | Behavior |
|---|---|
delete (default) | Time/size-based deletion — the "event stream" case |
compact | Keep only the latest value per key, forever — the "keyed/changelog" case |
compact,delete | Both: 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
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
| Layer | What's batched | Benefit |
|---|---|---|
| Producer → partition leader | Messages accumulate in buffer before sending | One network call per batch |
| Leader → disk (followers do the same) | OS page cache groups writes into sequential flushes | Sequential I/O — orders of magnitude faster |
| Leader → followers (other brokers) | Followers fetch in bulk | Replication keeps up |
| Partition leader → consumer | Consumer fetches configurable chunk | Processes 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
| Config | Default | Meaning |
|---|---|---|
batch.size | 16 KB | Flush when the batch reaches this size |
linger.ms | 0 ms | Flush 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.
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:
| Traffic | Amount |
|---|---|
| In from producers | 10 MB/s |
| Out to 2 followers (replication) | 20 MB/s |
| Out to 10 consumer groups | 100 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:
| Resource | Role | Usually the bottleneck? |
|---|---|---|
| Network card | Producer traffic in; replication + consumer traffic out | Most often |
| Disk | Sequential writes; reads for lagging consumers | Sometimes — especially with lagging consumers |
| RAM | Page cache that keeps recent data hot for readers | Indirectly — too little RAM turns reads into disk reads |
| CPU | Compression, TLS, checksums | Only 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
| Problem | Lever | Catch |
|---|---|---|
| Group needs more parallelism | Add 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 overloaded | Add brokers and reassign partitions (kafka-reassign-partitions or Cruise Control) | New brokers start empty — nothing moves until you reassign |
| One noisy group | Per-client byte-rate quotas | That group gets throttled |
| Lagging readers hit disk | Tiered storage — old data served from object storage (S3) | Higher latency for cold reads |
| Heavy batch / analytics readers | Mirror the topic to a separate cluster (MirrorMaker 2) | Second cluster to run; replication lag |
| Read load on leaders / cross-AZ cost | Follower 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
rfreplicas 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
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.
| Layer | Who | Role | Leader? |
|---|---|---|---|
| Log | Partition leader broker | Takes producer writes, assigns offsets, serves consumer fetches | Yes, elected by the controller |
| Log | ISR followers | Copy the leader; used only for durability and failover | Candidates if the leader dies |
| Serving | Your consumer services (e.g. profile-service, an Elasticsearch indexer) | Consume from the leader, build a queryable view, answer end-user reads | No |
- Write. The client produces
{user:42, name:"Sam"}. The partition leader appends it at offset 1057 and returns that offset. - Read with the offset. The client calls a serving node:
GET /user/42?min_offset=1057. - Wait if behind. Node B has applied only up to 1031. It holds the request (no reject, no redirect) until its consumer reaches 1057.
- Answer. Any node with
applied_offset ≥ 1057answers 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:
| Reason | Why it keeps cost down |
|---|---|
| Kafka runs on cheap disks | Kafka 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 anyway | They 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 systems | Search, cache and analytics all read the same Kafka copy. Each extra serving system makes the log's cost per system smaller. |