Message Streams & Kafka Essentials
Learn how message streams differ from queues by allowing multiple consumer types to read the same messages. Master Apache Kafka fundamentals like topics, partitions, and consumer groups.
Unlike message queues where one consumer grabs a message, message streams let multiple different types of consumers read the same message. This unlocks powerful patterns like processing the same event for search indexing AND analytics simultaneously.
EXERCISE
1The Problem: Multiple Actions, One Event
When a blog post is published, you need to index it in search AND update the authors post count. Using separate queues risks inconsistency if one fails. Message streams solve this elegantly.
The Scenario: Publishing a Blog
You're building Medium. When a user publishes a blog post, you need to:
- Index it in Elasticsearch (for search functionality)
- Increment author post count in the
Attempt 1: One Consumer Does Both
pushes message → RabbitMQ → Consumer reads it → Indexes to Elasticsearch → Updates database
Problem: What if Elasticsearch succeeds but database update fails before completion? Search shows 5 posts, but author profile shows 4. Data inconsistency.
Attempt 2: Two Separate Queues
API pushes to Queue A (for search) AND Queue B (for counter).
Problem: What if API crashes after writing to Queue A but before Queue B? Still inconsistent.
Root Cause: Multiple writes from one source create failure points.
Solution Needed: Write once, read by many different consumer types.
EXERCISE
2Message Streams: Write Once, Read Many
Message streams let multiple consumer types (search indexers, counters, analytics) all read the same messages independently, each at their own pace.
How Message Streams Work
Key Difference from Queues:
Message Queue: One message → One random consumer from a pool of identical workers
Message Stream: One message → Multiple different types of consumers
The Kafka Solution
When blog is published:
- API writes ONE event to Kafka:
{userId: 123, postId: 456, title: "..."} - Search Consumer Group reads this event → Indexes to Elasticsearch
- Counter Consumer Group reads THE SAME event → Updates post count
- Analytics Consumer Group could also read it → Logs to data warehouse
All three consume independently. If one crashes, others continue unaffected.
Messages Are Not Deleted
Unlike queues where consumed messages disappear, stream messages persist. Consumers iterate through them like reading a book. You can rewind and reprocess historical events anytime.
Real-World Benefits
Instagram: When you post a photo, one event triggers:
- Feed generation
- Notification dispatch
- Search indexing
- Analytics logging
- ML recommendation updates
All from one event in Kafka.
EXERCISE
3Topics and Partitions
Kafka organizes messages into topics (like channels). Each topic splits into partitions for parallel processing, dramatically improving throughput.
Topics: Organizing Events
A topic is a category of messages. Examples:
blog-publisheduser-registeredpayment-completed
When publishing a blog, you write to the blog-published topic.
Partitions: Enabling Parallelism
Each topic has multiple partitions (configurable, e.g., 3 partitions).
Why? One pipe processes messages sequentially. Three pipes process three messages simultaneously.
Partition Keys: Maintaining Order
Messages include a partition key (e.g., userId). Kafka hashes this key to determine which partition receives the message.
Critical Property: All messages with the same key go to the SAME partition.
Example: User 123's posts always go to Partition 2. This guarantees order for that user's events.
Math: With 3 partitions and 1 million users:
- Hash(userId) % 3 determines partition
- Each partition handles ~333,000 users
- Messages for user 123 always land in the same partition
Balancing Load
Hash functions distribute users evenly across partitions. No single partition becomes a bottleneck.
Visual Flow
API → Kafka Topic "blog-published"
├─ Partition 0 (Users: 1, 4, 7, 10...)
├─ Partition 1 (Users: 2, 5, 8, 11...)
└─ Partition 2 (Users: 3, 6, 9, 12...)
Each partition independently stores its messages in order.
EXERCISE
4Consumer Groups and Parallel Processing
Consumer groups enable multiple workers to process messages in parallel, with Kafka intelligently assigning partitions to avoid duplicate processing.
Consumer Groups: Coordinating Workers
A consumer group is a set of consumers with the same group ID working together.
Example: Search indexing service has 3 workers, all in consumer group search-indexers.
Partition Assignment
Rule: One partition can be read by only ONE consumer in a group at a time.
Scenario: 3 partitions, 3 consumers in group
Partition 0 → Consumer A
Partition 1 → Consumer B
Partition 2 → Consumer C
Perfect parallelism. Each consumer handles one partition.
Scaling Scenarios
Fewer Consumers Than Partitions (3 partitions, 1 consumer):
Consumer A reads from ALL three partitions. Slower but works.
Equal Consumers and Partitions (3 partitions, 3 consumers):
Optimal. Each consumer handles one partition.
More Consumers Than Partitions (3 partitions, 5 consumers):
Only 3 consumers work. Consumers D and E sit idle with no assigned partitions.
Lesson: Maximum parallelism = number of partitions. Want 5 parallel consumers? Create 5+ partitions.
Multiple Consumer Groups
Different groups read independently:
Partition 0
├─ Search Consumer (Group: search-indexers)
├─ Counter Consumer (Group: post-counters)
└─ Analytics Consumer (Group: analytics-processors)
All three groups iterate through the SAME messages independently.
Independent Progress
Search group might be on message 100.
Counter group might be on message 500.
Analytics group might be on message 50.
Each group tracks its own position. Slow consumers do not block fast ones.
EXERCISE
5Offsets and Resumability
Offsets track which messages consumers have processed, enabling resumption after crashes without losing progress or reprocessing everything.
What Are Offsets?
Each message in a partition gets a unique offset - a sequential number starting from 0.
Partition 0: [Msg0, Msg1, Msg2, Msg3, Msg4...]
Offsets: 0 1 2 3 4
Tracking Progress
Consumers commit offsets to Kafka after processing messages.
Example: Search consumer processes messages 0-5, then commits offset 5.
Kafka remembers: "Search group last read up to offset 5 in Partition 0."
Resuming After Failure
Consumer crashes after processing message 10 but before message 11.
On restart, it asks Kafka: "Where did I leave off?"
Kafka replies: "You committed offset 10."
Consumer resumes from offset 11. No messages lost. No duplicate processing (assuming proper commit logic).
Per-Group Offsets
Each consumer group maintains separate offsets.
Partition 0:
Search Group: Offset 100
Counter Group: Offset 500
Analytics Group: Offset 25
Groups progress independently without interfering.
Commit Strategies
Auto-commit: Kafka auto-commits periodically. Simple but risky if consumer crashes between processing and commit.
Manual commit: Consumer explicitly commits after successful processing. More control, safer.
Best practice: Process message → Verify success → Commit offset.
Unlike Message Queues
In RabbitMQ, you delete messages after processing.
In Kafka, you commit offsets. Messages remain in Kafka for other consumers and potential reprocessing.
Retention Policy
Messages do not live forever. Configure retention:
- Time-based: Delete messages older than 14 days
- Size-based: Delete oldest messages when partition exceeds 1TB
Default: Messages stay long enough for all consumer groups to process them.
EXERCISE
6Kafka in Production: Key Takeaways
Understanding partitions, consumer groups, and offsets is essential for building scalable event-driven systems with Kafka in production environments.
Essential Kafka Concepts Summary
Topic: Category of events (e.g., orders, users, payments)
Partition: Subdivision of topic enabling parallel processing
Partition Key: Determines which partition receives a message (ensures ordering for same key)
Consumer Group: Set of consumers cooperating to process messages
Offset: Sequential position of message in partition; used for tracking progress
Commit: Recording processed offset to enable resumption
Parallelism Formula
Maximum parallel consumers per group = Number of partitions
Want 10 workers processing in parallel? Create 10+ partitions.
Real-World Usage
Uber: Trip events partitioned by trip ID. All events for one trip stay ordered in same partition.
Netflix: Viewing events partitioned by user ID. Recommendations processed per user without mixing data.
LinkedIn: Activity stream partitioned by member ID. News feed updates maintain correct chronological order per user.
Design Decisions
How many partitions?
Start with 3-10 for development. Production systems use 30-100+ based on throughput needs.
Partition key selection?
Choose keys providing even distribution and maintaining necessary ordering. User ID and entity ID are common choices.
Retention period?
Balance storage costs vs. reprocessing needs. 7-30 days is typical. Some systems keep data forever for complete event history.
Getting Hands-On
Practice locally:
- Install Kafka on your machine
- Create topic with 3 partitions
- Write producer pushing messages with partition keys
- Create consumer group with 2 consumers
- Observe how partitions get assigned
- Crash one consumer, watch rebalancing
- Commit offsets and restart consumer
Understanding Kafka deeply requires experimentation. Theory plus hands-on practice builds true mastery.
Why Kafka Dominates
Scalability: Handle millions of messages per second
Durability: Messages persist until retention expires
Flexibility: Multiple consumer types process same events
Performance: Partitions enable massive parallelism
Reliability: Offsets ensure exactly-once or at-least-once processing
These properties make Kafka the standard for event-driven architectures at scale.
