Nextgen Blog
HomeLearnAIQuantumRoboticsSecuritySpaceAbout
Nextgen Blog

By Anubhav — full stack engineer, IIT Mandi CSE. Deep dives into AI, software engineering, and the technologies shaping the next generation of tech.

Navigate

  • Home
  • Learn
  • Blog
  • Archive
  • About

Topics

  • Artificial Intelligence
  • Quantum Computing
  • Robotics
  • Cybersecurity
  • Space Tech

Connect

Built with ❤️ & By - Anubhav

© 2026 Nextgen Blog by Anubhav. All rights reserved.

Privacy PolicyTerms of Service
Phase 04 · Storage, Queues & Event StreamingChapter 22 of 33
21.
Phase 04Read time ~29 minDifficulty advanced

Kafka & Event Streaming

In this chapter
  • 01Introduction
  • 02What Is Kafka?
  • 03Kafka vs Traditional Queue
  • 04Why Event Streaming?
  • 05Core Kafka Concepts
  • 06Broker
  • 07Topic
  • 08Partition
  • 09Why Partitions Exist
  • 10Partition Key
  • 11Per-Key Ordering
  • 12Global Ordering
  • 13Offset
  • 14Consumer Position
  • 15Consumer Groups
  • 16Partition Parallelism
  • 17Too Many Consumers
  • 18Multiple Consumer Groups
  • 19Queue Semantics with Consumer Groups
  • 20Consumer Lag
  • 21Why Lag Matters
  • 22Producer
  • 23Producer Batching
  • 24Compression
  • 25Producer Acknowledgements
  • 26Replication
  • 27Leader and Followers
  • 28ISR — In-Sync Replicas
  • 29Why ISR Matters
  • 30Replication Failure
  • 31Availability vs Durability Trade-Off
  • 32Retention
  • 33Why Retention Enables Replay
  • 34Offset Reset
  • 35Event Replay
  • 36Kafka as a Distributed Log
  • 37Event vs Command
  • 38Event
  • 39Command
  • 40Event Schema
  • 41Schema Evolution
  • 42Schema Registry
  • 43Consumer Rebalancing
  • 44Why Rebalancing Matters
  • 45Consumer Commit
  • 46Commit Timing
  • 47Batch Consumption
  • 48Kafka Transactions
  • 49Exactly-Once Processing
  • 50Idempotent Producer
  • 51Kafka and the Outbox Pattern
  • 52Kafka and Change Data Capture
  • 53Event Sourcing
  • 54CQRS
  • 55Kafka Streams
  • 56Stream Processing
  • 57Windowing
  • 58Event Time vs Processing Time
  • 59Event time
  • 60Processing time
  • 61Late Events
  • 62Kafka for Log Aggregation
  • 63Kafka for Analytics Pipelines
  • 64Kafka for Search Indexing
  • 65Kafka for Notifications
  • 66Kafka for Fraud Detection
  • 67Kafka Failure Scenarios
  • 68Broker failure
  • 69Consumer failure
  • 70Producer network failure
  • 71Consumer processing failure
  • 72Partition Failure and Recovery
  • 73Under-Replicated Partitions
  • 74Kafka Scaling Dimensions
  • 75Choosing Partition Count
  • 76Partition Key Design
  • 77Hot Partition
  • 78Ordering vs Hot Keys
  • 79Kafka Security
  • 80Kafka Observability
  • 81Broker
  • 82Topic/Partition
  • 83Producer
  • 84Consumer
  • 85Consumer Lag Alerting
  • 86Kafka Cost Considerations
  • 87Multi-Region Kafka
  • 88Kafka vs Database
  • 89Kafka vs Redis Streams
  • 90Kafka vs Traditional Queue
  • 91Common Mistakes
  • 92Mistake 1
  • 93Mistake 2
  • 94Mistake 3
  • 95Mistake 4
  • 96Mistake 5
  • 97Mistake 6
  • 98Mistake 7
  • 99Mistake 8
  • 100Mistake 9
  • 101Mistake 10
  • 102Mistake 11
  • 103Mistake 12
  • 104Interview Framework
  • 105Interview Question: Why Are Partitions Important?
  • 106Interview Question: How Does Kafka Preserve Ordering?
  • 107Interview Question: What Is Consumer Lag?
  • 108Interview Question: Why Does Kafka Support Replay?
  • 109Interview Question: What Is a Consumer Group?
  • 110Interview Question: Why Use Kafka Instead of Direct HTTP Calls?
  • 111Mini Project
  • 112Components
  • 113Mini Project — Requirements
  • 114Producer
  • 115Inventory Consumer
  • 116Notification Consumer
  • 117Analytics Consumer
  • 118Advanced Mini Project Features
  • 119Production Checklist
  • 120Key Mental Model
  • 121Chapter Summary
  • 122Interview Revision Checklist
  • 123Next Chapter
  • 124Chapter 21 — Event-Driven Architecture
