Kafka falling behind? What to fix before buying more
When Kafka falls behind, the instinct is to buy more capacity. Before you do, check how the topic was set up and what your consumers are doing. Those are often the real cause, and hardware won't fix them.
The business case
Kafka lag means your business is working from old information: orders, alerts and updates arrive late. Adding hardware costs money and may not help if the cause is one overloaded partition or one slow step. Some early decisions are hard to reverse, so they're cheapest to get right before a launch or a big new customer.
Jump to: the implementation / questions for your team
Kafka will take a remarkable amount of traffic. When a system can't keep up, the broker is often fine and the trouble is in how the topic was laid out or how the consumers behave. So start with the decisions that are hard to change, then tune.
Count your partitions before you create the topic
A partition is read by only one consumer in a group at a time, so the partition count caps your parallelism. Add a 26th consumer to a 25-partition topic and it sits idle.
The rough math: divide your peak rate by what one consumer can handle. Say you peak at 50,000 messages a second and one consumer does 2,000. That's 25 partitions just to keep up, and I'd double it for spikes and for catching up after an outage. Call it 50.
Measure that consumer number under real work. Don't use the broker's benchmark figures, because your consumer's speed depends on what it does with each message.
await admin.CreateTopicsAsync(new[]
{
new TopicSpecification
{
Name = "orders",
NumPartitions = 50,
ReplicationFactor = 3,
Configs = new Dictionary<string, string>
{
["min.insync.replicas"] = "2",
["retention.ms"] = "604800000",
},
},
});
Replication factor 3 with min.insync.replicas of 2 is the usual setup. One broker can die and writes carry on.
You can add partitions later, but it isn't free. Keys get remapped, so messages for one customer can land on a different partition than their older messages, and ordering breaks across the change. Too many partitions has costs as well, in memory, open files and failover time. Don't pick 5,000 to be safe.
Your key decides whether partitions help
Messages with the same key go to the same partition, which is how Kafka preserves order per key. It's also how you get a hot partition: key by customer, and when your largest customer sends 40% of the traffic, 40% of it goes to one partition and one consumer. The rest of the group sits around while the lag climbs on that one.
Check per-partition lag, not only the total. If one partition is far behind, you have a key problem, and more consumers won't touch it. Only key by what you need ordered. If you need order per order, key by order ID, not customer. For very large tenants you can split the key into sub-keys, accepting that order now only holds within each one.
Producer: trade a few milliseconds for a lot of throughput
Sending messages in batches is the biggest lever on the producer side.
var config = new ProducerConfig
{
BootstrapServers = brokers,
Acks = Acks.All,
EnableIdempotence = true,
LingerMs = 20,
BatchSize = 1_000_000,
CompressionType = CompressionType.Lz4,
};
using var producer =
new ProducerBuilder<string, string>(config).Build();
producer.Produce("orders", new Message<string, string>
{
Key = order.CustomerId,
Value = JsonSerializer.Serialize(order),
}, report =>
{
if (report.Error.IsError)
{
logger.LogError(
"Delivery failed: {Reason}", report.Error.Reason);
}
});
LingerMswaits a little so batches can fill. At high volume, 20 ms of added delay buys far fewer, far larger requests.BatchSizecaps a batch in bytes. If batches always hit it before linger runs out, raise it.CompressionTypecompresses whole batches, so better batching gives better compression. Lz4 is cheap on CPU. Zstd compresses harder and costs more.Acks.AllwithEnableIdempotencewaits for the in-sync replicas and stops producer retries from writing duplicates. It's slower thanacks=1, and I'd keep it for anything you can't afford to lose.
Don't copy these numbers blind. They're a starting point, and defaults differ between the Java client and librdkafka, which is what Confluent.Kafka uses. Note the delivery handler too: Produce returns before the message is sent, so that callback is the only place you learn it failed.
Consumer: most outages are rebalances
When a consumer stops polling for longer than max.poll.interval.ms, Kafka assumes it's dead and hands its partitions to others. They can hit the same slow work, get kicked out as well, and now the group spends its time reshuffling with very little being processed. The usual cause is one slow downstream dependency, and a model API is a slow dependency.
var config = new ConsumerConfig
{
BootstrapServers = brokers,
GroupId = "order-processor",
EnableAutoCommit = false,
AutoOffsetReset = AutoOffsetReset.Earliest,
PartitionAssignmentStrategy =
PartitionAssignmentStrategy.CooperativeSticky,
GroupInstanceId = Environment.MachineName,
MaxPollIntervalMs = 300_000,
FetchMinBytes = 64_000,
FetchWaitMaxMs = 100,
};
CooperativeStickymoves only the partitions that need moving, so a rebalance doesn't stop the whole group.GroupInstanceIdgives a consumer a stable identity, so a quick restart during a deploy doesn't trigger a rebalance. It has to be unique within the group and stay the same across restarts, so use a stable name like a StatefulSet pod name.FetchMinBytesandFetchWaitMaxMsbatch on the read side, trading a small delay for fewer requests.EnableAutoCommit = falselets you commit after the work is done, so a crash replays messages instead of losing them. That means duplicates are possible, so handlers need to be idempotent.
Raising MaxPollIntervalMs buys time but also delays detection of a consumer that's truly stuck. For slow work, it's better to hand messages to a bounded worker pool and keep the consume loop moving, using Pause and Resume on partitions when the pool is full. That's backpressure, and it keeps a slow dependency from turning into a group-wide failure.
Change one thing and measure
Watch consumer lag per partition, produce latency, average batch size, rebalance count and under-replicated partitions. Then run a load test at twice your peak, and kill a broker in the middle of it. Change one setting at a time. Kafka tuning done in bulk teaches you nothing, because you won't know which change helped.
If lag only grows, the honest answer may be that your processing is too slow. No Kafka setting fixes that. Find out what each message is waiting on.
Questions to ask your team
- How far behind do we get at peak, in minutes, and what does that delay mean for customers?
- Can we handle double our peak? When did we last test it?
- What happens if we lose a broker at peak?
- Does one large customer slow down everyone else?
- Are we paying for capacity we aren't using?
If you're about to spend more on Kafka, it's worth checking those first. I help teams find out what's actually slowing them down. Send me a message on LinkedIn with what yours does, and we can work out where to look first.