Kafka Real-World Patterns
Overview
Real-world Kafka deployments require proven patterns for reliability, scalability, and maintainability. This guide covers event mesh, circuit breaker, outbox pattern, change data capture, and event replay.
Pattern Categories
- Reliability: Circuit breaker, outbox pattern
- Scalability: Event mesh, partitioning
- Data Sync: CDC, event replay
- Idempotency: Idempotency keys, deduplication
Each pattern here answers a specific way that a naΓ―ve integration fails, and the fastest way to choose one is to name the failure first. A service that writes to a database and then produces to Kafka will eventually do one without the other; that is the outbox. A consumer that calls a slow payment gateway until the thread pool is exhausted needs a circuit breaker. A downstream system that must see the same rows as the source needs change data capture. A team that needs yesterday's data again, or a new consumer that wants history, needs replay. Reach for an event mesh only when several domains genuinely exchange events across boundaries, because the mesh multiplies every produce and consume operation by the number of interested services, and a fan-out that looks tidy in a diagram becomes a capacity question when the twentieth subscriber joins and the original producer's broker absorbs all of it.
Event Mesh Pattern
An event mesh is a routing discipline layered on clusters, not a new broker. Services publish in their own domain, subscriptions are declared as data rather than discovered by scanning every topic, and the routing layer moves events between clusters so that a consumer in one datacenter does not poll a cluster in another. The declaration is the valuable artifact: once publishes and subscribes live in version control, you can answer who depends on OrderCreated without archaeology, and you can refuse a subscription that would cross a trust boundary. The cost is indirection, because debugging now means asking why the router decided an event should not have arrived, so keep the routing rules small, deterministic and testable rather than expressive.
Event Mesh Topology
class EventMesh:
def __init__(self, kafka_clusters):
self.clusters = kafka_clusters
self.topics = {}
self.routes = {}
def register_service(self, service_name, topics, cluster):
"""Register a service with its topics"""
self.topics[service_name] = {
'topics': topics,
'cluster': cluster
}
def route_event(self, event, source_service):
"""Route event to appropriate consumers"""
consumers = self.get_consumers_for_event(event['type'])
for consumer in consumers:
cluster = self.topics[consumer]['cluster']
topic = self.topics[consumer]['topics'][event['type']]
self.send_to_cluster(cluster, topic, event)
def get_consumers_for_event(self, event_type):
"""Find all consumers interested in this event"""
consumers = []
for service, config in self.topics.items():
if event_type in config['topics']:
consumers.append(service)
return consumers
Event Routing Configuration
# event_mesh_config.yml
services:
order-service:
cluster: dc1
publishes:
- OrderCreated
- OrderUpdated
- OrderCancelled
subscribes:
- PaymentProcessed
- InventoryReserved
payment-service:
cluster: dc1
publishes:
- PaymentProcessed
- PaymentFailed
subscribes:
- OrderCreated
notification-service:
cluster: dc2
publishes: []
subscribes:
- OrderCreated
- PaymentProcessed
- OrderShipped
routing_rules:
OrderCreated:
- payment-service
- notification-service
- analytics-service
PaymentProcessed:
- order-service
- notification-service
- inventory-service
Circuit Breaker Pattern
The breaker protects the caller, not the dependency. Its value appears under partial failure: a payment API that answers in two seconds instead of two hundred slows every consuming thread, and once the thread pool and the connection pool are spent, the failure spreads to calls that were never broken. Opening the circuit converts a slow degradation into a fast, visible error, and the caller's fallback β queue the payment, return a pending state, serve the cached quote β becomes a deliberate product choice instead of an emergency.
Thresholds are where teams get the tuning wrong. Five failures is a sensible default only if failures are counted inside a rolling window; counting them for all time means one bad minute in March keeps the circuit open forever, and counting without a window makes a single blip during a deploy look like an outage. A thirty-second recovery timeout followed by a half-open probe is a good starting shape: the circuit admits one trial call, closes on success and reopens on the first failure, which keeps recovery attempts rare without needing an operator. Track how often the breaker opens as a first-class metric, because a circuit that opens every morning at nine is telling you about a scheduled job downstream, not about a flaky network.
Circuit Breaker Implementation
import time
from enum import Enum
class CircuitState(Enum):
CLOSED = "closed"
OPEN = "open"
HALF_OPEN = "half_open"
class CircuitBreaker:
def __init__(self, failure_threshold=5, recovery_timeout=30):
self.failure_threshold = failure_threshold
self.recovery_timeout = recovery_timeout
self.failure_count = 0
self.state = CircuitState.CLOSED
self.last_failure_time = None
def call(self, func, *args, **kwargs):
if self.state == CircuitState.OPEN:
if self._should_attempt_reset():
self.state = CircuitState.HALF_OPEN
else:
raise CircuitBreakerOpenError("Circuit breaker is open")
try:
result = func(*args, **kwargs)
self._on_success()
return result
except Exception as e:
self._on_failure()
raise
def _on_success(self):
self.failure_count = 0
self.state = CircuitState.CLOSED
def _on_failure(self):
self.failure_count += 1
self.last_failure_time = time.time()
if self.failure_count >= self.failure_threshold:
self.state = CircuitState.OPEN
def _should_attempt_reset(self):
return (time.time() - self.last_failure_time) >= self.recovery_timeout
# Usage with Kafka producer
class KafkaProducerWithCircuitBreaker:
def __init__(self, bootstrap_servers):
self.producer = KafkaProducer(bootstrap_servers=bootstrap_servers)
self.circuit_breaker = CircuitBreaker(failure_threshold=5)
def send(self, topic, message):
return self.circuit_breaker.call(
self.producer.send,
topic,
value=json.dumps(message).encode()
)
Circuit Breaker Configuration
# Circuit breaker for external service calls
circuit_breaker = CircuitBreaker(
failure_threshold=3, # Open after 3 failures
recovery_timeout=60, # Try recovery after 60 seconds
expected_exceptions=[ConnectionError, TimeoutError]
)
# Decorator usage
@circuit_breaker.decorator
def call_external_service(data):
response = requests.post('http://external-service/api', json=data)
response.raise_for_status()
return response.json()
Outbox Pattern
The outbox removes the dual write by making the database the single writer: the business row and the event row are inserted in one transaction, so either both exist or neither does. Everything after that is about moving the event row onto a topic without losing or reordering it, and three failure modes decide whether your implementation is correct. First is ordering: two poller workers selecting the same unprocessed rows will happily produce them out of order, so either run a single poller per database shard or partition work by aggregate id and keep per-aggregate order inside each worker. Second is acknowledgement: marking rows published before the broker confirms the write loses events on a crash, so wait for the producer future or flush the batch before committing the state change. Third is latency: a one-second poll means at least one second of end-to-end delay on a path that was supposed to feel synchronous, which is why production systems increasingly replace the poller with a log-based connector reading the outbox table's write-ahead log and forwarding changes within milliseconds. Whatever the transport, delete or archive published rows in batches, or the table grows until it rivals the business data it serves.
Transactional Outbox
from sqlalchemy import create_engine, Column, String, Text, DateTime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from datetime import datetime
import json
Base = declarative_base()
class OutboxEvent(Base):
__tablename__ = 'outbox_events'
id = Column(String(36), primary_key=True)
aggregate_type = Column(String(255), nullable=False)
aggregate_id = Column(String(36), nullable=False)
event_type = Column(String(255), nullable=False)
payload = Column(Text, nullable=False)
created_at = Column(DateTime, default=datetime.utcnow)
published = Column(String(1), default='N')
class OrderService:
def __init__(self, db_session, kafka_producer):
self.session = db_session
self.producer = kafka_producer
def create_order(self, order_data):
# 1. Create order in database
order = Order(**order_data)
self.session.add(order)
# 2. Create outbox event in same transaction
outbox_event = OutboxEvent(
id=str(uuid.uuid4()),
aggregate_type='Order',
aggregate_id=order.id,
event_type='OrderCreated',
payload=json.dumps({
'order_id': order.id,
'customer_id': order.customer_id,
'total': order.total
})
)
self.session.add(outbox_event)
# 3. Commit transaction
self.session.commit()
return order
class OutboxProcessor:
def __init__(self, db_session, kafka_producer):
self.session = db_session
self.producer = kafka_producer
def process_outbox(self):
# 1. Read unpublished events
events = self.session.query(OutboxEvent)\
.filter(OutboxEvent.published == 'N')\
.all()
for event in events:
# 2. Publish to Kafka
self.producer.send(
f'{event.aggregate_type.lower()}-events',
key=event.aggregate_id.encode(),
value=event.payload.encode()
)
# 3. Mark as published
event.published = 'Y'
self.session.commit()
Outbox Polling
class OutboxPoller:
def __init__(self, db_session, kafka_producer, poll_interval=1):
self.session = db_session
self.producer = kafka_producer
self.poll_interval = poll_interval
def start_polling(self):
while True:
try:
self.process_pending_events()
except Exception as e:
print(f"Error processing outbox: {e}")
time.sleep(self.poll_interval)
def process_pending_events(self):
with self.session.begin():
events = self.session.query(OutboxEvent)\
.filter(OutboxEvent.published == 'N')\
.limit(100)\
.all()
for event in events:
self.publish_event(event)
event.published = 'Y'
def publish_event(self, event):
self.producer.send(
f'{event.aggregate_type.lower()}-events',
key=event.aggregate_id.encode(),
value=event.payload.encode()
)
Change Data Capture (CDC)
Change data capture turns the database's own log into an event stream, which avoids instrumenting every service that writes to the shared tables. The connector reads the write-ahead log, so it sees committed changes in commit order with almost no load on the application, and on first start it takes a snapshot of the included tables so consumers receive history as well as subsequent changes. The envelope it produces is worth memorizing: an operation code for create, update, delete or snapshot read, the before and after images, source table metadata, and a commit timestamp, all written to a topic named from the configured prefix and the table.
Two operational facts cause most Debezium incidents. The replication slot that lets the connector read the log also pins that log on the source server, so if the connector stops for a day the slot keeps every WAL segment and the database eventually refuses writes for lack of disk; monitor slot lag the way you monitor the connector itself. Deletes are the second: emitting tombstones lets a compacted downstream topic actually remove the value, while skipping them leaves a resurrected row the next time a consumer replays the log. Schema changes need a decision too β automatic propagation suits a single owning team, whereas a fixed schema with a reviewed change process suits a platform where many consumers decode the same events.
Debezium Setup
{
"name": "postgres-cdc-connector",
"config": {
"connector.class": "io.debezium.connector.postgresql.PostgresConnector",
"database.hostname": "postgres",
"database.port": "5432",
"database.user": "debezium",
"database.password": "${file:/opt/kafka/secrets/db.properties:password}",
"database.dbname": "mydb",
"database.server.name": "dbserver1",
"schema.include.list": "public",
"table.include.list": "public.orders,public.users,public.payments",
"plugin.name": "pgoutput",
"slot.name": "debezium_slot",
"publication.name": "dbz_publication",
"topic.prefix": "dbserver1",
"tombstones.on.delete": "true",
"transforms": "route",
"transforms.route.type": "org.apache.kafka.connect.transforms.RegexRouter",
"transforms.route.regex": "([^.]+)\\.([^.]+)\\.([^.]+)",
"transforms.route.replacement": "$3"
}
}
CDC Event Processing
class CDCEventProcessor:
def __init__(self, kafka_consumer):
self.consumer = kafka_consumer
def process_cdc_events(self):
for message in self.consumer:
cdc_event = json.loads(message.value)
if cdc_event['op'] == 'c': # Create
self.handle_create(cdc_event)
elif cdc_event['op'] == 'u': # Update
self.handle_update(cdc_event)
elif cdc_event['op'] == 'd': # Delete
self.handle_delete(cdc_event)
def handle_create(self, event):
# Process new record
print(f"New {event['source']['table']}: {event['after']}")
# Publish domain event
domain_event = {
'event_type': f"{event['source']['table']}_created",
'data': event['after'],
'timestamp': event['ts_ms']
}
self.producer.send(
f"{event['source']['table']}-events",
value=json.dumps(domain_event).encode()
)
def handle_update(self, event):
# Process updated record
print(f"Updated {event['source']['table']}: {event['after']}")
def handle_delete(self, event):
# Process deleted record
print(f"Deleted {event['source']['table']}: {event['key']}")
Event Replay
Replay is ordinary consumption done deliberately: assign a new consumer group so the live group's offsets are untouched, seek to a timestamp rather than to the beginning, and pipe the records into a shadow topic or a repaired projection instead of into production. Timestamps come from the broker's index, which resolves to the first record at or after the requested time, so a replay that needs millisecond precision should filter on the event's own timestamp after the seek. The real constraints are cost and blast radius: re-reading a week of a busy topic is a large sequential read that competes with live consumers for the same page cache, and a replay that re-publishes into the original topics will duplicate every downstream effect unless those consumers are already idempotent. Replaying into a separate topic with the same partitioning keeps ordering intact while giving operators a safe place to inspect what the repaired stream contains before anyone points a live consumer at it.
Event Replay Service
class EventReplayService:
def __init__(self, kafka_consumer, event_handler):
self.consumer = kafka_consumer
self.handler = event_handler
def replay_events(self, topic, from_timestamp, to_timestamp):
"""Replay events from a specific time range"""
# Seek to beginning of topic
partitions = self.consumer.partitions_for_topic(topic)
for partition in partitions:
tp = TopicPartition(topic, partition)
self.consumer.seek_to_beginning(tp)
# Consume and process events
replayed_count = 0
for message in self.consumer:
event = json.loads(message.value)
# Filter by timestamp
if from_timestamp <= event['timestamp'] <= to_timestamp:
self.handler.process(event)
replayed_count += 1
return replayed_count
def replay_events_for_aggregate(self, topic, aggregate_id):
"""Replay events for a specific aggregate"""
self.consumer.subscribe([topic])
replayed_count = 0
for message in self.consumer:
event = json.loads(message.value)
if event.get('aggregate_id') == aggregate_id:
self.handler.process(event)
replayed_count += 1
return replayed_count
# Usage
replay_service = EventReplayService(consumer, order_handler)
# Replay last 24 hours
from datetime import datetime, timedelta
from_time = datetime.utcnow() - timedelta(hours=24)
to_time = datetime.utcnow()
replayed = replay_service.replay_events(
'order-events',
from_timestamp=int(from_time.timestamp() * 1000),
to_timestamp=int(to_time.timestamp() * 1000)
)
Idempotency Keys
An idempotency key is a promise that the same logical operation, whatever its transport, will have its side effect executed once. For API calls the key is usually supplied by the client; for stream consumers it is derived from the record, and the choice of derivation decides what your system survives. Hashing the business payload works across reprocessing but collapses two genuinely different events that share a payload, while hashing topic, partition and offset identifies exactly one record and stays correct through a replay from the beginning of the log. Many systems combine both: the offset key for cheap deduplication of at-least-once delivery, plus a business key where the downstream system enforces uniqueness on its own.
The dedupe store itself carries the policy. A cache with a fixed expiry is only correct if the expiry outlasts the longest possible replay, and since a topic retained for seven days can be read again next week, either extend the expiry to match or store the keys in a compacted topic that lives as long as the data does. Redis is the right tool when latency matters and loss of the dedupe cache merely risks duplicates; a compacted topic is the right tool when losing the record of processed work would break the invariant you are protecting, because the store then survives alongside the events it describes.
Idempotency Implementation
import hashlib
from functools import wraps
def idempotent(operation_name):
def decorator(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
# Generate idempotency key
key_data = f"{operation_name}:{args}:{kwargs}"
idempotency_key = hashlib.sha256(key_data.encode()).hexdigest()
# Check if already processed
if self.is_processed(idempotency_key):
return self.get_cached_result(idempotency_key)
# Process operation
result = func(self, *args, **kwargs)
# Cache result
self.cache_result(idempotency_key, result)
self.mark_processed(idempotency_key)
return result
return wrapper
return decorator
class OrderService:
def __init__(self, redis_client):
self.redis = redis_client
@idempotent("create_order")
def create_order(self, order_data):
# Process order
order = self.process_order(order_data)
return order
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')
def cache_result(self, key, result):
self.redis.setex(f"result:{key}", 86400, json.dumps(result))
def get_cached_result(self, key):
return json.loads(self.redis.get(f"result:{key}"))
Idempotency in Kafka
class IdempotentKafkaConsumer:
def __init__(self, consumer, redis_client):
self.consumer = consumer
self.redis = redis_client
def consume_idempotently(self, message):
# Generate idempotency key from message
idempotency_key = self.generate_key(message)
# Check if already processed
if self.is_processed(idempotency_key):
return {'status': 'skipped'}
# Process message
result = self.process_message(message)
# Mark as processed
self.mark_processed(idempotency_key)
return result
def generate_key(self, message):
# Use topic, partition, offset as idempotency key
key_data = f"{message.topic}:{message.partition}:{message.offset}"
return hashlib.sha256(key_data.encode()).hexdigest()
def is_processed(self, key):
return self.redis.exists(f"kafka:processed:{key}")
def mark_processed(self, key):
self.redis.setex(f"kafka:processed:{key}", 86400, '1')
Best Practices
Pattern Selection
| Pattern | Use Case | Complexity |
|---|---|---|
| Event Mesh | Multi-service communication | High |
| Circuit Breaker | External service calls | Medium |
| Outbox | Reliable event publishing | Medium |
| CDC | Database synchronization | High |
| Event Replay | Audit and debugging | Medium |
Implementation Checklist
- Event mesh routing configured
- Circuit breaker for external calls
- Outbox pattern for reliability
- CDC for database sync
- Event replay capability
- Idempotency keys implemented
- Dead letter queues configured
- Monitoring and alerting
Common Mistakes
Running several outbox poller workers that select the same unprocessed rows
Fix: Partition the work by aggregate id or keep one poller per shard, so events for the same entity keep their commit order
Leaving a stopped Debezium connector's replication slot unmonitored
Fix: Alert on slot lag and disk growth, because a pinned write-ahead log will fill the source database's volume within days
Replaying a topic into the live topics without checking consumer idempotency
Fix: Replay into a shadow topic with the same partitioning, inspect the result, and only then let idempotent consumers cut over
Summary
Real-world Kafka patterns including event mesh, circuit breaker, outbox pattern, CDC, and event replay provide reliable, scalable, and maintainable event-driven architectures. Choose patterns based on your specific requirements for reliability, scalability, and data consistency.
See Also
- Kafka Producer & Consumer β Building reliable producers and consumers with idempotency
- Kafka Streams & Connect β Stream processing and CDC integration with Kafka Connect
- Kafka Exactly-Once Semantics β Ensuring exactly-once delivery in distributed patterns