In this chapter (124 sections)
01Introduction02What Is Kafka?03Kafka vs Traditional Queue04Why Event Streaming?05Core Kafka Concepts06Broker07Topic08Partition09Why Partitions Exist10Partition Key11Per-Key Ordering12Global Ordering13Offset14Consumer Position15Consumer Groups16Partition Parallelism17Too Many Consumers18Multiple Consumer Groups19Queue Semantics with Consumer Groups20Consumer Lag21Why Lag Matters22Producer23Producer Batching24Compression25Producer Acknowledgements26Replication27Leader and Followers28ISR — In-Sync Replicas29Why ISR Matters30Replication Failure31Availability vs Durability Trade-Off32Retention33Why Retention Enables Replay34Offset Reset35Event Replay36Kafka as a Distributed Log37Event vs Command38Event39Command40Event Schema41Schema Evolution42Schema Registry43Consumer Rebalancing44Why Rebalancing Matters45Consumer Commit46Commit Timing47Batch Consumption48Kafka Transactions49Exactly-Once Processing50Idempotent Producer51Kafka and the Outbox Pattern52Kafka and Change Data Capture53Event Sourcing54CQRS55Kafka Streams56Stream Processing57Windowing58Event Time vs Processing Time59Event time60Processing time61Late Events62Kafka for Log Aggregation63Kafka for Analytics Pipelines64Kafka for Search Indexing65Kafka for Notifications66Kafka for Fraud Detection67Kafka Failure Scenarios68Broker failure69Consumer failure70Producer network failure71Consumer processing failure72Partition Failure and Recovery73Under-Replicated Partitions74Kafka Scaling Dimensions75Choosing Partition Count76Partition Key Design77Hot Partition78Ordering vs Hot Keys79Kafka Security80Kafka Observability81Broker82Topic/Partition83Producer84Consumer85Consumer Lag Alerting86Kafka Cost Considerations87Multi-Region Kafka88Kafka vs Database89Kafka vs Redis Streams90Kafka vs Traditional Queue91Common Mistakes92Mistake 193Mistake 294Mistake 395Mistake 496Mistake 597Mistake 698Mistake 799Mistake 8100Mistake 9101Mistake 10102Mistake 11103Mistake 12104Interview Framework105Interview Question: Why Are Partitions Important?106Interview Question: How Does Kafka Preserve Ordering?107Interview Question: What Is Consumer Lag?108Interview Question: Why Does Kafka Support Replay?109Interview Question: What Is a Consumer Group?110Interview Question: Why Use Kafka Instead of Direct HTTP Calls?111Mini Project112Components113Mini Project — Requirements114Producer115Inventory Consumer116Notification Consumer117Analytics Consumer118Advanced Mini Project Features119Production Checklist120Key Mental Model121Chapter Summary122Interview Revision Checklist123Next Chapter124Chapter 21 — Event-Driven Architecture

1. Introduction#

In Chapter 19, we learned message queues.

Now we move to a closely related but broader concept:

Distributed event streaming.

A traditional work queue is often modeled as:

Producer
   |
   v
Queue
   |
   v
Consumer

A distributed event-streaming platform such as Apache Kafka is better understood as a durable, partitioned, append-only event log:

Producer
   |
   v
   Topic
   |
   +---- Partition 0
   +---- Partition 1
   +---- Partition 2
   |
   v
Consumers

The important difference is that events can remain available after one consumer processes them.

Multiple independent consumer groups can read the same event stream at their own pace.

This enables:

  • event-driven architectures
  • real-time pipelines
  • analytics
  • log aggregation
  • data integration
  • event replay
  • audit streams
  • CDC pipelines
  • stream processing
  • microservice communication

2. What Is Kafka?#

Apache Kafka is a distributed event-streaming platform.

A simplified mental model is:

Kafka Cluster
      |
      +---- Topic A
      |       |
      |       +---- Partition 0
      |       +---- Partition 1
      |
      +---- Topic B
              |
              +---- Partition 0
              +---- Partition 1

Producers append records to topics.

Consumers read records from topics.

Kafka stores records for a configured retention period.


3. Kafka vs Traditional Queue#

A traditional work queue often emphasizes:

message
   ↓
one worker
   ↓
acknowledge
   ↓
remove/complete

Kafka emphasizes:

append event
   ↓
retain event
   ↓
consumers track position

For example:

OrderCreated
OrderPaid
OrderShipped

Kafka can retain these events so different consumers can independently read them.


4. Why Event Streaming?#

Suppose an e-commerce system creates an order.

Several systems need to react:

Order Service
      |
      v
OrderCreated
      |
      +----→ Inventory
      +----→ Analytics
      +----→ Notification
      +----→ Recommendation
      +----→ Fraud Detection

Without an event stream, the Order Service might have to directly call every service.

That creates coupling.

With an event stream, the producer publishes an event and consumers subscribe independently.


5. Core Kafka Concepts#

The most important terms are:

Concept Meaning
Broker Kafka server
Cluster Group of Kafka brokers
Topic Named event stream
Partition Ordered log within a topic
Record Individual message/event
Producer Writes records
Consumer Reads records
Consumer group Consumers cooperating on a workload
Offset Position of a record within a partition
Replication Copies partition data across brokers
Leader Broker currently serving writes/reads for a partition
Follower Replica of a partition
ISR In-sync replicas
Retention How long Kafka keeps records

These concepts form the foundation of Kafka.


6. Broker#

A broker is a Kafka server.

A Kafka cluster may contain multiple brokers:

Kafka Cluster
 
