Performance Tuning & Observability

7 min read

Topic 11: Performance Tuning & Observability

Welcome to the Performance Tuning & Observability module.

At this stage, your Kafka cluster is running, but "running" and "performing" are two very different states. A default Kafka installation is like a generic sports car with the speed limiter on—it works, but you aren't winning any races yet.

In this section, we will pop the hood. You will learn how to tune the engine (Producer/Consumer/Broker) for specific workloads and how to build a dashboard that tells you when something is about to break.


1. Producer Tuning: Optimizing for Throughput vs. Latency

Concept

Throughput is the amount of data moved over time (MB/s).
Latency is the time it takes for a single piece of data to move from source to destination (ms).

The Problem

You cannot maximize both simultaneously.

  • To get high throughput, you want to send huge packages of data less frequently (like a freight train).
  • To get low latency, you want to send small packages immediately (like a bike messenger).
    Default Kafka settings sit comfortably in the middle.

The Solution

We tune the batching mechanism. The producer accumulates records in a memory buffer before sending them.

🔧 Key Configurations

Parameter Default Description Tuning Strategy
batch.size 16384 (16KB) Upper limit of data size (in bytes) to collect before sending. Throughput: Increase to 32768 (32KB) or 131072 (128KB). <br> Latency: Keep default or lower.
linger.ms 0 How long to wait for more records to fill the batch. Throughput: Set to 5 - 100 ms. Forces producer to wait and fill the batch. <br> Latency: Keep 0 (send immediately).
compression.type none Compresses batches (gzip, snappy, lz4, zstd). Throughput: Use lz4 or zstd. Reduces network usage but increases CPU load.
acks all (or 1) How many brokers must acknowledge the write. Throughput: 1 (Leader only) or 0 (Fire & forget - risky!). <br> Safety: all (slower).

💻 Hands-on Example

Scenario: You are building a log aggregation system (High Throughput). You don't care if logs arrive 50ms later, but you need to move TBs of data.

java
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");

// OPTIMIZING FOR THROUGHPUT
props.put("linger.ms", "20");           // Wait 20ms to group messages
props.put("batch.size", "32768");       // Batch size 32KB
props.put("compression.type", "lz4");   // High speed compression
props.put("acks", "1");                 // Wait only for leader
props.put("buffer.memory", "33554432"); // 32MB buffer space

💡 Fun Fact: Setting linger.ms to just 5ms can often double your throughput with a barely noticeable impact on latency. It's the "magic number" in many production systems.


2. Consumer Tuning: Managing Fetch Sizes and Processing Time

Concept

The Consumer "pulls" data. If it pulls too little, it's chatty and slow. If it pulls too much, it might crash while processing.

The Problem

Consumer Lag. This happens when the producer is writing data faster than the consumer can process it. If a consumer takes too long to process a batch, the broker thinks it died and kicks it out of the group (Rebalancing), stopping the world.

The Solution

Tune how much data we fetch and how long we are allowed to keep it before asking for more.

🔧 Key Configurations

Parameter Default Description Tuning Strategy
fetch.min.bytes 1 Minimum data the broker should send. Throughput: Increase to 1024 (1KB) or more. The broker will wait until it has this much data before responding.
max.poll.records 500 Max number of messages returned in a single poll(). Stability: Decrease if your processing logic is heavy (e.g., DB writes). Prevents timeouts.
max.poll.interval.ms 300000 (5m) Max time allowed between polls before consumer is considered dead. Stability: Increase if your processing takes > 5 minutes per batch.
session.timeout.ms 45000 (45s) Time without a heartbeat before consumer is considered dead. Failover: Lower values detect failures faster but cause false positives on network blips.

💻 Hands-on Example

Scenario: An image processing consumer. Each image takes 1 second to process.

Problem: Default max.poll.records is 500. 500×1s=500s500 \times 1s = 500s.
Default max.poll.interval.ms is 300s.
Result: 500s > 300s. The consumer will be kicked out of the group constantly!

Fix:

java
Properties props = new Properties();
// ... standard config ...

// PROCESSING TUNING
props.put("max.poll.records", "200");      // 200 records * 1s = 200s processing time
props.put("max.poll.interval.ms", "300000"); // 300s limit. We are safe (200s < 300s).
props.put("fetch.min.bytes", "1024");      // Wait for at least 1KB of data

3. Broker Tuning: OS, JVM, and Disk Considerations

Concept

The Broker is the server. Its performance relies heavily on the underlying Linux OS and Java Virtual Machine (JVM).

The Problem

Kafka relies on the Page Cache (RAM) and File Descriptors.

  1. If the OS swaps memory to disk, performance tanks.
  2. If the broker runs out of file handles (Kafka opens a LOT of files), it crashes.

The Solution

Tune the OS to favor caching and allow massive file usage.

🐧 OS Tuning (Linux)

  • File Descriptors: Kafka uses one file descriptor per segment per partition.
    • Action: Increase limit to at least 100,000.
    • Command: ulimit -n 100000
  • Swappiness: We never want Kafka memory swapped to disk.
    • Action: Set vm.swappiness to 1 (do not swap unless absolutely necessary).
    • Command: sysctl vm.swappiness=1
  • Filesystem: Use XFS or EXT4. XFS is generally recommended for its efficient handling of large files.
    • Mount Option: use noatime. This stops the OS from writing a timestamp every time a file is read, saving disk I/O.

