Video in progress

Staff 🌱 Spring

How do you rotate a database password without stopping services (secret rotation)?

With two active accounts or two passwords: a new account/password is created, applications move to the new one gradually (restarting or re-reading dynamically), and once all connections have moved the old one is removed. The best option is Vault dynamic secrets: short-lived logins and automatic rotation.

📖 Answer

The problem: if you change the password in the database, existing connections in the pool keep working, but new connections won't open with the old password. And restarting every pod at once means downtime.

The two-account (A/B) method:

  1. app_user_b is created (or a second password for app_user, if the database supports it);
  2. the new value is written to the secret store;
  3. the applications move to the new account with a rolling restart;
  4. you check in pg_stat_activity that no active connections remain on the old account;
  5. the old account is dropped or locked.

You can also do it without a restart: give the Hikari pool the new password (HikariConfigMXBean.setPassword) and replace the old connections gradually with softEvictConnections(). You can automate it with Spring Cloud Vault + @RefreshScope or your own listener.

With Vault dynamic secrets, each pod gets its own temporary login at startup (say, valid for 24 hours), and before it expires it gets a new one and refreshes the pool. A leaked login soon becomes invalid by itself. In exchange, Vault becomes a critical dependency.

Also:

  • the pool's max-lifetime should be shorter than the password's validity, so old connections renew themselves;
  • automate rotation on a schedule (say, every quarter). A rotation done for the first time during an incident almost always ends in trouble;
  • rehearse the process in staging.