Intro
Apache Kafka has become a foundational component for real-time data pipelines, event streaming, and microservice communication. But behind every smoothly running Kafka cluster is a thoughtful capacity planning exercise that balances current throughput, future growth, and operational safety margins.
Capacity planning for Kafka is not a one-time task; it is an ongoing process of measurement, estimation, and adjustment. Without a clear plan, teams may over-provision and waste resources, or under-provision and risk outages, data loss, or unacceptable latency. This guide walks through a practical approach to Kafka capacity planning, including resource estimation, scaling signals, limits, growth risks, and operational safety margins, with worked examples you can adapt to your environment.
Whether you are a developer designing a new topic, a DevOps consultant evaluating a client's cluster, or a startup team planning for growth, this guide will give you concrete steps and formulas to size your Kafka deployment with confidence.
Version and Environment Inventory
Before you can plan capacity, you need a clear picture of your current or planned Kafka environment. This inventory includes software versions, hardware specifications, network topology, and workload characteristics.
Establish Kafka and Client Versions
Kafka's behavior and performance characteristics vary across versions. For example:
- Kafka 2.8 introduced the early access of KRaft (Kafka Raft) mode, removing the dependency on ZooKeeper.
- Kafka 3.0 made KRaft production-ready for new clusters.
- Kafka 3.3 introduced the first stable KRaft release, allowing entirely ZooKeeper-free clusters.
Knowing your version helps you understand feature availability and tuning parameters. For this guide, we assume Apache Kafka 3.5 with the classic ZooKeeper-based metadata management, but the principles apply to KRaft as well.
Action: Run the following command on a Kafka broker to confirm the version:
kafka-broker-api-versions.sh --bootstrap-server localhost:9092 | head -n 5
Expected output (example):
localhost:9092 (id: 1 rack: null) -> (
Produce(0): 0 to 9 [usable: 9],
Fetch(1): 0 to 13 [usable: 13],
ListOffsets(2): 0 to 7 [usable: 7],
Metadata(3): 0 to 12 [usable: 12],
...
)
This confirms the broker is reachable and shows supported API versions.
Document Hardware and Network Topology
Create a table for each broker in your cluster (or proposed cluster). Include CPU cores, memory, disk type and capacity, network bandwidth, and rack assignment.
| Broker ID | CPU Cores | Memory (GB) | Disk Type | Disk Size (GB) | Network (Gbps) | Rack |
|---|---|---|---|---|---|---|
| 1 | 16 | 64 | SSD | 2000 | 10 | rack1 |
| 2 | 16 | 64 | SSD | 2000 | 10 | rack2 |
| 3 | 16 | 64 | SSD | 2000 | 10 | rack1 |
Hypothetical example inventory table.
Identify Workload Characteristics
You need to know the expected production and consumption rates, message sizes, and topic configurations. For a new system, you can estimate from design documents; for an existing cluster, use metrics.
Use the kafka-topics.sh command to list existing topics and their configurations:
kafka-topics.sh --bootstrap-server localhost:9092 --list
kafka-topics.sh --bootstrap-server localhost:9092 --describe --topic orders
Example output for --describe:
Topic: orders TopicId: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx PartitionCount: 6 ReplicationFactor: 3
Topic: orders Partition: 0 Leader: 1 Replicas: 1,2,3 Isr: 1,2,3
...
Record the partition count, replication factor, and retention settings because they directly influence storage and throughput.
Prerequisites for Capacity Planning
- Monitoring in place: You need metrics from brokers (CPU, memory, disk I/O, network), JVM (heap usage, GC pauses), and Kafka-specific metrics (produce/fetch request rates, request latencies, under-replicated partitions). Tools like Prometheus with Kafka exporter, Datadog, or Confluent Control Center are common.
- Baseline load: If you have an existing cluster, capture a week of production metrics to understand peak and average loads.
- Growth projections: Estimate future traffic based on business forecasts, new feature launches, or seasonal patterns.
Safe Configuration Path
This section covers the key configuration decisions you can make safely to improve capacity and performance without introducing instability. Always apply changes in a staging environment first, and roll out gradually in production.
Broker Configuration Tuning
Increase File Descriptor Limits
Kafka uses many file descriptors for log segments and network connections. The default limit (often 1024) is too low. Set it to at least 128000 in /etc/security/limits.conf:
kafka soft nofile 128000
kafka hard nofile 128000
Then restart the broker. Verify with:
ulimit -n
Expected output: 128000
Adjust JVM Heap Size
Kafka brokers are not heavily dependent on large heaps because they use the page cache for log data. A heap of 6-8 GB is usually sufficient, even for high-throughput brokers. Avoid allocating more than 32 GB to prevent long GC pauses. Set in kafka-server-start.sh or KAFKA_HEAP_OPTS:
export KAFKA_HEAP_OPTS="-Xmx6g -Xms6g"
Optimize Log Retention
Retention policy determines how long data is kept and directly affects disk usage. Configure retention by time and/or size in server.properties:
log.retention.hours=72
log.retention.bytes=107374182400 # 100 GB per partition
log.segment.bytes=1073741824 # 1 GB segments
Use the command line to alter topic-specific retention:
kafka-configs.sh --bootstrap-server localhost:9092 --alter --entity-type topics --entity-name orders --add-config retention.ms=86400000
Topic Partitioning Strategy
Partitions are the unit of parallelism in Kafka. More partitions allow higher throughput but also increase overhead (more file handles, more metadata, longer recovery).
Formula for Initial Partition Count
A common heuristic: target throughput per partition is around 10-20 MB/s for produce or consume, depending on hardware. For a planned produce throughput of 100 MB/s, you would need at least 5-10 partitions per topic. However, consider the number of consumers in a consumer group; partitions set the upper limit for parallel consumption.
Hypothetical example: You expect 50,000 messages per second, each 2 KB in size. Total throughput = 50,000 x 2 KB = 100 MB/s. Using a conservative 10 MB/s per partition, you need 10 partitions. If you have 20 consumer instances, you might need at least 20 partitions to utilize all consumers.
You can increase partitions later (but not decrease), so plan ahead with some headroom.
Scenario: Repartitioning a Topic
Suppose you have an existing topic events with 3 partitions, and you need more parallelism. Use the kafka-topics.sh command to alter (increase) partitions:
kafka-topics.sh --bootstrap-server localhost:9092 --alter --topic events --partitions 6
Expected output: (no explicit confirmation; verify with describe)
kafka-topics.sh --bootstrap-server localhost:9092 --describe --topic events
Output shows PartitionCount: 6.
Replication Factor and Min ISR
Replication factor (RF) determines data durability. RF=3 is common for production, allowing one broker failure without data loss. But higher RF increases storage and network traffic.
Set the minimum in-sync replicas (ISR) to ensure producers wait for acknowledgements when replication is lagging. For RF=3, set min.insync.replicas=2 for topic-level config:
kafka-configs.sh --bootstrap-server localhost:9092 --alter --entity-type topics --entity-name orders --add-config min.insync.replicas=2
This ensures that at least two replicas acknowledge a write before the producer gets success.
Producer and Consumer Settings
Producer and consumer configurations impact cluster load. Key settings:
- Producer: Set
acks=allfor durability, but this increases latency slightly. Setcompression.type=lz4to reduce network and disk usage. - Consumer: Set
fetch.min.bytesandfetch.max.wait.msto balance latency and throughput.
Example producer configuration (Java properties):
Properties props = new Properties();
props.put("bootstrap.servers", "broker1:9092, broker2:9092");
props.put("acks", "all");
props.put("compression.type", "lz4");
props.put("linger.ms", "5");
props.put("batch.size", "16384");
Monitoring and Alerting Setup
Set up alerts based on key metrics to catch capacity issues early:
- Under-replicated partitions > 0 for more than a few minutes.
- CPU usage > 80% sustained.
- Disk usage > 70% (plan for expansion).
- Network throughput approaching link capacity.
Verification and Diagnostics
After making configuration changes or as part of ongoing capacity management, you need to verify that the cluster is healthy and performing as expected.
Check Cluster Health
Use kafka-broker-api-versions.sh to list active brokers:
kafka-broker-api-versions.sh --bootstrap-server localhost:9092 | grep '^\['
Expected output (with multiple brokers): [1, 2, 3]
Check for under-replicated partitions:
kafka-topics.sh --bootstrap-server localhost:9092 --describe --under-replicated-partitions
This will list any partitions that are behind; ideally, no output.
Monitor Throughput and Latency
Use command-line tools or JMX metrics to measure produce and consume rates.
Produce a Test Load
Use kafka-producer-perf-test.sh to generate a known load and measure throughput:
kafka-producer-perf-test.sh --topic test-perf --num-records 1000000 --record-size 1024 --throughput -1 --producer-props bootstrap.servers=localhost:9092 acks=all
Expected output includes:
1000000 records sent, 1024.000000 MB, 256.41 MB/sec, 250000.00 records/sec ...
Compare this to your estimated per-partition capacity.
Check Consumer Lag
Consumer lag is the difference between the latest offset and the consumer's current offset. High lag indicates consumers can't keep up. Use kafka-consumer-groups.sh:
kafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group my-consumer-group
Example output:
GROUP TOPIC PARTITION CURRENT-OFFSET LOG-END-OFFSET LAG CONSUMER-ID HOST CLIENT-ID
my-consumer-group orders 0 1000 1500 500 consumer-1-xxx /192.168.1.5 consumer-1
Lag of 500 means the consumer is behind by 500 messages. If lag grows continuously, you may need more partitions or consumers.
Examine Broker Metrics via JMX
Connect to a broker's JMX port (default 9999) using JConsole or a monitoring tool. Key metrics:
kafka.server:type=BrokerTopicMetrics,name=MessagesInPerSeckafka.server:type=BrokerTopicMetrics,name=BytesInPerSeckafka.server:type=BrokerTopicMetrics,name=BytesOutPerSeckafka.network:type=RequestMetrics,name=TotalTimeMs,request=Produce
Observe these under load to identify bottlenecks.
Validate Disk Space Usage
Run df -h on brokers to check disk usage:
df -h /var/lib/kafka/data
Example output:
Filesystem Size Used Avail Use% Mounted on
/dev/sdb1 2.0T 1.2T 800G 60% /var/lib/kafka/data
If usage exceeds 70%, plan to add disks or reduce retention.
Failure Modes and Recovery
Even with careful planning, failures can occur. Understanding common failure modes helps you prepare recovery procedures and minimize impact.
Broker Failure
If a broker fails, its partitions become under-replicated. Kafka automatically elects new leaders from in-sync replicas. However, if the failed broker stays down, you may lose redundancy.
Recovery: Bring the broker back online. If it's unrecoverable, add a new broker and reassign partitions.
Use kafka-reassign-partitions.sh to generate a reassignment plan. Create a JSON file reassign.json:
{
"partitions": [
{"topic": "orders", "partition": 0, "replicas": [1,2,4]}
],
"version": 1
}
Then execute:
kafka-reassign-partitions.sh --bootstrap-server localhost:9092 --reassignment-json-file reassign.json --execute
Monitor progress with --verify.
Disk Full
If a broker's disk fills up, Kafka will reject writes. This can cause producer failures and potentially data loss if not handled.
Recovery:
- Reduce retention temporarily:
kafka-configs.sh --bootstrap-server localhost:9092 --alter --entity-type topics --entity-name orders --add-config retention.ms=3600000
- Delete unused topics or old data.
- Add disk space or move partitions to other brokers.
Network Saturation
If network bandwidth is saturated, you'll see high request latencies and timeouts. This often happens during rebalancing or large consumer group changes.
Recovery: Limit replication traffic by setting num.replica.fetchers lower temporarily, or throttle reassignment traffic using kafka-configs.sh for leader.replication.throttled.rate.
JVM Garbage Collection Pauses
Long GC pauses can cause brokers to drop out of ISR, leading to leader elections and producer timeouts. Monitor GC metrics and tune heap accordingly. If pauses are frequent, consider reducing heap or adjusting GC algorithm (e.g., G1GC with -XX:MaxGCPauseMillis=20).
Rollback Configuration Changes
Always keep a backup of configuration files. If a change causes performance degradation, revert to the previous known-good configuration and restart brokers one by one.
For topic-level config changes, you can delete the overridden config to revert to broker defaults:
kafka-configs.sh --bootstrap-server localhost:9092 --alter --entity-type topics --entity-name orders --delete-config retention.ms
Operations Checklist
Use this checklist as a recurring review to ensure capacity remains adequate and the cluster is healthy.
Weekly Review
- [ ] Check for under-replicated partitions:
kafka-topics.sh --describe --under-replicated-partitions - [ ] Review consumer lag for all critical consumer groups.
- [ ] Monitor disk usage across brokers.
- [ ] Check broker CPU and memory utilization.
- [ ] Verify network throughput is below 70% of capacity.
Monthly Capacity Review
- [ ] Analyze produce and consume rate trends over the past month.
- [ ] Project growth for the next 3-6 months based on trends.
- [ ] Assess if partition counts need to be increased for high-traffic topics.
- [ ] Evaluate retention settings against storage capacity.
- [ ] Review replication factor and min ISR settings for critical topics.
Pre-Launch / Major Change Checklist
- [ ] Estimate new topic throughput and partition count using the formulas.
- [ ] Set appropriate retention and replication factor.
- [ ] Test producer and consumer performance in staging.
- [ ] Configure alerts for the new topic.
- [ ] Document expected resource usage and review after one week.
Table: Key Metrics and Alert Thresholds
| Metric | Warning Threshold | Critical Threshold | Action |
|---|---|---|---|
| Under-replicated partitions | > 0 for 5 minutes | > 0 for 15 minutes | Investigate broker health and network |
| CPU usage per broker | > 70% sustained 10 min | > 85% sustained 5 min | Consider adding brokers or tuning |
| Disk usage | > 70% | > 85% | Add disk or reduce retention |
| Consumer lag | > 1000 messages or growing | > 10000 or non-stop growth | Scale consumers or partitions |
| Network throughput | > 60% of link capacity | > 80% | Plan for network upgrade or traffic shaping |
Common Pitfalls and How to Avoid Them
Even experienced teams can fall into traps that undermine capacity planning. Here are the most frequent mistakes and how to steer clear of them.
Underestimating Partition Overhead
Why it happens: Teams focus only on throughput and create too many partitions, thinking it will increase parallelism. But each partition consumes file handles, memory, and increases metadata size. With thousands of partitions, broker startup and recovery times can balloon.
How to avoid: Use the throughput heuristic (10-20 MB/s per partition) and consider the number of consumers. Monitor file descriptor usage and broker recovery time. If partitions exceed a few thousand per broker, consider consolidating topics or using tiered storage.
Recovery: If you already have too many partitions, you cannot decrease them without recreating the topic. Plan a migration: create new topics with appropriate partition counts, then switch producers and consumers over.
Ignoring Replication Traffic in Network Sizing
Why it happens: Planners often calculate only producer and consumer traffic, forgetting that replication factor multiplies network I/O. For RF=3, each byte is written three times and read at least once during replication.
How to avoid: Multiply your expected ingress/egress by the replication factor when sizing network capacity. For example, if producers write 100 MB/s with RF=3, you need at least 300 MB/s of broker-to-broker network capacity plus producer/consumer traffic.
Recovery: If you find network saturation, reduce RF (with caution) or add network capacity. You can also throttle replication traffic during peak hours.
Setting Retention Too High
Why it happens: Business requirements for long data retention are often overestimated, leading to massive disk consumption and unnecessary cost.
How to avoid: Right-size retention by analyzing actual data usage. Use tiered storage or object storage for archival if needed. Monitor disk usage trends and set alerts.
Recovery: Reduce retention gradually and delete old data. Use kafka-configs.sh to alter retention per topic.
Not Testing with Realistic Load
Why it happens: Teams rely on vendor benchmarks or small-scale tests that don't reflect production workload characteristics, such as message key distribution, consumer group behavior, or network latency.
How to avoid: Always run performance tests with production-like data sizes, key distributions, and consumer counts. Use tools like kafka-producer-perf-test.sh and kafka-consumer-perf-test.sh or Trogdor.
Recovery: If you discover performance issues after deployment, simulate the production load in a staging environment and iterate on configurations before applying to production.
Conclusion
Kafka capacity planning is an essential discipline that combines technical understanding, proactive monitoring, and strategic foresight. By following the steps in this guide, you can avoid common pitfalls like under-provisioned clusters, unexpected outages, and runaway storage costs.
Start with a thorough inventory of your environment and workload. Apply safe configuration tuning such as file descriptor limits, heap sizing, and retention policies. Establish a solid partition strategy that balances parallelism and overhead. Verify cluster health with command-line tools and performance tests, and be ready to recover from failures with clear rollback procedures. Finally, institutionalize the operations checklist to keep your cluster running smoothly as traffic grows.
A first pilot can be narrow: pick one critical topic, estimate its needs, apply the tuning, and measure the outcomes for a week. This local, measurable approach reduces risk and provides valuable data for broader capacity planning efforts.
Use the checklists and tables as living documents, updating them as your system evolves. With consistent review and adjustment, your Kafka cluster can scale confidently to meet demand.