00:00

Kafka Performance Tuning: Throughput and Latency

Last updated:

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

The Kafka data path and why it is fastThe producer groups records per partition into batches and compresses them. A broker's network threads receive the request and its I/O threads append the batch sequentially to the partition log, which lands in the operating system page cache; the OS flushes it to disk in the background. Consumers fetch batches that are usually still in the page cache; for plaintext connections the broker uses the sendfile system call to copy data from the page cache to the socket without passing through the JVM. The consumer decompresses the batch. Producerbatch per partitioncompress (lz4, zstd) Brokernetwork + I/O threadssequential append OS page cacherecent data stays in memoryno copy in the JVM heap Disk: segment filesappend-only, sequential I/O Consumerfetch batches, decompress ① batched ② write ③ OS flushes later ④ zero-copysendfile Partitions spread the load overbrokers, disks and consumer threads Batches stay compressed from producer to consumer; the broker does not unpack them for storage.
Kafka’s data path: batched and compressed writes, sequential appends into the page cache, and zero-copy reads for consumers.
  • 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 fsync per 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 sendfile system 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.

SettingDefault (Kafka 4.4)For throughputFor low latency
linger.ms (producer)510–1000–5
batch.size (producer)1638464–256 KBdefault
compression.type (producer)nonelz4 or zstdlz4 or none
acks (producer)allall (keep durability)all; lower only for data you can lose
fetch.min.bytes (consumer)164 KB–1 MB1
fetch.max.wait.ms (consumer)500500lower, such as 100
max.poll.records (consumer)500higher, if processing is cheaplower

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:

HighThroughputProducerConfig.java
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-avg and batch-size-avg in the producer metrics: if batches stay small, raising batch.size has no effect and linger.ms is 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.bytes makes the broker wait (up to fetch.max.wait.ms) until enough data is available, reducing requests; max.partition.fetch.bytes (1 MB) and fetch.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

AreaGuidance
PartitionsEnough for peak consumer parallelism and to spread leaders over brokers; very high counts per broker add metadata and recovery cost
Threadsnum.network.threads (default 3) and num.io.threads (default 8); raise when request queues grow and CPU is available
Topic compression.typeDefault producer keeps the producer’s codec; a different codec forces the broker to recompress every batch
FlushingLeave log.flush.* at defaults; rely on replication for durability and the OS for flushing
HardwareMemory for page cache matters more than JVM heap; fast disks and network; keep the heap modest
ReplicationReplication 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:

Terminal
$ 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 acks to 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.

10. References