Video in progress

Senior 🌱 Spring

The database is temporarily down while the service is starting. Should the app crash or wait, and how do you handle this in Spring Boot?

By default Flyway, Hibernate and Hikari connect to the database at startup, and if they can't, the app fails to start. On Kubernetes that is usually right: the pod is restarted with backoff. For outages while running, though, the app must survive without dying: short timeouts and correct probes.

📖 Answer

I separate two situations: an outage at startup and an outage while running.

Startup. In Boot several database-related things run at startup: the Flyway migration, Hibernate's metadata and dialect detection, ddl-auto=validate. If they can't connect, an exception is thrown and the app stops. Hikari's initializationFailTimeout (default 1 ms) also fails immediately when the pool is opened.

I usually keep this "fail fast":

  • Kubernetes restarts the pod, and the CrashLoopBackOff delay grows on its own;
  • the cause is clear in the log, and a half-working app doesn't receive traffic.

There is one trap: while the database is recovering, 50 pods retry again and again at the same time and add extra load to it. Rolling out in stages and backoff help here.

In local docker-compose, depends_on + condition: service_healthy is enough, so I don't write retry in code for that.

Runtime. If the database disappears for 30 seconds while the app is running, the app must not die:

  • Hikari connection-timeout defaults to 30 s, and a Tomcat thread waits that long. Lower it to 2–5 seconds, otherwise all threads hang and the app stops answering even health requests;
  • if you add the database to the readiness group (management.endpoint.health.group.readiness.include=readinessState,db), the pod is taken out of traffic. Never add it to liveness: when the database goes down, all pods get killed and recovery slows down;
  • when the database comes back, Hikari picks up new connections on its own, and validation and max-lifetime replace the broken ones.

The best check is to deliberately switch the database off and on in staging: does the app recover by itself, how many requests are lost, did the alerts fire.