Broker 1
Broker 2
Broker 3
Broker 4

Different partitions are distributed across brokers.

This provides:

  • horizontal scalability
  • storage distribution
  • parallel processing
  • fault tolerance through replication

7. Topic#

A topic is a named stream of records.

Examples:

orders
payments
user-events
notifications
logs
click-events

Conceptually:

Topic: orders
 
OrderCreated
OrderCreated
OrderPaid
OrderCreated
OrderShipped

A topic is divided into partitions for scalability.


8. Partition#

A partition is an ordered append-only log.

Example:

Partition 0
 
offset 0 → event A
offset 1 → event B
offset 2 → event C
offset 3 → event D

The order is guaranteed within this partition.

Kafka does not automatically provide one global order across all partitions of a topic.


9. Why Partitions Exist#

Suppose a topic receives:

1 million events/sec

One server may not be sufficient.

Split the topic:

Topic
 |
 +---- P0
 +---- P1
 +---- P2
 +---- P3

Different partitions can be stored and processed in parallel.

This is one of Kafka's fundamental scalability mechanisms.


10. Partition Key#

A producer can choose a key.

Example:

key = userId

The producer can use the key to determine the partition.

Conceptually:

partition = hash(key) % partitionCount

Then:

User 101 → Partition 2
User 101 → Partition 2
User 101 → Partition 2

This can preserve ordering for that user's events.


11. Per-Key Ordering#

Suppose:

User 101
 
Login
UpdateProfile
Logout

If all three records go to the same partition:

P2
 
Login
UpdateProfile
Logout

their relative order is preserved.

At the same time:

User 202 → P0
User 303 → P1

can be processed concurrently.

This is often better than forcing global ordering.


12. Global Ordering#

If all events go to one partition:

P0
 
1
2
3
4
5

global ordering is straightforward.

But throughput and parallelism are limited.

Therefore:

more partitions
→ more parallelism
→ weaker global ordering

This is a key Kafka trade-off.


13. Offset#

An offset identifies a record's position within a partition.

Example:

Partition 0
 
offset 0 → A
offset 1 → B
offset 2 → C
offset 3 → D
offset 4 → E

A consumer can maintain:

current offset = 3

This means it has progressed to a particular position in the partition.


14. Consumer Position#

Suppose the consumer has processed:

0
1
2

and the next record is:

3

The consumer can continue from that position.

This is different from a traditional queue where the broker often tracks completion by removing or acknowledging the message.

Kafka's log remains.

The consumer tracks its position.


15. Consumer Groups#

A consumer group is a set of consumers working together.

Example:

Topic
 |
 +---- P0
 +---- P1
 +---- P2
 +---- P3
 
Consumer Group A
 |
 +---- Consumer 1
 +---- Consumer 2
 +---- Consumer 3
 +---- Consumer 4

Each partition is assigned to a consumer in the group.


16. Partition Parallelism#

Suppose:

4 partitions
4 consumers

A possible assignment:

C1 → P0
C2 → P1
C3 → P2
C4 → P3

Now processing can happen in parallel.


17. Too Many Consumers#

Suppose:

4 partitions
8 consumers

Only four consumers can actively own partitions at a time within that consumer group.

The others may remain idle.

Therefore:

Maximum useful parallelism within a consumer group is constrained by partition count.


18. Multiple Consumer Groups#

This is one of Kafka's most powerful ideas.

Suppose:

Topic: orders

Consumer group A:

Inventory

Consumer group B:

Analytics

Consumer group C:

Notifications

All groups can independently consume the same events.

                 orders topic
                     |
          +----------+----------+
          |          |          |
          v          v          v
      Inventory   Analytics  Notifications
       Group       Group       Group

This provides fan-out.


19. Queue Semantics with Consumer Groups#

Kafka can also behave like a work queue.

Suppose:

Topic
 |
 +---- P0
 +---- P1
 +---- P2

One consumer group:

Worker 1
Worker 2
Worker 3

Each partition is processed by one consumer in the group.

So the same Kafka topic can support different consumption models depending on how groups are configured.


20. Consumer Lag#

Consumer lag measures how far behind a consumer group is.

Conceptually:

latest available offset
        -
consumer processed position
        =
lag

Example:

Latest offset = 10,000
Consumer position = 9,700
 
Lag = 300

If lag continuously increases, consumers cannot keep up.


21. Why Lag Matters#

A system may appear healthy at the broker level while consumers are falling behind.

For real-time applications, lag may directly translate into user-visible delay.

Examples:

fraud detection delayed
analytics delayed
notifications delayed
search index delayed

Monitor both:

lag amount
+
lag growth rate

22. Producer#

A Kafka producer writes records.

Example event:

{
  "eventType": "OrderCreated",
  "orderId": "ORD-123",
  "userId": "U-42",
  "amount": 4999
}

The producer chooses:

  • topic
  • key
  • value
  • optional headers

Partition selection may depend on the key.


23. Producer Batching#

Sending every record individually can be inefficient.

A producer can batch multiple records:

Event 1
Event 2
Event 3
Event 4
     |
     v
one batch
     |
     v
Kafka

Benefits:

  • fewer network requests
  • better throughput
  • improved compression efficiency

Trade-off:

  • small batching delay may increase latency

