Video in progress

When a pod starts, the database is not ready yet and the application crashes. Should you wait with an init container, or should the app retry itself?

The main protection should be in the application itself: the DB drops during normal operation too, so the app should wait with a short retry or be able to come up even without the dependency. An init container covers only startup time and can add a new problem of its own.

📖 Answer

Waiting with an init container looks easy:

initContainers:
  - name: wait-db
    image: postgres:16
    command: ["sh", "-c", "until pg_isready -h db -p 5432; do sleep 2; done"]

But it solves only the first start. If the DB fails over tomorrow, the app still has to recover by itself. On top of that, if the DB goes down for half an hour, all new pods get stuck in Init:0/1, and both rollouts and autoscaling stop.

What there is on the Spring Boot side:

  • HikariCP checks the connection at startup, and spring.datasource.hikari.initialization-fail-timeout controls how long it waits. With a negative value the pool comes up immediately and gets connections in the background;
  • Flyway connects to the DB at startup. spring.flyway.connect-retries and spring.flyway.connect-retries-interval make it retry several times;
  • make the startupProbe long enough to cover this wait, otherwise the kubelet kills the app while it is waiting;
  • Kubernetes itself retries too: if the app crashes, the kubelet restarts it. For a short time this is also fine, the logs just get noisy.

When an init container is appropriate: when startup really depends on something else and doing it in the app is expensive. For example, preparing a certificate or secret file, fixing file permissions, downloading required configuration.

The general rule: design around the assumption that "a dependency can disappear at any moment", not around "startup order". That holds in Kubernetes and outside it.