Kafka in practice (1): partition count, large messages, lag and long-running tasks
Common Kafka operating problems and the patterns that solve them: sizing partitions from write and read throughput, shrinking a topic, large messages with a claim check, consumer lag, long-running tasks, poison pills with retry topics and a DLT, and hot partitions.
On this page
1. The problem
The payments team sees lag growing, bumps the topic from 8 to 32 partitions and scales consumers to 32 pods. Lag doesn't drop: the bottleneck is the DB, and 32 pods just pile more connections onto an overloaded DB. Worse, murmur2(key) % 32 remaps every key, so events for the same account lose order during the switch.
2. Key idea
partitions = target throughput / throughput per partition. On the write side, about 10 MB/s per partition; on the read side it depends on logic and the DB, so load test. Example: a 5,000 msg/s peak with one consumer handling 400 msg/s → 13 needed; choose 16 for headroom and an even split across 2, 4 or 8 instances.
Partitions only grow. To shrink, move to a new topic (MirrorMaker 2) and pick the new group's starting point deliberately: the default latest skips everything copied.
| Problem | Approach | Cost |
|---|---|---|
| A 20 MB message | claim check: upload to S3 first, send the key, size and checksum | another storage system, orphaned files to clean up |
| Growing lag | measure per-record processing time before scaling | scaling is capped by the partition count |
| Multi-minute tasks | a multi-stage pipeline, one topic per stage | more topics |
| A record that always fails | bounded retries, then a dead letter topic (DLT) | breaks per-key order if non-blocking |
Lag beyond retention is data loss.
2.1 What about long-running tasks?
| Approach | Use when | Don't use when |
|---|---|---|
Lower max.poll.records, raise max.poll.interval.ms |
processing time is stable | one unusually slow record triggers another rebalance |
| A multi-stage pipeline | several external calls, variable timing | a simple single-step flow |
Raising session.timeout.ms doesn't save long tasks: heartbeats run on a background thread, and the limit being hit is max.poll.interval.ms.
3. In Java
Spring Kafka: retry with backoff, then the DLT; permanent errors go straight there.
@Bean
DefaultErrorHandler errorHandler(KafkaTemplate<Object, Object> template) {
var recoverer = new DeadLetterPublishingRecoverer(template); // sends to <topic>-dlt
var backoff = new ExponentialBackOffWithMaxRetries(3);
backoff.setInitialInterval(1_000);
backoff.setMultiplier(2.0); // 1 s, 2 s, 4 s
var handler = new DefaultErrorHandler(recoverer, backoff);
handler.addNotRetryableExceptions( // permanent: straight to the DLT
DeserializationException.class, ValidationException.class);
return handler;
}
// A record failing on the DB 3 times -> orders-dlt, the partition moves on; a deserialisation error -> DLT at onceIn-place retries keep per-key order; @RetryableTopic (non-blocking) doesn't. Add ErrorHandlingDeserializer so deserialisation errors reach the handler instead of jamming poll().
Measuring lag, and claim check in detail
kafka-consumer-groups.sh --describe --group paymentprintsCURRENT-OFFSET,LOG-END-OFFSETandLAGper partition. Therecords-lag-maxmetric only sees partitions that consumer holds; Burrow or Kafka Lag Exporter monitor from outside and export time-based lag to Prometheus.- Common causes of lag: producer spikes, a slow DB or external API, GC pauses, constant rebalancing.
- Claim check: upload the file first, confirm, then send the message. A bucket lifecycle rule (delete after N days) longer than the topic's retention. Send the object key, not a public URL. Key objects by content hash so retries don't create duplicates.
- Messages of 1–5 MB: try
compression.type=zstdfirst; JSON usually compresses 5–10×. - Raising the message limit to 10 MB means changing 5 settings across topic, broker, producer and consumer, slows replication, and lets big records block small ones behind them.
4. Working with AI
Hand to AI: partition counts from load tests, error handler and DLT config.
Check in AI-written code:
- The partition count comes with a calculation from measured throughput, not "32 to be safe".
- No raised
max.message.bytes; large payloads go through a claim check. - Retries are bounded; permanent errors go straight to the DLT; someone reads the DLT.
-
max.poll.records × p99 processingstays well belowmax.poll.interval.ms.
5. Exercises
Exercise 1: Pick a partition count
Topic orders: a 6,000 msg/s peak, 800 bytes per message. Load test: one consumer handles 500 msg/s, the DB takes at most 20 write connections. Order by customer_id is required. The AI suggests 64 partitions "for comfort". Choose a number and explain.
Solution to Exercise 1
- Write side: 6,000 × 800 B ≈ 4.8 MB/s, one partition is enough.
- Read side: 6,000 / 500 = 12 consumers.
- The DB takes only 20 write connections: more than 20 consumers is pointless.
Choose 16 or 24: about 1.5–2× peak headroom, under the DB limit, and an even split across several instance counts. 64 doesn't help because the DB is the ceiling, and it costs broker resources and slows rebalances. Since order by key matters, over-provision from the start to avoid growing later (which remaps keys).
Exercise 2: Read a stalled-partition incident
Lag on orders-7 has grown steadily since 02:00; other partitions are fine. The consumer log repeats Retrying record orders-7@88231 every second with JsonParseException. The error handler is FixedBackOff(1000, FixedBackOff.UNLIMITED_ATTEMPTS). Diagnose it, say what you do in the first 15 minutes, and fix the root cause.
Solution to Exercise 2
- Diagnosis: a poison pill. The record at offset 88231 can't be parsed (a permanent error) but the handler retries forever, so partition 7 is stuck there.
- 15 minutes: move that record to the DLT by hand (read it with
kafka-console-consumer --partition 7 --offset 88231, write it toorders-dlt), then reset the group's offset to 88232 while consumers are stopped. - Root fix:
ErrorHandlingDeserializer+ aDefaultErrorHandlerwith bounded retries,addNotRetryableExceptionsfor deserialisation errors, and aDeadLetterPublishingRecoverer. Find the producer that wrote broken JSON and add schema validation on the producer side.
Summary
- Partition counts come from measured throughput on both sides, with room to grow.
- Partitions only grow; growing remaps keys. To shrink, move to a new topic.
- Large messages go through a claim check, not a raised limit.
- Lag: find the cause first, scale second.
- Bounded retries, permanent errors to the DLT.
Read more: Part 2: Dual writes, exactly-once and message ordering.
Practice interview questions on this topic
- What is consumer lag, how do you measure it, and should you add consumers as soon as lag grows?
- One record always makes the consumer throw: what happens, and how do you design retries and a DLQ that keep ordering?
- How do you choose the partition count for a new topic, and should you just create lots of partitions to be safe?
- How does Kafka choose a record's partition, and what goes wrong when you change a live topic's partition count?
- How does KafkaProducer.send() work internally: async sends, batching, linger.ms, compression and timeouts?
- How do heartbeats, session.timeout.ms and max.poll.interval.ms differ, and how do you handle records that take minutes?
Comments
Community rules