Kafka Performance Tuning: Throughput and Latency
Kafka performance comes from a few design decisions that work together: an append-only log written sequentially, heavy use of the operating system’s page cache, batching and compression from producer to consumer, zero-copy transfer to consumers, and partitions that spread work over many brokers and threads. Tuning Kafka is mostly about choosing, per workload, where to sit between maximum throughput and minimum latency.
This article explains how Kafka achieves high throughput and low latency internally, then gives concrete producer, consumer, broker and topic settings for each goal, with a way to measure the result.
1. How Kafka Achieves High Throughput and Low Latency
- Sequential, append-only log. Each partition is a series of segment files that are only appended to. Sequential disk I/O is far faster than random I/O on both HDDs and SSDs.
- Page cache instead of an application cache. Brokers write to the operating system’s page cache and let the OS flush to disk. Consumers reading recent data are served from memory, and the cache survives broker restarts because it belongs to the OS, not the JVM. Durability comes from replication, not from an
fsyncper write. - Batching end to end. The producer groups records per partition; one request carries many batches; consumers fetch many records per request. Fewer, larger requests mean less network and CPU overhead per record.
- Compression of whole batches. A batch of similar JSON records compresses well. It stays compressed on the broker and over the network and is decompressed by the consumer.
- Zero-copy transfer. On plaintext connections the broker uses the
sendfilesystem call to move data from the page cache straight to the network socket. With TLS, data must be encrypted in user space, so this optimisation does not apply. - Partitions for parallelism. Partitions of a topic are led by different brokers and read by different consumers, so throughput scales horizontally.
- Efficient binary protocol and a small, fixed set of threads per broker: network threads handle sockets and I/O threads handle requests.
2. Throughput vs Latency: The Trade-off
Batching is the main lever. Bigger batches give more throughput per CPU and per byte, but each record waits a little longer for its batch to fill. Kafka’s defaults are a balance; tune them toward one goal only when you know which one matters.
| Setting | Default (Kafka 4.4) | For throughput | For low latency |
|---|---|---|---|
linger.ms (producer) | 5 | 10–100 | 0–5 |
batch.size (producer) | 16384 | 64–256 KB | default |
compression.type (producer) | none | lz4 or zstd | lz4 or none |
acks (producer) | all | all (keep durability) | all; lower only for data you can lose |
fetch.min.bytes (consumer) | 1 | 64 KB–1 MB | 1 |
fetch.max.wait.ms (consumer) | 500 | 500 | lower, such as 100 |
max.poll.records (consumer) | 500 | higher, if processing is cheap | lower |
Since Kafka 4.0 the default linger.ms is 5 instead of 0, because a short wait usually produces fuller batches with little latency cost.
3. Producer Tuning
A throughput-oriented producer for an event pipeline, keeping full durability:
Properties props = new Properties();
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "broker1:9092,broker2:9092,broker3:9092");
props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
props.put(ProducerConfig.ACKS_CONFIG, "all"); // durability is not traded away
props.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, true);
props.put(ProducerConfig.LINGER_MS_CONFIG, 20); // wait up to 20 ms to fill a batch
props.put(ProducerConfig.BATCH_SIZE_CONFIG, 131_072); // 128 KB per partition batch
props.put(ProducerConfig.COMPRESSION_TYPE_CONFIG, "lz4"); // cheap CPU, good ratio
props.put(ProducerConfig.BUFFER_MEMORY_CONFIG, 67_108_864); // 64 MB to absorb bursts
KafkaProducer<String, String> producer = new KafkaProducer<>(props);
- Send asynchronously. Calling
send(record).get()for every record turns the producer into a one-record-at-a-time client and destroys batching. Use callbacks or collect futures. - Reuse one producer per application; it is thread-safe and batches records from all threads.
- Watch
record-queue-time-avgandbatch-size-avgin the producer metrics: if batches stay small, raisingbatch.sizehas no effect andlinger.msis the setting to increase.
4. Consumer Tuning
- Parallelism first: one consumer thread per partition is the upper bound of a group’s parallelism. See Kafka Consumer Lag and Backpressure for scaling beyond that.
- Fetch sizes:
fetch.min.bytesmakes the broker wait (up tofetch.max.wait.ms) until enough data is available, reducing requests;max.partition.fetch.bytes(1 MB) andfetch.max.bytes(50 MB) cap response sizes. - Processing cost dominates: most slow consumers are slow because of per-record database or HTTP calls. Batch listeners and bulk writes usually beat any fetch tuning.
- Commit less often: committing after every record adds a round trip per record; commit per batch.
5. Broker and Topic Tuning
| Area | Guidance |
|---|---|
| Partitions | Enough for peak consumer parallelism and to spread leaders over brokers; very high counts per broker add metadata and recovery cost |
| Threads | num.network.threads (default 3) and num.io.threads (default 8); raise when request queues grow and CPU is available |
Topic compression.type | Default producer keeps the producer’s codec; a different codec forces the broker to recompress every batch |
| Flushing | Leave log.flush.* at defaults; rely on replication for durability and the OS for flushing |
| Hardware | Memory for page cache matters more than JVM heap; fast disks and network; keep the heap modest |
| Replication | Replication factor 3 with acks=all costs a follower round trip; do not trade it away for latency on important data |
6. Measuring Performance
Kafka ships a load-generation tool. Compare settings on a test topic with the same partition count and replication as production:
$ bin/kafka-producer-perf-test.sh --topic perf-test --num-records 2000000 --record-size 1024 \
--throughput -1 --bootstrap-server localhost:9092 \
--command-property acks=all linger.ms=20 batch.size=131072 compression.type=lz4
... records sent, ... records/sec (... MB/sec), ... ms avg latency, ... ms max latency,
... ms 50th, ... ms 95th, ... ms 99th, ... ms 99.9th.
Run it several times, change one setting at a time, and look at both throughput and the 99th-percentile latency. Use real payloads if possible, because compression ratios depend heavily on the data.
7. Common Mistakes
- Blocking on every send with
.get(), then blaming Kafka for low throughput. - Lowering
acksto fix latency that is actually caused by small batches or a slow consumer. - Large JVM heaps on brokers, which take memory away from the page cache.
- A topic-level compression codec different from the producer’s, causing recompression on every write.
- Tuning without measuring, or measuring with a payload that compresses unlike production data.
8. Summary
Kafka is fast because it appends sequentially to a log in the OS page cache, moves data in compressed batches, serves consumers with zero-copy transfers on plaintext connections, and parallelises through partitions. To tune it, decide whether a workload needs throughput or latency: raise linger.ms, batch.size, compression and fetch sizes for throughput; keep batches small and waits short for latency. Keep acks=all for important data, send asynchronously, and measure every change with realistic data.
9. Related Reading
10. References
- Apache Kafka design: Persistence, efficiency and the producer
- Apache Kafka 4.4: Producer configs (linger.ms, batch.size, compression.type)
- Apache Kafka 4.4: Consumer configs (fetch.min.bytes, fetch.max.wait.ms)
- Apache Kafka 4.4: Broker configs (num.network.threads, num.io.threads)
- Apache Kafka 4.4: Monitoring (producer and consumer metrics)
Kafka Performance Tuning Interview Questions and Answers
Common interview questions on Kafka Performance Tuning, from basic to scenario-based, with short answers you can explain in your own words.
Basic questions
Q. Kafka is designed for throughput. What keeps its latency low at the same time?
Answer: Recent data is served from the OS page cache, so most consumer reads never touch the disk. Brokers do not fsync each write; durability comes from replication, so a write is acknowledged as soon as the in-sync replicas have it in memory. Consumers use long polling: with fetch.min.bytes=1 the broker answers a waiting fetch as soon as new data arrives, instead of the consumer polling on a timer. Producer batching waits are short by default (linger.ms=5), and zero-copy transfer keeps the broker’s send path cheap on plaintext connections.
Q. What is zero-copy in Kafka, and when does it not apply?
Answer: When a consumer fetches data, the broker can use the sendfile system call to move bytes from the page cache directly to the network socket, without copying them into the JVM and back. This saves CPU and memory bandwidth, and works because brokers store batches in the same format they send. It does not apply to TLS connections, because data must be encrypted in user space before it is sent, so TLS clusters need more broker CPU.
Intermediate questions
Q. Why does Kafka rely on the OS page cache instead of caching data in the JVM heap?
Answer: Java objects carry large memory overhead and a big heap leads to long garbage-collection pauses. The page cache stores the bytes compactly, is shared with the zero-copy path, and stays warm when the broker process restarts. Recent data, which most consumers read, is therefore served from memory. This is why brokers run with a modest heap and leave most of the machine’s memory to the OS.
Q. Why did Kafka 4.0 change the producer’s default linger.ms from 0 to 5?
Answer: With linger.ms=0, a producer sends a batch as soon as the sender thread is free, which under moderate load produces many small requests. Waiting a few milliseconds lets more records join each batch, so the producer sends fewer, larger requests with better compression and less broker overhead. According to the Kafka 4.0 upgrade notes, the efficiency gain typically results in similar or even lower producer latency, despite the extra wait. Latency-critical producers can still set it back to 0.
Tricky and scenario questions
Q. A producer reaches only a few thousand records per second, while the brokers are almost idle. What do you check?
Answer: First, whether the code calls send(...).get() per record, which makes every send wait for a round trip; switch to asynchronous sends with callbacks. Then check batching metrics (batch-size-avg, record-queue-time-avg): small batches call for higher linger.ms and batch.size. Also check whether all records go to one partition because of a constant key, whether compression is off for large text payloads, and whether a new producer is created per message.
Q. A trading service needs end-to-end latency under 20 ms at the 99th percentile. How would you configure producers and consumers?
Answer: Keep batching waits short: linger.ms 0–5 on the producer and fetch.min.bytes=1 on the consumer, so the broker answers a fetch as soon as data exists. Keep acks=all but run brokers in low-latency networks, since replication adds a follower round trip. Use lz4 or no compression, keep consumer processing fast with small max.poll.records, avoid rebalances with static membership and cooperative assignment, and keep enough partitions so no consumer is a hot spot. Then verify with percentile measurements under realistic load.