24. Compression#

Kafka producers can compress batches.

Common compression choices include:

  • gzip
  • Snappy
  • LZ4
  • Zstandard

Compression can reduce:

  • network traffic
  • storage usage

but consumes CPU.

Choose based on workload and infrastructure.


25. Producer Acknowledgements#

The producer needs to know how reliably the broker accepted a record.

Conceptually:

Producer
   |
   | record
   v
Broker
   |
   | acknowledgement
   v
Producer

Different acknowledgement settings trade off latency, durability, and failure behavior.


26. Replication#

Kafka can replicate partitions.

Example:

Partition 0
 
Broker 1 → Leader
Broker 2 → Replica
Broker 3 → Replica

Replication factor:

3

means there are three copies according to the configured replication model.

If one broker fails, another replica may take over.


27. Leader and Followers#

For a replicated partition:

Partition 0
 
Broker 1
  Leader
 
Broker 2
  Follower
 
Broker 3
  Follower

The leader handles the normal partition operations.

Followers replicate the leader's data.


28. ISR — In-Sync Replicas#

ISR means:

In-Sync Replicas.

These are replicas considered sufficiently caught up with the partition leader according to Kafka's replication rules.

Example:

P0
 
Leader → Broker 1
ISR → Broker 1, Broker 2, Broker 3

If Broker 3 falls too far behind, it may leave the ISR.

ISR → Broker 1, Broker 2

29. Why ISR Matters#

ISR membership affects durability and failover decisions.

A replica that is not sufficiently synchronized should not be treated the same as a healthy in-sync replica.

This is especially important when discussing:

  • producer acknowledgements
  • leader failure
  • durability
  • replication health

30. Replication Failure#

Suppose:

Broker 1 = Leader
Broker 2 = Follower
Broker 3 = Follower

Broker 1 crashes.

Kafka can elect another eligible replica as leader.

Conceptually:

Broker 1
   X
 
Broker 2
   |
   v
New Leader

Clients refresh metadata and continue using the new leader.


31. Availability vs Durability Trade-Off#

A system must choose how much acknowledgement and replication it requires.

More durability generally means:

more replicas / stronger acknowledgement
→ potentially higher latency

Lower latency settings may accept more risk under failures.

System design is about choosing based on business requirements.


32. Retention#

Kafka does not necessarily delete a record immediately after a consumer reads it.

Instead, records remain according to retention policies.

Retention can be based on:

time

or:

storage size

Example:

retain for 7 days

After retention expires, old data can be removed.


33. Why Retention Enables Replay#

Suppose:

Consumer A processed events yesterday.

A new consumer starts today.

If the events are still retained, it can read older records.

This enables:

  • rebuilding state
  • reprocessing
  • debugging
  • new consumers
  • recovery

Replay is one of the major differences between a durable event log and a simple transient work queue.


34. Offset Reset#

A consumer may need to choose where to begin reading.

Possible concepts include:

earliest
latest
specific offset

For example:

start from earliest

means reading retained historical records.

Starting from the latest position means processing new events going forward.


35. Event Replay#

Suppose analytics logic was incorrect.

Events:

Day 1
Day 2
Day 3
...

After fixing the consumer:

Historical Kafka events
        |
        v
Corrected consumer
        |
        v
Rebuild analytics

This can avoid requiring the original producer to regenerate every event.


36. Kafka as a Distributed Log#

A powerful mental model:

append
append
append
append
append

The partition is an ordered log.

Consumers move through the log using offsets.

P0:
 
0 → A
1 → B
2 → C
3 → D
4 → E

This log abstraction is central to Kafka.


37. Event vs Command#

A useful distinction:

Event#

Something that happened.

OrderCreated
PaymentCompleted
UserRegistered

Command#

Instruction to perform something.

CreateOrder
SendEmail
ChargeCard

Event streams are especially natural for facts about things that have already happened.


38. Event Schema#

A good event should be explicit.

Example:

{
  "eventId": "evt_123",
  "eventType": "OrderCreated",
  "eventVersion": 2,
  "occurredAt": "2026-10-01T10:00:00Z",
  "producer": "order-service",
  "payload": {
    "orderId": "ORD-123",
    "userId": "U-42"
  }
}

Useful metadata:

  • event ID
  • event type
  • version
  • timestamp
  • producer
  • correlation/trace ID

39. Schema Evolution#

Consumers and producers are deployed independently.

Suppose version 1 contains:

{
  "userId": "123"
}

Version 2 adds:

{
  "userId": "123",
  "country": "IN"
}

Adding an optional field is often easier to roll out safely than removing or changing the meaning of an existing field.

Event schemas should be designed for compatibility.


40. Schema Registry#

Large Kafka ecosystems often use a schema registry or an equivalent schema-management system.

Conceptually:

Producer
   |
   v
Schema Registry
   |
   v
Kafka
   |
   v
Consumer

It can help manage:

  • schema versions
  • compatibility rules
  • serialization formats
  • validation

Common serialization approaches include JSON, Avro, Protobuf, and JSON Schema.


41. Consumer Rebalancing#

When consumers join or leave a group, Kafka may redistribute partitions.

Example:

Before:
 
C1 → P0, P1
C2 → P2, P3

C2 leaves.

