Quick revision
The short answer
After a failover, the pool is full of connections to the old primary, and they fail only when someone uses them, so errors continue until every stale connection has been tried and replaced. HikariCP validates a connection on borrow only if it has been idle longer than a short window, so recently used broken connections can still be handed out. We shorten recovery by setting maxLifetime and keepaliveTime so stale connections are retired and probed, making sure the JVM does not cache the old DNS address, using the driver's multi-host or target-server-type options where available, setting socket timeouts, and retrying idempotent operations once on connection errors.
What to remember
In this answer, we saw that failover leaves the pool full of connections to the old primary, which fail only when used, and that HikariCP skips validation for recently used connections, so errors continue until each stale one is tried. We shortened recovery with a lower maxLifetime and a keepaliveTime, socket and connect timeouts, a short JVM DNS cache TTL, the driver's multi-host and targetServerType options, and a single retry for idempotent operations on connection errors.
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.
After a failover, the pool is full of connections to the old primary, and they fail only when someone uses them, so errors continue until every stale connection has been tried and replaced. HikariCP validates a connection on borrow only if it has been idle longer than a short window, so recently used broken connections can still be handed out. We shorten recovery by setting maxLifetime and keepaliveTime so stale connections are retired and probed, making sure the JVM does not cache the old DNS address, using the driver's multi-host or target-server-type options where available, setting socket timeouts, and retrying idempotent operations once on connection errors.
Why this question is asked
Failover is meant to be a non-event: the database cluster promotes a standby in seconds and the application carries on. In practice many services keep failing for minutes, and the database team rightly points out that the new primary was ready long before. The gap is almost always in the client: the pool, the driver and the JVM's DNS cache. Interviewers ask this debugging question to see whether we understand how those layers hold on to the past. In this answer, we will walk through what happens to pooled connections during a failover, how HikariCP validates connections, then the settings for lifetime and keepalive, DNS, driver options and retries.
1What Happens to Pooled Connections During a Failover
A pool keeps long-lived TCP connections to the database. When the primary fails and a standby is promoted, those connections point at a server that is gone or no longer accepts writes. How they fail depends on how the old primary went away. If its process was stopped cleanly, the connections are closed with a reset and fail immediately on next use. If the host vanished or the network was cut, the client's TCP connections may look perfectly alive: nothing arrives to tell the client otherwise, and the first query on such a connection waits until a TCP or driver timeout fires, which can be minutes by default.
In both cases a connection fails only when someone uses it. The pool does not know the database has changed. So the service sees a stream of errors, one per stale connection, interleaved with slow requests stuck on dead sockets, until the pool has replaced them all.
8 messages in order. Play them, or step through them one at a time.
Each stale connection produces one failure before it is replaced.
2How HikariCP Validates Connections
HikariCP does test connections before handing them out, but only some of them. When a connection is borrowed, if it has been idle for longer than a short window, about 500 ms in current versions, HikariCP checks it with the JDBC isValid() method, or the connectionTestQuery if configured, bounded by validationTimeout, 5 seconds by default. A connection that was used within that window is handed out without a check, because testing on every borrow would add a round trip to every request.
Under steady traffic, most connections are used every few milliseconds, so they skip validation and the broken ones reach application code. When a connection fails with an error that indicates a broken connection, typically an SQLState in class 08, HikariCP evicts it and later opens a fresh one. That is why recovery is gradual: each broken connection must fail once.
3Retire and Probe: maxLifetime and keepaliveTime
maxLifetime, 30 minutes by default, retires connections at a certain age, and keepaliveTime makes the pool periodically test idle connections, so a dead one is discovered and replaced while idle rather than when a request borrows it. Neither forces instant recovery, but they bound how long the pool can carry stale connections, especially ones to the old primary that still work but point at a demoted read-only server.
That last case matters in clusters where the old primary stays up as a replica: connections to it still work for reads, but writes fail with errors such as cannot execute UPDATE in a read-only transaction, which do not look like connection failures and so do not trigger eviction. With a shorter maxLifetime, for example 5 to 10 minutes, such connections drain away on their own; with the default they might linger for half an hour. HikariCP's softEvictConnections() through its MXBean can also evict all connections on demand, which some teams trigger from a failover event.
Notice socketTimeout on the URL. Without it, a query on a connection whose server vanished can hang for the operating system's TCP retransmission timeout, often many minutes. socketTimeout, in seconds for pgjdbc, caps how long the driver waits for data; it must be longer than the slowest legitimate query. connectTimeout bounds new connection attempts to a dead host. Check your driver version for exact property names and units.
4DNS Caching in the JVM
Many managed databases fail over by moving a DNS name to the new primary's address. The new connections the pool opens then go wherever the JVM thinks the name points. The JVM caches successful DNS lookups: the security property networkaddress.cache.ttl controls for how long, and when it is not set and no security manager is installed, the JDK caches for 30 seconds. Some environments set it to cache forever, in which case the pool keeps reconnecting to the old address until the JVM restarts, which looks exactly like a service that only recovers after a redeploy.
So we check the effective setting in the java.security file of our runtime and in any startup flags, and set a short TTL, for example 30 seconds or less, as cloud providers recommend for their database endpoints. We also check other caches on the path, such as a sidecar proxy or a local DNS resolver with its own TTL.
5Driver Options and Retries
Drivers can help choose the right server themselves. pgjdbc accepts several hosts in the URL and targetServerType=primary, so it tries each host and connects only to the one that accepts writes; loadBalanceHosts and hostRecheckSeconds tune how it picks and remembers hosts. MySQL Connector/J has its own multi-host and failover URL formats, and cloud providers offer drivers or proxies that track topology. Where the database exposes a single DNS name with fast updates, the plain URL is fine; where it exposes individual hosts, the multi-host options remove the dependency on DNS.
Finally, even with all of that, some requests in flight during failover will fail. For idempotent operations, such as reads or writes protected by an idempotency key, retrying once after a short delay on a connection error hides most of the failover from users. The retry must start a new transaction on a new connection, and must not be applied to non-idempotent writes, which could otherwise run twice. Spring Retry or Resilience4j can express that policy with a filter on the exception type, for example Spring's TransientDataAccessResourceException or the SQLState class 08.
6Follow-up questions
Why not validate every connection on borrow?
It would add a database round trip to every borrow, which for short queries can double the database work and add latency to every request. And it still would not catch connections that break between the check and the query, or connections to a demoted primary that pass a validity check. Shorter lifetimes, keepalives, socket timeouts and a retry give better protection at lower cost.
How would you test this before a real incident?
We trigger a failover in a staging environment that matches production topology while a load test runs, and measure how long errors continue and why, looking at pool metrics and error types. Many cloud databases have a forced-failover operation for exactly this. Repeating the test after each change shows which setting actually shortened recovery.
What does a demoted primary look like in the logs?
Connections still work, but writes fail with read-only errors, for example cannot execute INSERT in a read-only transaction on PostgreSQL, SQLState 25006. HikariCP does not treat that as a broken connection, so those connections are not evicted. targetServerType=primary for new connections and a shorter maxLifetime, or evicting the pool on failover, fix it.
7Conclusion
In this answer, we saw that failover leaves the pool full of connections to the old primary, which fail only when used, and that HikariCP skips validation for recently used connections, so errors continue until each stale one is tried. We shortened recovery with a lower maxLifetime and a keepaliveTime, socket and connect timeouts, a short JVM DNS cache TTL, the driver's multi-host and targetServerType options, and a single retry for idempotent operations on connection errors.
Open with
The core problem is that the pool still holds connections to the old primary, and a pooled connection only fails when someone uses it. If the old server disappeared without closing sockets, a query can even hang until a TCP timeout.
Then, if they want more
HikariCP does validate on borrow, but only connections that have been idle longer than about half a second, so under steady traffic most broken connections are handed straight to requests, fail once, and only then get evicted. That is why recovery takes minutes even though the new primary was ready in seconds.
My changes would be: set socketTimeout and connectTimeout on the driver so dead connections fail quickly instead of hanging; lower maxLifetime, say to ten minutes, and set keepaliveTime so idle connections are probed and stale ones drain away, which also matters when the old primary comes back as a read-only replica and writes start failing with read-only errors that do not trigger eviction.
Then DNS: if failover moves a DNS name, I would make sure the JVM's networkaddress.cache.ttl is short and not cached forever, otherwise the pool keeps reconnecting to the old address. Where the database exposes several hosts, I would use pgjdbc's multi-host URL with targetServerType=primary. Some teams also evict the whole pool on a failover event.
Finally, I would retry idempotent operations once on connection errors with a new transaction, and test all of this with a forced failover in staging under load.
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
- java.sql, package 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 "After a database failover, a service keeps failing with broken-connection errors for...": https://scrivio-interview-library.netlify.app/databases/jdbc/fea99fae1b/