skip to content

After `wrangler secret put` replaced a Cloudflare Worker's payment provider key, some requests kept using the old key; what in the code explains it?

level: seniorimportance: should knowfreq 36%

answer

  1. a bindings-only deploy
  2. isolates may be reused
  3. a client cached in module scope
  4. build from env per request

basics

~20 s

A provider client built in global scope from the old secret. A deploy that changes only bindings may reuse running isolates, so a module-level object keeps the value it was built with, while each request's env carries the new one.

solid answer

~50 s

`wrangler secret put` creates and deploys a new version whose code is unchanged; only its bindings differ. Cloudflare may then keep using isolates that already run the code instead of reloading it, which is fast but means module scope is not evaluated again. If the Worker built its provider client once, either at top level from the imported `env` or lazily with `client ??= new ProviderClient(env.PROVIDER_API_KEY)`, that object still holds the old key on every reused isolate, while fresh isolates build it with the new key: hence only some requests fail. The `env` passed to each request carries the current value. The fix is to construct anything derived from a binding inside the handler, or to rebuild it whenever `env.PROVIDER_API_KEY` differs from the value it was built with. Before blaming the code, confirm that no gradual deployment is still sending part of the traffic to an older version.

code

javascript · 28 lines
javascript
class ProviderClient {
  constructor(apiKey) {
    this.headers = { Authorization: `Bearer ${apiKey}` };
  }
  refund(paymentId) {
    return fetch(`https://provider.example/v1/payments/${paymentId}/refund`, {
      method: "POST",
      headers: this.headers,
    });
  }
}

// Risky: one client per isolate can outlive a secret change.
// let cached;
// cached ??= new ProviderClient(env.PROVIDER_API_KEY);

export default {
  async fetch(request, env) {
    const client = new ProviderClient(env.PROVIDER_API_KEY);
    const paymentId = new URL(request.url).searchParams.get("payment");
    try {
      const res = await client.refund(paymentId);
      return new Response(null, { status: res.ok ? 202 : 502 });
    } catch {
      return new Response("provider unreachable", { status: 502 });
    }
  },
};

go deeper

for a junior

Recall that wrangler secret put deploys a new version, and that the env given to each request carries the current value.

for a middle

Explain that a bindings-only deploy may reuse running isolates, so module scope is not re-run and globals keep old derived values.

for a senior

Diagnose mixed old and new behaviour as cached clients, fix it per request or with a value-keyed cache, and rule out a gradual version split first.

for a principal

Set a codebase rule that nothing derived from a binding lives in module scope unchecked, and review for it as you review for per-user globals.

## The symptom A payments-webhook Worker calls its provider with an API key held in a per-Worker secret. The team replaces the key with `wrangler secret put PROVIDER_API_KEY`, the provider revokes the old one, and for a while a fraction of refund calls fail with an authentication error, while others succeed. Nothing in the Wrangler file changed and no code was deployed. ## Why the old key survives 1. **`wrangler secret put` deploys a new version at once.** The version has the same code and different bindings: one secret has a new value. 2. **Cloudflare may reuse running isolates for a bindings-only change.** Its documentation says that when only bindings change, existing isolates already running the Worker may be reused, so the code is not reloaded. 3. **Module scope runs once per isolate.** Top-level statements, and any variable assigned on the first request, keep their values for the life of the isolate. 4. **So a cached client keeps the old key.** Reused isolates serve requests with a client built from the old secret; newly started isolates build one with the new secret. The result is the mixed behaviour the team sees. The per-request `env` is not the problem: each request's `env` carries the current value. The stale copy is the one the code made *from* `env` and kept. ## Why the platform behaves this way Reusing isolates is a deliberate optimisation. Changing a var or a secret should not cost every location a fresh load of the Worker's code, so Cloudflare may keep existing isolates and hand them the new bindings on the next request. The trade-off is stated in the bindings documentation: anything you create in global scope from a binding might continue to exist despite changes to that binding. Because isolates are never guaranteed to live long, the stale behaviour can also fade on its own as old isolates are replaced, which makes the bug look intermittent and easy to dismiss until the next key change brings it back. ## Patterns that can go stale | Pattern | Can keep an old value after a bindings change? | |---|---| | `new ProviderClient(env.PROVIDER_API_KEY)` inside `fetch` | No | | Reading `env.PROVIDER_API_KEY` where it is used | No | | `client ??= new ProviderClient(env.PROVIDER_API_KEY)` with `client` in module scope | Yes | | Top-level `new ProviderClient(env.PROVIDER_API_KEY)` using the imported `env` | Yes | | A top-level object parsed from a var, such as a feature-flag map | Yes | The same reasoning covers vars: changing a var is also a bindings-only deploy. A quick test for any module-level variable is to ask what it was computed from. If the answer includes `env`, directly or through a helper, then its value is a snapshot of the bindings as they were when that isolate first computed it, and nothing in the platform refreshes the snapshot for you. Constants written in the source, compiled regular expressions and lookup tables built from code alone are safe to keep in module scope; copies of binding values are not. ## Fixes - **Construct per request.** Building a small client object inside the handler is cheap and always matches that request's `env`. Cloudflare's documentation recommends exactly this. - **Cache with a key check** when construction is expensive: store the value the client was built from beside it, and rebuild when `env.PROVIDER_API_KEY` differs. - **Pass values down explicitly**, or use `AsyncLocalStorage`, rather than parking derived objects in globals. - **Review module scope** for anything derived from a binding, the same way you review it for per-user data. ## Ruling out other causes - **A version split.** If the team shipped the key with `wrangler versions secret put` and a gradual `wrangler versions deploy`, part of the traffic is meant to reach the older version with the old key; check the current deployment's version percentages before touching code. - **The wrong Worker.** `wrangler secret put` targets the Worker named in the Wrangler file unless `--name` says otherwise; confirm the secret landed on the Worker that serves the failing requests. - **Old values elsewhere in module scope.** Search the code for every place a binding's value is copied into a variable outside the handler; the provider client is the usual one, but a signing helper or a parsed configuration object behaves the same way.

  • The client is expensive to build; how do you keep one per isolate without serving a replaced key?
    Cache it together with the value it was built from and compare on each request: if the cached key differs from `env.PROVIDER_API_KEY`, build a new client. The check is a string comparison, so the client is rebuilt only after the binding actually changes, and every request uses a client that matches its own `env`.
  • Would storing the key as a plaintext var instead of a secret avoid the problem?
    No. A var is a binding too, so changing it is also a bindings-only deploy that may reuse running isolates. It would also publish the credential in the Wrangler file. The cure is in how the code derives objects from `env`, not in the binding type.

  • Waiting for the secret to propagate instead of looking for a cached client.
  • Believing every deploy discards running isolates and re-runs module scope.
  • Caching a client built from env in a global with no check on the key.
  • Suspecting the env passed to the handler of holding the old value.
  • Moving the key into a plaintext var so that changes take effect.