SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
  • Message Queues
  • Pub/Sub
  • Message Brokers
  • Delivery Semantics
  • Dead Letter Queues
  • Kafka Deep Dive
  • Retries with Backoff
  • RabbitMQ and SQS
  • Event Streaming vs Message Queues
  • Message Ordering
  • Task Queues, Workers and Scheduled Jobs
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/APIs and Communication/Asynchronous Communication

Kafka Deep Dive

Topics, partitions, offsets and consumer groups: how Kafka stores and delivers a huge stream of events.

⏱ 17 min readAdvancedMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

Kafka is a system that stores a huge stream of events in a log: an ordered list where new events are only ever added at the end. Many programs can write to it, and many others can read it, each at their own speed.

  • A topic is a named stream (for example "orders"). It is cut into partitions, and each partition is its own log.
  • Every message in a partition has a number called an offset. A reader just remembers "I have read up to offset 41".
  • Readers work as a consumer group: the partitions are shared between them, so the work is split and scales out.
  • Messages are kept after they are read (for a set time or size), so they can be read again.

02Concept: What is it?

A normal queue hands a message to one worker and then throws it away. Kafka works differently. It is a distributed, replicated commit log. Producers append messages to the end. Consumers read from any position they like. Reading does not delete anything.

One log on one machine would be too small and too slow, so a topic is split into partitions, spread over many machines (brokers). A partition is the unit of two things: parallelism (one partition is read by one consumer of a group at a time) and ordering (order is kept only inside one partition).

A topic, its partitions and a consumer group
📤Producer 1
📤Producer 2
→↓key decides the partition
Topic: orders
📜Partition 0offsets 0, 1, 2 ...
📜Partition 1offsets 0, 1, 2 ...
📜Partition 2offsets 0, 1, 2 ...
→↓one reader each
Consumer group A
🖥️Consumer 1P0
🖥️Consumer 2P1 and P2
Each partition is read by at most one consumer in the group. A second group would get its own full copy of the stream.

The key idea: the key picks the partition

A message can carry a key (such as a user id or order id). Kafka runs a hash on the key to choose the partition, so the same key always lands in the same partition. That is how you keep all events of one order in the right order, while different orders spread over many partitions.

🧠Two numbers to remember
A partition keeps order and is read by one consumer per group. So the number of partitions is the most parallel a consumer group can ever be.

03Real-Life Example

🍵A big library of diaries
Imagine a town where every shop writes its sales into a diary. Nobody tears out pages. New lines are added at the bottom, and each line has a number. There are four diaries (partitions), and the rule is: a shop always uses the same diary, so one shop's story stays in order. The accountants (a consumer group) share the four diaries between them. Each accountant keeps a bookmark in each diary they read. If one accountant goes home sick, another takes over their diaries and starts from the bookmark. Next year, an auditor (another group) can read all the diaries again from page one.
Diaries
Kafka
One diary
One partition (an append-only log)
The line number
The offset
A shop always uses the same diary
The message key picks the partition
A group of accountants sharing the diaries
A consumer group
A bookmark in each diary
The committed offset
An accountant leaves, the others split the diaries again
A rebalance
Copies of each diary in other offices
Replicas (a leader and followers)
Old pages kept for a year, then thrown away
Retention
Reading with a bookmark
📜Partition log0 1 2 3 4 5 6 7
→↓read from offset 5
🖥️Consumerprocess
→↓commit offset 8
🔖Bookmarknext read starts at 8

04Why Do We Need It?

🚀Very high throughput
Appending to the end of a log and reading it in order is fast. Many partitions on many machines add up to huge volume.
↔️Many readers, no fight
Each consumer group has its own bookmark. Analytics, search and billing can all read the same stream at different speeds.
⏪Replay
Messages stay after being read. A new service, or a fixed bug, can read the history again from the start.
🧯Durable
Each partition is copied to other machines, so a broker can die without losing confirmed messages.
🔌Decoupling
Producers do not know who reads. Teams add new consumers without touching the producer.
🧱A buffer for spikes
The log absorbs a burst. Slow consumers catch up later, and the lag tells you how far behind they are.
Kafka is a durable, replayable log that many readers share. Partitions give it speed and order, and consumer groups share the work.

05Where Do We Use It?

🛒Event backbones
Order placed, payment done, item shipped: services react to events instead of calling each other.
📊Activity tracking
Clicks, page views and searches flow in at huge volume, to be counted and analysed.
🪵Log and metric pipelines
Servers send logs and metrics to a topic, and several tools read them.
🗃️Change data capture
Every change in a database is published as an event, to keep search, caches and warehouses in sync.
🌊Stream processing
Engines such as Kafka Streams and Flink read topics, compute, and write new topics.
📜Event sourcing
A log of everything that happened is the source of truth for a system.

06Types / Parts / How It Works

How Kafka is built

