Scrivio Interview library
DesignIntermediate7 min read · updated 12 November 2026

A Spring Boot service consumes bursts of events from Kafka and writes them to a database that can only take 2,000 writes per second. Design back-pressure so the service stays healthy during bursts.

Kafka itself is the buffer: the service should consume at the rate the database can take, about 2,000 writes per second, and let consumer lag grow during a burst instead of pulling everything into memory. I limit work per poll with max.poll.records, write in batches, pause the listener container when the database slows down, keep each poll's processing well under max.poll.interval.ms, and alert on lag and on the time it will take to drain.

Why this question is asked

Bursty event streams are normal: a marketing campaign, a batch import upstream or a replay after an incident can push 20,000 events per second for ten minutes into a topic that usually sees 500. If the consumer tries to keep up by pulling as fast as Kafka delivers, it either fills its own memory or overwhelms the database, and both end in an outage. Interviewers ask this design question to see whether we know where the buffer should live and which Kafka and Spring settings control the pace. In this answer, we will see why Kafka is the right buffer, size the consumer to the database, batch the writes, pause when the database is slow, avoid rebalances, and decide what to monitor.

1Kafka Is Already the Buffer

A Kafka topic is a durable log on disk. Messages stay there for the retention period, often 7 days, whether anyone has read them or not. The consumer's position in each partition is its committed offset, and the difference between the newest message and that offset is the lag. Lag is not an error; it is simply work waiting in a safe place.

This changes how we think about bursts. If 12 million events arrive in ten minutes and the database can take 2,000 writes per second, draining them takes 100 minutes no matter what we do. The only question is where they wait during those 100 minutes. In Kafka they wait on replicated disk, survive restarts and cost nothing in our service. In an in-memory queue inside the service they take heap, vanish on a crash and slow down garbage collection. So the design goal is simple: read only as fast as we can write, and let lag absorb the burst.

2Sizing the Consumer to the Database

Each call to poll() returns up to max.poll.records records (500 by default). We process that batch, the offsets are committed, and we poll again. The number of records in flight is therefore bounded by the number of consumer threads times max.poll.records. If we never hand records to an unbounded executor, the service's memory use is flat however big the burst is.

Suppose the topic has 12 partitions and we run 3 instances with concurrency 2, so 6 consumer threads. To stay near 2,000 writes per second in total, each thread should do about 330 per second. With batched inserts of 200 rows taking around 100 ms, one thread can write about 2,000 rows per second, so 6 threads could exceed the database's limit by a large margin. We either lower concurrency, or, more robustly, add a shared limit on writes, for example a token bucket at 2,000 per second shared by the instances or a per-instance rate of about 650 per second.

YAML
spring:
kafka:
consumer:
max-poll-records: 200 # at most 200 records per poll per thread
enable-auto-commit: false
properties:
max.poll.interval.ms: 300000 # 5 minutes before the broker considers us dead
listener:
type: batch # receive the whole poll as a List
concurrency: 2 # 2 consumer threads per instance
ack-mode: batch # commit after each successful batch

3Writing in Batches

A database that takes 2,000 single-row inserts per second can often take far more rows per second when they arrive as batched statements, because each round trip and commit is shared. A batch listener receives the poll result as a list, and we write it with one JDBC batch in one transaction.

Java
@KafkaListener(topics = "events", groupId = "event-writer")
public void onBatch(List<EventRecord> records) {
writeLimiter.acquire(records.size()); // shared 2,000 per second budget; blocks when spent
jdbc.batchUpdate(
"INSERT INTO events(id, type, payload) VALUES (?, ?, ?) ON CONFLICT (id) DO NOTHING",
records, 200,
(ps, r) -> { ps.setString(1, r.id()); ps.setString(2, r.type()); ps.setString(3, r.json()); });
} // returns normally: offsets for these 200 records are committed

Notice two details. The limiter makes the listener thread wait before writing, which is exactly the back-pressure we want: while it waits, it does not poll, and lag grows in Kafka. And ON CONFLICT DO NOTHING makes the write idempotent, because after a crash or rebalance some records will be delivered again; Kafka consumers give at-least-once delivery, so duplicates must be harmless.

4Pausing When the Database Slows Down

The rate limit protects the database from us, but the database can also slow down on its own: a vacuum, a failover, another service's heavy query. When write latency rises or the connection pool is exhausted, the worst response is to keep polling and queue work in memory. Spring for Apache Kafka lets us pause the listener container instead. A paused consumer keeps calling poll() internally so it stays in the group and avoids a rebalance, but the poll returns no records.