Partitions may be reassigned:

C1 → P0, P1, P2, P3

This redistribution is called rebalancing.


42. Why Rebalancing Matters#

Rebalancing can temporarily affect processing.

Frequent consumer membership changes may cause:

  • processing pauses
  • partition movement
  • increased latency
  • operational instability

Therefore consumers should be stable and correctly configured.


43. Consumer Commit#

Consumers need to persist their progress.

Conceptually:

Processed offset = 500

The consumer commits that position.

If the consumer crashes, it can resume from a known committed position.


44. Commit Timing#

There is an important trade-off.

If the consumer commits before processing:

commit
  |
process
  |
crash

the message may not be processed again.

Potentially:

message lost from consumer's work

If it commits after processing:

process
  |
commit
  |
crash before commit

the message may be processed again.

Therefore:

commit after successful processing
+
idempotent processing

is a common reliability strategy.


45. Batch Consumption#

Consumers often fetch multiple records.

Example:

Batch:
A
B
C
D
E

The consumer processes them and commits progress.

Batching improves throughput but creates failure considerations.

If record D fails:

A ✓
B ✓
C ✓
D ✗
E ?

The consumer must have a clear strategy for retry and commit boundaries.


46. Kafka Transactions#

Kafka supports transactional capabilities that can help coordinate certain producer operations.

Transactions can be useful when a workflow needs atomicity across a set of Kafka writes.

For example:

read input
   |
process
   |
write output

A transactional design can help prevent partially published output from becoming visible inappropriately.

However, transactions do not magically create a global transaction across arbitrary external databases and services.


47. Exactly-Once Processing#

Kafka supports mechanisms for stronger processing guarantees, but system design should distinguish:

broker semantics
consumer processing
external side effects

Suppose:

Kafka event
   |
   v
Consumer
   |
   v
External payment API

Kafka's transaction guarantees cannot automatically make the external payment API exactly-once.

For external side effects, you may still need:

  • idempotency keys
  • transactional database patterns
  • deduplication
  • carefully designed workflows

48. Idempotent Producer#

A producer may retry after an uncertain network outcome.

Without protection:

send event
   |
   v
broker stores
   |
   X
ACK lost
   |
   v
producer retries

The same logical event might be written twice.

Idempotent producer mechanisms help prevent certain duplicate writes caused by producer retries.


49. Kafka and the Outbox Pattern#

Suppose:

Order DB
Kafka

The application wants:

save order
+
publish OrderCreated

A failure between those operations can cause inconsistency.

The transactional outbox pattern remains useful:

DB transaction
   |
   +---- Order
   |
   +---- Outbox event
              |
              v
        Outbox publisher
              |
              v
             Kafka

This separates database atomicity from Kafka publishing.


50. Kafka and Change Data Capture#

Change Data Capture (CDC) captures database changes.

Conceptually:

Database
   |
   v
CDC Tool
   |
   v
Kafka
   |
   +---- Analytics
   +---- Search
   +---- Data Lake
   +---- Other Services

This can reduce tightly coupled application-level integration.


51. Event Sourcing#

Event sourcing stores business state as a sequence of events.

Instead of only storing:

Account balance = 500

the system stores:

Deposit 1000
Withdraw 300
Withdraw 200

Current state can be derived from the event history.

Conceptually:

Events
  |
  v
Projection
  |
  v
Current State

Kafka can be used as part of event-driven architectures involving event sourcing, but Kafka itself does not automatically make a system event-sourced.


52. CQRS#

CQRS means:

Command Query Responsibility Segregation.

Separate:

write model

from:

read model

Example:

Commands
   |
   v
Write Service
   |
   v
Events
   |
   v
Kafka
   |
   +----→ Search Projection
   |
   +----→ Analytics Projection
   |
   +----→ Read Model

Different consumers build specialized read models.


53. Kafka Streams#

Kafka Streams is a stream-processing approach for applications that process Kafka data.

Examples:

orders
   |
   v
filter
   |
   v
aggregate
   |
   v
sales-by-region

Operations may include:

  • filtering
  • mapping
  • joining
  • grouping
  • aggregation
  • windowing

The important idea is:

event stream
→ continuous computation
→ derived stream/state

54. Stream Processing#

Suppose events arrive:

purchase
purchase
purchase
purchase

A streaming application can continuously compute:

sales per minute

rather than waiting for a nightly batch job.

This enables:

  • real-time dashboards
  • fraud detection
  • anomaly detection
  • recommendations
  • operational alerts

55. Windowing#

Some analytics need time windows.

Example:

How many purchases occurred
during the last 5 minutes?

A streaming system can use a time window:

10:00–10:05
10:05–10:10
10:10–10:15

Windowing introduces additional questions around:

  • event time
  • processing time
  • late events
  • watermarks
  • out-of-order events

These are advanced stream-processing concepts.


56. Event Time vs Processing Time#

Event time#

When the event actually occurred.

event.occurredAt

Processing time#

When the consumer processed it.

worker.now()

They can differ significantly.

Example:

Event occurred: 10:00
Arrived: 10:05
Processed: 10:06

Real-time analytics often needs to reason about event time.


57. Late Events#

Suppose a purchase happened at:

10:01

but arrives at:

10:07

A window for 10

