When tuning Kafka for production, two of the most important goals are achieving high throughput and keeping latency low.
These goals are related, but they don't always work in the same direction.
For example, an analytics pipeline processing millions of events per second might prioritize throughput. A real-time fraud detection system, on the other hand, might care more about processing each event as quickly as possible.
Both systems can use Kafka, but their performance requirements are very different.
Kafka provides several configuration options that influence how messages are batched, transmitted, replicated, and consumed. Understanding how these settings interact is essential for making the right trade-offs.
In this chapter, we'll explore how to tune Kafka for throughput and latency, when to prioritize each, and how to find a practical balance between them.
Let's start with a simple example.
Imagine a producer sending 10,000 messages per second to Kafka.
One approach is to send each message in a separate network request.
This minimizes intentional waiting, but it creates substantial overhead. Every request requires network processing, protocol handling, and broker resources.
Another approach is to group messages into batches before sending them.
Instead of sending 10,000 individual requests, the producer might send 100 requests containing 100 messages each.
This reduces request overhead and makes better use of network bandwidth.
However, some messages may need to wait while the producer collects enough data for a batch.
This illustrates the central trade-off:
Larger batches generally improve throughput, while smaller batching delays can improve latency for individual messages.
But the relationship isn't always that simple.
If a system is overloaded with small requests, increasing batching can reduce queueing and improve both throughput and latency.
The real goal is to find the configuration that works best for your workload.
Producer batching is one of the most effective ways to tune Kafka performance.
Instead of sending every record immediately, the Kafka producer accumulates records in memory and groups them into batches for individual partitions.
Two configurations are particularly important:
batch.sizelinger.msThe batch.size configuration controls the target maximum size of a producer record batch, in bytes.
For example:
This configures a batch size of 64 KiB.
Larger batches can improve throughput because the producer sends fewer requests and reduces per-record overhead.
They can also improve compression efficiency.
However, increasing the batch size has some costs.
The producer may allocate more memory for batches, and under low traffic, batches may remain partially filled.
batch.size doesn't mean the producer always waits until a batch is full. It can send a partially filled batch, and linger.ms controls how long it waits for more records first.
The linger.ms configuration controls how long the producer may wait for additional records before sending an incomplete batch.
For example:
This allows the producer to wait up to approximately 10 milliseconds to accumulate more records.
If the batch fills earlier, it can be sent immediately.
The flow below shows how the two settings decide when a batch leaves the producer.
Consider two configurations.
The producer doesn't introduce an intentional batching delay, so messages can be sent promptly.
However, batches may be smaller, increasing request overhead.
The producer allows larger batches and more time to accumulate records.
This can reduce the number of requests and improve throughput, particularly when traffic is moderate.
The downside is that messages may spend additional time waiting in the producer.
Neither configuration is universally better.
Also, modern Kafka producers use a default linger.ms of 5 milliseconds, introduced in Kafka 4.0, because modest batching often improves efficiency without significantly increasing latency.
The best values depend on message size, traffic volume, partition distribution, and your latency requirements.
Compression is another important performance optimization.
Kafka producers support several compression algorithms, including:
gzipsnappylz4zstdCompression reduces the amount of data transmitted over the network and stored on disk.
Suppose your application generates 100 MB of events per second.
If compression reduces the data size to 40 MB, Kafka needs to transfer and store substantially less data.
This can improve throughput when network bandwidth or storage I/O is the limiting resource.
However, compression requires CPU resources.
Different algorithms offer different trade-offs.
For many production workloads, LZ4 and Zstd are useful starting points.
For example:
Kafka compresses complete record batches, so larger batches can also improve compression effectiveness.
This creates an interesting interaction between compression and batching.
Increasing batching may improve compression, reducing network traffic enough to offset some of the additional waiting time.
The right choice should be based on actual CPU utilization, network bandwidth, and latency measurements.
Kafka producers can choose how many acknowledgments are required before a write is considered successful.
The setting is:
There are three main options.
The producer doesn't wait for a broker acknowledgment.
This reduces acknowledgment overhead, but the producer cannot confirm whether the broker successfully stored the record.
The partition leader acknowledges the write after appending the record locally.
This avoids waiting for follower replication, but acknowledged records can still be lost during certain leader failures.
The leader waits until the write satisfies Kafka's in-sync replica acknowledgment requirements.
This provides stronger durability guarantees, particularly when combined with an appropriate replication factor and min.insync.replicas.
The trade-off is that replication can increase acknowledgment latency.
The sequence below marks the point where the producer gets its answer under each setting.
Lowering acks purely to improve performance can introduce unacceptable data-loss risks. For most production systems where reliability matters, acks=all is a sensible starting point. Optimize batching, compression, and infrastructure before weakening durability guarantees.
Throughput and latency tuning also apply to consumers.
Consumers fetch records from brokers in batches rather than making a separate request for every message.
Two important settings are:
fetch.min.bytesfetch.max.wait.msThis setting specifies the minimum amount of data the broker should try to collect before responding to a fetch request.
For example:
This requests at least 1 MiB of data before the broker normally returns a response.
Larger fetches can improve throughput by reducing the number of network responses.
However, if traffic is low, the consumer may have to wait longer.
This setting limits how long the broker waits when the requested minimum amount of data isn't available.
For example:
The broker can return a response after approximately 100 milliseconds even if the minimum fetch size hasn't been reached.
These two settings work together.
Consider a consumer with:
The broker tries to accumulate 1 MiB of data but doesn't wait indefinitely.
Here is how the broker decides when to answer that fetch request.
For a high-throughput analytics pipeline, this may be reasonable.
For a real-time notification service, smaller fetch minimums and shorter wait times may be more appropriate.
Remember that these settings affect broker fetch responses, not the time your application spends processing records.
After fetching records, consumer applications must decide how to process them.
Consider a consumer writing events into a database.
One approach is to insert every event individually.
This provides relatively immediate processing, but it can generate thousands of database requests.
Another approach is to accumulate 100 events and insert them together.
Batch inserts often improve efficiency by reducing database round trips and transaction overhead.
However, the application may need to wait for enough records to accumulate.
You can also use a hybrid approach:
Process a batch when either:
This allows efficient batching under high traffic while preventing excessive waiting during quiet periods.
The exact thresholds depend on your workload.
Coordinate batch processing with offset commits so that failures don't cause unprocessed records to be incorrectly marked as completed.
One subtle aspect of Kafka performance is that the same configuration can behave differently under different traffic levels.
Imagine a producer with:
Under heavy traffic, batches may fill almost immediately.
The producer doesn't need to wait for the full linger interval, so it achieves high throughput with little additional batching delay.
Under light traffic, batches may not fill quickly.
Messages can wait closer to the configured linger interval before being sent.
This means batching settings often have a greater effect on latency during low-traffic periods.
There's another important behavior near capacity.
As brokers or consumers become overloaded, requests begin queueing.
At this point, latency can increase sharply even if the incoming traffic increases only slightly.
For this reason, tuning should be tested under both normal and peak workloads.
A configuration that performs well during a short benchmark may behave differently during sustained production traffic.
Let's compare three common types of workloads.
Imagine a fraud detection system where events should reach the processing application within tens of milliseconds.
The priority is low end-to-end latency.
You might start with:
These settings favor prompt delivery while preserving strong producer acknowledgment guarantees.
You would also need fast consumer processing, healthy replication, and enough spare cluster capacity.
Now consider a pipeline collecting clickstream events for analytical processing.
A small delay is acceptable as long as the system handles large volumes efficiently.
A starting configuration might be:
This favors larger batches, better compression, and fewer requests.
Actual performance will depend on traffic distribution and available resources.
Many systems need both reasonable latency and good throughput.
For example, an order-processing service might need dependable delivery without optimizing for the absolute lowest possible latency.
A reasonable starting point could be:
These aren't universal production presets. They are starting points for benchmarking, not configurations to copy blindly.
The most important part of tuning is measuring whether your changes actually help.
Start by defining your goals.
For example:
Then change one configuration at a time.
Measure producer throughput, request latency, batch sizes, compression efficiency, broker resource utilization, consumer lag, and processing latency.
Test under representative message sizes, traffic patterns, and partition distributions.
Also test sustained loads rather than relying only on short bursts.
If increasing batch.size improves throughput by 20% but pushes P99 latency beyond your application's requirement, it may not be the right trade-off.
Similarly, if reducing linger.ms improves latency but causes excessive broker request overhead, a slightly larger value may produce better overall results.
Kafka throughput and latency tuning is primarily about controlling how efficiently data moves through the system and how long records wait at each stage.
Producer batching, compression, and consumer fetch sizes are some of the most important tuning mechanisms.
Larger batches generally improve resource efficiency, while smaller waiting intervals help reduce delays when traffic is low.
Acknowledgment settings also affect latency, but reliability should not be sacrificed without understanding the consequences.
Most importantly, throughput and latency are not always competing goals. Better batching and reduced resource contention can sometimes improve both.
Start with your application's requirements, measure performance under realistic load, and adjust configurations based on observed bottlenecks.
10 quizzes