Quick revision
The short answer
We let the database's capacity set the pace of the whole pipeline: the Kafka consumer only fetches records when there is demand, prefetch and internal queues are bounded, flatMap concurrency matches the connection pool, and offsets are committed only after a record has been written. When internal queues pass a threshold we pause the partitions instead of buffering, we watch consumer lag and processing time, and we decide in advance what to do with records we cannot process, such as sending them to a dead-letter topic.
What to remember
In this answer, we designed a Kafka consumer whose speed is set by the database. Kafka is pull based, so we fetch only while there is demand and let unfetched records wait on the broker as lag. Concurrency is bounded at the pool size, ordering is kept per partition with concatMap, and offsets are acknowledged only after an idempotent write. Internal queues have fixed sizes, and when they pass a threshold we pause partitions while still polling, so the group does not rebalance. Failures go to a dead-letter topic by an explicit, agreed rule, and lag, processing time and pause counts tell us whether the design holds.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We let the database's capacity set the pace of the whole pipeline: the Kafka consumer only fetches records when there is demand, prefetch and internal queues are bounded, flatMap concurrency matches the connection pool, and offsets are committed only after a record has been written. When internal queues pass a threshold we pause the partitions instead of buffering, we watch consumer lag and processing time, and we decide in advance what to do with records we cannot process, such as sending them to a dead-letter topic.
Why this question is asked
Kafka makes it easy to receive data faster than we can handle it. A broker can deliver tens of thousands of records per second, while the database that stores them might manage two thousand writes per second on a good day and two hundred during a vacuum or a failover. A naive reactive consumer turns that gap into a growing in-memory queue, then an out-of-memory crash, then a rebalance storm that makes lag even worse. Interviewers ask this design question to see whether we can apply backpressure across a boundary where the producer is not in our process. In this answer, we will recap how Kafka consumers pull, design the pipeline stage by stage with the reason for each limit, handle ordering and commits, add pausing and overflow rules, and close with the metrics that tell us it works.
1A Quick Recap of How a Kafka Consumer Pulls
A Kafka consumer is pull based. It calls poll(), the broker returns up to max.poll.records records (500 by default), and the consumer is expected to call poll() again within max.poll.interval.ms (five minutes by default) or the group considers it dead and moves its partitions to another member, which is called a rebalance. Each partition is an ordered log, and the consumer's position in it is tracked by a committed offset.
Because the consumer pulls, Kafka itself is a perfect buffer: records we have not fetched stay safely on the broker's disk. The danger is entirely inside our service, between poll() and the database. If we keep polling while the database is slow, the records move from the broker's disk into our heap. So the design goal is simple to state: never fetch more than we can soon process, and let unfetched records wait in Kafka, which shows up as lag.
2Designing the Pipeline Stage by Stage
We use a consumer that respects demand. Reactor Kafka's KafkaReceiver.receive() was built for this: it polls only while downstream has outstanding demand and pauses the partitions internally when it does not, while still calling poll() so the group does not rebalance. Reactor Kafka's maintenance has wound down in recent years, so check the project's status for your version; the same design works with a plain KafkaConsumer or Spring Kafka's listener container, using pause() and resume() by hand.
Next, we bound concurrency at the database. If the R2DBC pool has 20 connections, then at most 20 writes can make progress at once, and anything above that only waits in a queue. So the flatMap that performs the writes gets a concurrency of 20, not the default of 256. That single number ties the whole pipeline's demand to the real capacity of the slowest component.
- Kafka brokerunfetched records wait here safely; this is lag, not memory
- Demand-driven receiverpolls only while there is demand; bounded prefetch
- Per-partition ordering
concatMapkeeps key order inside each partition - Bounded write concurrency
flatMapconcurrency 20 = R2DBC pool size 20 - Databasethe slowest stage sets the pace for everything above
- Offset acknowledgementonly after a successful or dead-lettered write
6 layers, from the top down. Step through them one at a time.
Notice that ordering and concurrency are decided together. concatMap processes one record at a time within a partition, so records with the same key stay in order. The outer flatMap with a concurrency of 20 processes up to 20 partitions in parallel, which matches the pool. If ordering does not matter, we could use a single flatMap(save, 20) instead and get even parallelism across records.
Acknowledging an offset only marks it as processed; Reactor Kafka then commits acknowledged offsets in the background on a commit interval or batch size. Because we acknowledge after the database write, a crash means some records are processed twice, never lost, so the write must be idempotent, for example an upsert keyed by the event id.
3Pausing Partitions When Internal Queues Fill
Even with demand-driven receiving, there are places where records can gather: the prefetch between operators, a buffer we added for batching, or work queued for a dependency. We give each of these a fixed size and watch it. With a plain consumer, the pattern is to keep a counter of records in flight, call consumer.pause(partitions) when it passes a high threshold, say 2,000, keep calling poll() so the consumer stays in the group (paused partitions return no records), and call resume() when the count drops below a low threshold, say 500. The gap between the two thresholds stops the consumer from flapping between paused and running.
The reason we pause instead of simply not polling is the rebalance rule. A consumer that stops polling for longer than max.poll.interval.ms is thrown out of the group, its partitions move to another instance, that instance hits the same slow database, and the group ends up rebalancing over and over while nobody makes progress.
- Poll the brokerkeeps the consumer alive in the group
- In-flight records above 2,000?YesPause all assigned partitionsNoKeep fetching
- Process and write recordsconcurrency bounded by the pool
- In-flight records below 500?YesResume the partitionsNoStay paused, keep polling
- Acknowledge offsets after each writecommit in the background
5 steps in order. Play them, or step through them one at a time.
4Deciding the Overflow Behaviour Explicitly
Backpressure handles a database that is slow. It does not handle a record that can never be written, or a database that is down for an hour. For those cases we decide in advance, with the business, what the service does. A record that fails after a few retries with backoff goes to a dead-letter topic with the error attached, so the partition can move on and someone can replay it later. When the database is unavailable altogether, the right behaviour is usually to stop consuming and let lag grow, because Kafka is already a durable buffer with days of retention; shedding data is only right for data the business agreed can be lost, such as analytics samples.
What we never do is let the overflow behaviour be decided by accident, for instance by an unbounded queue that turns a slow database into a crashed consumer and then into duplicate processing after the rebalance.
5Metrics That Tell Us It Works
Lag, the difference between the latest offset in a partition and our committed offset, is the main signal. Steady lag is fine; growing lag means we are slower than the producers. We expose it per partition, together with processing time per record, database write latency, pool usage, the number of in-flight records and how often partitions are paused. Alerts go on lag that grows for more than a few minutes and on the dead-letter rate, not on a single spike.
With these numbers, capacity planning becomes arithmetic. If producers peak at 5,000 records per second and one instance with a 20-connection pool writes 1,500 per second, we need at least four instances and enough partitions to spread across them, and a burst above that becomes temporary lag rather than an incident.
6Follow-up questions
Why not just increase max.poll.records to go faster?
Fetching more per poll does not make the database faster. It only increases how many records sit in our memory at once and how long one batch takes, which brings us closer to max.poll.interval.ms. Throughput comes from more database capacity, more parallel partitions or batching the writes, not from bigger fetches.
Should offsets be committed before or after the database write?
After. Committing before means a crash between commit and write loses the record. Committing after means a crash between write and commit processes it twice, which we make harmless with an idempotent write such as an upsert keyed by the event id. At-least-once with idempotent writes is the usual choice.
How do you keep ordering when processing in parallel?
Kafka only guarantees order within a partition, and producers put all events for one key in the same partition. So we process each partition sequentially, with concatMap or one worker per partition, and get parallelism across partitions. More parallelism then means more partitions, which is a topic design decision made up front.
7Conclusion
In this answer, we designed a Kafka consumer whose speed is set by the database. Kafka is pull based, so we fetch only while there is demand and let unfetched records wait on the broker as lag. Concurrency is bounded at the pool size, ordering is kept per partition with concatMap, and offsets are acknowledged only after an idempotent write. Internal queues have fixed sizes, and when they pass a threshold we pause partitions while still polling, so the group does not rebalance. Failures go to a dead-letter topic by an explicit, agreed rule, and lag, processing time and pause counts tell us whether the design holds.
Open with
The principle I would use is that the slowest component, the database, sets the pace, and everything else is bounded to match it. Kafka is pull based, so it is already a durable buffer: records I have not fetched sit safely on the broker as lag.
Then, if they want more
The risk is only inside my service, so I never fetch much more than I can process soon. I would use a demand-driven receiver, like Reactor Kafka's receive, which only polls while downstream has demand, or a plain consumer with pause and resume.
Then I bound write concurrency to the connection pool, so with 20 connections the flatMap concurrency is 20. If ordering matters I group by partition and use concatMap inside each partition, with parallelism across partitions.
I acknowledge offsets only after the write succeeds and make the write idempotent, an upsert by event id, so a crash gives duplicates but never loss.
Any internal queue has a fixed size; if in-flight records pass a high threshold I pause the partitions but keep polling, so I don't exceed max.poll.interval and trigger a rebalance, and I resume below a low threshold.
For records that keep failing I retry with backoff and then send them to a dead-letter topic, and if the database is down I stop consuming rather than shed data, unless the business agreed that data can be dropped. Finally I expose lag per partition, processing time, pool usage and pause counts, and alert on lag that keeps growing.
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 documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Spring Framework reference, Spring WebFlux, Project Reactor reference guide
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 "Design how a Kafka-consuming reactive service applies backpressure so that a slow...": https://scrivio-interview-library.netlify.app/spring-boot/reactive-fundamentals/9568f3c514/