Sub topic 13
Rotating and revoking keys
This chapter assumes you can set environment variables, use a CI secrets store, and read short Python snippets. It also assumes you already keep your LLM API key out of source code. The focus here is what happens afterward: replacing a key on a schedule, and killing one that is no longer safe.
Revoking and rotating are different actions
Revoking a key means telling the provider to stop accepting it. After revocation, every request that uses the key fails, usually with an HTTP 401 status. Revocation is permanent. Most provider consoles have no "undo" button.
Rotating a key means replacing it with a new one. A rotation has four parts: create a new key, deploy it everywhere the old key was used, confirm that traffic uses the new key, and then revoke the old key.
You revoke without rotating when a key is no longer needed, for example when a project ends. You rotate when the work continues and needs a working key.
Why rotate at all
A key that never changes has an unbounded exposure window. Any copy that ever existed stays valid. Copies you may not know about include:
- an old laptop backup
- a teammate's shell history
- a CI log from last year
- a screenshot in a chat thread
Rotation shrinks that window. A stolen key is only useful until the next rotation.
Rotation also tests your setup. If rotating a key breaks production, you have learned that you don't know where the key is used. It is much better to find that out on a calm Tuesday than during a leak.
You should rotate in these situations:
- A key may have been exposed. Do this immediately.
- A person with access to the key leaves the team.
- A laptop or CI runner that held the key is lost or retired.
- Your policy says so. Every 90 days is a common interval, but follow your organization's rule.
Rotating without downtime
The risk in rotation is order. If you revoke the old key before every service has the new one, those services fail. The safe approach is an overlap period in which both keys are valid.
The steps in order:
- Create the new key. Give it a name that includes the date or purpose, such as
chat-backend-prod-2026-11. Copy it when it is shown, because most consoles display it only once. - Store it where the old one lives. Update your local
.env, the CI secret, and your deployment platform's secret store. - Restart or redeploy. A running process reads environment variables once, at startup, so it keeps using the old key until it restarts.
- Verify. Send a test request with the new key. Then check the provider's usage page. Most consoles show a "last used" time for each key.
- Wait for the old key to go quiet. When its last-used time stops advancing, nothing depends on it.
- Revoke the old key.
If the old key is still being used after you think everything has moved, something you forgot is using it. Find it before revoking, unless the old key is compromised. In that case revoke first (see the next chapter).
Verifying a new key without printing it
Before you revoke anything, confirm that the new key works. This script checks a key stored in a named environment variable and prints only the variable name and the status code.
import os
import sys
import requests
# Usage: python check_key.py LLM_API_KEY_NEW
var_name = sys.argv[1]
api_key = os.environ.get(var_name)
if not api_key:
sys.exit(f"{var_name} is not set")
response = requests.post(
"https://api.example.com/v1/chat", # placeholder URL: use your provider's documented endpoint
headers={"Authorization": f"Bearer {api_key}"},
json={"prompt": "Say hello"},
timeout=30,
)
print(f"{var_name}: HTTP {response.status_code}")Run it with the new key held under a temporary variable name, so both keys can coexist in one shell:
export LLM_API_KEY_NEW="paste-the-new-key-here"
python check_key.py LLM_API_KEY_NEWA 200 means the key works. A 401 usually means the key was copied wrongly or has been revoked. A 403 can mean the key is valid but lacks a permission. A 429 means you hit a rate or spend limit, which is a separate problem from authentication.
Run the same check against the old key after you revoke it. You want to see a 401. That confirms the revocation took effect.
Updating the places where the key lives
Make an inventory before you start. Typical places:
| Location | How to update | Needs restart? |
|---|---|---|
| Local `.env` file | Edit the `LLM_API_KEY=` line | Yes, restart the app |
| Shell session | Run `export` again | Applies to new commands |
| CI secrets | Replace the repository or environment secret | Next workflow run picks it up |
| Deployment platform | Update the secret or environment setting | Yes, redeploy or restart |
| Teammates' machines | Each person updates their own `.env` | Yes |
| Secret manager | Write a new version | Depends on how the app reads it |
For GitHub Actions, the gh command line tool can replace a secret. Run it without a value and it prompts for one, so the key does not land in your shell history:
gh secret set LLM_API_KEYIf you keep separate keys for development, staging, and production, as the scoping chapter recommends, rotate them one at a time. Start with development, so a mistake in your procedure costs little.
Two keys at once in application code
For services that must never drop a request, some teams let the app accept a second key and fall back to it. This is optional. Most small projects do not need it, because a restart takes seconds. If you do use it, keep the code simple:
import os
keys = [
k for k in (os.environ.get("LLM_API_KEY"), os.environ.get("LLM_API_KEY_NEXT")) if k
]
if not keys:
raise RuntimeError("No LLM API key is set")
api_key = keys[0]This picks the first key that is set. During rotation you put the new key in LLM_API_KEY, leave the old one in LLM_API_KEY_NEXT only if you need a fallback, and remove it once the old key is revoked. Avoid code that retries with other keys after a 401 on its own. It hides problems and can send a leaked key to a provider long after you meant to retire it.
Revocation edge cases
- Running processes keep the old key in memory. Revoking the key makes those processes start failing. This is expected, and it is also how you find forgotten deployments.
- Provider propagation delay. Some providers take seconds or minutes to enforce a revocation. Run your check again after a short wait before you decide it failed.
- Organization keys versus personal keys. Deleting a team member's account on some platforms also disables their keys. On others it does not. Check how your provider behaves.
- Spend already incurred. Revoking stops new requests. It does not cancel charges from earlier requests, and the provider may bill for usage that arrives late.
- Keys with shared names. If two services share one key, revoking it breaks both. Separate keys per service avoid this.
Common errors
| Mistake | Result | Fix |
|---|---|---|
| Revoking before deploying the new key | Outage | Keep the old key valid until the new key is confirmed in use |
| Updating `.env` but not restarting | App still uses the old key | Restart, then verify |
| Updating CI but not the deployment platform | Tests pass, production fails | Use the inventory table |
| Pasting the new key into chat or a ticket to share it | A new leak | Share through the secret store |
| Never testing the old key after revocation | You don't know it is dead | Expect a 401 and confirm |
| Rotating only when a leak happens | No practiced procedure | Rotate on a schedule |
Building a rotation habit
Put rotation on a calendar. Keep a short runbook with the inventory table, the order of steps, and the verification command. The first rotation is slow. By the third, it takes ten minutes.
Exercise
Your production service has used one LLM API key for a year. You create a new key. List the order of steps to replace the old key without downtime, and say what you check before revoking.
Show answer
Create the new key and copy it when it is shown. Store it in every place the old key lives (secret store, CI secret, deployment settings, local .env). Restart or redeploy so processes read the new value. Send a test request with the new key and confirm HTTP 200. Check the provider console's usage and last-used time and wait until the old key shows no new activity. Then revoke the old key and confirm that a request with it returns 401.
Exercise
After you update the key in your deployment platform, the app still returns results, and the console shows the old key was used a minute ago. What is the most likely cause, and what should you do before revoking?
Show answer
A running process still holds the old key because environment variables are read at startup, or another service or environment still uses it. Restart or redeploy the app, then check the last-used time again. If the old key keeps being used, find the remaining consumer (another environment, a cron job, a teammate's machine) and update it before revoking.