PartWhat it isWhy it matters
BrokerA server that stores partitions and serves reads and writesA cluster has many brokers, so data and load are spread
Topic and partitionA named stream, cut into ordered logsPartitions are the unit of order and parallelism
OffsetThe position of a message in its partitionA consumer only has to remember one number per partition
ProducerWrites messages, choosing the topic and (often) a keyThe key sets the partition and so the ordering
Consumer groupA set of consumers that share a topic's partitionsGives scale. Each partition has one reader in the group
Replica: leader and followersEvery partition has one leader and some followersReads and writes go to the leader. Followers copy it
ISR (in-sync replicas)Followers that are fully caught up with the leaderOnly these may take over without losing confirmed data
ControllerThe part of the cluster that tracks leaders and membersNewer versions run this inside Kafka (KRaft) instead of ZooKeeper

Consumer groups, in three pictures

Fewer consumers than partitions, equal, and more
2 consumers, 4 partitions
C1P0 P1
C2P2 P3
4 consumers, 4 partitions
C1P0
C2P1
C3P2
C4P3
6 consumers, 4 partitions
C1P0
C2P1
C3P2
C4P3
C5idle
C6idle
Reading a partition Idle
Extra consumers beyond the partition count do nothing. That is why you pick the partition count with growth in mind.

Keeping data safe: replicas and acks

Each partition has a leader and followers on other brokers. The producer setting acks decides when the leader may say "saved".

acksThe producer waits forRisk
0NothingFastest. A message can be lost with no error
1The leader's own writeA leader crash right after OK can lose the message
allEvery in-sync replica (and at least min.insync.replicas of them)Slowest, but a confirmed message survives a leader failure
VisualizerPartitions, consumers, lag and a rebalanceSlide the partitions and consumers up and down. Make one key very busy and see the lag stay on one partition. Then crash a consumer and watch its partitions move.
Message keys
Partitions: amber = messages waiting (lag), cyan = already read. 40 messages arrived at once and each consumer reads one per tick.
P0
lag 9→ C0
P1
lag 2→ C1
P2
lag 2→ C2
P3
lag 9→ C0
🖥️C0P0 P3
🖥️C1P1
🖥️C2P2
Partitions
4
unit of parallelism
Working consumers
3
of 3 alive
Idle consumers
0
no partition to read
Total lag
22
messages not yet read
Some consumers read more than one partition. That works, but each one has more to do. More consumers (up to the number of partitions) would finish sooner.

A simplified model with a simulated clock and no random numbers. Partition assignment here spreads partitions over live consumers in turn (real assignors differ), and the rebalance pause is shortened for teaching.

Visualizeracks and a dying leader: which messages survive?Switch between acks=0, 1 and all, then let the leader die. Make a follower fall behind, and raise min.insync.replicas to see a write refused.
Producer setting (acks)
Follower F2
The leader of a partition dies after the producer sent 5 messages (m1 to m5). One in-sync follower takes over.
m1
m2
m3
m4
m5
Producer was told
✓
✓
✓
✓
✓
Leader (crashed)
m1
m2
m3
m4
m5
Follower F1
m1
m2
m3
Follower F2
m1
m2
After F1 takes over
kept
kept
kept
LOST
LOST
Told saved
5
by the producer
Lost for good
2
confirmed but gone
In-sync replicas
3
leader + followers that keep up
With acks=1 the leader said OK as soon as it wrote the message, before the followers copied it. The leader then died, so 2 messages that the producer was told were saved are gone.

Illustrative numbers: when the leader dies, F1 has copied 3 messages and F2 has copied 2. Real clusters differ. The min.insync.replicas slider only matters with acks=all. Only an in-sync replica should take over (a clean election), which is the setting you want for data you cannot lose.

07How to Use It / Steps / Implementation

Using Kafka well

  1. 1
    Choose the key first
    Pick the key that must stay in order (order id, user id). Avoid a key that is very hot, as it overloads one partition.
  2. 2
    Pick the partition count with growth in mind
    It is the ceiling for consumer parallelism. You can add partitions later, but doing so changes which partition a key maps to, so old and new events of one key can end up apart.
  3. 3
    Use a replication factor of 3 for important data
    Combine it with acks=all and a min.insync.replicas setting, so a confirmed message survives losing a broker.
  4. 4
    Turn on the idempotent producer
    Retries then cannot create duplicates in the log. Transactions can go further and make a read-process-write step atomic within Kafka.
  5. 5
    Commit offsets after the work is done
    That gives at-least-once delivery. Make the consumer idempotent, as a crash before the commit means the message is read again.
  6. 6
    Handle bad messages
    Send messages that keep failing to a dead letter topic, so one poison message does not block a whole partition.
  7. 7
    Watch consumer lag
    Lag is how far a group is behind the end of the log. A growing lag is the first sign of a slow or stuck consumer.
A consumer loop, in plain steps (not real code)
loop:
  messages = poll(topic)        # get a batch from my partitions
  for each message:
      do_the_work(message)      # must be safe to repeat
  commit(offsets)               # then move my bookmark forward
