Apache Kafka
When to Use
Load this skill when the user needs to:
- Design Kafka topics, choose partition count and replication factor
- Configure producers (acks, idempotence, batching, compression)
- Configure consumers (commit strategies, rebalancing, exactly-once)
- Set up Kafka Connect source/sink connectors
- Handle errors with Dead Letter Queues
- Monitor consumer lag and cluster health
- Write Python producers/consumers with
confluent-kafka
Core Concepts
Broker cluster (3+ nodes)
└─ Topic (logical stream of records)
└─ Partition 0 [offset 0, 1, 2, 3, ...] ← replicated to follower brokers
└─ Partition 1 [offset 0, 1, 2, ...]
└─ Partition N ...
Producer → writes to partitions (by key hash or round-robin)
Consumer Group → each partition consumed by exactly one consumer in the group
N partitions ÷ M consumers = M≤N for full parallelism
Offset — position of a consumer in a partition; committed to __consumer_offsets topic. Leader replica — handles reads and writes; followers replicate. ISR (In-Sync Replicas) — replicas that are caught up with the leader.
Topic Design
Partition Count
Partitions = max(target_throughput_MB/s ÷ per_partition_throughput, desired_consumer_parallelism)
Rules of thumb:
- Start with 6–12 partitions for most topics; increase later (but keyed topics can't repartition without rekeying).
- Never set partitions < number of consumers in the consuming group.
- Avoid over-partitioning — each partition has file handles and memory overhead on every broker.
Replication & Durability
bash
# Create topic with production settings
kafka-topics.sh --bootstrap-server broker:9092 --create \
--topic orders \
--partitions 12 \
--replication-factor 3 \
--config min.insync.replicas=2 \
--config retention.ms=604800000 \
--config compression.type=snappy
| Parameter | Recommended | Notes | |
|---|
replication.factor | 3 | Survive 1 broker loss | |
min.insync.replicas | 2 | With acks=all ensures at least 2 copies | |
unclean.leader.election.enable | false | Prevent data loss from lagging replica becoming leader | |
retention.ms | 7 days (604800000) | Or -1 for infinite; override per topic | |
retention.bytes | -1 or explicit | Size-based retention per partition | |
cleanup.policy | delete or compact | compact for changelog/event-sourcing topics | |
compression.type | snappy or lz4 | Set on topic; producer compression preferred | |
Topic Naming Convention
<domain>.<entity>.<event> → payments.orders.placed
<env>.<domain>.<entity> → prod.payments.orders
<team>.<service>.<event> → checkout.cart.item_added
dlq.<original-topic> → dlq.payments.orders.placed
Producer Configuration
Durability vs Throughput Trade-offs
python
# HIGH DURABILITY — production default for critical data
durable_producer = {
"bootstrap.servers": "broker1:9092,broker2:9092,broker3:9092",
"client.id": "orders-producer-v1",
# Durability
"acks": "all", # wait for all ISR acks
"enable.idempotence": True, # exactly-once per session
"max.in.flight.requests.per.connection": 5, # up to 5 with idempotence=True
# Throughput
"batch.size": 65536, # 64 KB batch size
"linger.ms": 10, # wait up to 10ms to fill batch
"compression.type": "snappy", # snappy: fast; gzip: best ratio; lz4: balanced
# Resilience
"retries": 2147483647, # retry indefinitely (with idempotence)
"delivery.timeout.ms": 120000, # give up after 2 min total
"request.timeout.ms": 30000,
"buffer.memory": 67108864, # 64 MB send buffer
}
# HIGH THROUGHPUT — telemetry / non-critical events
throughput_producer = {
"bootstrap.servers": "broker:9092",
"acks": "1", # leader ack only
"batch.size": 131072, # 128 KB
"linger.ms": 50,
"compression.type": "lz4",
"buffer.memory": 134217728, # 128 MB
}
Idempotent Producer (prevents duplicates on retry)
enable.idempotence=True assigns each producer a PID and a sequence number per partition. The broker deduplicates retried messages within the producer session. Requires: acks=all, max.in.flight.requests.per.connection ≤ 5, retries > 0.
Transactional Producer (exactly-once across partitions)
python
from confluent_kafka import Producer
producer = Producer({
"bootstrap.servers": "broker:9092",
"transactional.id": "order-processor-1", # unique per producer instance
"enable.idempotence": True,
})
producer.init_transactions()
try:
producer.begin_transaction()
producer.produce("orders", key="1001", value='{"status":"placed"}')
producer.produce("audit", key="1001", value='{"action":"order_placed"}')
producer.commit_transaction()
except Exception as e:
producer.abort_transaction()
raise
Python Producer — Full Example
python
from confluent_kafka import Producer
from confluent_kafka.serialization import StringSerializer, SerializationContext, MessageField
import json, logging
logger = logging.getLogger(__name__)
def delivery_callback(err, msg):
if err:
logger.error(f"Delivery failed | topic={msg.topic()} partition={msg.partition()} error={err}")
else:
logger.debug(f"Delivered | topic={msg.topic()} partition={msg.partition()} offset={msg.offset()}")
producer = Producer({
"bootstrap.servers": "broker:9092",
"acks": "all",
"enable.idempotence": True,
"compression.type": "snappy",
"batch.size": 65536,
"linger.ms": 10,
})
def send_order(order: dict) -> None:
producer.produce(
topic="orders",
key=str(order["order_id"]).encode(),
value=json.dumps(order).encode(),
on_delivery=delivery_callback,
)
producer.poll(0) # trigger delivery callbacks without blocking
# After batch:
producer.flush() # block until all in-flight messages delivered
Consumer Configuration
Core Settings
python
consumer_config = {
"bootstrap.servers": "broker:9092",
"group.id": "orders-service-v1",
"client.id": "orders-consumer-1",
# Offset reset: what to do when no committed offset exists
"auto.offset.reset": "earliest", # earliest | latest | error
# ALWAYS disable auto-commit for production — control commits manually
"enable.auto.commit": False,
# Rebalance protocol
"partition.assignment.strategy": "cooperative-sticky", # minimises rebalance disruption
# Session & poll timeouts
"session.timeout.ms": 30000, # consumer considered dead after 30s without heartbeat
"heartbeat.interval.ms": 10000, # heartbeat every 10s (< session.timeout.ms / 3)
"max.poll.interval.ms": 300000, # max 5 min between poll() calls before consumer kicked
# Throughput
"fetch.min.bytes": 1024, # wait for at least 1 KB before returning
"fetch.max.wait.ms": 500,
"max.poll.records": 500, # max messages per poll()
}
Commit Strategies
python
from confluent_kafka import Consumer, KafkaError, TopicPartition
consumer = Consumer(consumer_config)
consumer.subscribe(["orders"])
# --- Strategy 1: Synchronous commit after each batch (safe, lower throughput)
try:
while True:
msgs = consumer.consume(num_messages=100, timeout=1.0)
for msg in msgs:
if msg.error():
logger.error(msg.error())
continue
process(msg)
if msgs:
consumer.commit(asynchronous=False) # block until broker confirms
except Exception:
pass
finally:
consumer.close()
# --- Strategy 2: Async commit in loop + sync commit on shutdown (balanced)
try:
while True:
msg = consumer.poll(1.0)
if msg is None:
continue
if msg.error():
logger.error(msg.error())
continue
process(msg)
consumer.commit(asynchronous=True)
except KeyboardInterrupt:
consumer.commit(asynchronous=False) # final sync flush
finally:
consumer.close()
# --- Strategy 3: Manual per-partition offset commit (exactly-once with external store)
def on_assign(consumer, partitions):
# restore offsets from external store (e.g. DB) on rebalance
for p in partitions:
offset = db.get_offset(p.topic, p.partition) or OFFSET_BEGINNING
p.offset = offset
consumer.assign(partitions)
consumer.subscribe(["orders"], on_assign=on_assign)
while True:
msg = consumer.poll(1.0)
if msg is None:
continue
process_and_save_to_db(msg) # write result + offset atomically
consumer.commit(offsets=[
TopicPartition(msg.topic(), msg.partition(), msg.offset() + 1)
], asynchronous=False)
Consumer Group Operations (CLI)
bash
# List all consumer groups
kafka-consumer-groups.sh --bootstrap-server broker:9092 --list
# Describe group — shows lag per partition
kafka-consumer-groups.sh --bootstrap-server broker:9092 \
--describe --group orders-service-v1
# Reset offsets to beginning (for re-processing)
kafka-consumer-groups.sh --bootstrap-server broker:9092 \
--group orders-service-v1 --topic orders \
--reset-offsets --to-earliest --execute
# Shift offsets back by N messages
kafka-consumer-groups.sh --bootstrap-server broker:9092 \
--group orders-service-v1 --topic orders \
--reset-offsets --shift-by -1000 --execute
# Reset to specific datetime
kafka-consumer-groups.sh --bootstrap-server broker:9092 \
--group orders-service-v1 --topic orders \
--reset-offsets --to-datetime 2024-01-15T00:00:00.000 --execute
Exactly-Once Semantics (EOS)
| Delivery Guarantee | Producer | Consumer | Use When | |
|---|
| At-most-once | acks=0/1, no retry | auto.commit before processing | Metrics, telemetry | |
| At-least-once | acks=all + retries | commit after processing | Most pipelines (handle idempotent consumers) | |
| Exactly-once | enable.idempotence=True + transactions | isolation.level=read_committed | Financial, inventory, audit | |
python
# Exactly-once consumer: only read committed transactional messages
consumer = Consumer({
**consumer_config,
"isolation.level": "read_committed", # skip messages from aborted transactions
})
Schema Registry
Enforces schema evolution rules; decouples producers from consumers.
python
from confluent_kafka.schema_registry import SchemaRegistryClient
from confluent_kafka.schema_registry.avro import AvroSerializer, AvroDeserializer
from confluent_kafka.serialization import SerializationContext, MessageField
schema_registry_conf = {"url": "http://schema-registry:8081"}
schema_registry_client = SchemaRegistryClient(schema_registry_conf)
order_schema_str = """
{
"type": "record",
"name": "Order",
"namespace": "com.example",
"fields": [
{"name": "order_id", "type": "long"},
{"name": "amount", "type": "double"},
{"name": "status", "type": "string"}
]
}
"""
avro_serializer = AvroSerializer(schema_registry_client, order_schema_str)
avro_deserializer = AvroDeserializer(schema_registry_client)
# Producer with Avro serialization
producer = Producer({"bootstrap.servers": "broker:9092"})
producer.produce(
topic="orders",
value=avro_serializer(
{"order_id": 1001, "amount": 299.99, "status": "placed"},
SerializationContext("orders", MessageField.VALUE),
),
)
Schema compatibility modes (set per subject):
| Mode | Rule | |
|---|
BACKWARD (default) | New schema reads old data (consumers upgrade first) | |
FORWARD | Old schema reads new data (producers upgrade first) | |
FULL | Both directions | |
NONE | No checks — dangerous | |