–10
may already have been calculated.

The system needs a strategy for late data.

Possible approaches include:

  • waiting for a grace period
  • updating previous results
  • dropping very late events
  • compensating later

58. Kafka for Log Aggregation#

Applications can emit logs/events:

Service A
Service B
Service C
Service D
   |
   v
 Kafka
   |
   v
Log Processing
   |
   +---- Search
   +---- Storage
   +---- Alerting

Kafka can act as a durable buffer between applications and downstream log-processing systems.


59. Kafka for Analytics Pipelines#

Example:

Applications
    |
    v
Kafka
    |
    +---- Stream Processor
    |
    +---- Data Warehouse
    |
    +---- Data Lake

Kafka becomes the event backbone.

Different consumers can process the same source stream for different purposes.


60. Kafka for Search Indexing#

Example:

Product DB
    |
    v
ProductChanged
    |
    v
Kafka
    |
    v
Search Indexer
    |
    v
Search Engine

The database remains the system of record.

Kafka transports changes.

The search engine becomes a derived read model.


61. Kafka for Notifications#

Order Service
    |
    v
Kafka
    |
    v
Notification Consumer
    |
    +---- Email
    +---- SMS
    +---- Push

This allows notification processing to scale independently.


62. Kafka for Fraud Detection#

Transactions
    |
    v
Kafka
    |
    v
Fraud Stream Processor
    |
    +---- rules
    +---- aggregates
    +---- model scoring
    |
    v
Risk Decision

Streaming enables decisions shortly after events arrive.


63. Kafka Failure Scenarios#

Broker failure#

A broker fails.

Potential response:

replica becomes leader

Consumer failure#

Consumer crashes.

Potential response:

partition reassigned

Producer network failure#

Producer retries.

Potential issue:

duplicate send

Use idempotent producer mechanisms where appropriate.

Consumer processing failure#

Message may be retried depending on consumer design.

Need:

idempotency
retry
DLQ strategy

64. Partition Failure and Recovery#

Suppose:

P0 leader → Broker 1
P0 replica → Broker 2
P0 replica → Broker 3

Broker 1 fails.

An eligible replica can become leader.

After recovery, the original broker can catch up.

Replication and leader-election behavior are critical to availability.


65. Under-Replicated Partitions#

If replicas fall behind or become unavailable, a partition can become under-replicated.

Monitor:

under-replicated partitions
offline partitions
ISR shrink/expansion

Persistent under-replication is an operational warning sign.


66. Kafka Scaling Dimensions#

Kafka can scale through:

more brokers
more partitions
consumer parallelism
producer batching
compression
storage capacity
network capacity

But scaling one dimension can expose another bottleneck.

For example:

more partitions
→ more consumer parallelism
→ more metadata / operational overhead

Partition count is therefore an architectural decision.


67. Choosing Partition Count#

Consider:

target throughput
consumer parallelism
expected growth
ordering requirements
broker capacity
retention volume

A common mistake is choosing too few partitions initially and discovering later that consumer parallelism is insufficient.

But excessively high partition counts also create operational overhead.


68. Partition Key Design#

A good key should generally provide:

  • required ordering scope
  • reasonable distribution
  • stable routing
  • enough cardinality

Bad key:

country

if:

India = 80% traffic

Potential result:

one hot partition

Better key might be:

userId
accountId
orderId

depending on business requirements.


69. Hot Partition#

Example:

Partition 0 → 80,000 events/sec
Partition 1 → 5,000
Partition 2 → 5,000
Partition 3 → 5,000

Total throughput may look acceptable, but Partition 0 becomes the bottleneck.

This is why average throughput can hide partition-level problems.


70. Ordering vs Hot Keys#

Suppose all events for one extremely active account must remain ordered.

Using:

accountId

as the key preserves order but may create a hot partition.

Possible solutions depend on requirements.

If strict ordering is not required across all events, the workload can sometimes be further partitioned.

If strict ordering is mandatory, the hot key may remain a fundamental limit.

This is a business requirement vs scalability trade-off.


71. Kafka Security#

Production Kafka deployments should consider:

authentication
authorization
TLS
encryption
network isolation
secret management
audit logging
topic-level permissions
consumer/producer permissions

Do not allow every application unrestricted access to every topic.

Use least privilege.


72. Kafka Observability#

Monitor at least:

Broker#

CPU
memory
disk
network
request latency

Topic/Partition#

throughput
partition size
replication health
under-replication

Producer#

send rate
error rate
retry rate
latency
batch size

Consumer#

lag
processing rate
errors
rebalance frequency
commit latency

73. Consumer Lag Alerting#

A useful alert may consider:

lag > threshold
AND
lag increasing

because a static lag of 1,000 may be acceptable for one workload but dangerous for another.

Business SLA matters.

For example:

fraud detection:
seconds matter
 
daily analytics:
minutes or hours may be acceptable

74. Kafka Cost Considerations#

Kafka cost includes:

broker compute
disk
network
replication
retention
cross-region traffic
operations
monitoring

Replication factor 3 means additional storage and network overhead.

Long retention also increases storage requirements.

Compression can reduce storage and network usage.


75. Multi-Region Kafka#

Global systems may need regional Kafka clusters.

Example:

Region A
 Kafka A
    |
    v
