Scrivio Interview library
ScenarioIntermediate7 min read · updated 12 November 2026

A Spring Boot service consumes Kafka messages and also runs a long batch export. During deployments, some messages are processed twice and exports are left half-written. How would you make shutdown safe?

Make sure the Kafka listener containers stop cleanly as part of the context shutdown and commit offsets for records they finished, accept that some duplicates will still happen with at-least-once delivery and make the consumer idempotent, and make the export either save progress and stop when interrupted or move it to a separate job workload. Then give the pod a terminationGracePeriodSeconds long enough for this drain, and order shutdown with SmartLifecycle phases so components stop in the right sequence.

Why this question is asked

A deployment should be a non-event, but services that mix message consumption and long batch work often turn every release into a small incident: duplicate charges, emails sent twice, and export files that downstream systems pick up half written. Interviewers use this scenario to see whether we understand Kafka's delivery guarantees, what Spring does during shutdown, and how to design long work so it can be interrupted. In this answer, we will see why both problems happen, make the consumer stop cleanly and be idempotent, make the export safe, set the grace period, and order shutdown with lifecycle phases.

1Why Duplicates and Half-Written Exports Happen

A Kafka consumer reads records from a partition and periodically commits an offset, the position up to which it has finished. If a consumer stops after processing some records but before committing their offsets, the partition is reassigned to another consumer during the rebalance, and that consumer starts from the last committed offset. It processes those records again. This is the at-least-once guarantee: nothing is lost, but some records may be delivered twice.

The export has a different problem. It is a long loop writing rows to a file or a table. When Kubernetes sends SIGTERM and, 30 seconds later, SIGKILL, the loop is simply cut off. Whatever was written so far stays, without a marker that it is incomplete, and nothing resumes it.

2Stopping the Kafka Listener Cleanly

In Spring for Apache Kafka, the listener containers are SmartLifecycle beans, so when the application context closes, they are stopped before ordinary beans are destroyed. By default, a stopping container finishes processing the records from its current poll and commits their offsets before closing the consumer, and the consumer leaves the group so the rebalance starts promptly. The details depend on the ack mode and on properties such as stopImmediate and the container's shutdown timeout, so check your version and settings.

Two things often break this in practice. If the pod is killed with SIGKILL because the grace period is too short, no commit happens at all. And if processing one batch can take longer than the shutdown timeout, the container gives up waiting. So we keep batches small enough to finish quickly, with max.poll.records, and we make sure the grace period covers the drain.

YAML
spring:
kafka:
consumer:
max-poll-records: 100 # a batch finishes in seconds, not minutes
enable-auto-commit: false # the container commits after processing
listener:
ack-mode: record # commit after each record: fewer duplicates, more commits
# Log on SIGTERM:
# Stopping container ... orders-consumer
# Committing: {orders-3=OffsetAndMetadata{offset=18452}}
# Consumer orders-consumer-1 left the group

ack-mode record narrows the window of duplicates to at most one record per partition at the cost of more commit traffic; the default batch mode commits once per poll. Either way, a crash or a kill can still cause duplicates, which is why the next step matters most.

3Duplicates Are Expected: Make the Consumer Idempotent

Even with a perfect shutdown, duplicates will happen: a pod can crash, a node can disappear, or a rebalance can be triggered by a slow consumer exceeding max.poll.interval.ms. So the consumer must be idempotent, meaning that processing the same record twice has the same effect as processing it once.

The usual way is to record each processed message's ID in the same database transaction as the business change, with a unique constraint. A second attempt fails on the constraint, or is detected with a lookup, and is skipped.

Java
@KafkaListener(topics = "payments")
@Transactional
public void onPayment(PaymentEvent e) {
int inserted = jdbc.update(
"INSERT INTO processed_message(id) VALUES (?) ON CONFLICT DO NOTHING", e.id());
if (inserted == 0) return; // 0: already processed, skip the duplicate
ledger.post(e); // 1: first time, apply the change
}

Notice that the marker and the ledger posting commit together. If the pod dies before the commit, both are rolled back and the redelivered record is processed normally; if it dies after, the redelivery is skipped.

4Making the Long Export Interruptible

For the export, we have two good options. The first is to make it interruptible and resumable. The export writes in chunks, saves a checkpoint after each chunk, such as the last exported ID, and checks a stop flag between chunks. When shutdown begins, it finishes the current chunk, saves the checkpoint and returns. The next run resumes from the checkpoint. The output should be written to a temporary name and renamed or marked complete only at the end, so readers never see a half-written file as finished.

The second option is often better: move the export out of the web service into a separate workload, a Kubernetes Job or a CronJob, that is not stopped by deployments of the service. It can have its own resources and retry policy, and Spring Batch gives us chunk checkpoints and restart for free.

