How to Rotate Database Credentials Safely
Rotate database passwords without downtime using dual credentials, connection pool draining and a verified cutover, plus a rollback path.
On this page
Introduction
Rotating a database password sounds simple until it happens across a running fleet with connection pools, replicas, background jobs and replicas of the application. Change the password in the wrong order and every connection fails, turning a routine security task into an outage. Safe rotation uses a sequence that always leaves a working credential available: create the new credential alongside the old, deploy it, verify every consumer uses it, then retire the old one. This tutorial covers that sequence and the failure modes that break it.
Why Naive Rotation Causes Outages
The instinct is to change the password in the database and update the application at the same time. But between those two operations, the application holds connections with the old password. If the database invalidates the old password immediately, those connections and any new ones fail until the application picks up the new value. With a fleet, the update propagates unevenly and some instances fail while others succeed.
A second failure mode is cached credentials: configuration management, secret managers and container environments may hold the old password and not refresh on schedule. Even after the application is redeployed, an instance that reads a cached value still fails. Safe rotation must account for every place a credential is stored and every process that holds a live connection.
# naive (breaks)
1. ALTER ROLE app PASSWORD 'new' <- old password instantly invalid
2. redeploy app <- instances still connecting with old
# result: errors from step 1 until step 2 completes fleet-wide
# safe (no downtime)
1. create role app_v2 with new password, same grants
2. deploy app to use app_v2 (both roles valid)
3. verify no connection uses app_v1
4. drop / disable app_v1
5. remove app_v1 from secrets
Dual Credentials and Overlap
The key idea is a period during which both the old and the new credentials are valid, and the application can use either. You create a new role or user with the new password and the same privileges, deploy the application to use it, and leave the old one valid until every consumer has moved. Only then do you disable the old credential.
Make the overlap long enough to cover the slowest consumer: a long-running job that holds a connection for hours, a replica that lags, a manual admin session. Monitor who is still using the old credential and extend the overlap if consumers remain, rather than cutting over on a fixed schedule and hoping.
-- Create the successor role with identical grants.
CREATE ROLE app_v2 LOGIN PASSWORD 'generated-strong-password';
GRANT app_readwrite TO app_v2; -- same privileges as app_v1
-- After all consumers moved, disable the old role (keep it for rollback).
ALTER ROLE app_v1 NOLOGIN; -- stop new logins, keep the role
-- Then, once confirmed unused:
-- DROP ROLE app_v1;
Deploying the New Credential
Deploy the new credential to the secret store first, then roll the application so it picks it up. If the application reads the credential at startup, a rolling restart moves instances to the new value one at a time; if it reads dynamically, the secret store updates and consumers refresh. Either way the database accepts both during the overlap, so a partially rolled fleet keeps working.
Track the deployment. Query the database for active sessions grouped by user, or watch the application’s connection user metric, so you can see the proportion on the new credential rising to one hundred percent. The cutover to disabling the old credential is driven by that observation, not by a timer.
-- See who is still connecting with the old credential.
SELECT usename, count(*) AS sessions, max(state) AS state
FROM pg_stat_activity
WHERE usename IN ('app_v1', 'app_v2')
GROUP BY usename;
-- disable app_v1 only when app_v1 shows zero sessions for a sustained period
Connection Pool Draining
A connection pool holds live sessions, so even after you disable the old credential, existing sessions may linger until the pool recycles them. Close and reopen pools deliberately at cutover: deploy a change that drains the old pool and builds a new one, so no session survives on the retired credential.
For a fleet, stagger the drain so you do not close every pool at once, which would spike the database with a thundering herd of new connections. Drain one instance or one batch at a time, verifying health between batches. If a batch fails, stop; the old credential is still available for rollback.
# cutover sequence with pools
1. disable old credential in the DB (NOLOGIN) - existing sessions persist
2. roll the app in batches: each instance drains its old pool, opens a new one
3. between batches, check health + error rate
4. after all batches: confirm 0 sessions on the old user
5. remove the old password from the secret store
# rollback at any step: re-enable the old role (NOLOGIN -> LOGIN)
Replicas, Jobs and Every Consumer
Enumerate every consumer of the credential before you start: web instances, worker processes, cron jobs, analytics tools, replicas, the connection pooler, and manual admin access. A credential rotates only when its slowest and least obvious consumer has moved. A forgotten analytics dashboard is exactly what turns a clean rotation into a late-night incident.
Some consumers cannot be updated quickly, such as a vendor tool with a hard-coded credential. For those, keep the old role valid longer and document the exception, or issue a separate credential with narrower privileges. The rotation plan is only as good as the completeness of its consumer inventory.
# consumer inventory to fill before rotating
[ ] web/app instances [ ] background workers
[ ] cron / scheduled jobs [ ] analytics/BI tools
[ ] read replicas [ ] connection pooler (pgbouncer)
[ ] migrations tool [ ] vendor integrations (hard-coded?)
# rotation completes only when the last consumer has moved
Automation and Verification
Automate the sequence so it is repeatable and auditable, but verify at each step rather than trusting the automation blindly. Automate creation of the successor role, the secret update, the rolling deploy, the session check and the final disable, with health gates between steps and an automatic halt if a gate fails.
Verify the new credential actually works before disabling the old one: run a health query through the new credential from every consumer class, not just the web tier. A credential that works from the app but not from the migration tool will fail at the worst moment. Verification is what makes the cutover safe to automate.
# automated rotation with gates
create app_vN -> update secret -> roll app in batches
gate: health ok? error rate flat? --no--> halt (rollback available)
verify new cred from each consumer -> disable old (NOLOGIN)
gate: 0 sessions on old for 10m? --no--> re-enable old, investigate
remove old secret -> done (audit log written)
Common Pitfalls and Conclusion
Do not change the password in place; create a successor with overlapping validity. Do not cut over on a timer instead of observing that consumers have moved. Do not forget pooled connections, replicas and background jobs. Do not skip verification from every consumer class. And always keep a rollback: re-enabling the old role is cheap, while recovering from a broken cutover is not.
Safe rotation is a sequence, not an event: create the new credential alongside the old, deploy it across the fleet, verify every consumer uses it and none use the old, drain pools, then retire the old credential with a rollback path at every step. Follow the sequence and a security requirement becomes a routine deploy instead of an outage.
Sources: PostgreSQL: CREATE ROLE, PostgreSQL: Monitoring pg_stat_activity, NIST SP 800-57: Key management.
FAQ
- Can I just update the password in place?
- Not without downtime, because connections holding the old password break the moment the old one is invalidated. Create a successor credential with overlapping validity so both work during the deploy, then retire the old one once no consumer uses it.
- How do I know when it is safe to disable the old credential?
- When the database shows zero sessions using it for a sustained period, across a rolling window that covers your longest-lived connection. Then drain pools and disable it, keeping the ability to re-enable it for rollback.
Report a problem with this articleOpens a pre-filled issue on GitHub.