☕ JVM Tuning

  • Garbage Collection (GC): Kafka creates many short-lived objects.
  • Recommendation: Use G1GC (Garbage First GC). It is the default in modern Java and handles large heaps well.
  • Heap Size: Don't give Kafka all your RAM. Kafka needs the OS Page Cache.
    • Rule of Thumb: If you have 32GB RAM, give 6-8GB to Kafka Heap. Leave the rest for the OS to cache files!

4. Observability: Key JMX Metrics You Must Monitor

Concept

Kafka exposes internal metrics via JMX (Java Management Extensions). You must collect these (using Prometheus, Datadog, JConsole, etc.) to know if the system is healthy.

The Problem

There are thousands of metrics. Which ones actually matter?

The Solution

Focus on the Critical 4 categories.

📊 1. Cluster Health (The "Is it on fire?" metrics)

Metric Name MBean Why it matters
UnderReplicatedPartitions kafka.server:type=ReplicaManager,name=UnderReplicatedPartitions Most Critical. If > 0, data is not being copied to followers. High risk of data loss.
ActiveControllerCount kafka.controller:type=KafkaController,name=ActiveControllerCount Should be exactly 1 for the whole cluster. If 0 or >1, the cluster has a "split brain" or no leader.

📉 2. Broker Performance

Metric Name MBean Why it matters
RequestHandlerAvgIdlePercent kafka.server:type=KafkaRequestHandlerPool,name=RequestHandlerAvgIdlePercent Indicates how busy the broker is. If < 20%, your broker is overloaded and can't handle requests.
BytesInPerSec / BytesOutPerSec kafka.server:type=BrokerTopicMetrics,name=BytesInPerSec Throughput indicators. Sudden drops indicate upstream/downstream failures.

🐢 3. Consumer Lag

  • Metric: records-lag-max
  • Context: Measures how far behind the consumer is from the latest message.
  • Rule: Lag should stay stable. If it grows continuously, your consumer is too slow.

⚠️ Pro Tip:

Never alert on "CPU Usage" alone. A Kafka broker using 80% CPU is often healthy (just busy compressing data). Alert on UnderReplicatedPartitions and Consumer Lag.


📝 Summary Checklist

  1. Producers: Use linger.ms > 0 for throughput.
  2. Consumers: Ensure max.poll.records fits within max.poll.interval.ms.
  3. OS: vm.swappiness=1, ulimit -n 100000.
  4. Monitoring: If UnderReplicatedPartitions > 0, wake up the ops team.

🔗 References

Challenge

You are a Kafka administrator responsible for tuning a production cluster that serves two very different applications. Your task is to provide the optimal configuration settings based on the requirements.

Part 1: High-Throughput Log Ingestion Producer

An application is sending a massive volume of diagnostic logs to a Kafka topic. The primary goal is to maximize data ingestion throughput. Network bandwidth is a moderate concern, and the loss of a few individual log messages is acceptable if it prevents system slowdown.

  • Provide four key producer configuration properties to achieve this.

Part 2: Critical Transaction Processing Consumer

A second application consumes financial transaction records. Data integrity is paramount, and absolutely no records can be lost. The processing for each individual record is computationally expensive and takes approximately 1.5 seconds to complete. The consumer must be configured to handle this slow processing without being erroneously marked as failed by the broker.

  • Provide three key consumer configuration properties to ensure reliable, slow processing. Your settings should allow for processing a batch of 150 records.

Part 3: Broker Host OS Optimization

Finally, you need to apply two critical performance optimizations to the underlying Linux operating system hosting the Kafka brokers.

  • Write the two specific Linux commands that should be executed on the broker hosts to tune them for Kafka's I/O patterns.

Expected result

The user must provide correct Kafka configuration properties and Linux commands that align with the described scenarios.

Part 1: Producer Configuration Solution

The configuration should prioritize throughput over latency and data durability.

  • acks=1 or acks=0: 1 is a good balance, ensuring the leader has the record. 0 provides the absolute highest throughput at the risk of data loss.
  • linger.ms: A value significantly greater than 0, like 20 or 50, to allow batches to build up.
  • batch.size: A large value, such as 32768 (32KB) or 65536 (64KB), to send more data in a single request.
  • compression.type: lz4 or zstd to reduce network traffic at the cost of some CPU.

Part 2: Consumer Configuration Solution

The configuration must prevent the consumer from timing out while it processes its batch.

  • max.poll.records=150: This is given in the prompt.
  • max.poll.interval.ms: The value must be greater than the total processing time. Calculation: 150 records * 1500 ms/record = 225,000 ms. A correct value would be 230000 or higher.
  • fetch.min.bytes: A value greater than the default of 1, like 1024, to improve throughput by making the broker wait for more data before responding.

Part 3: Broker OS Tuning Commands Solution

The user must provide two specific and common Linux tuning commands for Kafka.

  • File descriptors: ulimit -n 100000 (or a similarly high number). This is required because Kafka uses a large number of file handles for log segments.
  • Memory swapping: sysctl -w vm.swappiness=1. This command drastically reduces the kernel's tendency to swap memory to disk, which is critical because Kafka heavily relies on the OS page cache for performance.
plain text

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.