Complete Guide to Apache Kafka in Production
Operate Apache Kafka in production: partitions, replication, consumer groups, tuning, monitoring, security, and cluster operations explained.
Introduction
Apache Kafka runs some of the busiest data pipelines in the industry, and it’s unforgiving when you get the operational details wrong. A misconfigured min.insync.replicas can silently turn a durable pipeline into a data-loss incident; an under-provisioned partition count caps your throughput before you even notice; a stalled consumer group can back up millions of messages while your alerts say nothing.
This guide covers the parts of Kafka that matter once you leave localhost: how partitions and replication actually behave under failure, how consumer groups distribute work, what the tuning knobs really change, what to monitor, and the operational procedures you’ll run on live clusters. Every configuration shown here is production-tested — the values aren’t defaults, they’re the ones that keep you safe.
If you’re still deciding between Kafka and a simpler broker like RabbitMQ, our message queue comparison covers when each one pays off. This guide assumes you’ve already chosen Kafka.
Kafka Architecture Fundamentals
Kafka is a distributed commit log. Producers append events to partitioned topics, brokers store and replicate those partitions, and consumer groups read them in parallel. A cluster of three or more brokers is coordinated by a controller that assigns partition leaders — historically via ZooKeeper, now via KRaft (more on that below).
- Broker: A Kafka server. Clusters typically have 3+ brokers for fault tolerance.
- Topic: A named stream of events, divided into partitions.
- Partition: An ordered, append-only sequence of events. The unit of parallelism — and of durability, since replication happens per partition.
- Offset: A monotonically increasing ID for each message within a partition.
- Consumer Group: A set of consumers that share partitions of a topic.
- Replication: Each partition has a leader plus follower replicas on other brokers.
The key mental model: everything in Kafka is partitioned. Ordering, parallelism, replication, and consumer assignment all happen per partition, never per topic. Most production incidents trace back to a partition-level assumption that didn’t hold.
Partition Design
Partitions determine how much parallelism you get on both the produce and consume side. The partition key decides where a message lands: messages with the same key go to the same partition and stay ordered relative to each other — which is exactly what you want for events about the same entity.
from kafka import KafkaProducer
import json
producer = KafkaProducer(
bootstrap_servers=["kafka1:9092", "kafka2:9092", "kafka3:9092"],
key_serializer=str.encode,
value_serializer=lambda v: json.dumps(v).encode("utf-8")
)
# Partitioning: messages with the same key go to the same partition
# This guarantees ordering for events related to the same entity
def send_order_event(order_id, event_type, data):
producer.send(
"orders",
key=str(order_id), # Same order_id → same partition → ordered
value={
"order_id": order_id,
"event_type": event_type,
"data": data,
"timestamp": "2026-07-04T12:00:00Z"
}
)
producer.flush()
Two warnings worth internalizing: ordering is only guaranteed within a partition, so a producer writing the same key to different partitions is a bug. And key choice is a hot-partition risk — if 40% of your traffic shares one key, 40% of your load lands on one broker.
Choosing Partition Count
Partition count is one of the few decisions in Kafka you can’t undo — Kafka doesn’t support decreasing partitions. Getting it right is a balance between throughput, consumer parallelism, and cluster overhead.
| Factor | Recommendation |
|---|---|
| Throughput target | 1 partition per 10MB/s write throughput |
| Consumer parallelism | At least as many partitions as consumers |
| Broker count | Partitions per broker should stay under 2000 |
| Retention | More partitions = more memory for offsets |
| Future growth | Over-partition early (can’t easily reduce) |
# Create a topic with 12 partitions and replication factor 3
kafka-topics.sh --create \
--bootstrap-server kafka1:9092 \
--topic orders \
--partitions 12 \
--replication-factor 3 \
--config retention.ms=604800000 \
--config compression.type=lz4
When in doubt, over-partition moderately. Six partitions that turn out too few forces a topic migration with dual writes and consumer re-pointing — a painful day. Twelve that turn out too many costs you a bit of memory and metadata churn, which you’ll never notice. Don’t go overboard, though: thousands of partitions per broker slows leader elections and increases recovery time.
Replication and Fault Tolerance
Each partition has one leader and N-1 followers living on different brokers. Producers write to and consumers read from the leader; followers fetch the leader’s log and stay in sync. When a broker dies, one of the in-sync followers is elected leader and traffic continues — assuming you configured things right.
Replication Factor
Replication Factor 1: No tolerance for broker failure (data loss)
Replication Factor 2: Tolerates 1 broker failure (not recommended — no safety margin)
Replication Factor 3: Tolerates 1 broker failure (production standard)
Replication Factor 5: Tolerates 2 broker failures (high availability)
RF=3 is the standard for a reason: you can lose one broker and still tolerate a second going down while the first recovers, which is the failure scenario that actually bites you during rolling upgrades. RF=2 looks like fault tolerance on paper but leaves zero margin — if one replica is behind during a failure, you’ve lost data.
In-Sync Replicas (ISR)
A replica counts as “in-sync” once it’s fetched all messages from the leader within replica.lag.time.max.ms (default 10s). Only ISR replicas are eligible to become leaders, which is what makes min.insync.replicas meaningful.
# Check ISR for a topic
kafka-topics.sh --describe \
--bootstrap-server kafka1:9092 \
--topic orders
# Output:
# Topic: orders Partition: 0 Leader: 1 Replicas: 1,2,3 Isr: 1,2,3
# Topic: orders Partition: 1 Leader: 2 Replicas: 2,3,1 Isr: 2,3,1
Set min.insync.replicas=2 with RF=3. That combination means a write with acks=all is acknowledged by the leader plus at least one follower — and the cluster refuses writes entirely if only one replica is alive, which is what you want. Setting min.insync.replicas=1 keeps availability but breaks the durability guarantee under a two-broker outage.
acks Configuration
The acks setting controls how many replicas must acknowledge a write before the producer considers it successful. It’s the single most important durability knob on the producer side.
# acks=0: Fire and forget — no acknowledgment (highest throughput, data loss risk)
producer = KafkaProducer(bootstrap_servers=["kafka1:9092"], acks=0)
# acks=1: Leader acknowledges (good balance for most use cases)
producer = KafkaProducer(bootstrap_servers=["kafka1:9092"], acks=1)
# acks=all: Leader + all ISR replicas acknowledge (strongest durability)
producer = KafkaProducer(
bootstrap_servers=["kafka1:9092"],
acks="all",
retries=3,
max_in_flight_requests_per_connection=1 # Prevent out-of-order on retry
)
acks=1 has a subtle failure mode: if the leader acknowledges and then crashes before followers replicate, that write is gone and you won’t know it happened. For anything you can’t afford to lose — payments, orders, audit logs — use acks=all. For metrics or telemetry where a lost batch is tolerable, acks=1 buys you meaningfully lower latency.
KRaft vs ZooKeeper
Since Kafka 3.3, clusters can run without ZooKeeper using KRaft (Kafka Raft), where a subset of brokers acts as a controller quorum managing cluster metadata through the Raft consensus protocol. Since Kafka 4.0, KRaft is the only mode — ZooKeeper support was removed entirely.
What this changes operationally:
- Fewer moving parts: no separate ZooKeeper ensemble to secure, monitor, and upgrade.
- Faster controller failover: leader election for the controller happens in milliseconds instead of seconds, which shortens the window where partition reassignments stall.
- Single migration path: existing ZooKeeper clusters migrate via
kafka-migrationtooling; new clusters should start on KRaft and never touch ZooKeeper.
# server.properties — a KRaft combined-mode node (small clusters only)
process.roles=broker,controller
node.id=1
controller.quorum.voters=1@kafka1:9093,2@kafka2:9093,3@kafka3:9093
listeners=PLAINTEXT://:9092,CONTROLLER://:9093
controller.listener.names=CONTROLLER
For production clusters, dedicate controller nodes once you pass ~50-100 partitions per broker’s worth of metadata churn — combined mode is fine for small clusters and dev environments.
Consumer Groups
Consumer groups let a set of consumer instances split a topic’s partitions between them: each partition is read by exactly one consumer in the group at a time. They’re the main horizontal-scaling mechanism on the read side — but they come with a sharp edge called the rebalance.
Topic: orders (6 partitions)
Consumer Group A (3 consumers):
Consumer 1 → Partitions 0, 1
Consumer 2 → Partitions 2, 3
Consumer 3 → Partitions 4, 5
Consumer Group B (2 consumers):
Consumer 1 → Partitions 0, 1, 2
Consumer 2 → Partitions 3, 4, 5
# Adding a consumer to Group A:
Consumer 4 → Partitions 4
Consumer 3 → Partitions 5 (rebalance)
A few things the diagram doesn’t show: consumers beyond the partition count sit idle (a 7th consumer in Group A does nothing), groups are independent of each other (A and B each get a full copy of the stream), and offset commits are per-group — which is how different applications consume the same events without stepping on each other.
Rebalancing and the Cooperative Sticky Assignor
Every time a consumer joins or leaves the group — deploy, scale event, crash, or a max.poll.interval.ms timeout — the group rebalances: every consumer stops, partitions get reassigned, and consumption resumes. The default “eager” rebalancing protocol pauses the whole group, which turns every rolling deploy into a processing hiccup.
Two mitigations: use partition.assignment.strategy=CooperativeStickyAssignor so consumers only give up the partitions being moved instead of all of them, and make sure your processing fits comfortably inside max.poll.interval.ms so healthy consumers don’t get kicked for looking dead.
Basic Consumer
Always disable auto-commit for anything that matters. Auto-commit fires on a timer regardless of whether you’ve processed the batch, which produces exactly the “lost messages” bug that’s hard to reproduce in staging.
from kafka import KafkaConsumer
import json
consumer = KafkaConsumer(
"orders",
bootstrap_servers=["kafka1:9092", "kafka2:9092", "kafka3:9092"],
group_id="order-processor",
auto_offset_reset="earliest",
enable_auto_commit=False,
key_deserializer=lambda k: k.decode("utf-8") if k else None,
value_deserializer=lambda v: json.loads(v.decode("utf-8"))
)
for message in consumer:
try:
process_order(message.value)
consumer.commit() # Manual commit after successful processing
except Exception as e:
logger.error(f"Failed to process message: {e}")
# Message will be re-delivered on next poll
At-Least-Once Processing
Manual commit gives you at-least-once semantics: if the consumer crashes after processing but before committing, the message comes back. That means your processing must be idempotent or your downstream must deduplicate — there’s no way around it without transactions.
from kafka import KafkaConsumer, TopicPartition
import json
consumer = KafkaConsumer(
"orders",
bootstrap_servers=["kafka1:9092"],
group_id="order-processor",
enable_auto_commit=False,
auto_offset_reset="earliest"
)
def process_with_retry(message, max_retries=3):
for attempt in range(max_retries):
try:
process_order(message.value)
return True
except Exception as e:
if attempt == max_retries - 1:
# Send to dead letter topic
send_to_dlt(message)
return True # Mark as handled to skip
time.sleep(2 ** attempt) # Exponential backoff
return False
for message in consumer:
if process_with_retry(message):
consumer.commit()
The dead-letter topic isn’t optional in production. Without it, one poison message blocks the partition forever — your consumer retries it until the lag alarm goes off and someone manually skips the offset at 2 a.m.
Exactly-Once Semantics
Kafka supports exactly-once through the transactional API: consume, transform, produce, and commit the input offsets atomically. Use it when a duplicate would corrupt downstream state — payments, inventory, ledger writes. For idempotent-tolerant pipelines, at-least-once with dedupe is simpler and cheaper.
from kafka import KafkaProducer, KafkaConsumer
from kafka.errors import KafkaError
# Transactional producer
producer = KafkaProducer(
bootstrap_servers=["kafka1:9092"],
transactional_id="order-processor-tx",
enable_idempotence=True
)
consumer = KafkaConsumer(
"orders",
bootstrap_servers=["kafka1:9092"],
group_id="order-processor-tx",
isolation_level="read_committed"
)
# Consume-transform-produce pattern with exactly-once
producer.init_transactions()
for message in consumer:
try:
producer.begin_transaction()
# Process and produce to output topic
result = transform_order(message.value)
producer.send("processed-orders", value=result)
# Commit consumer offset within the transaction
producer.send_offsets_to_transaction(
consumer.position(message.partition),
consumer.consumer_group_metadata()
)
producer.commit_transaction()
except KafkaError:
producer.abort_transaction()
Transactions cost latency — each one adds coordination with the transaction coordinator on the broker. Reserve them for the pipelines that genuinely need them.
Performance Tuning
Producer Tuning
Producer throughput is dominated by batching: every linger_ms you add increases latency slightly but lets compression and batch size do real work. The defaults are tuned for interactivity, not bulk throughput.
producer = KafkaProducer(
bootstrap_servers=["kafka1:9092"],
# Batching: accumulate messages before sending
batch_size=65536, # 64KB batch size
linger_ms=10, # Wait up to 10ms for batch to fill
# Compression: reduce network overhead
compression_type="lz4", # lz4 (fast), snappy (balanced), zstd (best ratio)
# Buffering: in-memory buffer for unsent messages
buffer_memory=67108864, # 64MB buffer
# Durability
acks="all",
retries=3,
max_in_flight_requests_per_connection=5,
# Serialization
key_serializer=str.encode,
value_serializer=lambda v: json.dumps(v).encode("utf-8")
)
Compression happens on the producer and stays compressed end-to-end — lz4 is nearly free CPU-wise and typically cuts payload 50-70% on JSON. zstd compresses better but costs more CPU; use it when network egress is your bottleneck, not before.
Consumer Tuning
Consumer throughput is mostly fetch sizing: too-small fetches mean more round-trips, too-large means you’re holding data while the max.poll.interval.ms clock ticks down.
consumer = KafkaConsumer(
"orders",
bootstrap_servers=["kafka1:9092"],
# Fetch settings
fetch_min_bytes=1024, # Wait for at least 1KB before returning
fetch_max_wait_ms=500, # Max wait time for fetch_min_bytes
max_partition_fetch_bytes=1048576, # 1MB per partition
# Poll settings
max_poll_records=500, # Max records per poll
max_poll_interval_ms=300000, # 5min max processing time
# Offset management
enable_auto_commit=False,
auto_offset_reset="earliest"
)
If a poll returns more records than you can process inside max.poll.interval.ms, the consumer gets kicked and rebalanced — processing pauses group-wide. Either shrink max_poll_records or move processing off the poll thread.
Broker Tuning
# server.properties — key production settings
# Replication
default.replication.factor=3
min.insync.replicas=2
# Log retention
log.retention.hours=168 # 7 days
log.segment.bytes=1073741824 # 1GB segments
log.retention.check.interval.ms=300000
# Network
socket.send.buffer.bytes=102400
socket.receive.buffer.bytes=102400
socket.request.max.bytes=104857600
# Threads
num.network.threads=3
num.io.threads=8
# Topic defaults
num.partitions=6
log.cleanup.policy=delete # or "compact" for key-based retention
num.io.threads matters more than it looks: all disk I/O goes through these, so under-provisioning on fast NVMe leaves throughput on the table. Rule of thumb: one per disk.
Cluster Sizing and Storage
Broker sizing is mostly a disk problem. Kafka is a log system: every byte in gets written, replicated, and retained. Plan backwards from retention: total disk = ingress rate × retention period × replication factor × headroom.
Example: 50 MB/s ingress, 7-day retention, RF=3
Raw: 50 MB/s × 604,800 s = 30 TB retained data
Per broker (3 brokers): 10 TB + ~30% headroom ≈ 13 TB usable per broker
Keep these operational truths in mind:
- Disk type matters: Kafka is sequential-write heavy, so it works fine on spinning disks — but NVMe shortens recovery time dramatically when a broker resyncs terabytes after a failure.
- Retention is per-topic: don’t set a global 7-day policy and forget it. Audit topics need years; debug topics need hours.
- Disk fills are catastrophic: when a broker hits its log segment limit, partitions go offline and leadership churns. Alert at 70%, escalate at 85%.
- Tiered storage (Kafka 3.6+) can offload older segments to S3, which changes the sizing math for long-retention topics entirely — brokers keep only the hot tail.
Quotas and Throttling
One misbehaving producer can saturate the cluster and starve every other client. Kafka’s produce/fetch quotas prevent that by rate-limiting clients by client-id, user, or IP.
# Limit a client to 10 MB/s produce and 50 MB/s fetch
kafka-configs.sh --bootstrap-server kafka1:9092 \
--entity-type clients --entity-name bulk-loader \
--alter --add-config 'producer_byte_rate=10485760,consumer_byte_rate=52428800'
Quotas matter most in multi-tenant clusters and during bulk operations — a MirrorMaker initial sync or a reprocessing job can otherwise monopolize broker I/O. Set a default quota per client-id so nothing can hog the cluster unnoticed.
Schema Registry and Serialization
JSON over Kafka works until it doesn’t: a renamed field silently breaks every consumer that still reads the old shape. A schema registry (Confluent’s is the de facto standard) version-controls your Avro/Protobuf/JSON-Schema contracts and enforces compatibility on the producer.
from confluent_kafka.avro import AvroProducer
producer = AvroProducer(
{"bootstrap.servers": "kafka1:9092",
"schema.registry.url": "http://schema-registry:8081"},
default_value_schema=order_schema # Registered + versioned centrally
)
Start with backward compatibility — new consumers must read old data — and move to full compatibility once you’re confident. The alternative (“we’ll coordinate deploys”) works until the day a producer ships before a consumer, which is the day you learn why registries exist.
Monitoring
Kafka exposes hundreds of JMX metrics; a handful actually predict outages. Watch these before you build dashboards for everything else.
| Metric | Description | Alert Threshold |
|---|---|---|
| Under-replicated partitions | Partitions with lagging followers | > 0 |
| Offline partitions | Partitions without a leader | > 0 |
| Consumer lag | Difference between log end and committed offset | > 10,000 |
| Bytes in/out per second | Throughput | Baseline + 50% |
| Request latency | Time to serve requests | > 100ms |
| Active controller count | Should always be 1 | != 1 |
| ISR shrinks per second | Replicas falling out of sync | > 0 sustained |
UnderReplicatedPartitions and OfflinePartitions are the two alerts that must page someone. Everything else degrades gracefully; these two mean your durability window is shrinking right now.
For a broader observability setup, the monitoring and alerting guide covers Prometheus + Alertmanager wiring for these metrics.
Consumer Lag Monitoring
Lag is the number that tells you consumers are keeping up. Compute it per group — a single global lag metric hides which service is drowning.
from kafka import KafkaConsumer, TopicPartition
import json
consumer = KafkaConsumer(
"orders",
bootstrap_servers=["kafka1:9092"],
group_id="order-processor"
)
# Get current lag
def get_consumer_lag(consumer, topic, group_id):
partitions = consumer.partitions_for_topic(topic)
if not partitions:
return 0
total_lag = 0
for partition in partitions:
tp = TopicPartition(topic, partition)
# Get the end offset of the partition
end_offset = consumer.end_offsets([tp])[tp]
# Get the consumer's committed position
committed = consumer.committed(tp)
if committed is not None:
total_lag += end_offset - committed
return total_lag
lag = get_consumer_lag(consumer, "orders", "order-processor")
if lag > 10000:
alert(f"High consumer lag: {lag} messages behind")
JMX Metrics via Command Line
# Check under-replicated partitions
kafka-topics.sh --describe --bootstrap-server kafka1:9092 --under-replicated-partitions
# Check consumer group lag
kafka-consumer-groups.sh --describe \
--bootstrap-server kafka1:9092 \
--group order-processor
# Output:
# GROUP TOPIC PARTITION CURRENT-OFFSET LOG-END-OFFSET LAG CONSUMER-ID
# order-processor orders 0 15000 15200 200 consumer-1
Operational Procedures
Adding Partitions
# Increase partitions (cannot decrease later)
kafka-topics.sh --alter \
--bootstrap-server kafka1:9092 \
--topic orders \
--partitions 24
# Note: existing messages stay in their original partitions
# New messages may be distributed differently if key hashing changes
Existing data doesn’t redistribute — adding partitions only affects new messages. That also means key-based routing shifts: keys that hashed to partition 3 of 12 may hash to partition 3 of 24 or elsewhere, so consumers relying on key ordering see a transient break at the boundary.
Reassigning Partitions
When you add brokers, nothing moves automatically — new brokers sit empty until you rebalance. Reassignment copies partition data between brokers and changes leadership, which is I/O heavy, so do it during low-traffic windows.
# Generate reassignment plan
kafka-reassign-partitions.sh --bootstrap-server kafka1:9092 \
--topics-to-move-json-file topics.json \
--generate
# Execute reassignment
kafka-reassign-partitions.sh --bootstrap-server kafka1:9092 \
--reassignment-json-file plan.json \
--execute
# Verify completion
kafka-reassign-partitions.sh --bootstrap-server kafka1:9092 \
--reassignment-json-file plan.json \
--verify
Throttle reassignment with --throttle (bytes/sec) to keep the copy traffic from competing with production I/O. A fast reassignment that saturates the cluster is a self-inflicted outage.
Preferred Leader Election
After a broker rejoins the cluster, its partitions may have been led elsewhere. Preferred leader election moves leadership back to the configured preferred broker, evening out the load.
# Trigger preferred leader election to restore original leader assignments
kafka-leader-election.sh --bootstrap-server kafka1:9092 \
--election-type preferred \
--all-topic-partitions
Security
TLS Encryption
TLS in Kafka encrypts broker-to-client and broker-to-broker traffic. It’s mandatory for anything leaving a private subnet — and required for most compliance regimes regardless of subnet.
# server.properties — TLS listeners
listeners=SSL://:9093
ssl.keystore.location=/etc/kafka/keystore.jks
ssl.keystore.password=${SSL_KEYSTORE_PASSWORD}
ssl.truststore.location=/etc/kafka/truststore.jks
ssl.client.auth=required
security.inter.broker.protocol=SSL
Keep certificates out of config files — mount them as secrets. Rotate before expiry; an expired broker cert takes a broker offline and looks like a hardware failure in the metrics.
SASL Authentication
# server.properties
listeners=SASL_SSL://:9092
advertised.listeners=SASL_SSL://kafka1:9092
sasl.enabled.mechanisms=SCRAM-SHA-512
sasl.mechanism.inter.broker.protocol=SCRAM-SHA-512
listener.security.protocol.map=SASL_SSL:SASL_SSL
ssl.keystore.location=/etc/kafka/keystore.jks
ssl.keystore.password=changeit
ssl.truststore.location=/etc/kafka/truststore.jks
ssl.truststore.password=changeit
# Python client with SASL
producer = KafkaProducer(
bootstrap_servers=["kafka1:9092"],
security_protocol="SASL_SSL",
sasl_mechanism="SCRAM-SHA-512",
sasl_plain_username="producer-user",
sasl_plain_password="secure-password",
ssl_cafile="/path/to/ca-cert"
)
Prefer SCRAM-SHA-512 over PLAIN — PLAIN sends credentials that require TLS to be safe, SCRAM never transmits the password. For anything enterprise-facing, OAuth/OIDC (OAUTHBEARER) replaces per-service passwords entirely.
ACLs
# Grant produce permission to a user on a topic
kafka-acls.sh --bootstrap-server kafka1:9092 \
--add --allow-principal User:producer-user \
--producer --topic orders
# Grant consume permission to a consumer group
kafka-acls.sh --bootstrap-server kafka1:9092 \
--add --allow-principal User:consumer-user \
--consumer --topic orders --group order-processor
ACLs are per-principal and per-resource — grant the minimum: producers get WRITE on their topics, consumers get READ + DESCRIBE on topics plus READ on their group. Never grant User:* wildcard permissions outside development.
Disaster Recovery and MirrorMaker 2
Replication inside a cluster protects against broker failure. It does nothing for a total cluster loss — a region outage, a corrupted log directory, or a fat-fingered kafka-topics.sh --delete. For that you need cluster replication.
MirrorMaker 2 is Kafka’s built-in replication tool: a Kafka Connect connector that mirrors topics (and, optionally, consumer offsets and ACLs) between clusters.
# mm2.properties — replicate orders topics from primary to DR cluster
clusters = primary, dr
primary.bootstrap.servers = kafka1:9092
dr.bootstrap.servers = dr1:9092
primary->dr.enabled = true
primary->dr.topics = orders.*
primary->dr.sync.group.offsets.enabled = true
The DR cluster costs roughly a full replica of your production cluster’s I/O and storage — budget accordingly, and verify failover works before you need it. “We have MM2 running” isn’t a DR plan; “we failed over and measured RTO of 12 minutes” is.
Production Checklist
- Replication factor >= 3 for all topics
- min.insync.replicas >= 2
- acks=all for critical producers
- Partition count sized for throughput and consumer parallelism
- Consumer lag monitoring with alerts
- Dead letter topic for failed messages
- Graceful shutdown handling for consumers
- SASL/SSL authentication enabled
- ACLs configured per topic and consumer group
- Log retention configured per topic requirements
- JMX metrics exported to monitoring system
- Broker disk usage alerts at 70% and 85%
- Disaster recovery plan (MirrorMaker2 or cluster replication)
- Schema registry for Avro/Protobuf serialization
- Quotas configured for multi-tenant or bulk-loader clients
See Also
- Message Queues — RabbitMQ, Kafka, and SQS detailed analysis
- Complete Guide to Monitoring and Alerting
- Complete Guide to Event-Driven Systems
- Complete Guide to RabbitMQ Architecture
- Apache Kafka Documentation — Design (official)
- Apache Kafka Documentation — Operations (official)
- Apache Kafka Configuration Reference (official)
All configuration examples on this page ship as runnable files in the companion repository — a KRaft docker-compose cluster, client configs, and producer/consumer scripts ready for docker compose up.
Frequently Asked Questions
How many partitions should I use?
Start with 6-12 partitions per topic for moderate throughput. Add more if you need more consumer parallelism or higher write throughput. Rule of thumb: 1 partition per 10MB/s throughput. Don't exceed 2000 partitions per broker — leader elections and metadata overhead grow with partition count.
What happens when a broker fails?
If the broker was a partition leader, one of the ISR replicas takes over as leader. If replication factor is 3 and min.insync.replicas is 2, the cluster continues operating with 2 replicas. Producers with acks=all experience a brief pause until the new leader is elected — usually under a second on a healthy cluster.
Can I reduce the number of partitions?
No — Kafka doesn't support decreasing partitions. If you need fewer, create a new topic with the desired count and migrate producers and consumers. Choose partition count carefully at creation time; over-partitioning early is always the safer mistake.
What is log compaction?
Log compaction retains only the latest value for each key, removing older entries. It's useful for changelog topics where you only care about current state — user profiles, feature flags, config. Use log.cleanup.policy=compact instead of the default delete policy. Compaction and retention can coexist on different topics in the same cluster.
Should I still use ZooKeeper?
Not for new clusters — Kafka 4.0 removed ZooKeeper support entirely, and KRaft has been stable since 3.3. If you're running an older ZooKeeper cluster, plan a migration rather than a greenfield replacement; the official tooling handles the metadata conversion.
How do I achieve exactly-once processing?
Use Kafka's transactional API: a transactional producer with transactional_id, consume-transform-produce inside a transaction, and commit the consumer offset as part of it. Consumers must set isolation_level=read_committed. It costs latency — reserve it for pipelines where a duplicate is genuinely harmful.
Related Resources
Complete Guide to Serverless Architecture
Decide when to go serverless and when not to. FaaS patterns, cold starts, cost models, vendor lock-in, and migration strategies for production.
PatternCircuit Breaker Pattern in Python, JavaScript, and Java
Prevent cascading failures by stopping requests to failing services. An architectural pattern for resilient distributed systems.
PatternBulkhead Pattern: Isolate Resources to Limit Blast Radius
Isolate resources per service to limit blast radius. Covers thread pool isolation, connection pool partitioning, semaphore bulkheads, and resource quotas.
GuideMessage Queues Compared: RabbitMQ vs Kafka vs SQS
A decision guide for choosing between RabbitMQ, Kafka, and AWS SQS. Covers delivery guarantees, ordering, throughput, DLQs, and real production tradeoffs.
GuideComplete Guide to Event-Driven Systems
Design event-driven backends: event sourcing, CQRS, sagas, outbox pattern, idempotency, eventual consistency, and production patterns.
GuideRabbitMQ Architecture: Lifecycle, Queue Types, Failures
Follow a message through RabbitMQ: how exchanges, bindings and queues route it, the three ways it can die, and how to choose between classic, quorum and stream queues on RabbitMQ 4.x.