AI Code Tutorial · No. 01
Rotate database passwords on Railway, without restarting the database.
A brief you can hand to a coding agent. It changes the Postgres and Redis passwords behind a Flask app through a private tunnel, keeps Postgres running, limits Redis to one short planned restart, and tests every step before it moves on.
Why this, and why now.
On 21 October 2026 Railway disclosed that an unauthorised party may have reached the systems that store customer environment variables, and for some of them obtained the decrypted values. Its advice is plain: roll every variable stored on the platform. Read Railway’s security disclosure.
Most secrets are easy. You rotate an API key in the provider’s dashboard and paste the new one back. Database passwords are the awkward ones, because each one lives in two places at once: in the variable your app reads when it starts, and inside the database itself, which is what actually checks it.
Railway’s own guides use a Regenerate button that changes both in one step. It is the right call if you think a credential is being abused right now. It also restarts the database, drops every open session and leaves your apps unable to connect until you redeploy them.
This tutorial takes the other route. Your coding agent changes each half separately. For Postgres it times the switch to the moment the new app container starts; Redis accepts the old and the new password side by side while the apps redeploy. Postgres never restarts. Redis gets one short, planned restart at the very end, once every app already uses the new password. The window in which an app and its database disagree shrinks from minutes to seconds.
The idea
One password, two places.
The agent works from your machine. It reaches the databases through a private tunnel, and it changes the Railway variables through the CLI. Neither database is exposed to the internet at any point.
The variable.
What your app reads. Railway hands variables to a container once, when it starts. Changing a variable does nothing to a running app; only a new deployment picks it up. With --skip-deploys you can change it without restarting anything.
The database.
What checks the password. Postgres stores it in its own catalogue; Redis holds it in memory. Both accept a new password while running, and both keep already-open connections alive when it changes. Redis can even hold two passwords at once; Postgres cannot. On restart, Postgres keeps the new password and Redis reloads it from its variables.
The whole method in one sentence: change the variable first without deploying, then flip Postgres at the exact moment the new app container boots, and let Redis accept both passwords until every app has moved.
The workflow
Six phases, each with a gate.
The agent does not move to the next phase until the current one passes its gate. Phases 0 to 2 change nothing your users can feel. Only phase 3 touches live traffic, and only after you say go.
Fig. 2 — The rotation, phase by phase
-
PHASE 0
Inspect
Read-only. Map who uses which password, and check what each database really holds.
Gate: Every consumer known
-
PHASE 1
Generate
New secrets in private files. Postgres hash computed locally.
Gate: Nothing printed
-
PHASE 2
Stage
New values set on Railway without deploying anything.
Gate: References resolve
-
PHASE 3
Redeploy & switch
Redeploy the app. Flip Postgres as its new container starts. Then drop the old Redis password and restart Redis once so it keeps the new one.
Gate: You said go
-
PHASE 4
Verify
Logs, connections, old password refused, real pages served.
Gate: All tests pass
-
PHASE 5
Clean up
Delete secrets, close tunnels, write the report.
Gate: Nothing left running
The switch window
Seconds, not minutes.
The order is what makes this safe. The agent switches Postgres only once the new container exists, so a build that hangs, fails or queues for twenty minutes changes nothing at all. Redis has no such window; see below.
-
Stage
The variable now holds the new password. Nothing restarts; the running app still uses the old one.
-
Redeploy
A new container builds. The old one keeps serving. This can take minutes, and nothing has changed yet.
-
Switch · about 1–5 s
The new container starts. The agent changes the Postgres password within a second or two. Redis needs no switch here.
-
Live
Traffic moves to the new container, which already has the new password.
Redis takes both passwords at once.
Since Redis 6 a user can hold several passwords. Before any app redeploys, the agent adds the new one next to the old with ACL SETUSER default >new. Old and new containers both connect, however long the builds take and however many apps share the Redis, so there is nothing to time. Once no connection is older than the last app redeploy, it removes the old one with ACL SETUSER default <old. Never use CONFIG SET requirepass for this: it replaces every password at once and ends the overlap.
Redis remembers the old password.
ACL SETUSER changes only the running server, but Railway’s Redis images read the password from the deployment’s variables every time they start, and the running deployment still holds the old value. Once the old password is removed, a crash or host restart would quietly put it back and lock every app out. So right after removing it, the agent redeploys Redis itself: usually under 30 seconds, longer for a large volume. Apps should degrade, not die, for that long; check how long yours tolerate a missing Redis before you plan the window.
Before you start
Ten minutes of preparation.
Railway CLI, logged in
The agent uses it for tunnels, variables, redeploys and logs. Check with railway whoami.
An SSH key on your Railway account
The private tunnel rides on it. Remember that it opens tunnels to every project you own.
psql and redis-cli
On the machine the agent runs on. The psql major version does not need to match the server for these queries.
Builds that work
Check the Railway status page. During the incident builds were paused; a rotation that cannot deploy strands your app.
A fresh backup of every volume
Redis will restart, and this is production. Take a manual volume backup and wait until it completes. Check that a backup schedule exists at all; not every volume has one.
Pinned images
A service on an image like vendor/app with no version tag can pull a newer release when redeployed, and run migrations with it. Pin each one to the version it runs today first.
A second way in
railway connect only recognises Railway’s own database templates; a custom image such as pgvector gets “No supported database found”. railway ssh into the database container, where local connections are trusted, is the fallback.
Approve every command
Run the agent in a mode where you confirm each command. If your tool has an automatic mode, switch it off for this job.
Phase by phase
What the agent actually does.
You do not need to type any of this. It is here so you can follow along and know what a good run looks like.
Phase 0 · read-only
Inspect before touching.
- Map every consumer. Which services read which password, and whether as a reference like ${{Postgres.PGPASSWORD}} or as a pasted copy. Pasted copies do not follow a change; they get converted to references.
- Check for public access. A public TCP proxy means the database is reachable from the internet. If nothing outside the project needs it, switch it off first.
- Prove which password the database holds. Variables drift. The agent reads the stored SCRAM hash and checks each candidate variable against it locally, printing only true or false.
- Check logging. log_statement should be none, so nothing about the change lands in server logs.
- Know Redis. Uptime, persistence, users and connected clients, and how it gets its password at start: a start command with --requirepass $REDIS_PASSWORD, or an image script that reads the variable. Either way it will need one restart. With append-only persistence off, force a snapshot just before it.
- Check that Redis can hold two passwords. Version 6 or later, no aclfile, and every client in CLIENT LIST logged in as user=default. If any of these fails, stop: the overlap method does not apply as written.
- Look for duplicate variables. Some Redis templates hold the password twice, as REDIS_PASSWORD and REDISPASSWORD, both pasted. Both must change, or one should reference the other.
- Read the app’s start-up code. Does it retry the database on boot? Does its “Redis unavailable” fallback actually work with the library versions installed today? How long does it survive without Redis before it exits?
# a private tunnel per database (discard output: it can echo secrets) railway connect "Postgres" --tunnel-only -P 55432 >/dev/null 2>&1 & railway connect "Redis" --tunnel-only -P 56379 >/dev/null 2>&1 & # which variables does the stored hash match? (true/false only) psql "host=127.0.0.1 port=55432 user=postgres" -XAt \ -c "select rolpassword from pg_authid where rolname='postgres'" # logging, roles, who is connected psql ... -c "show log_statement" -c "show password_encryption" psql ... -c "select usename, client_addr, count(*) from pg_stat_activity group by 1,2" # the tunnel lands on 127.0.0.1: a wrong password still connects PGPASSWORD=wrong psql "host=127.0.0.1 port=55432 user=postgres" -c "select 1" redis-cli -h 127.0.0.1 -p 56379 INFO server | grep -E 'redis_version|uptime' redis-cli -h 127.0.0.1 -p 56379 CLIENT LIST # user=default on every app redis-cli -h 127.0.0.1 -p 56379 CONFIG GET aclfile # must be empty # no tunnel for this image? go in through the container, # feeding the script on stdin (quoted args get mangled) railway ssh -s "Postgres" -- sh < scratch/inspect.sh
Gate: the agent reports every consumer, every mismatch and a plan per app, then waits.
Phase 1
Generate, never print.
- 40 random letters and digits per database, from a cryptographic generator. Long, and nothing that needs escaping in a URL.
- Private files, not the screen. A scratch folder outside the repository, readable by you only. Secrets move through files and standard input.
- Keep the old Redis password. You need it to authenticate the change, and again to remove it at the end. Save it before staging anything.
- Hash the Postgres password locally. The agent computes the SCRAM-SHA-256 verifier on your machine and sends only that. The plain password never reaches the server.
- Keep the verifier away from the shell. It is full of $ signs. Inside psql -c "…" the shell expands them, Postgres stores the mangled text as a plain password, and both the old and the new password stop working. Send it in a file or a quoted heredoc.
# the verifier Postgres stores, computed locally import base64, hashlib, hmac, os def scram(pw, it=4096): salt = os.urandom(16) sp = hashlib.pbkdf2_hmac("sha256", pw.encode(), salt, it) ck = hmac.new(sp, b"Client Key", "sha256").digest() sk = hmac.new(sp, b"Server Key", "sha256").digest() b = lambda x: base64.b64encode(x).decode() return (f"SCRAM-SHA-256${it}:{b(salt)}" f"${b(hashlib.sha256(ck).digest())}:{b(sk)}") # later, from a file or a quoted heredoc, never -c "...": # ALTER ROLE postgres PASSWORD '<verifier>';
Gate: each verifier checks out against its password, and nothing secret appeared in the output.
Phase 2
Stage without deploying.
- --skip-deploys is the whole trick. Without it, Railway redeploys the database and you are back to a restart.
- Fix pasted copies now. An app holding a literal password gets a reference instead, so it can never drift again.
- Check by comparison, not by looking. The agent confirms each app’s resolved variable equals the new secret, and that no deployment started.
- Give Redis a second password. ACL SETUSER default >new adds the new password and keeps the old one. Running apps notice nothing; PING now works with either.
# new value on the database service, no redeploy railway variable set POSTGRES_PASSWORD --stdin --skip-deploys \ -s "Postgres" < scratch/pg_new railway variable set REDIS_PASSWORD --stdin --skip-deploys \ -s "Redis" < scratch/redis_new # and REDISPASSWORD too, if the template pasted it twice # a pasted copy becomes a reference printf '%s' '${{Postgres.PGPASSWORD}}' | \ railway variable set PGPASSWORD --stdin --skip-deploys -s "web" # Redis: add the new password, keep the old one printf 'ACL SETUSER default >%s\n' "$(cat scratch/redis_new)" | \ REDISCLI_AUTH="$(cat scratch/redis_old)" \ redis-cli -h 127.0.0.1 -p 56379 --no-auth-warning
Gate: every reference resolves to the new value, Redis answers both the old and the new password, and nothing has redeployed. Then the agent stops and asks you.
Phase 3 · live traffic
Redeploy, then switch on cue.
- Redeploy the app and poll its deployment status every three seconds.
- On DEPLOYING, switch Postgres. ALTER ROLE with the verifier. Open connections stay logged in. Redis needs no cue: it already accepts both passwords.
- Build failed or stuck? Do not switch. The old container keeps working on the old password. Nothing is broken.
- Keep watching after success. A container can report success and crash twenty seconds later. The agent watches for a minute.
- Redeploy the same build. Redeploy the existing deployment rather than the branch head, so a rotation never ships unreleased commits alongside it.
- Last, drop the old Redis password and restart once. When every Redis client connected after the last app redeploy, so nothing still uses the old password, remove it with ACL SETUSER default <old and check it gets WRONGPASS. Then force a snapshot and redeploy Redis. Then PING with the container’s own $REDIS_PASSWORD must answer PONG.
railway redeploy -s "web" -y # poll until the new deployment leaves BUILDING railway deployment list -s "web" --json # every 3 s # the moment it reads DEPLOYING: psql "host=127.0.0.1 port=55432 user=postgres" \ -v ON_ERROR_STOP=1 -f scratch/alter.sql # alter.sql: ALTER ROLE postgres PASSWORD 'SCRAM-SHA-256$...'; # every app on the new password? drop the old one redis-cli ... CLIENT LIST # all ages younger than the last redeploy printf 'ACL SETUSER default <%s\n' "$(cat scratch/redis_old)" | \ REDISCLI_AUTH="$(cat scratch/redis_new)" \ redis-cli -h 127.0.0.1 -p 56379 --no-auth-warning # then make Redis keep it across restarts redis-cli ... BGSAVE railway redeploy -s "Redis" -y
Gate: the new Postgres password logs in and the old one is refused, Redis refuses the old password and answers the new one even after its restart, and every deployment is still healthy a minute later.
Phase 4
Verify like a sceptic.
A homepage returning 200 proves nothing if a CDN cached it. The agent requests a page that needs the database, with a cache-busting query string, reads the new deployment’s logs for authentication errors, and confirms the old password is refused. The full list is in the table below.
Phase 5
Leave nothing behind.
Delete the scratch secrets and scripts. Close every tunnel, and check the ports: stopping the CLI can leave the underlying SSH process listening. Finish with a short written report of what changed, every check and its result, and any downtime with timestamps.
The checklist
Every test the agent runs.
Seventeen checks. None of them prints a secret; every comparison is true or false.
| When | Test | How | Pass |
|---|---|---|---|
| Before | Stored password matches the variables | Check the SCRAM hash in pg_authid against each candidate variable, locally | Each app’s copy matches |
| Before | Statement logging is off | show log_statement | none |
| Before | Tunnel uses local trust | Connect through the tunnel with a deliberately wrong password | Connects |
| Before | Builds are working | Status page, and a recent successful deployment | Green |
| Before | Every volume is backed up | A manual backup, listed as completed | Fresh backup |
| Before | Image services are pinned | Each image source carries a version tag that matches the running digest | No bare latest |
| Before | Redis can hold two passwords | redis_version, CONFIG GET aclfile, user= in CLIENT LIST | 6 or later, empty, default |
| Stage | References resolve to the new secret | Compare each app’s resolved variable with the new secret | All true, no deploy started |
| Stage | Redis accepts both passwords | PING with the old password, then with the new one | PONG twice |
| Switch | New hash is stored | rolpassword equals the new verifier | true |
| Switch | Postgres logs in with the new password | A real password login over the network, old and new | New in, old refused |
| After | Deployment stays healthy | Deployment status, one minute after success | Still SUCCESS |
| After | Redis refuses the old password | PING with the old password, once it is removed | WRONGPASS |
| After | Redis survives a restart | After the Redis redeploy, PING with the container’s own $REDIS_PASSWORD | PONG |
| After | No authentication errors | Logs: password authentication failed, WRONGPASS, NOAUTH, Traceback | None after the switch |
| After | The app really uses the database | Uncached request to a database-backed page | 200 |
| After | Nothing left running | Scratch folder and tunnel ports | Empty and closed |
Failure modes
What can go wrong, and the fix.
The build hangs.
The agent waits and switches nothing. The old container keeps serving on the old password. Retry the build later.
The new container crashes after the switch.
Read its logs. Both halves of the password now match, so a fresh redeploy usually comes up clean.
A fallback path is broken.
Code that only runs when Redis is down has often never run at all. Read it in phase 0, and pin the library it depends on.
A password was pasted, not referenced.
That app keeps the old value and fails after the switch. Phase 0 finds these; phase 2 converts them.
A tunnel outlives the session.
Stopping the CLI can leave its SSH process holding the port. Check with lsof and close it.
A secret gets printed.
Treat it as exposed and rotate that one again. The prompt forbids printing, but tools can echo connection strings.
Redis restarts and forgets.
ACL SETUSER without a Redis redeploy works until the first restart, which brings back the old password and locks every app out. Redeploy Redis once, right after removing the old password.
The shell eats the verifier.
A SCRAM verifier inside a double-quoted command loses its $ parts. Postgres stores the remains as a plain password and nobody can log in. Re-run the ALTER from a file; the login test catches it within seconds.
A redeploy upgrades the app.
An unpinned image pulls the newest release and may migrate the database on boot. Pin the running version before the first redeploy.
The prompt
Hand this to your coding agent.
Fill in the parts in square brackets. The agent inspects first, reports, and waits for your go-ahead before it touches live traffic.
You are going to rotate the database passwords behind a web app hosted on Railway.
Project: [Railway project name], environment: [production]
Databases: [Postgres service name(s)], [Redis service name]
Apps that use them: [app service name(s)]
Goal: a new password for every database, with no Postgres restart, one short planned Redis restart at the end, and no more than a few seconds in which an app and its database disagree.
HARD RULES
- Never print, log or paste a secret. Keep secrets in files with mode 600 in a scratch folder outside the repository. Pass them through files or standard input. Compare values with equality or hash checks only.
- Never restart, redeploy or "Regenerate" a Postgres service. Use --skip-deploys on every variable change. The only database restart allowed is the single Redis redeploy in step 21.
- Change the Redis password only with ACL SETUSER (add, then remove). Never use CONFIG SET requirepass: it replaces every password at once.
- Never put a SCRAM verifier inside a double-quoted shell string; its $ signs get expanded. Send SQL from a file or a quoted heredoc.
- Redeploy existing deployments; never deploy the branch head as part of this job.
- Work read-only until I approve. Stop and wait for me after Phase 0 and after Phase 2, and whenever a check fails.
- If a command is denied, do not look for a workaround. Tell me.
PHASE 0 - INSPECT (read-only)
1. Confirm the Railway CLI is logged in and linked to the right project and environment. Confirm builds are working: a recent successful deployment, and the Railway status page.
2. For each database, list every service that uses its credentials and whether each one uses a reference (${{Service.VAR}}) or a pasted literal. Report every literal, including duplicates on the database service itself (REDIS_PASSWORD and REDISPASSWORD).
3. Report any database with a public TCP proxy. Do not change it.
4. Report every image-based service without a version tag, with the version it runs now. Report every volume and whether a backup schedule exists.
5. Open one tunnel per database: railway connect "<service>" --tunnel-only -P <port>. Discard its output; it can contain secrets. If the CLI does not recognise the database, use railway ssh -s "<service>" -- sh and feed scripts on standard input instead.
6. Postgres: read the stored SCRAM verifier from pg_authid and check locally which variables it matches (POSTGRES_PASSWORD, PGPASSWORD and each app's copy). Report the server version, log_statement, password_encryption, login roles and current connections.
7. Connect through the tunnel with a deliberately wrong password. If it does not connect (no local trust), stop: we must save the old password before staging.
8. Redis: PING with the current password. Report the version, uptime, persistence settings, ACL users (hashes redacted), connected clients, and how it receives its password at start (start command or image script). Confirm it is version 6 or later, CONFIG GET aclfile is empty, and every client in CLIENT LIST is user=default. If not, stop and report.
9. Read the app's start-up code. Does it retry the database on boot? What does it do if Redis rejects it or disappears, how long until it gives up, and does that fallback work with the library versions installed in production?
Then report your findings and a plan per app, and wait.
PHASE 1 - GENERATE
10. Generate a 40-character alphanumeric password per database with a cryptographically secure generator, into mode-600 files.
11. Save the current Redis password to a file before changing anything. You need it to authenticate, and to remove it at the end.
12. For Postgres, compute the SCRAM-SHA-256 verifier locally (4096 iterations, random 16-byte salt) and check it against the new password.
PHASE 2 - STAGE (no restarts)
13. Pin every unpinned image service to the version it runs now, without deploying. Take a manual backup of every volume and wait until each one completes.
14. Set the new POSTGRES_PASSWORD and REDIS_PASSWORD (and any duplicate) on the database services with: railway variable set <VAR> --stdin --skip-deploys -s "<service>"
15. Replace every pasted literal in an app with a reference to the database service's variable.
16. Confirm each app's resolved variable now equals the new secret, and that no deployment started.
17. Add the new password to Redis next to the old one: ACL SETUSER default ><new>, authenticated with the saved old password, the command sent over standard input. Confirm PING works with both the old and the new password.
Then show me the exact plan for Phase 3, and wait.
PHASE 3 - REDEPLOY AND SWITCH (only after my go-ahead)
18. Redeploy one app's existing deployment, or one batch. Poll railway deployment list --json every 3 seconds.
19. The moment its new deployment reaches DEPLOYING, run ALTER ROLE <user> PASSWORD '<verifier>' from a file through the tunnel. Then confirm the stored hash equals the new verifier, a real login with the new password works, and the old password is refused. Redis needs no timing: it accepts both passwords.
20. When every Redis consumer has redeployed and CLIENT LIST shows no connection older than the last redeploy, remove the old password: ACL SETUSER default <<old>, authenticated with the new password, sent over standard input. Confirm the old password now gets WRONGPASS.
21. Then run BGSAVE, wait for it, and redeploy the Redis service once so its start-up reads the new variable. Tell me first how long each app can survive without Redis.
22. If a deployment fails or hangs, do not switch that database. Report and wait.
23. Watch each new deployment for 60 seconds after it reports SUCCESS. If it crashes, read its logs, report, and redeploy once the cause is understood.
PHASE 4 - VERIFY
24. Each new deployment still reports SUCCESS after 60 seconds.
25. The new deployments' logs show no "password authentication failed", WRONGPASS, NOAUTH or tracebacks after the switch, other than during the Redis restart.
26. Redis: the old password gets WRONGPASS; PING with the Redis container's own $REDIS_PASSWORD gets PONG.
27. pg_stat_activity and CLIENT LIST show connections from the new containers.
28. A database-backed page returns 200 with a cache-busting query string, so no CDN cache answers for it.
PHASE 5 - CLEAN UP
29. Delete the scratch secrets and scripts.
30. Close every tunnel, and check with lsof that no SSH process still listens on the tunnel ports.
31. Give me a short report: what changed, each check and its result, any downtime with timestamps, and anything left for me (local .env files, external tools that used the old passwords).
Works with any agent that can run shell commands: Claude Code, Codex, Cursor and the like. Run it with command approval switched on.
Questions
The short answers.
Does changing a Postgres password on Railway need a database restart?
No. PostgreSQL keeps role passwords in its own catalogue, so ALTER ROLE takes effect immediately and the server keeps running. The POSTGRES_PASSWORD variable is only read when the data directory is first created. Railway’s Regenerate button restarts the database to apply a new password; the method in this tutorial does not.
Do open connections drop when the password changes?
No. In both PostgreSQL and Redis, sessions that are already authenticated stay authenticated. Only new connections need the new password. That is why the Postgres switch can be timed to the moment a new app container starts. Redis does not even need the timing: it can accept the old and the new password at once.
Why not just press Regenerate in the Railway dashboard?
It is simpler and it is Railway’s documented route, so use it if you believe a credential is being abused right now. The cost is a database restart, dropped sessions and an outage until every dependent service has been redeployed. This tutorial trades that for a few more steps and an agent doing them carefully.
Is it safe to let an AI agent touch production database credentials?
It can be, with rules. The agent never prints a secret, works read-only until you approve, stops at fixed gates, and runs in a permission mode where you approve each command. Treat it like a careful junior engineer with a checklist, not an autopilot.
Why does Redis need a restart after all?
Because Railway’s Redis images read the password from the deployment’s variables every time they start. ACL SETUSER changes only the running server, and the running deployment still carries the old variable, since the new one was staged with --skip-deploys. Any restart, from a crash or host maintenance, would bring the old password back and, once the apps have moved to the new one, lock out every app. One planned redeploy of Redis, once every app already uses the new password, closes that gap. Postgres has no such issue: it keeps the password in its own catalogue.
What happens if the app build fails halfway through?
Nothing breaks. The database password is only switched once the new container is starting, so a failed or stuck build leaves the old container running on the old password. You retry the build, then switch.
Does this only work for Flask?
No. Any app that reads its database and Redis credentials from environment variables at start-up behaves the same way: Django, FastAPI, Rails, Node, Celery workers. The example here is a Flask app served by gunicorn because that is a common Railway setup.