Scrivio Interview library
ScenarioIntermediate6 min read · updated 12 November 2026

A service opens a connection pool in @PostConstruct and closes it in @PreDestroy. During Kubernetes rolling updates, requests fail with closed-pool errors. What is happening and how do you fix it?

The pool is closed while requests that still need it are running, because shutdown order does not match request draining: Kubernetes keeps sending traffic for a moment after SIGTERM, and without graceful shutdown the web server does not wait for in-flight requests before Spring destroys the singletons. We fix it by enabling graceful shutdown (server.shutdown=graceful, the default in recent Spring Boot versions; check your version), which drains requests in a SmartLifecycle phase that runs before any singleton is destroyed, by adding a preStop delay so the load balancer stops routing first, and by letting Spring manage the pool as its own bean with a destroy method.

Why this question is asked

Rolling updates are supposed to be invisible to users: new pods come up, old pods go down, and nobody notices. When every deployment produces a burst of errors, the cause is almost always the shutdown sequence, and here the visible symptom is a connection pool that is already closed. Interviewers use this scenario to check that we understand both the Spring side, the order in which beans and lifecycle phases stop, and the Kubernetes side, how traffic is removed from a terminating pod. In this answer, we will reproduce the setup, follow the shutdown timeline to see where the race is, and then go through the three fixes and how they fit together.

1The Setup That Fails

The service creates a connection pool itself, inside a business bean, and relies on the bean's lifecycle annotations to open and close it.

Java
@Service
class InventoryService {
private HikariDataSource pool;
@PostConstruct
void open() { pool = new HikariDataSource(config()); }
@PreDestroy
void close() { pool.close(); } // runs during context shutdown
Stock find(String sku) {
try (Connection c = pool.getConnection()) { // SQLException: HikariDataSource ... has been closed.
/* query */
}
}
}

In normal running this works. During a rolling update, the old pods log a handful of SQLExceptions saying the data source has been closed, and callers see 500 errors. Nothing is wrong with the pool; it is closed exactly when @PreDestroy says. The problem is that requests are still using it.

2What Happens When Kubernetes Stops a Pod

When Kubernetes decides to stop a pod, two things start at the same time. The kubelet sends SIGTERM to the container, and the control plane removes the pod from the Service's endpoints, which tells load balancers, kube-proxy and ingress controllers to stop sending it traffic. The second path is asynchronous and takes a little while, often a second or a few seconds, to reach every node and proxy. So for a short time after SIGTERM, new requests keep arriving at a pod that has started shutting down.

On SIGTERM, Spring Boot's shutdown hook closes the application context. Closing first stops the Lifecycle beans, including the embedded web server, and then destroys the singletons, which runs our @PreDestroy and closes the pool. If the web server is stopped immediately, which was the default before graceful shutdown became standard, requests already running keep executing on their threads while the context moves on to destroying beans. Those requests, and any that slipped in, reach pool.getConnection() after close().

Step throughThe race during a rolling update
KubernetesLoad balancerSpring appPool
SIGTERM
remove pod from endpoints (takes time)
context close: stop web server immediately
new request still routed here
@PreDestroy: pool.close()
in-flight request: getConnection()
SQLException: pool has been closed

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

Two independent races: traffic still arriving, and in-flight work outliving the pool.

3Fix 1: Enable Graceful Shutdown

Spring Boot's graceful shutdown makes the web server stop accepting new requests and wait for the in-flight ones to finish before the context continues. It is enabled with server.shutdown=graceful, which became the default in recent Spring Boot versions (3.4 and later; check your version), and it waits at most spring.lifecycle.timeout-per-shutdown-phase, 30 seconds by default.

Text
# application.properties
server.shutdown=graceful
spring.lifecycle.timeout-per-shutdown-phase=20s
# log on SIGTERM
INFO o.s.b.w.e.tomcat.GracefulShutdown : Commencing graceful shutdown. Waiting for active requests to complete
INFO o.s.b.w.e.tomcat.GracefulShutdown : Graceful shutdown complete

The reason this fixes the ordering is how it is built. Graceful shutdown is implemented as a SmartLifecycle bean, a bean with start and stop callbacks grouped into phases, and the context stops all Lifecycle beans before it destroys any singleton. So by the time @PreDestroy closes the pool, every request the server accepted has finished. Notice that it only covers web requests: @Async tasks, schedulers and message listeners need their own settings, such as spring.task.execution.shutdown.await-termination=true for Spring's task executor.

4Fix 2: A preStop Delay for the Load Balancer

Graceful shutdown solves the in-flight requests, but not the new ones that arrive after SIGTERM because the endpoint removal has not propagated yet. Those reach a server that is no longer accepting connections and fail. The usual fix is a preStop hook, a command Kubernetes runs before it sends SIGTERM, that simply waits a few seconds.

