Rotating an API key is a two-minute job in a dashboard and a two-day job in a fleet. The gap is almost never the key itself — it is everything that cached the old one: the process that read os.environ at boot, the container image that baked a value in at build time, and the worker that has been holding a streaming response open for the last few minutes.
This post covers three patterns that get you through a rotation without dropping traffic: a dual-key fallback, a hot reload for long-lived processes, and a canary that proves the new key works before you revoke the old one. All three assume the same precondition — your provider lets you hold two valid keys at once, which AiCredits does.
Why Key Rotation Breaks Things
Three failure modes account for most rotation incidents. Restart-based rotation drops in-flight requests. Rolling restarts across a fleet leave some instances on the old key and some on the new, so a revoke that looks safe in aggregate breaks a shrinking slice of traffic. And long-lived clients — anything that built an OpenAI client once at import — never re-read the environment at all.
There is also a quieter trap: people rotate on the wrong error. A 401 means the key was rejected; a 429 means slow down; a timeout means the network. Treating all three as rotation triggers produces storms where every instance flips keys at once for no reason.
Pattern 1: Dual-Key Overlap With Auth-Error Fallback
Keep two variables in the environment — a primary and a secondary — and build one client per variable. On an authentication error, switch to the other key and remember the winner so you do not pay for a failed probe on every subsequent request.
import os
import openai
from openai import OpenAI
BASE_URL = 'https://api.aicreditsapi.com/v1'
class RotatingClient:
"""Prefers one key, falls back to the other on a 401, remembers what worked."""
def __init__(self, key_vars, base_url=BASE_URL):
self.key_vars = key_vars
self.base_url = base_url
self.preferred = 0
self._clients = {}
def _client(self, env_var):
if env_var not in self._clients:
self._clients[env_var] = OpenAI(
api_key=os.environ[env_var], base_url=self.base_url
)
return self._clients[env_var]
def complete(self, messages, model='deepseek-v4-flash'):
last_error = None
for offset in range(len(self.key_vars)):
index = (self.preferred + offset) % len(self.key_vars)
env_var = self.key_vars[index]
try:
result = self._client(env_var).chat.completions.create(
model=model, messages=messages
)
self.preferred = index
return result
except openai.AuthenticationError as exc:
last_error = exc
print('[rotation] %s rejected, trying the next key' % env_var)
raise RuntimeError('no configured API key was accepted') from last_error
rotator = RotatingClient(('AICREDITS_API_KEY_PRIMARY', 'AICREDITS_API_KEY_SECONDARY'))
reply = rotator.complete([{'role': 'user', 'content': 'One-line summary: deploy v2 is live.'}])
print(reply.choices[0].message.content)
The rollout order matters more than the code. Ship the secondary key first — present in the environment but unused — then promote it by swapping the order in config, then revoke the old one. Every step is reversible except the last, which is exactly the property you want during an incident.
Pattern 2: Hot Reload for Long-Lived Processes
Here is the part that trips people up: on Linux and macOS you cannot change a running process's environment from outside. export NEW_KEY=... in your shell affects new processes only, and reassigning os.environ inside the program changes what your code sees but not what the operating system sees.
So a real hot reload reads the key from something mutable — a file mounted into the container, a secrets manager, or an agent that writes one — and swaps the client behind a lock. The retiring client stays alive until its in-flight requests finish, which is what keeps streaming responses from being truncated mid-answer.
import os
import signal
import threading
from contextlib import contextmanager
from openai import OpenAI
BASE_URL = 'https://api.aicreditsapi.com/v1'
class HotReloadPool:
def __init__(self, env_var='AICREDITS_API_KEY', key_file_var='AICREDITS_API_KEY_FILE'):
self.env_var = env_var
self.key_file_var = key_file_var
self._lock = threading.Lock()
self._client = None
self._generation = 0
self._inflight = {}
def _read_key(self):
path = os.environ.get(self.key_file_var)
if path:
with open(path) as fh:
return fh.read().strip()
return os.environ[self.env_var]
def _build(self):
return OpenAI(api_key=self._read_key(), base_url=BASE_URL)
@contextmanager
def acquire(self):
with self._lock:
if self._client is None:
self._client = self._build()
self._generation += 1
gen, client = self._generation, self._client
self._inflight[gen] = self._inflight.get(gen, 0) + 1
try:
yield client
finally:
with self._lock:
self._inflight[gen] -= 1
if self._inflight[gen] == 0:
self._inflight.pop(gen, None)
def reload(self):
with self._lock:
self._client = self._build()
self._generation += 1
pool = HotReloadPool()
reload_requested = threading.Event()
signal.signal(signal.SIGHUP, lambda *_: reload_requested.set())
def _watch_for_sighup():
while True:
reload_requested.wait()
reload_requested.clear()
pool.reload()
print('[rotation] client reloaded from the mounted secret')
threading.Thread(target=_watch_for_sighup, daemon=True).start()
with pool.acquire() as client:
response = client.chat.completions.create(
model='deepseek-v4-flash',
messages=[{'role': 'user', 'content': 'Reply with the single word: ready'}],
)
print(response.choices[0].message.content)
On Kubernetes the mounted secret file is refreshed by the kubelet asynchronously, so trigger reload() from a small mtime poller rather than assuming the write is instant. Under systemd or on a plain VM, have your deploy script update the file and send SIGHUP. Windows has no SIGHUP, so use a file watcher there.
Pattern 3: Canary Before You Revoke
A key that authenticates is not necessarily a key that works. Test the new key against the model your service actually calls before you point traffic at it — a key can pass an auth check and still lack access to the model you need. This script exits non-zero, which makes it usable as a CI gate or a pre-deploy step.
import os
import sys
from openai import OpenAI
BASE_URL = 'https://api.aicreditsapi.com/v1'
def canary(env_var, model='deepseek-v4-flash'):
key = os.environ.get(env_var)
if not key:
print('%s is not set' % env_var, file=sys.stderr)
return False
client = OpenAI(api_key=key, base_url=BASE_URL)
try:
response = client.chat.completions.create(
model=model,
messages=[{'role': 'user', 'content': 'Reply with the single word: ready'}],
max_tokens=8,
)
except Exception as exc:
print('%s failed: %s' % (env_var, type(exc).__name__), file=sys.stderr)
return False
print('%s ok: %r' % (env_var, response.choices[0].message.content))
return True
if __name__ == '__main__':
sys.exit(0 if canary('AICREDITS_API_KEY_NEW') else 1)
Which Pattern Fits
| Approach | Restart needed | In-flight requests | Fleet coordination | Best fit |
|---|---|---|---|---|
| Single env var, redeploy | Yes | Dropped unless you drain | Every instance at once | Side projects and scripts |
| Dual key with 401 fallback | No | Survive on the other key | None | Most HTTP services |
| SIGHUP or file hot reload | No | Drain on the retiring client | Per instance | Long-lived workers, VMs |
| Secrets manager versioned ref | No | Drain | Centralised | Multi-team and compliance |
A Rotation Checklist That Survives an Audit
Create the replacement key before touching the old one, and keep both valid through at least one full deploy and longer than your longest request.
Canary the new key against the model you really use, not just the cheapest one available.
Move one instance first, watch the 401 rate and error budget, then continue.
Log a fingerprint — a hash prefix — and never the key. You need to know which key served a request; you never need to read it back.
Revoke the old key last, and confirm its 401 count is zero before deleting the record.
Rotate on events, not only on a calendar: a contractor leaving, a laptop lost, a secret pasted into a ticket. A schedule your team quietly skips is worse than no schedule, because it creates false confidence.
The only rotation you can trust is one you have rehearsed. Run it in staging with an already-revoked key — you will find the restart you forgot about.
Pitfalls Worth Knowing
docker build --build-arg API_KEY=...is visible in image history. Inject secrets at runtime, never at build time.Streaming responses keep a client busy. Drop it without draining and your graceful shutdown becomes a truncated answer.
A revoked key with no fallback produces a burst of 401s that your monitoring may read as an outage. Alert on 401s grouped by key fingerprint.
If a key has ever been committed, rotate it. Deleting the commit does not delete the clones.
Doing This on AiCredits
AiCredits issues keys from the dashboard and lets you hold several at once, which is the whole prerequisite for the overlap patterns above. Billing is credit-based against your account rather than per-key, so revoking an old key does not disturb your balance, and the canary in Pattern 3 becomes a single command you can wire into CI.
Sign-up is international: card or PayPal, no Chinese phone number or bank account required. Current rates — including how off-peak usage and cache hits are handled — are listed at aicreditsapi.com/pricing. Check there rather than trusting a blog post, including this one.
FAQ
Yes, if two conditions hold: your provider lets you keep two valid keys at once, and your process can see the new key without a restart. The first is a dashboard setting; the second means reading from a mounted file or a secrets manager, because a running process cannot have its OS-level environment altered from outside.
No. On Linux and macOS the environment is fixed when the process starts. Reassigning os.environ inside the program affects only code that reads it again, and it does not change what the operating system sees. That is why hot reload patterns read from a file or secret store instead.
Yes. Per-service and per-environment keys mean a leak has a bounded blast radius, usage is attributable, and revoking one service's key does not take down another. It also simplifies the fallback pattern, since each process holds only the two keys it needs.
Run the canary against the model your service actually calls. Testing only deepseek-v4-flash proves the key is valid but not that it can reach deepseek-v4-pro, so match the canary to production. Once it passes, move a single instance over before the rest of the fleet.
On the pricing page at aicreditsapi.com/pricing, including how off-peak usage and cache hits are treated. Rates change, so check the source rather than a number copied into an article.