Region B
 Kafka B

Possible architectures include:

  • active-active
  • active-passive
  • regional ingestion
  • replicated event streams

Cross-region replication introduces:

  • latency
  • bandwidth cost
  • failure complexity
  • duplicate/conflict concerns

Design according to business requirements.


76. Kafka vs Database#

Kafka is not a replacement for a general-purpose transactional database.

Database:

query current state
update records
transactions
constraints
relationships

Kafka:

append events
stream events
retain history
replay
fan-out

They often work together:

Application
   |
   +----→ Database
   |
   +----→ Kafka

77. Kafka vs Redis Streams#

Both can support stream-like workloads, but they have different architectural characteristics.

Kafka is commonly chosen for:

  • very large durable event streams
  • long retention
  • partition-based scalability
  • replay
  • large event backbones

Redis Streams may be useful when:

  • Redis is already central to the architecture
  • low-latency stream operations are needed
  • workload size and durability requirements fit Redis

Choose based on requirements rather than brand preference.


78. Kafka vs Traditional Queue#

A simplified comparison:

Concern Traditional Queue Kafka
Main abstraction Work queue Distributed log
Consumption Often removes/completes work Consumers track offsets
Replay Often limited Natural with retention
Fan-out Usually needs pub/sub Consumer groups
Partitioning Depends on system Core scalability mechanism
Ordering Queue-specific Per-partition
Retention Often shorter Configurable durable retention
Streaming Possible Core use case

Actual guarantees vary by technology and configuration.


79. Common Mistakes#

Mistake 1#

Thinking Kafka is just a faster queue.

Mistake 2#

Assuming topic-wide ordering.

Mistake 3#

Ignoring partition-key design.

Mistake 4#

Adding consumers beyond partition parallelism and expecting unlimited scaling.

Mistake 5#

Ignoring consumer lag.

Mistake 6#

Assuming Kafka transactions make external APIs exactly-once.

Mistake 7#

Using Kafka as a replacement for every database.

Mistake 8#

Putting giant payloads directly into Kafka.

Mistake 9#

Ignoring schema evolution.

Mistake 10#

Ignoring rebalancing behavior.

Mistake 11#

Choosing too many or too few partitions without capacity planning.

Mistake 12#

Ignoring replication and under-replicated partitions.


80. Interview Framework#

When asked:

Design a Kafka-based architecture.

Start with:

What events?
How many events/sec?
Average event size?
Peak traffic?
How long should events be retained?
How much ordering is required?
How many consumers?
Need replay?
Need real-time processing?
Need multiple independent consumers?
What are the durability requirements?
Single region or multi-region?

Then design:

Producers
   |
   v
Kafka Cluster
   |
   +---- Topic
   |      |
   |      +---- Partitions
   |
   +---- Consumer Groups
           |
           +---- Workers

Then discuss:

partition key
replication
acks
offsets
consumer lag
rebalancing
retry
DLQ
idempotency
schema evolution
security
monitoring

81. Interview Question: Why Are Partitions Important?#

Partitions provide horizontal scalability and parallelism. They allow a topic's data to be distributed across brokers and processed concurrently by consumers. Ordering is maintained within a partition, not automatically across the entire topic.


82. Interview Question: How Does Kafka Preserve Ordering?#

Kafka preserves record order within a partition. To preserve order for a business entity, use a stable partition key such as user ID or order ID so related events are routed to the same partition.


83. Interview Question: What Is Consumer Lag?#

Consumer lag is the difference between the latest available position in a partition and the consumer group's processed/committed position. Growing lag indicates that consumers are falling behind the incoming workload.


84. Interview Question: Why Does Kafka Support Replay?#

Kafka retains records according to configured retention policies, while consumers track their own offsets. A consumer can therefore start from an earlier retained position and process historical events again.


85. Interview Question: What Is a Consumer Group?#

A consumer group is a set of consumers that cooperate to process partitions of a topic. Within a group, a partition is normally assigned to one consumer at a time, enabling horizontal work distribution.


86. Interview Question: Why Use Kafka Instead of Direct HTTP Calls?#

Kafka can provide:

decoupling
buffering
asynchronous processing
replay
fan-out
independent consumer scaling

Direct HTTP calls may still be better when:

the caller needs an immediate response

The decision depends on communication semantics.


87. Mini Project#

Build a small event-driven order platform.

Components#

Order API
   |
   v
Kafka
   |
   +---- Inventory Consumer
   |
   +---- Notification Consumer
   |
   +---- Analytics Consumer

Implement events:

OrderCreated
OrderPaid
OrderCancelled
OrderShipped

Use:

orderId

as the partition key so one order's lifecycle remains ordered.


88. Mini Project — Requirements#

Implement:

Producer#

POST /orders

Publish:

OrderCreated

Inventory Consumer#

Consumes:

OrderCreated

Notification Consumer#

Consumes:

OrderCreated
OrderShipped
OrderCancelled

Analytics Consumer#

Consumes all order events.

Store:

orders
order_events
analytics

in appropriate persistence layers.


89. Advanced Mini Project Features#

Add:

consumer groups
multiple partitions
consumer lag monitoring
retry topic
dead-letter topic
idempotency
schema version
outbox pattern
event replay
metrics
distributed tracing

