Kafka with Microservices
Overview
Kafka enables event-driven microservices architecture with patterns like event sourcing, CQRS, and saga orchestration. This guide covers implementing these patterns for scalable, resilient distributed systems.
Benefits of Event-Driven Architecture
- Decoupling: Services communicate via events
- Scalability: Independent scaling of producers/consumers
- Resilience: Fault isolation between services
- Auditability: Complete event history
- Flexibility: Easy addition of new consumers
Those benefits are real, and so is the bill that comes with them. Once services coordinate through events instead of calls, a write is no longer confirmed by a response: it is confirmed by an event other services eventually process, so every reader must tolerate a read model that is seconds behind and every writer must assume its event may be delivered twice. Distributed transactions cannot help, because the database commit and the Kafka produce happen in two systems, and two-phase commit across them would cost exactly the availability the architecture was meant to buy. What replaces the transaction is design discipline: events as immutable facts, consumers that treat duplicates as no-ops, sagas that compensate instead of roll back, and a dead-letter path for records that will never succeed. Teams that adopt the patterns without the discipline end up with a system that is harder to debug than the monolith it replaced, which is why the sections below pair each pattern with the failure it prevents.
Event Sourcing
An event-sourced aggregate keeps no mutable row at all: the current state is whatever you get by folding every event for that aggregate in order, which makes the event log both the source of truth and the audit trail. The whole design rests on ordering, and ordering in Kafka is a property of a partition, so the partition key must be the aggregate id. With that key, all events for one order land in one partition, one consumer handles them sequentially, and the fold is deterministic; key by anything else and two events for the same order can be processed by different consumers in different orders, after which the state is simply wrong in a way no test on a single-machine queue will catch.
Ordering then pushes on topic layout. The sample below routes each event type to its own topic, which reads naturally and keeps topics small, but it forfeits cross-event ordering for an aggregate: OrderCreated and PaymentProcessed in separate topics can be consumed in either order. Production systems usually write every event of one aggregate to a single topic keyed by aggregate id, or accept the risk only where the reader can deduce order from timestamps embedded in the data. Replay cost is the second constraint: folding ten thousand events to answer one query is fine occasionally and unacceptable on every request, so aggregates that grow long get periodic snapshots stored alongside the log, with the fold restarting from the most recent snapshot instead of from event zero.
Event Store Implementation
Event Store Implementation
from kafka import KafkaProducer
from datetime import datetime
import json
import uuid
class EventStore:
def __init__(self, bootstrap_servers):
self.producer = KafkaProducer(
bootstrap_servers=bootstrap_servers,
value_serializer=lambda v: json.dumps(v).encode('utf-8'),
key_serializer=lambda k: k.encode('utf-8')
)
def append_event(self, aggregate_id, event_type, data, metadata=None):
event = {
'event_id': str(uuid.uuid4()),
'aggregate_id': aggregate_id,
'event_type': event_type,
'data': data,
'timestamp': datetime.utcnow().isoformat(),
'metadata': metadata or {}
}
# Use aggregate_id as key for ordering
self.producer.send(
f'{event_type.lower()}-events',
key=aggregate_id,
value=event
)
return event['event_id']
def get_events(self, aggregate_id, from_version=0):
# Query event store for aggregate events
pass
# Usage
event_store = EventStore('kafka:9092')
# Create order
order_id = str(uuid.uuid4())
event_store.append_event(
aggregate_id=order_id,
event_type='OrderCreated',
data={
'customer_id': 'cust-123',
'items': [{'product_id': 'prod-456', 'quantity': 2}],
'total': 99.99
}
)
# Add payment
event_store.append_event(
aggregate_id=order_id,
event_type='PaymentProcessed',
data={
'payment_id': 'pay-789',
'amount': 99.99,
'method': 'credit_card'
}
)
Event Replay
class EventReplayer:
def __init__(self, event_store):
self.event_store = event_store
def rebuild_state(self, aggregate_id):
events = self.event_store.get_events(aggregate_id)
state = {}
for event in events:
state = self.apply_event(state, event)
return state
def apply_event(self, state, event):
if event['event_type'] == 'OrderCreated':
return {
'id': event['aggregate_id'],
'status': 'created',
'customer_id': event['data']['customer_id'],
'items': event['data']['items'],
'total': event['data']['total'],
'version': 1
}
elif event['event_type'] == 'PaymentProcessed':
state['status'] = 'paid'
state['payment_id'] = event['data']['payment_id']
state['version'] += 1
return state
elif event['event_type'] == 'OrderShipped':
state['status'] = 'shipped'
state['tracking_number'] = event['data']['tracking_number']
state['version'] += 1
return state
return state
CQRS (Command Query Responsibility Segregation)
Splitting the write model from the read model buys two things and costs one. It buys independent scaling â the projection can be a denormalized table shaped exactly for the screen while the event store stays append-only â and it buys freedom to add a new read model later without touching the write path. What it costs is consistency: after a command returns, the read model may not reflect it for hundreds of milliseconds, so the interface must either show a pending state or read its confirmation from the write side. Hiding that gap is a product decision, not a database one.
Projections are where the pattern usually breaks. They consume the same event stream as every other consumer, which means they must be idempotent, because a rebalance or a replay after a bug fix will hand them events they already applied; inserting a row that already exists should be an update or a skip, never a duplicate-key failure that stops the projection entirely. Projections must also be rebuildable from the log: if the read model can be regenerated by starting a fresh consumer at offset zero, the schema of the read side can change whenever the product needs it, and the time to rebuild becomes the real measure of how event-driven the system actually is. Anything written to the read model by the command handler itself reintroduces the dual-write problem this pattern exists to remove.
Command Handler
Command Handler
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import List
@dataclass
class CreateOrderCommand:
customer_id: str
items: List[dict]
total: float
@dataclass
class ProcessPaymentCommand:
order_id: str
amount: float
payment_method: str
class CommandHandler(ABC):
@abstractmethod
def handle(self, command):
pass
class OrderCommandHandler(CommandHandler):
def __init__(self, event_store, validation_service):
self.event_store = event_store
self.validator = validation_service
def handle(self, command):
if isinstance(command, CreateOrderCommand):
return self.handle_create_order(command)
elif isinstance(command, ProcessPaymentCommand):
return self.handle_process_payment(command)
def handle_create_order(self, command):
# Validate command
if not self.validator.validate_order(command):
raise ValueError("Invalid order")
# Generate order ID
order_id = str(uuid.uuid4())
# Create order event
self.event_store.append_event(
aggregate_id=order_id,
event_type='OrderCreated',
data={
'customer_id': command.customer_id,
'items': command.items,
'total': command.total
}
)
return {'order_id': order_id, 'status': 'created'}
Query Handler
class OrderQueryService:
def __init__(self, read_database):
self.db = read_database
def get_order(self, order_id):
return self.db.query(f"SELECT * FROM orders WHERE id = '{order_id}'")
def get_customer_orders(self, customer_id):
return self.db.query(f"SELECT * FROM orders WHERE customer_id = '{customer_id}'")
def get_order_summary(self):
return self.db.query("""
SELECT status, COUNT(*) as count, SUM(total) as revenue
FROM orders
GROUP BY status
""")
Projection Builder
class OrderProjectionBuilder:
def __init__(self, read_database):
self.db = read_database
def handle_event(self, event):
if event['event_type'] == 'OrderCreated':
self.db.insert('orders', {
'id': event['aggregate_id'],
'customer_id': event['data']['customer_id'],
'status': 'created',
'total': event['data']['total'],
'created_at': event['timestamp']
})
elif event['event_type'] == 'PaymentProcessed':
self.db.update('orders',
{'id': event['aggregate_id']},
{'status': 'paid', 'payment_id': event['data']['payment_id']}
)
elif event['event_type'] == 'OrderShipped':
self.db.update('orders',
{'id': event['aggregate_id']},
{'status': 'shipped', 'tracking_number': event['data']['tracking_number']}
)
Saga Pattern
A saga replaces the rollback with compensation: each step does its work and, if a later step fails, the earlier steps undo themselves in reverse order. Two shapes exist and they are not interchangeable. An orchestrator holds the sequence in one place, so the flow is readable, testable and easy to time out, at the cost of a component that must itself be highly available and must store its state somewhere durable â often a Kafka topic keyed by order id, which gives ordered, replayable saga history for free. Choreography scatters the sequence across the services, so no single component can stall, but the flow becomes invisible: to answer "where is this order stuck" you must read four topics and correlate them.
Either shape inherits at-least-once delivery, and that fact dominates the design. The orchestrator may see InventoryReserved twice and must not request payment twice, so each step handler keys its own idempotency record on the saga id plus step number. Missing events are the twin problem: if InventoryReserved never arrives because the inventory service is down, the saga must arm a timeout that fires, decides whether to wait or compensate, and records that decision â an unattended saga is not slow, it is stuck, and stuck sagas hold inventory and money indefinitely. Keep the timeout inside the compensation path rather than in a cron job, and make every compensator safe to run twice, because a redelivery after a partial failure is the normal case, not the exception.
Saga Orchestrator
Saga Orchestrator
class OrderSaga:
def __init__(self, event_store):
self.event_store = event_store
self.state = {}
def start_saga(self, order_id, order_data):
self.state[order_id] = {
'step': 'reserve_inventory',
'data': order_data
}
# Step 1: Reserve inventory
self.event_store.append_event(
aggregate_id=order_id,
event_type='InventoryReservationRequested',
data=order_data['items']
)
def handle_event(self, event):
order_id = event['aggregate_id']
if event['event_type'] == 'InventoryReserved':
# Step 2: Process payment
self.state[order_id]['step'] = 'process_payment'
self.event_store.append_event(
aggregate_id=order_id,
event_type='PaymentRequested',
data={'amount': self.state[order_id]['data']['total']}
)
elif event['event_type'] == 'PaymentProcessed':
# Step 3: Complete order
self.state[order_id]['step'] = 'complete_order'
self.event_store.append_event(
aggregate_id=order_id,
event_type='OrderCompleted',
data={'status': 'completed'}
)
elif event['event_type'] == 'PaymentFailed':
# Compensate: Release inventory
self.state[order_id]['step'] = 'compensate'
self.event_store.append_event(
aggregate_id=order_id,
event_type='InventoryReleaseRequested',
data=self.state[order_id]['data']['items']
)
Saga Choreography
class OrderSagaChoreography:
def __init__(self):
self.handlers = {
'OrderCreated': self.handle_order_created,
'InventoryReserved': self.handle_inventory_reserved,
'PaymentProcessed': self.handle_payment_processed,
'PaymentFailed': self.handle_payment_failed
}
def handle_event(self, event):
handler = self.handlers.get(event['event_type'])
if handler:
return handler(event)
def handle_order_created(self, event):
# Trigger inventory reservation
return {
'event_type': 'InventoryReservationRequested',
'data': event['data']['items']
}
def handle_inventory_reserved(self, event):
# Trigger payment processing
return {
'event_type': 'PaymentRequested',
'data': {'amount': event['data']['total']}
}
def handle_payment_processed(self, event):
# Complete order
return {
'event_type': 'OrderCompleted',
'data': {'status': 'completed'}
}
def handle_payment_failed(self, event):
# Compensate by releasing inventory
return {
'event_type': 'InventoryReleaseRequested',
'data': event['data']['items']
}
Idempotent Consumers
Duplicates are not an edge case in this architecture; they are the documented behaviour of every rebalance, every retry and every replay after a bug fix. An idempotent consumer therefore treats a record it has already processed as a success rather than an error, and the design question is only which key identifies "the same work". Using the business key â order id plus event id â survives a replay from offset zero and a consumer restarting on a different partition, which makes it the right choice for anything with side effects. Using topic, partition and offset is cheaper and perfectly unique for a single record, but it stops matching once the same logical event is re-processed from a different position. The store behind the check needs a lifetime rule too: the dedupe entry must outlive the longest possible redelivery horizon, and since a topic retained for seven days can be replayed a week later, a cache entry with a twenty-four hour expiry silently fails exactly when a replay is most likely.
For side effects that Kafka itself can own â producing to an output topic, committing offsets â the broker's transactional producer and isolation.level=read_committed give exactly-once effects without any of this machinery. Everything outside Kafka, from a payment gateway to a row in PostgreSQL, needs the dedupe store, and the safest pattern is to write the side effect and its idempotency record in the same database transaction, so a crash between the two leaves nothing half-done.
Idempotency Key
Idempotency Key
import hashlib
from functools import wraps
def idempotent_consumer(func):
@wraps(func)
def wrapper(self, message):
# Generate idempotency key
idempotency_key = self.generate_idempotency_key(message)
# Check if already processed
if self.is_processed(idempotency_key):
return {'status': 'skipped', 'reason': 'already_processed'}
# Process message
result = func(self, message)
# Mark as processed
self.mark_processed(idempotency_key)
return result
return wrapper
class OrderProcessor:
def __init__(self, kafka_producer, redis_client):
self.producer = kafka_producer
self.redis = redis_client
def generate_idempotency_key(self, message):
# Use order_id + timestamp as idempotency key
data = f"{message['order_id']}:{message['timestamp']}"
return hashlib.sha256(data.encode()).hexdigest()
def is_processed(self, key):
return self.redis.exists(f"processed:{key}")
def mark_processed(self, key):
self.redis.setex(f"processed:{key}", 86400, '1') # 24 hour TTL
@idempotent_consumer
def process_order(self, message):
# Process order
order = message['data']
# Validate order
if not self.validate_order(order):
raise ValueError("Invalid order")
# Process payment
payment_result = self.process_payment(order)
# Publish payment event
self.producer.send('payment-events', value={
'order_id': order['id'],
'payment_id': payment_result['id'],
'status': 'completed'
})
return {'status': 'processed', 'order_id': order['id']}
Dead Letter Queue
A record that cannot be processed is a problem the consumer must dispose of, not merely report. With manual offset commits, a poison record that throws on every attempt blocks its partition for the whole group, so the only correct behaviour is to route it to a dead-letter topic, commit the original offset, and let the rest of the partition keep flowing; the same record with automatic commits simply gets skipped and vanishes, which is worse. Retries deserve structure before they become dead letters: a bounded number of attempts with exponential backoff, the attempt count carried in a record header so it survives the round trip, and the original topic, partition and offset preserved in the dead-letter payload so an operator can replay the exact record later.
Dead letters accumulate quietly, and the failure mode is a topic nobody reads that grows for six months until the cluster runs out of disk. Alert when the rate rises rather than when a single record arrives, alert again on depth, and give the topic a short retention with an export process, because a dead-letter topic retained forever becomes an unsearched archive of production failures. Replay tooling is the last piece: a small consumer that reads the dead-letter topic, fixes or skips, and re-produces to the original topic with the same key is what turns the queue from a graveyard into a recovery path.
DLQ Handler
DLQ Handler
class DeadLetterHandler:
def __init__(self, kafka_producer, alert_service):
self.producer = kafka_producer
self.alert_service = alert_service
def handle_dead_letter(self, original_message, error):
# Create dead letter message
dead_letter = {
'original_topic': original_message.topic,
'original_partition': original_message.partition,
'original_offset': original_message.offset,
'original_key': original_message.key,
'original_value': original_message.value,
'error': str(error),
'timestamp': datetime.utcnow().isoformat(),
'retry_count': original_message.headers.get('retry_count', 0)
}
# Send to DLQ
self.producer.send('dead-letter-queue', value=dead_letter)
# Alert if too many retries
if dead_letter['retry_count'] >= 3:
self.alert_service.send_alert(
severity='high',
message=f"Message failed after {dead_letter['retry_count']} retries",
details=dead_letter
)
return dead_letter
Best Practices
Service Design
- Single Responsibility: Each service handles one bounded context
- Event Immutability: Events are facts, never modified
- Idempotent Consumers: Handle duplicate messages gracefully
- Saga Pattern: Use for distributed transactions
- Dead Letter Queues: Handle failed messages
Common Patterns
- Event Sourcing: Store all state changes as events
- CQRS: Separate read/write models
- Saga: Coordinate distributed transactions
- Outbox Pattern: Ensure reliable event publishing
- Change Data Capture: Sync databases via events
Common Mistakes
Keying events by a field other than the aggregate id and losing per-aggregate ordering
Fix: Partition by aggregate id so all events for one order reach the same partition and the fold is deterministic
Building SQL strings with an f-string in a query service that takes ids from an event
Fix: Use parameterized queries, because event payloads are attacker-controlled input the moment a topic is writable by another team
Storing idempotency keys with a 24 hour expiry on a topic retained for seven days
Fix: Make the dedupe lifetime exceed the longest redelivery horizon, or write the side effect and the key in one database transaction
Summary
Kafka enables powerful event-driven microservices patterns including event sourcing, CQRS, and saga orchestration. Implement idempotent consumers, dead letter queues, and proper error handling for resilient distributed systems.
See Also
- Kafka Producer & Consumer â Building event-driven producers and consumers
- Kafka Streams & Connect â Using Kafka Streams for microservice data processing
- Kafka Real-World Patterns â Outbox pattern, CDC, and event mesh for microservices