Java
@Component
class ExportRunner implements SmartLifecycle {
private volatile boolean running;
private volatile boolean stopRequested;
public void runExport() {
long lastId = checkpoints.load("daily-export"); // resume point, e.g. 120000
while (!stopRequested) {
List<Row> chunk = repo.nextChunk(lastId, 1000);
if (chunk.isEmpty()) { files.markComplete("daily-export"); break; }
files.append("daily-export.part", chunk);
lastId = chunk.getLast().id();
checkpoints.save("daily-export", lastId); // progress survives a restart
}
}
@Override public void stop(Runnable callback) {
stopRequested = true; // loop ends after the current chunk
awaitCurrentChunk();
running = false;
callback.run();
}
@Override public void start() { running = true; }
@Override public boolean isRunning() { return running; }
@Override public int getPhase() { return Integer.MAX_VALUE; } // stopped first
@Override public void stop() { stop(() -> {}); }
}

5Grace Period and Shutdown Order

All of this needs time. terminationGracePeriodSeconds must cover the preStop delay, the drain of the Kafka containers, the current export chunk, and the web server's graceful shutdown. For a service like this, 60 to 90 seconds is common, and the export's chunk size is chosen so one chunk always fits.

Order matters too. Spring stops SmartLifecycle beans in descending phase order: the highest phase stops first. We want the export to stop taking new chunks and the Kafka listeners to stop consuming before the things they depend on, such as the DataSource and the producers that send results, are closed. Since those are destroyed after all lifecycle beans have stopped, giving our runner a high phase and letting the containers stop with their default phase gives a safe order.

Step throughSafe shutdown order for the service
  1. preStop sleepload balancers stop routing HTTP traffic
  2. SIGTERM: context closesSmartLifecycle beans stop, highest phase first
  3. Export runner stopsfinishes current chunk, saves checkpoint
  4. Kafka listener containers stopfinish current records, commit offsets, leave group
  5. Web server drains in-flight requestsgraceful shutdown
  6. DataSource and producers closeafter all lifecycle beans have stopped

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

Everything that writes finishes before the resources it writes to are closed.

6Follow-up questions

Would Kafka transactions or exactly-once semantics remove the need for idempotency?

Only for read-process-write flows that stay inside Kafka, where offsets and output records commit atomically. As soon as the consumer writes to a database or calls an external API, Kafka's transactions cannot cover that side effect, so an idempotent consumer is still required.

How does the newer consumer rebalance protocol help?

Kafka 4 makes the new consumer group protocol generally available, where the broker coordinates assignments incrementally. Partitions move with less disruption and consumers not affected keep processing, which reduces the pause and some of the duplicate work during deployments. It does not change the at-least-once guarantee, so idempotency is still needed.

Why not just increase the grace period to an hour for the export?

A very long grace period slows every rollout and node drain, and it still fails when a node crashes. Long work should be resumable no matter what, and then a moderate grace period is enough.

7Conclusion

In this answer, we saw that duplicates come from records processed but not committed before a rebalance, and half-written exports from long work that is killed without saving progress. We stopped the Kafka listener containers cleanly so they commit finished records, made the consumer idempotent because at-least-once delivery will always produce some duplicates, made the export check for interruption and save checkpoints or moved it to a separate job workload, set terminationGracePeriodSeconds to cover the drain, and used SmartLifecycle phases to stop components in the right order.

What to say in the interviewAbout 90 seconds aloud

Open with

Two separate problems. The duplicates come from Kafka's at-least-once delivery: if a consumer processed records but did not commit their offsets before it stopped, the next owner of the partition processes them again.

Then, if they want more

So I make sure shutdown is clean. Spring Kafka's listener containers are SmartLifecycle beans, so on context close they finish the current records and commit offsets, as long as the pod is not SIGKILLed first. I keep batches small with max.poll.records so a drain takes seconds, and give the pod a grace period long enough for it.

But duplicates still happen on crashes and rebalances, so the consumer must be idempotent; I store the message ID in a table with a unique constraint in the same transaction as the business change, and skip records already seen.

For the export, I would make it interruptible: process in chunks, save a checkpoint after each, check a stop flag, and write to a temporary file that is only marked complete at the end, so nobody reads half a file.

Often it is even better to move it to a Kubernetes Job or Spring Batch, which deployments of the service do not interrupt. Finally I order shutdown with SmartLifecycle phases: the export runner has the highest phase so it stops first, then the listeners, then the web server, and the data source closes last.

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
Kubernetes documentation
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 Kafka messages and also runs a long batch export. During...": https://scrivio-interview-library.netlify.app/spring-boot/containers-and-kubernetes/868b137c1b/