Java
@Scheduled(fixedDelay = 5_000)
void adjust() {
var container = registry.getListenerContainer("event-writer");
double p95 = dbMetrics.writeLatencyP95Millis();
if (p95 > 500 && !container.isPauseRequested()) {
container.pause(); // stop fetching; lag grows safely in Kafka
} else if (p95 < 200 && container.isPauseRequested()) {
container.resume(); // database recovered; start draining
}
}
Step throughOne consumer thread during a burst
  1. poll() up to 200 recordsnothing is buffered beyond this batch
  2. Is the database healthy?p95 write latency and pool usage
    YesContinueNoPause the container
  3. Wait for write budgetshared limit of 2,000 per second
  4. Batch insert in one transactionidempotent on event id
  5. Commit offsetsthen poll again

5 steps in order. Play them, or step through them one at a time.

The thread never holds more than one batch; the rest waits in Kafka.

The two thresholds, 500 ms to pause and 200 ms to resume, keep the consumer from flapping on and off. A circuit breaker around the database calls can drive the same decision. For a single failed batch, a DefaultErrorHandler with a backoff retries the records without losing them, and it also pauses the consumer during the backoff so the poll loop stays alive.

5Staying Inside max.poll.interval.ms

Kafka removes a consumer from the group if it does not call poll() within max.poll.interval.ms (5 minutes by default). Its partitions are then reassigned, a rebalance, and the uncommitted records are delivered again to another consumer. If our slow processing caused the timeout, the next consumer meets the same slow database, times out too, and the group can enter a loop of rebalances while making little progress.

So the time to process one poll, including waiting for the rate limiter and database retries, must stay well under that limit. With 200 records and a budget wait of a few hundred milliseconds we are far below it. The two levers are fewer records per poll and shorter retry backoffs inside the listener; increasing max.poll.interval.ms only hides the problem, because it also makes real failures slower to detect.

6Monitoring Lag and Time to Drain

Because lag is now our planned buffer, it becomes the main health signal. Raw lag alone is misleading: 2 million records of lag is fine if we drain them in 20 minutes and alarming if it would take a day. So we alert on estimated time to drain, lag divided by the net consumption rate, and compare it with what the business can accept, such as "events visible in reports within 1 hour". We also watch the oldest unprocessed message's age against topic retention, because if lag ever approaches 7 days, data starts to be deleted before we read it. Kafka exposes consumer lag through its metrics and the kafka-consumer-groups tool, and Micrometer can publish the consumer's records-lag-max metric.

7Follow-up questions

Why not just add more consumer instances during the burst?

Because the bottleneck is the database, not the consumers. More instances would read faster and push more than 2,000 writes per second into a database that cannot take them, making things worse. Scaling consumers only helps when processing per record is the limit. Also, consumers in a group cannot exceed the number of partitions, so with 12 partitions a 13th consumer would be idle.

What if some events are more urgent than others?

Then they should not share a topic and a rate with the bulk events. A separate topic for urgent events with its own consumer and a reserved share of the database budget, say 500 of the 2,000 writes per second, keeps them flowing while the bulk topic drains slowly. Inside one partition Kafka has no priority, so separation is the practical tool.

8Conclusion

In this answer, we saw that Kafka is the right place for a burst to wait, so the consumer should read at the database's pace and let lag grow. We bounded the work per poll with max.poll.records, wrote in idempotent batches under a shared write budget, paused the listener container when the database slowed, kept processing under max.poll.interval.ms to avoid rebalances, and made lag and time to drain the alerts that tell us whether the system keeps up.

What to say in the interviewAbout 90 seconds aloud

Open with

The key idea is that Kafka is already a durable buffer, so I would not try to absorb a burst in the service's memory. The service should consume at the rate the database can take, around 2,000 writes a second, and simply let consumer lag grow during the burst and drain afterwards.

Then, if they want more

To bound memory, I limit how much each poll returns with max.poll.records, say 200, and never hand records to an unbounded executor. I would use a batch listener and write each poll with one JDBC batch insert that is idempotent on the event id, because Kafka delivery is at least once.

To make sure all instances together stay under 2,000 writes a second, I would put a shared rate limit in front of the writes, and the listener thread blocks on it, which is the back-pressure.

If the database itself slows down, I pause the listener container, which keeps the consumer in the group but stops fetching, and resume once write latency recovers, using two thresholds so it does not flap. I also keep processing time for one poll well under max.poll.interval.ms, otherwise Kafka thinks the consumer is dead, rebalances, and redelivers the same records.

Finally, since lag is the planned buffer, I alert on the estimated time to drain it and on the age of the oldest message relative to retention, rather than on the raw lag number.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A Spring Boot service consumes bursts of events from Kafka and writes them to a database...": https://scrivio-interview-library.netlify.app/spring-boot/scalability/b60d6556bc/