⚠️Commit order decides your guarantee
Commit before the work and a crash loses messages (at most once). Commit after the work and a crash repeats messages (at least once). Most systems choose the second and make the work idempotent.

08Key Terms to Know

TermMeaning in easy words
TopicA named stream of messages, split into partitions
PartitionOne ordered, append-only log. The unit of order and parallelism
OffsetThe position of a message inside a partition
BrokerA Kafka server that stores partitions
Producer / ConsumerA program that writes messages / a program that reads them
Consumer groupConsumers that share a topic's partitions, one reader per partition
RebalanceHanding partitions to different consumers when one joins or leaves
Consumer lagHow many messages a group still has to read
Replication factorHow many copies of each partition exist
ISRIn-sync replicas: the followers that are fully caught up
Log compactionKeeping only the latest message for each key, instead of deleting by age

09Pros, Cons and Trade-offs

✅ Pros
  • Very high throughput and scale
  • Messages stay and can be replayed
  • Many independent consumer groups
  • Order within a partition
  • Durable and replicated
⚠️ Cons
  • More to run and understand than a simple queue
  • Order only inside one partition
  • Partition count limits parallelism
  • No per-message retry or delay out of the box
  • Hot keys and rebalances need care

Trade-offs

ChoiceWe gainWe lose
More partitionsMore parallel consumers and throughputMore files and overhead, longer rebalances, and key mapping changes when you add them
acks=allNo loss of confirmed messagesHigher write latency, and writes fail when too few replicas are in sync
acks=1Faster writesA leader crash can lose confirmed messages
Long retentionReplay far back in timeMore disk and cost
Key per entityOrder for each entityA hot key overloads one partition
Commit after workNo lost messagesDuplicates after a crash, so the consumer must be idempotent

10Common Problems and Mistakes

Common mistakes

  1. Expecting a global order. Kafka orders messages only inside one partition. Different partitions have no order between them.
  2. A hot key. One very busy key sends most traffic to one partition, and no number of consumers can help.
  3. More consumers than partitions. The extra consumers sit idle.
  4. Slow processing inside the poll loop. The group may think the consumer is dead and trigger a rebalance, so work is repeated.
  5. Forgetting idempotency. At-least-once means duplicates. Without a safe consumer they do damage.
  6. acks=1 for data you cannot lose. A leader crash at the wrong moment loses confirmed messages.
  7. Treating Kafka as a database for everything. It is a log. Querying by anything other than offset and key needs another system.

Things to watch

⏳Consumer lag
A growing lag means consumers are slower than producers. Add consumers (up to the partition count) or speed up the work.
🔁Rebalance storms
Consumers that keep joining and leaving cause constant pauses. Check timeouts and the processing time per batch.
☠️Poison messages
One bad message can block a partition forever. Route it to a dead letter topic after a few tries.
💾Disk and retention
Retention, replication and partition count together decide your storage bill.

11Real-World Examples

🏢Where it came from
Kafka was built inside a large social network to move activity data between systems, and was later open sourced.
🚕Ride and delivery apps
Location updates, trip events and payments flow as topics that many services read.
🏦Finance
Banks use it for event streams such as transactions and fraud signals, where replay and audit matter.
🎬Streaming services
Play, pause and search events feed recommendations and dashboards.
☁️Managed services
Cloud providers offer hosted Kafka, so teams do not run the brokers themselves.
🔗Data pipelines
Tools such as Kafka Connect and Debezium move data between databases and topics.
📝Note
Defaults and exact settings change between Kafka versions and between managed services. Check the documentation of the version you use.
Mini case: order events with three groups
🛒Order servicekey = order id
→↓orders topic
📜6 partitionsreplication factor 3
→↓three groups
💳Billing
🔎Search indexer
📈Analytics
One topic, three groups. Each group has its own bookmark and its own speed.

12Related Topics to Read Next

Message Brokers→

Kafka is one kind of broker. Compare it with others.

Delivery Semantics→

Offsets and acks decide at-most-once, at-least-once or exactly-once.

Pub/Sub→

Consumer groups give both queue-style sharing and publish-subscribe.

Event Streaming vs Message Queues→

When a replayable log is better than a classic queue.

Message Ordering→

Order inside one partition, and how to keep it end to end.

Replication→

Partition replicas use the same leader and follower idea.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔What: a replicated, append-only log. Messages stay and can be replayed.
  • ✔Partition: an ordered log, the unit of order and parallelism.
  • ✔Key: same key, same partition, so order per key.
  • ✔Consumer group: partitions shared, one reader each. Extra consumers sit idle.
  • ✔Offsets: commit after the work gives at-least-once. Make the consumer idempotent.
  • ✔Safety: replication factor 3, acks=all, min.insync.replicas, idempotent producer.
  • ✔Watch: consumer lag, rebalances, hot keys.
  • ✔One line: “A shared, replayable diary: the key picks the page, and the group shares the pages.”
← Previous
Dead Letter Queues
Next →
Retries with Backoff