Then simulate:

consumer crash
broker failure
duplicate event
slow consumer
traffic spike
hot partition
schema change

Observe how the architecture behaves.


90. Production Checklist#

Before calling a Kafka architecture production-ready:

[ ] Partition strategy
[ ] Partition key defined
[ ] Capacity planned
[ ] Replication configured
[ ] Durability requirements defined
[ ] Producer acknowledgement strategy
[ ] Idempotent producer where needed
[ ] Consumer groups designed
[ ] Offset strategy
[ ] Consumer lag monitoring
[ ] Retry strategy
[ ] DLQ strategy
[ ] Idempotent consumers
[ ] Schema evolution
[ ] Replay strategy
[ ] Retention policy
[ ] Security
[ ] Encryption
[ ] Monitoring
[ ] Alerting
[ ] Backup/recovery plan
[ ] Multi-region requirements
[ ] Cost model

91. Key Mental Model#

Think about Kafka as:

              Kafka Cluster
                    |
          +---------+---------+
          |         |         |
          v         v         v
        Topic     Topic     Topic
          |
     +----+----+----+
     |    |    |    |
     v    v    v    v
    P0   P1   P2   P3
     |    |    |    |
     +----+----+----+
          |
      Consumer Groups
       /      |      \
      v       v       v
 Analytics Inventory Notifications

The most important relationship is:

Topic
  ↓
Partitions
  ↓
Offsets
  ↓
Consumer Groups
  ↓
Independent processing

92. Chapter Summary#

The key concepts from this chapter are:

  1. Kafka is a distributed event-streaming platform.
  2. Topics contain records.
  3. Topics are divided into partitions.
  4. Partitions provide scalability and ordered logs.
  5. Ordering is guaranteed within a partition.
  6. Partition keys determine where related records are routed.
  7. Consumer groups distribute partition processing.
  8. Multiple consumer groups provide fan-out.
  9. Consumers track offsets.
  10. Consumer lag measures processing delay.
  11. Kafka retains records according to retention policies.
  12. Retention enables replay.
  13. Replication protects partition data from broker failures.
  14. Leaders and followers coordinate replicated partitions.
  15. ISR represents replicas considered in sync.
  16. Producer acknowledgements affect durability and latency.
  17. Idempotent producers reduce duplicate writes from retries.
  18. Consumer rebalancing redistributes partitions.
  19. At-least-once processing still requires idempotency.
  20. Kafka transactions can provide stronger guarantees within supported boundaries.
  21. External side effects still need their own reliability design.
  22. The outbox pattern helps bridge database changes and event publication.
  23. CDC can stream database changes into Kafka.
  24. Kafka can support event-driven architectures and replay.
  25. CQRS can use Kafka to build derived read models.
  26. Event sourcing stores state-changing events as history.
  27. Kafka Streams enables continuous event processing.
  28. Windowing supports time-based stream analytics.
  29. Schema evolution must be designed explicitly.
  30. Partition design is one of the most important Kafka architecture decisions.

The core principle is:

Partition for scale.
Key for ordering.
Offset for position.
Replication for durability.
Consumer groups for parallelism.
Retention for replay.
Idempotency for correctness.

93. Interview Revision Checklist#

You should now be able to explain:

  • What Kafka is.
  • Kafka vs a traditional message queue.
  • Broker.
  • Cluster.
  • Topic.
  • Partition.
  • Record.
  • Offset.
  • Producer.
  • Consumer.
  • Consumer group.
  • Partition key.
  • Per-key ordering.
  • Global ordering limitations.
  • Consumer lag.
  • Replication.
  • Leader/follower.
  • ISR.
  • Producer acknowledgements.
  • Retention.
  • Replay.
  • Consumer commits.
  • Rebalancing.
  • Idempotent producers.
  • Idempotent consumers.
  • Kafka transactions.
  • Exactly-once processing limitations.
  • Schema evolution.
  • Schema registry.
  • Event sourcing.
  • CQRS.
  • CDC.
  • Kafka Streams.
  • Windowing.
  • Event time vs processing time.
  • Late events.
  • Hot partitions.
  • Partition capacity planning.
  • Kafka security.
  • Kafka observability.
  • Kafka multi-region architecture.

94. Next Chapter#

Chapter 21 — Event-Driven Architecture#

In the next chapter we will move from Kafka mechanics to the architecture style built around events.

We will learn:

  • What Event-Driven Architecture (EDA) is
  • Events vs commands vs queries
  • Event producers and consumers
  • Event brokers
  • Event choreography
  • Orchestration
  • Event notification
  • Event-carried state transfer
  • Event sourcing
  • CQRS
  • Saga patterns
  • Distributed workflows
  • Eventual consistency
  • Idempotency
  • Duplicate events
  • Ordering
  • Schema evolution
  • Event versioning
  • Retry and dead-letter strategies
  • Observability
  • Failure handling
  • Microservices with events
  • Real-world EDA architectures
  • E-commerce case study
  • Payment workflow case study
  • Notification architecture
  • System-design interview questions

Finished this chapter?

Mark it as complete to track your mastery.

Previous ChapterChapter 19 — Message QueuesNext ChapterChapter 21 — Event-Driven Architecture
PrevNext