YAML
# deployment.yaml (excerpt)
spec:
terminationGracePeriodSeconds: 45 # must cover preStop + graceful shutdown
containers:
- name: inventory
lifecycle:
preStop:
exec:
command: ["sh", "-c", "sleep 10"] # newer Kubernetes also offers a native sleep action
Step throughShutdown order after the fixes
  1. Kubernetes runs preStop: sleep 10endpoints removed meanwhile, traffic stops
  2. SIGTERM, Spring closes the context
  3. SmartLifecycle phase: graceful shutdownserver refuses new requests, drains in-flight
  4. Other Lifecycle beans stoplisteners, schedulers
  5. Singletons destroyedpool closed last, nobody uses it
  6. Process exits before the grace period ends

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

During those ten seconds the pod keeps serving normally while every proxy learns that it is going away. Then SIGTERM arrives, graceful shutdown drains the last requests, and only then is the pool closed. Notice the arithmetic: terminationGracePeriodSeconds must be larger than the preStop delay plus the shutdown timeout, here 10 + 20 = 30 seconds within 45, or Kubernetes sends SIGKILL in the middle of the drain.

5Fix 3: Let Spring Own the Pool

Finally, the pool should not be hidden inside a business service. If we declare it as its own bean, Spring knows that InventoryService depends on it and destroys InventoryService before the pool, and it closes the pool through its inferred close() method without any @PreDestroy code from us. Spring Boot already does this for the standard DataSource when we just set spring.datasource properties.

Java
@Configuration
class InventoryDataConfig {
@Bean // destroy method inferred: HikariDataSource.close() is called at shutdown
HikariDataSource inventoryPool(InventoryPoolProperties p) { return new HikariDataSource(p.toConfig()); }
}
@Service
class InventoryService {
private final DataSource pool;
InventoryService(DataSource pool) { this.pool = pool; } // dependents are destroyed before the pool
}

This also makes the pool visible to Spring Boot's health checks and metrics, which a pool created inside @PostConstruct is not.

6Follow-up questions

Why not just catch the SQLException and retry?

Because the pool will not come back in a pod that is shutting down, so the retry fails too, and the caller still waits. The client side should retry on another instance, which a load balancer or a resilient HTTP client does, but the server should avoid producing the error in the first place.

How long should the preStop delay be?

Long enough for endpoint removal to reach every proxy in our cluster, commonly 5 to 15 seconds. We can measure it by watching how long requests keep arriving after the pod is marked terminating, and keep the total within terminationGracePeriodSeconds.

Does readiness help here?

Spring Boot marks readiness as refusing traffic when shutdown begins, which helps components that watch readiness. But endpoint removal on termination already happens independently, so the preStop delay is what covers the propagation gap.

7Conclusion

In this answer, we saw that the closed-pool errors come from a shutdown order that does not match request draining. Kubernetes keeps routing traffic briefly after SIGTERM, and without graceful shutdown the web server does not wait for in-flight requests before @PreDestroy closes the pool. We enabled graceful shutdown, which is a SmartLifecycle phase that runs before singleton destruction, added a preStop delay with a grace period that covers both waits, and moved the pool into its own Spring-managed bean with an inferred destroy method.

What to say in the interviewAbout 80 seconds aloud

Open with

What is happening is a mismatch between when the pool closes and when requests stop. When Kubernetes terminates a pod, it sends SIGTERM and removes the pod from the endpoints at the same time, but the removal takes a few seconds to reach every proxy, so new requests keep arriving.

Then, if they want more

Spring Boot's shutdown hook closes the context: it stops the Lifecycle beans, including the web server, and then destroys the singletons, which runs the @PreDestroy that closes the pool. If the web server is stopped immediately, in-flight requests are still running and hit a closed pool. I would fix it in three parts.

First, graceful shutdown, server.shutdown=graceful, which is the default in recent Boot versions, so the server stops accepting and waits for active requests. It is a SmartLifecycle phase, so it completes before any singleton is destroyed, with spring.lifecycle.timeout-per-shutdown-phase as the limit.

Second, a preStop hook that sleeps about ten seconds, so the load balancer stops routing before SIGTERM, with terminationGracePeriodSeconds covering preStop plus the drain. Third, I would make the pool its own @Bean, so Spring closes it through the inferred close method after the services that depend on it, instead of hiding it inside a service.

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.
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 service opens a connection pool in @PostConstruct and closes it in @PreDestroy. During...": https://scrivio-interview-library.netlify.app/spring-boot/bean-lifecycle/e88b461d79/