Scrivio Interview library
DesignIntermediate7 min read · updated 12 November 2026

You have a Kafka consumer, an HTTP server and a scheduled job runner in one service. Design start and stop ordering using SmartLifecycle so no work is lost at shutdown.

At shutdown we first stop taking new work: the web server stops accepting requests and drains the ones in progress, the Kafka consumers stop polling, and the scheduler stops triggering jobs. Then we let in-flight requests, messages and jobs finish within a timeout, committing Kafka offsets only for messages that are done, and only after that do we close shared resources such as producers and connection pools. With SmartLifecycle this is expressed as phases, where components that must stop earlier get higher phases, plus spring.lifecycle.timeout-per-shutdown-phase and an integration test that shuts the service down under load.

Why this question is asked

Services are stopped all the time: every deployment, every autoscaling decision and every node drain sends a termination signal. If shutdown is careless, each of those events loses a little work: an HTTP request cut off half way, a Kafka message processed but its offset not committed so it is processed twice, or a job half done. Interviewers ask this design question to see whether we can reason about ordering across components and turn it into concrete Spring configuration. In this answer, we will set out the goal, look at what each of the three components needs, design the phases, configure the timeouts and finally test it.

1The Goal: Stop Taking Work, Finish Work, Then Release Resources

A safe shutdown has three stages, and the order is what matters. First, no new work may enter: the load balancer must stop sending requests, consumers must stop fetching messages, and the scheduler must stop firing jobs. Second, work that already entered must finish or be handed back cleanly, within a bounded time. Third, the shared things all that work used, such as the Kafka producer, the database connection pool and HTTP clients, may be closed, because nobody needs them any more.

If we close a shared resource too early, in-flight work fails. If we keep taking new work, the second stage never ends. Spring's SmartLifecycle phases are the tool that enforces the order: beans with a higher phase stop first, and Spring waits for each phase to finish before moving to the next. Singletons such as the connection pool are destroyed only after every lifecycle bean has stopped.

2What Each Component Needs

The HTTP server needs graceful shutdown. With server.shutdown=graceful, Spring Boot makes the embedded server stop accepting new connections and wait for active requests to complete; graceful shutdown is the default since Spring Boot 3.4 (check your version). In Kubernetes we also need the pod removed from the load balancer before the server stops listening, which Spring Boot helps with by switching the readiness state to refusing traffic when the context starts closing, and a short preStop sleep covers the delay before endpoints are updated.

The Kafka consumer needs to stop polling, finish the records it already fetched, and commit their offsets. Spring for Apache Kafka's listener container is a SmartLifecycle bean: when stopped, it lets the current batch finish and commits offsets for processed records according to its acknowledgement mode, waiting up to its shutdown timeout. Records fetched but not processed are not committed, so another consumer in the group will receive them after the rebalance.

The job runner needs to stop starting new jobs and let running ones finish. For a ThreadPoolTaskScheduler we set it to wait for tasks to complete on shutdown, with an await period; in Spring Boot that is spring.task.scheduling.shutdown.await-termination=true and spring.task.scheduling.shutdown.await-termination-period. Long jobs must also check a stop flag and save a checkpoint.

3Designing the Phases

Now we place the components. The rule is simple: the earlier a component must stop, the higher its phase. The web server goes highest, because requests in progress may still publish Kafka messages or run quick jobs. Next come the Kafka listener containers and our job runner, which can drain in parallel in the same phase. Below them sits anything those depend on that is itself a lifecycle bean, such as an outbox relay that sends pending messages. The Kafka producer factory and the Hikari pool are not lifecycle beans; they are closed during singleton destruction, which happens after the lowest phase has stopped.

Java
@Component
class JobRunner implements SmartLifecycle {
private final ThreadPoolTaskExecutor workers;
private volatile boolean running;
@Override public void start() { running = true; }
@Override public void stop(Runnable callback) {
running = false; // scheduler checks this and starts no new job
CompletableFuture.runAsync(() -> {
awaitRunningJobs(Duration.ofSeconds(25)); // jobs save a checkpoint if told to stop
callback.run(); // phase may now finish
});
}
@Override public void stop() { stop(() -> {}); }
@Override public boolean isRunning() { return running; }
@Override public int getPhase() { return Integer.MAX_VALUE - 1000; } // same band as the consumers
}
Step throughShutdown order across the service
KubernetesWeb serverKafka consumerJob runnerPools and producer
SIGTERM; readiness -> refusing traffic
stop accepting, drain requests (highest phase)
next phase: stop polling
finish batch, commit offsets
same phase: no new jobs
running jobs finish or checkpoint
all phases done: destroy singletons
flush producer, close Hikari pool

8 messages in order. Play them, or step through them one at a time.

New work stops first, in-flight work finishes next, shared resources close last.

Notice that the runner only flips a flag and then drains in the background. Spring calls stop(callback) on every bean in a phase and then waits for all the callbacks together, so the Kafka containers and the job runner drain at the same time, and the phase timeout bounds the whole thing. The exact phases Spring Boot and Spring for Apache Kafka use vary by version, so we choose our numbers relative to them.

4Configuring the Timeouts

Every stage has a timeout, and they must fit inside the time the platform gives us. Suppose Kubernetes allows terminationGracePeriodSeconds of 60. We spend 5 seconds in a preStop sleep so the load balancer stops sending traffic, give each lifecycle phase at most 20 seconds, and keep a margin for closing pools and the JVM exit. If the pod is not gone after 60 seconds, Kubernetes kills it with SIGKILL and anything unfinished is lost, so the sum of our timeouts must stay below that.

YAML
server:
shutdown: graceful
spring:
lifecycle:
timeout-per-shutdown-phase: 20s # web phase and consumer phase each get up to 20s
task:
scheduling:
shutdown:
await-termination: true
await-termination-period: 20s
kafka:
listener:
ack-mode: record # commit each record after it is processed
# Kubernetes: preStop sleep 5s, terminationGracePeriodSeconds: 60 (5 + 20 + 20 + margin)

The Kafka listener container's own shutdown timeout should also be no longer than the phase timeout, otherwise Spring moves on while the container is still draining. Check the container property name in your version; it is a container property rather than a Spring Boot one in some releases.

5Testing That No Work Is Lost

Shutdown code that is never tested will be wrong, because it only runs in the middle of real deployments. We write an integration test with Testcontainers that starts the service with a real Kafka broker, sends a steady stream of HTTP requests and messages, schedules a few slow jobs, and then closes the application context in the middle. Afterwards we check three things: every HTTP request either completed or was refused before it started, every message was processed at least once and none was lost (duplicates are allowed and counted), and every job either completed or left a checkpoint.

We also log how long each phase takes, so slower draining shows up before it causes SIGKILLs in production.

6Follow-up questions

Why give earlier-stopping components a higher phase rather than a lower one?

Because Spring stops lifecycle beans in descending phase order. It starts the lowest phase first and stops it last, assuming low phases are foundations that others depend on. The web server depends on everything else, so it should start last and stop first, which means the highest phase.

What happens to a Kafka message that was being processed when the timeout expired?

If processing did not finish, its offset is not committed. When the consumer leaves the group, the partition is reassigned and another instance receives the message again from the last committed offset. So the message is not lost, but it may be processed twice, which is why listeners must be idempotent, for example by recording processed message ids.

Should we pause the Kafka consumers before stopping the web server?

It depends on the flow, and pausing consumers early is harmless when it shortens the drain. The key point is that both stop taking new work before shared resources close.

7Conclusion

In this answer, we designed a shutdown that loses no work: stop taking new work, let in-flight work finish within a bound, then release shared resources. We mapped the HTTP server, the Kafka consumers and the job runner onto SmartLifecycle phases, with higher phases for components that must stop earlier, configured graceful shutdown and spring.lifecycle.timeout-per-shutdown-phase to fit inside the platform's grace period, and proved the behaviour with an integration test that shuts the service down under load.

What to say in the interviewAbout 80 seconds aloud

Open with

I would design the shutdown in three stages: stop accepting new work, let in-flight work finish within a timeout, and only then close shared resources. For the HTTP server, I would use Spring Boot's graceful shutdown so it stops accepting connections and drains active requests, and in Kubernetes a short preStop sleep plus the readiness state going to refusing traffic so the load balancer stops sending requests.

Then, if they want more

For Kafka, the listener container is a SmartLifecycle bean: when it stops it finishes the current batch and commits offsets for processed records, and anything unprocessed will be redelivered, so listeners must be idempotent. For scheduled jobs, the runner stops starting new jobs and waits for running ones, with long jobs saving a checkpoint.

I would express the order with phases: Spring stops higher phases first, so the web server gets the highest phase, consumers and the job runner share a lower one and drain in parallel, and pools and the producer close afterwards during singleton destruction.

I would set spring.lifecycle.timeout-per-shutdown-phase, say 20 seconds, so the total fits within the pod's grace period, and I would test it with Testcontainers by closing the context under load and checking nothing was lost.

About this answer

Last updated
12 November 2026
Versions it names
Spring Boot 3.4
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.
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 "You have a Kafka consumer, an HTTP server and a scheduled job runner in one service....": https://scrivio-interview-library.netlify.app/spring-boot/bean-lifecycle/2e2225f8a8/