Kafka Performance Tuning
Overview
Kafka performance tuning requires balancing throughput and latency while optimizing CPU, memory, disk I/O, and network resources. This guide covers optimization strategies for producers, brokers, consumers, and networking.
Performance Goals
- High Throughput: Maximize messages/bytes per second
- Low Latency: Minimize end-to-end delay
- Resource Efficiency: Optimize CPU, memory, disk usage
- Scalability: Handle growth without degradation
Every Kafka request travels the same road: the client batches records into a buffer, a sender thread ships the batch to the broker that leads the partition, the broker's network threads hand it to the request handler pool, the records land in the page cache and are appended to the log, the follower replicas fetch them, and only then does the client consider the write complete. A bottleneck in any one of those stages shows up as a different symptom, so tuning starts by locating the stage rather than by changing a number. Sustained throughput problems point at batching, disk or replication; latency problems point at linger settings, fetch sizes and queueing behind saturated threads; a sudden collapse in both usually means the page cache has been evicted or a garbage collection pause has started repeating. Capture a baseline with kafka-producer-perf-test before touching anything, because a configuration change that improves a synthetic benchmark while your real workload has 400 topics and 12 partitions per topic often makes production worse.
Producer Tuning
Batching Configuration
# Producer batch settings
batch.size=32768 # 32KB batch size
linger.ms=5 # Wait 5ms to fill batch
buffer.memory=67108864 # 64MB buffer memory
max.in.flight.requests.per.connection=5 # Allow 5 in-flight requests
These four settings interact, and the arithmetic explains why. With batch.size=32768 and 1 KB records, each batch holds 32 records; linger.ms=5 means the sender waits up to five milliseconds to collect them, so a partition receiving 10,000 records per second fills the batch in 3.2 milliseconds and the wait never costs anything, while a partition receiving 40 records per second waits the full five milliseconds and still ships a batch of two records, adding latency for no gain. That is the whole trade: raise linger.ms when traffic is dense, lower it when partitions are sparse or the workload is interactive. buffer.memory=67108864 caps how many records can wait to be acknowledged â about 65,000 records at 1 KB â and once it fills, the sending thread blocks instead of failing, so buffer-available-percent stuck below 100 is your signal that the broker side cannot keep up with the client.
Durability settings follow from the replication factor. acks=all combined with min.insync.replicas=2 on a three-replica topic means a write survives losing one broker, and the write fails fast when only one replica is available rather than silently degrading; acks=1 accepts the leader's local write only, which trades a window of data loss for roughly a round-trip of latency per batch. Enabling idempotence keeps max.in.flight.requests.per.connection=5 safe, because the broker discards duplicates and restores order across retries; without it, five in-flight requests plus retries can reorder or duplicate records on the wire.
Batching Strategy
from kafka import KafkaProducer
# High throughput configuration
producer = KafkaProducer(
bootstrap_servers=['kafka:9092'],
batch_size=32768, # 32KB batches
linger_ms=5, # Wait for batch fill
buffer_memory=67108864, # 64MB buffer
max_in_flight_requests_per_connection=5,
acks='all',
compression_type='lz4'
)
# Low latency configuration
producer = KafkaProducer(
bootstrap_servers=['kafka:9092'],
batch_size=16384, # 16KB batches
linger_ms=0, # Send immediately
buffer_memory=33554432, # 32MB buffer
max_in_flight_requests_per_connection=1,
acks='all',
compression_type='none'
)
Compression Options
| Algorithm | CPU Usage | Compression Ratio | Latency |
|---|---|---|---|
| none | None | 1:1 | Lowest |
| gzip | High | ~3:1 | High |
| snappy | Low | ~2:1 | Low |
| lz4 | Low | ~2.5:1 | Low |
| zstd | Medium | ~3.5:1 | Medium |
# Compression configuration
producer = KafkaProducer(
bootstrap_servers=['kafka:9092'],
compression_type='lz4', # Best balance of speed/ratio
batch_size=65536, # 64KB for better compression
linger_ms=10 # Allow larger batches
)
Compression happens per batch inside the client, which is why batch size and algorithm cannot be tuned independently: a 16 KB batch of small JSON records compresses to roughly half, while the same records in 2 KB batches lose a fifth of their ratio to per-record framing. Watch compression-rate-avg to see the real factor your data achieves rather than the vendor figure, and expect the win to be largest on the network-bound path â compressing to save disk on a broker whose bottleneck is CPU will make matters worse. The broker never decompresses a batch it does not need to; it stores the compressed form and passes it on, so compression.type=producer on the topic is the correct default and setting lz4 or zstd broker-side only burns CPU during log cleaning. Choose zstd when bandwidth is the scarce resource and you can afford the CPU, lz4 when you want the ratio without giving up much speed, and leave gzip for legacy consumers that cannot decode anything else.
Producer Performance Testing
# kafka-producer-perf-test
kafka-producer-perf-test.sh \
--topic test-topic \
--num-records 1000000 \
--record-size 1024 \
--throughput -1 \
--producer-props \
bootstrap.servers=kafka:9092 \
batch.size=32768 \
linger.ms=5 \
compression.type=lz4 \
acks=1
Broker Tuning
Thread Configuration
# Server thread settings
num.io.threads=16 # I/O threads (disk operations)
num.network.threads=8 # Network threads (socket handling)
num.replica.fetchers=4 # Replica fetch threads
background.threads=10 # Background tasks
Thread counts should follow hardware rather than folklore. num.io.threads feeds the log append path, so size it at one thread per spinning disk or two to four per solid-state drive; on a modern server with a single NVMe device, sixteen is generous and sixty-four mostly produces context switching and queueing inside the kernel. num.network.threads handles socket reads and writes and scales with cores: eight suits a sixteen-core broker carrying a few hundred connections, while a broker fronting thousands of clients needs more because each request is framed, buffered and validated on that pool before it reaches disk. The number to watch is RequestHandlerAvgIdlePercent â when it sits below 0.7 during peak traffic, handlers are saturated and requests are queueing, and the correct response is more threads only if the disks still have headroom; if disk utilisation is already above 90%, extra threads just move the queue. num.replica.fetchers matters in proportion to replication traffic, with four a common choice on a three-broker cluster that also serves client traffic, because follower fetches compete with client fetches for the same network and page cache.
Log Configuration
# Log flush settings
log.flush.interval.messages=10000 # Flush every 10K messages
log.flush.interval.ms=1000 # Flush every second
log.flush.scheduler.interval.ms=500 # Check every 500ms
# Log segment settings
log.segment.bytes=1073741824 # 1GB segments
log.roll.hours=168 # Roll weekly
log.index.size.max.bytes=10485760 # 10MB index
log.index.interval.bytes=4096 # Index interval
Flush settings are where well-meaning tuning does the most damage. The broker's default is effectively "never force a flush", because durability comes from having the record on two or three replicas rather than from the leader's write reaching the platter before acknowledging; forcing a flush every 1000 messages or every second converts a sequential write pattern into a synchronous one and can halve throughput on a disk that was already keeping up through the page cache. Keep the aggressive flush values only for a single-broker cluster with replication factor one that must survive power loss, where you are trading throughput for a guarantee replication cannot give you. Segment settings deserve attention for a different reason: a 1 GB segment rolling every 168 hours means a topic holds about 250 active index files per partition, while log.index.size.max.bytes left at 10 MB on a topic with very large keys forces index reads back to disk, so watch LogFlushRateAndLatencyMs and the time spent in log cleaner threads rather than tuning flushes by intuition.
Memory Configuration
# Memory allocation
heap.size=8G # JVM heap size
socket.send.buffer.bytes=1048576 # 1MB send buffer
socket.receive.buffer.bytes=1048576 # 1MB receive buffer
socket.request.max.bytes=104857600 # 100MB max request
Disk I/O Optimization
# Filesystem optimization
mount -o noatime,nodiratime /dev/sda1 /kafka-logs
# I/O scheduler (for SSDs)
echo noop > /sys/block/sda/queue/scheduler
# RAID configuration (RAID 10 for performance)
mdadm --create /dev/md0 --level=10 --raid-devices=4 /dev/sd{a,b,c,d}1
Consumer Tuning
Fetch Configuration
# Consumer fetch settings
fetch.min.bytes=1048576 # 1MB minimum fetch
fetch.max.wait.ms=500 # Wait up to 500ms
max.partition.fetch.bytes=1048576 # 1MB per partition
max.poll.records=500 # Process 500 records per poll
max.poll.interval.ms=300000 # 5 minutes max processing
Fetch settings trade latency against efficiency, and the two numbers must be read together. fetch.min.bytes=1048576 tells the broker to hold a response until a full megabyte has accumulated or fetch.max.wait.ms=500 elapses, so a quiet topic answers in half a second and a busy topic answers as soon as the megabyte is there â which is exactly why you can raise the first number to cut broker request rate without slowing a loaded system. Lower both to 1 byte and 100 milliseconds when a user is waiting on a single record. Memory follows from max.partition.fetch.bytes times the number of partitions assigned to one consumer: 1 MB across 100 partitions means up to 100 MB per fetch response in that consumer's heap, which is how a modest consumer group dies with an out-of-memory error after a partition reassignment doubles one member's assignment.
Polling behaviour causes more outages than fetch tuning ever will. The group expects a poll at least every session.timeout.ms, and it expects the previous batch of records to be finished within max.poll.interval.ms; process 500 records slower than the five-minute default and the coordinator considers the member gone, revokes its partitions, and restarts the whole group. The fix is to shrink max.poll.records until processing comfortably fits the interval, then handle long work asynchronously, because a rebalance during a traffic spike costs far more than a few extra polls.
Consumer Strategy
from kafka import KafkaConsumer
# High throughput consumer
consumer = KafkaConsumer(
'orders',
bootstrap_servers=['kafka:9092'],
group_id='order-processor',
fetch_min_bytes=1048576, # 1MB minimum
fetch_max_wait_ms=500, # Wait for batch
max_partition_fetch_bytes=1048576,
max_poll_records=500,
auto_offset_reset='earliest',
enable_auto_commit=False
)
# Low latency consumer
consumer = KafkaConsumer(
'orders',
bootstrap_servers=['kafka:9092'],
group_id='order-processor',
fetch_min_bytes=1, # Get anything available
fetch_max_wait_ms=100, # Quick response
max_partition_fetch_bytes=65536,
max_poll_records=50,
auto_offset_reset='earliest',
enable_auto_commit=False
)
Consumer Performance Testing
# kafka-consumer-perf-test
kafka-consumer-perf-test.sh \
--topic test-topic \
--messages 1000000 \
--group perf-test-group \
--bootstrap-server kafka:9092 \
--fetch-size 1048576
Network Tuning
Socket Configuration
# Producer network
socket.send.buffer.bytes=1048576 # 1MB send buffer
socket.request.max.bytes=104857600 # 100MB max request
# Consumer network
socket.receive.buffer.bytes=1048576 # 1MB receive buffer
fetch.min.bytes=1048576 # 1MB minimum fetch
# Broker network
num.network.threads=8
socket.receive.buffer.bytes=1048576
socket.send.buffer.bytes=1048576
OS Tuning
# Increase file descriptor limits
ulimit -n 100000
# Kernel network tuning
sysctl -w net.core.rmem_max=16777216
sysctl -w net.core.wmem_max=16777216
sysctl -w net.core.rmem_default=16777216
sysctl -w net.core.wmem_default=16777216
sysctl -w net.ipv4.tcp_rmem="4096 87380 16777216"
sysctl -w net.ipv4.tcp_wmem="4096 65536 16777216"
sysctl -w net.core.netdev_max_backlog=5000
Performance Monitoring
Key Metrics
# Performance metrics to track
metrics:
- name: kafka_server_BrokerTopicMetrics_MessagesInPerSec
description: "Messages received per second"
target: "> 100000"
- name: kafka_server_BrokerTopicMetrics_BytesInPerSec
description: "Bytes received per second"
target: "> 100MB/s"
- name: kafka_server_ReplicaManager_UnderReplicatedPartitions
description: "Under-replicated partitions"
target: "= 0"
- name: kafka_consumer_group_lag
description: "Consumer group lag"
target: "< 1000"
Performance Dashboard
{
"panels": [
{
"title": "Throughput (MB/s)",
"type": "timeseries",
"targets": [
{
"expr": "sum(rate(kafka_server_BrokerTopicMetrics_BytesInPerSec[5m]))",
"legendFormat": "Inbound"
},
{
"expr": "sum(rate(kafka_server_BrokerTopicMetrics_BytesOutPerSec[5m]))",
"legendFormat": "Outbound"
}
]
},
{
"title": "Latency (p99)",
"type": "timeseries",
"targets": [
{
"expr": "histogram_quantile(0.99, kafka_network_RequestMetrics_TotalTimeMs_bucket)",
"legendFormat": "p99 latency"
}
]
}
]
}
Benchmarking
End-to-End Benchmark
import time
from kafka import KafkaProducer, KafkaConsumer
import statistics
def benchmark_producer(num_messages, message_size, batch_size, linger_ms):
producer = KafkaProducer(
bootstrap_servers=['kafka:9092'],
batch_size=batch_size,
linger_ms=linger_ms,
compression_type='lz4',
acks='all'
)
start_time = time.time()
for i in range(num_messages):
message = b'x' * message_size
producer.send('benchmark-topic', value=message)
producer.flush()
end_time = time.time()
elapsed = end_time - start_time
throughput = num_messages / elapsed
mb_throughput = (num_messages * message_size) / elapsed / 1024 / 1024
print(f"Throughput: {throughput:.0f} messages/sec")
print(f"Bandwidth: {mb_throughput:.1f} MB/sec")
print(f"Latency avg: {elapsed/num_messages*1000:.2f} ms")
# Run benchmark
benchmark_producer(
num_messages=100000,
message_size=1024,
batch_size=32768,
linger_ms=5
)
Common Issues and Solutions
High Latency
| Symptom | Cause | Solution |
|---|---|---|
| High end-to-end latency | Large batches | Reduce batch.size and linger.ms |
| Slow consumer processing | Small fetches | Increase fetch.min.bytes |
| Network congestion | Insufficient buffers | Increase socket buffers |
Low Throughput
| Symptom | Cause | Solution |
|---|---|---|
| Low messages/sec | No compression | Enable compression.type=lz4 |
| High CPU usage | Compression overhead | Use snappy or lz4 |
| Disk I/O bottleneck | Too many small writes | Increase batch.size |
Common Mistakes
Raising linger.ms and batch.size to chase throughput without watching latency
Fix: Compute how long a batch takes to fill at your real record rate, then cap linger below the latency budget so dense partitions batch and sparse partitions do not wait
Setting log.flush.interval.ms to a small value to avoid losing data
Fix: Rely on replication with min.insync.replicas=2 for durability and leave flushing to the page cache unless you run a single broker with replication factor one
Leaving max.poll.records at 500 while processing each record slowly
Fix: Shrink the poll batch until processing finishes well inside max.poll.interval.ms, because exceeding it triggers a group-wide rebalance instead of a slow consumer warning
Summary
Kafka performance tuning requires optimizing producer batching, broker threading, consumer fetching, and network buffers. Monitor key metrics and adjust configurations based on your specific throughput and latency requirements.
See Also
- Kafka Architecture â Understanding brokers, partitions, and replication internals
- Kafka Producer & Consumer â Configuring producers and consumers for optimal performance
- Kafka Monitoring â Tracking performance metrics with Prometheus and Grafana