Producers and Consumers
Kafka is fundamentally a data streaming platform that enables applications to exchange events at scale.
At a high level:
- Producers write data into Kafka.
- Kafka stores the data.
- Consumers read the data from Kafka.
Everything that happens in Kafka revolves around this simple flow.
Understanding Producers and Consumers is essential because they are the primary interfaces through which applications interact with Kafka.
The Producer Side
A Producer is an application that publishes records to Kafka.
Examples:
- E-commerce application sending order events
- Payment service sending payment events
- Mobile application sending analytics events
- Web server sending logs
Example event:
{
"orderId": 1001,
"customerId": 500,
"amount": 1500
}
The application generating this event is acting as a producer.
Producer Responsibilities
A Kafka Producer is responsible for:
- Creating records
- Determining the target topic
- Determining the target partition
- Sending records to brokers
- Retrying failed requests
- Handling acknowledgements
- Ensuring delivery guarantees
Producer Architecture
A producer is not just a simple network client.
Internally it contains several components.
Serializer
Kafka transmits bytes across the network.
Before sending data, Kafka converts objects into byte arrays.
Example:
{
"orderId": 1001
}
may become:
7B226F726465724964223A313030317D
Common serializers:
- String Serializer
- JSON Serializer
- Avro Serializer
- Protobuf Serializer
Partitioner
The partitioner decides where a record should be stored.
Example:
Topic: orders
Partitions: 3
The partitioner chooses:
Partition 0
Partition 1
Partition 2
for each record.
Buffer Memory
Producers do not immediately send every message.
Instead, records are temporarily stored in memory.
This allows batching.
Sender Thread
A background thread continuously sends accumulated batches to Kafka brokers.
The application thread remains free to continue processing.
Producer Workflow
The lifecycle of a record looks like:
Step 1: Create Record
Application generates an event.
{
"userId": 101,
"action": "LOGIN"
}
Step 2: Serialization
Record converted into bytes.
Step 3: Partition Selection
Producer determines target partition.
Step 4: Buffering
Record stored in memory.
Step 5: Batching
Multiple records combined together.
Batching significantly improves throughput.
Step 6: Network Transmission
Batch sent to broker.
Step 7: Acknowledgement
Broker confirms successful write.
Producer Partitioning Strategies
Partitioning is one of Kafka's most important concepts.
It determines:
- Scalability
- Ordering
- Load Distribution
Round Robin Partitioning
Messages distributed evenly.
Example:
Message 1 → Partition 0
Message 2 → Partition 1
Message 3 → Partition 2
Message 4 → Partition 0
Advantages:
- Even distribution
- Excellent load balancing
Disadvantages:
- Ordering across related records lost
Key-Based Partitioning
Kafka hashes the key.
Partition = hash(key) % totalPartitions
Example:
User 101
always maps to the same partition.
Advantages:
- Ordering preserved for a given key
Disadvantages:
- Poor key distribution may create hot partitions
Sticky Partitioning
When records have no key, Kafka attempts to keep sending records to the same partition temporarily.
Benefits:
- Larger batches
- Better throughput
Custom Partitioners
Applications may implement custom logic.
Example:
Premium Users → Partition 0
Regular Users → Partition 1
Useful for specialized workloads.
Producer Acknowledgements
After writing data, brokers send acknowledgements.
The producer controls how much confirmation it requires.
acks = 0
Producer does not wait.
No confirmation returned.
Advantages:
- Lowest latency
Disadvantages:
- Possible message loss
acks = 1
Producer waits for leader acknowledgement.
Advantages:
- Good balance
Disadvantages:
- Data may still be lost if leader crashes before replication
acks = all
Producer waits for all in-sync replicas.
Advantages:
- Maximum durability
Disadvantages:
- Higher latency
Producer Delivery Guarantees
Kafka supports three delivery models.
At Most Once
Message may be lost.
Message never duplicated.
0 or 1 delivery
At Least Once
Message never lost.
Duplicate delivery possible.
1 or more deliveries
Most common production setup.
Exactly Once
Message delivered exactly one time.
Exactly 1 delivery
Requires:
- Idempotent Producer
- Transactions
The Consumer Side
A Consumer reads records from Kafka.
Examples:
- Order Processing Service
- Notification Service
- Analytics Service
- Fraud Detection Service
Consumer Responsibilities
Consumers:
- Subscribe to topics
- Fetch records
- Process records
- Track offsets
- Handle failures
Consumer Architecture
Internally, consumers are simpler than producers.
Fetcher
Fetches records from brokers.
Poll Loop
Applications continuously call:
consumer.poll(...)
to retrieve records.
Kafka uses a pull-based model.
Why Pull Instead of Push?
Push Model:
Potential issue:
Consumer overwhelmed.
Pull Model:
Consumer controls consumption speed.
This improves scalability.
Consumer Workflow
Step 1: Subscribe
Consumer subscribes to topic.
consumer.subscribe(...)
Step 2: Poll
Fetch records from broker.
Step 3: Process
Business logic executes.
Example:
Send Email
Update Database
Generate Invoice
Step 4: Commit Offset
Consumer stores progress.
Step 5: Continue
Process repeats forever.
Consumer Groups
Consumer Groups are one of Kafka's most powerful features.
Why Consumer Groups Exist
Without groups:
Only one consumer processes everything.
Scaling becomes difficult.
Consumer Group Concept
Kafka distributes partitions among consumers.
Partition Assignment
Suppose:
Topic Partitions = 3
Consumers = 3
Assignment:
Each partition belongs to only one consumer within the group.
More Consumers Than Partitions
Example:
Partitions = 3
Consumers = 5
Extra consumers remain idle.
More Partitions Than Consumers
Example:
Partitions = 6
Consumers = 3
Consumers process multiple partitions.
Consumer Rebalancing
A rebalance occurs whenever partition ownership changes.
Common Triggers
New Consumer Joins
Consumer 4 Added
Partitions reassigned.
Consumer Leaves
Consumer 2 Crashed
Remaining consumers receive its partitions.
Partition Count Changes
Topic partitions increased.
Reassignment required.
Rebalance Example
Before:
After Consumer 3 Joins:
Rebalance Cost
During rebalancing:
- Consumption pauses
- Ownership changes
- Offset synchronization occurs
Frequent rebalances reduce throughput.
Consumer Offset Management
Offsets represent consumer progress.
Automatic Commit
Kafka periodically commits offsets.
enable.auto.commit=true
Advantages:
- Simple
Disadvantages:
- Potential message loss
Manual Commit
Application controls commits.
Advantages:
- Greater reliability
Disadvantages:
- More complexity
Commit After Processing
Preferred pattern:
If processing succeeds:
Commit.
If processing fails:
Do not commit.
Record can be retried.
End-to-End Producer to Consumer Flow
The complete flow looks like:
Detailed sequence: