Kafka Performance Tuning: The Knobs That Matter
Senior level ยท Which settings actually move the needle, and in which direction.
Prerequisites
- !Producer batching and linger.ms
- !How brokers write segments to disk
What You'll Learn
- 1Trade throughput against latency with the five settings that control it
- 2Tune broker log and network settings for your workload shape
- 3Recognize when a client bottleneck is actually broker saturation
- 4Run a profiling loop that isolates one variable at a time
Throughput and latency are not negotiated independently
Almost every producer setting that increases throughput also increases latency, and vice versa. The settings that matter are small in number. linger.ms waits before sending so more records batch together. batch.size caps how large a batch grows, and must be raised before linger.ms can help. compression.type trades CPU for bytes on both the producer and the broker. max.in.flight.requests.per.connection allows more requests outstanding, which improves throughput but risks reordering on retries. acks controls durability and how long a produce call waits.
# High-throughput ingest
linger.ms=20
batch.size=262144
compression.type=lz4
acks=1
max.in.flight.requests.per.connection=5
buffer.memory=67108864
# Low-latency path on the same cluster
linger.ms=1
batch.size=16384
compression.type=none
acks=all
max.in.flight.requests.per.connection=1
The second profile is not slower because of the compression choice; it is slower because linger.ms was reduced and the batch never grows. Pick one profile per service and stop tuning once the requirement is met, because endless micro-tuning of an application whose bottleneck is upstream produces nothing but churn.
Batching first, always
Before touching anything else, check that batches are forming. A producer sending four hundred records per second to a topic with six partitions sends one record per batch, and no amount of buffer.memory changes that. Raise linger.ms until average batch size stops growing, then raise batch.size if the batches are hitting the cap. Only after batching is healthy does compression earn its keep, since compressing one-record batches is pure CPU waste.
The producer records average batch size and batch size distribution, so the check costs nothing. If batch size stays at one after linger.ms=20, the application is awaiting a downstream response between sends, and no producer setting will fix a chatty caller.
Broker settings that match the hardware
# Dedicated SSD log directory
num.io.threads=32
num.network.threads=8
socket.send.buffer.bytes=102400
socket.receive.buffer.bytes=102400
socket.request.max.bytes=104857600
# Segment sizing: fewer, larger segments reduce file handles and index churn
log.segment.bytes=1073741824
log.roll.hours=168
log.index.size.max.bytes=10485760
# Default retention, overridden per topic where needed
log.retention.hours=168
log.retention.bytes=-1
# Replication
num.replica.fetchers=4
replica.fetch.max.bytes=1048576
num.io.threads should exceed the core count when disks are the bottleneck, since the point is to keep the write path from queueing behind a single slow fsync. Segment size of one gigabyte with a weekly roll means the active segment is rarely closed, which cuts index churn on busy topics; small segments exist to support tight retention, so only shrink them where retention is measured in minutes.
num.replica.fetchers is the setting most often left at default while under-replication persists. Each fetcher thread serves a subset of the followers; raising it lets a busy broker keep a larger ISR in sync, at the cost of additional disk reads on the leader.
Consumers: the knob is almost always not a knob
# Consumer side
fetch.min.bytes=1
fetch.max.wait.ms=500
max.partition.fetch.bytes=1048576
max.poll.records=500
# The poll interval must exceed the worst-case processing time
max.poll.interval.ms=300000
A consumer that is behind is almost never limited by fetch settings. More usually the poll loop is doing slow work before returning, so the group rebalances, or the processing step is a synchronous call to a database that cannot keep up. max.poll.interval.ms is the guardrail: if a single poll takes longer than it, the member is kicked and triggers a rebalance that looks like an unrelated stability problem.
A profiling loop that isolates one variable
| Observation | Likely cause | First knob to try |
|---|---|---|
| Low producer throughput, batch size near one | Batches not forming | linger.ms, then batch.size |
| CPU pegged on broker with network idle | Compression or too many small writes | Larger segments, less frequent rolls |
| Under-replicated partitions on the leader | Follower fetchers saturated | num.replica.fetchers |
| Lag grows only during business hours | Downstream processing, not Kafka | Consumer code, not consumer config |
| Produce latency p99 spiky with steady mean | GC pauses on the broker | Heap size, G1 tuning, or more brokers |
โ ๏ธDo not tune across a noisy baseline
Measuring what you changed
# Broker-side view of request latency by type
kafka-run-class.sh kafka.tools.GetOffsetShell \
--broker-list kafka1:9092 --topic orders --time -1
# Throughput sanity check with a built-in perf tool
kafka-producer-perf-test.sh --topic perf-test \
--num-records 1000000 --record-size 1024 \
--throughput -1 \
--producer-props bootstrap.servers=kafka1:9092 \
linger.ms=20 batch.size=262144 compression.type=lz4
Always measure with the same record size distribution as production. A perf test with one-kilobyte uniform records will happily show five hundred megabytes per second and tell you nothing about a topic whose real records are forty kilobytes with occasional two-megabyte outliers hitting max.request.size.
Filesystem and disk choices that actually matter
Kafka is a sequential write workload by design, which is why it performs well on spinning disks and why the filesystem choice matters less than most teams expect, as long as you avoid the filesystems that do not handle append-only workloads well. The general guidance is to use XFS or ext4 on a dedicated volume, with the log directory on its own physical device or RAID array separate from the operating system and application filesystems. Sharing a disk with the OS means a log rotation or a package update can introduce latency spikes into a path that is otherwise purely sequential.
The page cache is not a cache you configure; it is a consequence of leaving memory available. Kafka relies on the operating system page cache for reads of recently written segments, so a broker with enough memory to hold the active segments of its busiest topics serves almost all consumer fetches from memory rather than from disk. Overcommitting memory to the JVM heap at the expense of the page cache is a common and counterproductive tuning choice; Kafka's heap needs are modest relative to the benefit of a warm page cache, which is why the default heap sizes are small and should stay that way until GC metrics say otherwise.
The write path is where the disk characteristics matter most. Kafka fsyncs on segment roll and on transaction commit, not on every append, so a disk with high fsync latency will not slow down steady-state ingest but will make segment rolls and transaction commits visibly slower. For transactional workloads, fsync latency is directly on the critical path of every commit, which is the main reason NVMe or a well-tuned RAID controller earns its cost on a transactional cluster even though a spinning array would be adequate for a pure append workload.
Compaction changes the read pattern. A compacted topic still needs to read the full segment during compaction to determine which keys to retain, so a broker hosting heavily compacted topics does more random reads than a pure retention-based broker. If compaction is a significant share of your topics, consider placing compacted topics on their own brokers or at least monitoring read latency separately from write latency, because the two workloads stress the disk in different ways.
One frequently overlooked setting is the number of log directories. A broker can span multiple directories, and doing so lets the OS stripe writes across devices without the operational complexity of a hardware RAID array. If you have multiple NVMe devices available, giving each its own log directory and letting Kafka balance topic partitions across them usually outperforms a single RAID volume, and it makes device failure a matter of moving one directory's topics rather than rebuilding an entire array.
Network buffers and the kernel defaults
The kernel's default TCP buffer sizes are tuned for general-purpose traffic, not for a system that moves hundreds of megabytes per second between brokers on a low-latency link. Raising net.core.wmem_max and net.core.rmem_max, and setting the socket send and receive buffer bytes in the broker configuration to match, prevents the window size from becoming the throughput ceiling on long fat networks. This is rarely the bottleneck in a single-region cluster, but it becomes one quickly when replication crosses a higher-latency link between availability zones.
The other network setting worth reviewing is the connection and request handling thread counts. num.network.threads handles the socket reads and writes, while num.request.threads handles the parsed request processing. Too few network threads means sockets sit unattended during a slow request; too many means context switching overhead with no throughput gain. The defaults are reasonable for a modest cluster and should only be raised after confirming that broker CPU is not the limiting factor and that the increase in a staging environment actually moved the metric you care about.
Common Mistakes
Raising buffer.memory to fix low producer throughput
Fix: Check batch size first. If batches contain one record, buffering just delays the same traffic; raise linger.ms and batch.size instead.
Setting acks=all on a low-latency path without raising max.poll.interval.ms
Fix: All-replica acks add network round-trip time; measure and decide deliberately rather than inheriting the durability default for a latency-sensitive service.
Increasing num.replica.fetchers without checking disk headroom
Fix: Fetchers issue additional reads on the leader. More threads on an already saturated disk makes under-replication worse, so verify disk utilization before raising it.
Tuning compression on single-record batches
Fix: Compression pays off on batches. Form healthy batches first, or you burn CPU compressing records one at a time.
Best Practices
- Fix batching before anything else; most throughput problems stop there
- Define one producer profile for throughput services and one for latency services, and codify both in shared client libraries
- Size segments and roll frequency from retention needs, not from defaults
- Keep a baseline measurement of produce latency and throughput per service so tuning changes are attributable
- Scale consumers by partitions, not by threads; more consumer threads than partitions buys nothing
Interview Questions
Q1: Which three producer settings most affect throughput?
linger.ms, batch.size and compression.type. They control how long records wait, how large the batch grows and how many bytes hit the wire; without healthy batches the other two do nothing.
Q2: Why would raising buffer.memory not help a slow producer?
Buffer memory only holds records waiting to be sent. If batches are tiny or the caller is blocking between sends, more buffer just delays the same limited traffic without increasing send rate.
Q3: What is the risk of max.in.flight.requests.per.connection greater than one with retries enabled?
On a retry after an earlier request already succeeded, records can be written out of order. With idempotent or transactional producers, or with idempotence enabled, reordering is prevented by the broker.
Q4: How do you fix under-replicated partitions caused by a slow follower?
Check replica.fetch.max.bytes and num.replica.fetchers first, then network latency to the follower. Raising fetchers helps only when the leader has CPU and disk headroom to serve additional fetch streams.
Q5: A consumer group keeps rebalancing during peak load. What do you check?
Whether a single poll plus processing exceeds max.poll.interval.ms. Slow downstream calls in the poll loop are the usual cause; raise the interval only after confirming processing time genuinely needs it.
Key Takeaways
- Throughput and latency trade through linger.ms, batch.size and compression; batch health comes first
- Broker tuning centers on io threads, replica fetchers and segment sizing matched to retention
- Consumer lag is usually a processing problem, not a fetch configuration problem
- One variable at a time, measured over a full business cycle, is the only attribution that holds
- Measure with production-like record sizes, or the numbers will not transfer