Essay

My 429 retry passed every test and could not run

GitHub sign-in on Cloudflare Workers started failing with 429s at the token exchange. My first fix was careful, well tested, and could not have run on any 429 I went on to measure. The second moved one fetch to a different place on the network.

OpenPike is a bring-your-own-key LLM gateway that runs on Cloudflare Workers. On November 21 I added GitHub sign-in. Over the next few days, several sign-ins failed. Not many, and I don’t have an exact count, but a failed sign-in is the worst first impression a product can make.

This is the story of two fixes. The first was careful, well tested, and could not have run on any 429 I later measured. The second moved one fetch to a different place on the network.

The flow

I use a GitHub OAuth App with the web application flow, state, and PKCE (S256). No auth library, just three fetch calls:

  1. The browser goes to github.com/login/oauth/authorize and comes back to my callback with a code and state.
  2. The Worker POSTs the code, client secret and PKCE verifier to github.com/login/oauth/access_token. This is the call that failed.
  3. The Worker calls api.github.com/user and api.github.com/user/emails with the token, then drops it. Those calls are authenticated and were never refused.

Two constraints shape every decision after this.

The code is single use and short lived. GitHub’s docs say the temporary code expires after 10 minutes. After an ambiguous failure, like a 502 or a timeout, GitHub may already have spent it, so retrying is unsafe. A 429 should mean the request was refused before the code was used. That’s my reasoning, not something GitHub documents as a guarantee.

A person is waiting on a blank callback page. There’s room for a second or two. Not minutes.

Act 1: the error that lied

The original callback treated every failure the same way:

} catch (err) {
  console.error(`github oauth failed step=${err.step} status=${err.status}`); // simplified
  return failTo("unavailable"); // "Could not reach GitHub to finish signing in"
}

The error page told people OpenPike couldn’t reach GitHub. A live log tail said otherwise:

github oauth failed step=token status=429

OpenPike could reach GitHub fine. GitHub was answering, and the answer was 429.

GitHub documents a limit of 2,000 access token requests per hour for OAuth apps. Its per-user limit is different: signing the same user in ten times within an hour triggers a re-authorization prompt, not a 429. Neither obviously explained what I saw. My suspicion went to the network instead: a Worker’s fetch leaves from Cloudflare addresses that are shared with other customers’ Workers. If GitHub throttles one of those addresses, every Worker behind it gets throttled with it.

That was a suspicion, not evidence. I fixed the code first.

Act 2: the retry that could not run

The first fix was a bounded retry, only for 429, that respected Retry-After:

const TOKEN_RETRY_DELAYS_MS = [1_000, 2_000];
const MAX_RETRY_AFTER_MS = 5_000; // the person is on a blank callback page

function retryDelayMs(headers: Headers, fallbackMs: number): number | null {
  const raw = headers.get("retry-after");
  if (raw === null) return fallbackMs;
  if (!/^\d{1,12}$/.test(raw)) return null;
  const ms = Number(raw) * 1000;
  return ms <= MAX_RETRY_AFTER_MS ? ms : null;
}

async function exchangeCode(body: string): Promise<Response> {
  for (let attempt = 0; ; attempt += 1) {
    const res = await fetch(GITHUB_TOKEN_URL, { /* POST, 10s timeout */ });
    const fallback = TOKEN_RETRY_DELAYS_MS[attempt];
    if (res.status !== 429 || fallback === undefined) return res;
    const delay = retryDelayMs(res.headers, fallback);
    if (delay === null) return res;
    await res.body?.cancel();
    await new Promise((resolve) => setTimeout(resolve, delay));
  }
}

Every rule in it is sensible. Retry only on 429. At most twice. Respect Retry-After. Don’t make a person wait more than a few seconds. The tests covered all of it, including a short Retry-After and a long one, against a mocked GitHub. I merged it on November 24 at 11:29.

Then I measured. Every 429 my probe saw (Act 4) said Retry-After: 300. For a value of 300 seconds, retryDelayMs returns null, and the retry gives up immediately. It could not have run on a single one of them. My production log line from the failed sign-in had recorded only the status, not the headers, so I didn’t know that when I designed the retry.

The tests weren’t wrong. They proved the code handled a long Retry-After exactly as designed. They just couldn’t tell me which value GitHub actually sends, and I had picked my design before I’d seen the header.

Two parts of that change were worth keeping.

A separate error for 429. It now redirects with github_busy and tells the person GitHub is limiting requests, instead of claiming GitHub is unreachable.

Safe diagnostics. I started logging the rate limit headers, keeping only whole numbers so no unexpected header value could reach the logs:

const digits = (name: string): string => {
  const value = headers.get(name);
  return value && /^\d{1,12}$/.test(value) ? value : "none";
};

Act 3: an off switch

While the cause was still open, I added a staff switch that turns GitHub sign-in off without a deploy. It’s stored in the app’s database and read on each sign-in page load and each sign-in request, so it applies at once.

It’s enforced on the server, not just by hiding the button: the start and callback routes redirect without calling GitHub, so sign-ins already in progress stop too. The failure modes differ on purpose. If the settings table doesn’t exist yet (the app deployed before its migration), the switch counts as on. If the read fails for any other reason, it counts as off, so an off switch is never silently ignored.

Email sign-in links kept working the whole time, and nobody’s existing session was touched. Having a second way in is what made it safe to take time on the real cause.

Act 4: evidence

To find out whether my app had anything to do with it, I wrote a throwaway probe: a temporary Worker, protected by a random token and capped at 50 requests, that posted made-up credentials to GitHub’s token endpoint. I deleted it right after. A 404 means the request reached GitHub, which rejected the fake client. A 429 means it was refused.

It ran from two kinds of places. A plain Worker runs near the caller and its fetch leaves from there. A Durable Object is a single named instance that runs in one place; a location hint asks Cloudflare to create it in a given region.

Path Ran in 429s Tries
Direct fetch from the Worker Columbus 8 20
Durable Object, wnam hint Dallas 0 6
Durable Object, enam hint Chicago 0 6
Durable Object, weur and eeur hints London, Warsaw, Stockholm 0 12
Durable Object, apac hint Hong Kong, Tokyo 0 6

The direct runs, in order, 500 ms between tries:

run 1: 429 404 404 404
run 2: 429 429 429 404
run 3: 404 404 404 404
run 4: 429 429 429 429
run 5: 404 404 404 404

And the headers:

All 8 of the 429s All 42 of the 404s
Retry-After 300 absent
X-RateLimit-Remaining absent absent
X-GitHub-Request-Id absent present
Body JSON with "code":"429" and a docs link {"error":"Not Found"}

What I took from it:

  • My quota doesn’t explain it. The credentials were made up, so no OAuth app of mine was involved, and the same 429s came back. That answers “how close were you to the 2,000 per hour limit?” better than any count of my own sign-ins would.
  • It looks like a refusal in front of GitHub’s sign-in application. The 429s had no request ID, which every request that reached GitHub carried, and the same request passed or failed from one moment to the next. That fits blocking by shared source address. It is an inference.
  • My retry could not have helped. Every 429 asked for 300 seconds.
  • A quick direct retry helps only sometimes. Three of five runs were blocked on the first try. Two recovered, after one and three retries. One failed all four.

The caveats matter. This was 50 requests over a couple of minutes. Columbus was the only direct location I tested. The probe doesn’t separate “runs in a Durable Object” from “leaves from a different place”, and the routes that worked could be refused tomorrow.

I wasn’t the first to see this. Garrul, another app on Workers, hit the same thing in October: the same 429 with Retry-After: 300 on the token exchange, roughly a quarter of its own test requests blocked, and no difference from setting a User-Agent. Its fix retries a 429 up to five times, 300 ms apart, on the same reasoning that GitHub refuses the request before the code is spent. That’s a reasonable approach, and simpler than mine. One project’s report isn’t proof of the cause, but it was reassuring to see the same shape.

Here’s the probe, lightly trimmed. It’s test code, not production code:

import { DurableObject } from "cloudflare:workers";

async function attempts(n, gapMs) {
  const out = [];
  for (let i = 0; i < n; i++) {
    if (i) await new Promise((r) => setTimeout(r, gapMs));
    try {
      const res = await fetch("https://github.com/login/oauth/access_token", {
        method: "POST",
        headers: { accept: "application/json", "content-type": "application/x-www-form-urlencoded", "user-agent": "egress-test" },
        body: "client_id=dummy&client_secret=dummy&code=dummy",
        redirect: "manual",
        signal: AbortSignal.timeout(10000),
      });
      out.push({
        status: res.status,
        retryAfter: res.headers.get("retry-after"),
        remaining: res.headers.get("x-ratelimit-remaining"),
        requestId: res.headers.has("x-github-request-id"),
        body: (await res.text()).slice(0, 90),
      });
    } catch (err) {
      out.push({ error: err.name });
    }
  }
  return out;
}

export class Probe extends DurableObject {
  async run(n, gapMs) {
    return { colo: await colo(), attempts: await attempts(n, gapMs) }; // colo() reads /cdn-cgi/trace
  }
}

export default {
  async fetch(req, env) {
    const url = new URL(req.url);
    if (!env.TOKEN || req.headers.get("x-test-token") !== env.TOKEN) return new Response("Not found", { status: 404 });
    const n = Math.min(Number(url.searchParams.get("n") ?? 1), 4);
    const gap = Math.min(Number(url.searchParams.get("gap") ?? 300), 2000);
    const region = url.searchParams.get("region");
    if (!region) return Response.json({ colo: req.cf?.colo ?? null, attempts: await attempts(n, gap) });
    const id = env.PROBE.idFromName(`${region}-${url.searchParams.get("k") ?? "0"}`);
    return Response.json(await env.PROBE.get(id, { locationHint: region }).run(n, gap));
  },
};

Act 5: move the fetch

The fix moves only the token exchange into a Durable Object, with one second try from another region if the first is refused. Production code, lightly trimmed:

export const EXCHANGE_REGIONS = ["wnam", "enam"] as const satisfies readonly DurableObjectLocationHint[];

export class GitHubExchange extends DurableObject<AppEnv> {
  /** One POST to GitHub's token endpoint. Never retries, and never throws for a failed request. */
  async exchange(body: string): Promise<ExchangeResult> {
    try {
      const res = await fetch(GITHUB_TOKEN_URL, {
        method: "POST",
        headers: { accept: "application/json", "content-type": "application/x-www-form-urlencoded", "user-agent": "OpenPike" },
        body,
        redirect: "manual",
        signal: AbortSignal.timeout(10_000),
      });
      if (!res.ok) {
        await res.body?.cancel();
        return { status: res.status, accessToken: null, detail: res.status === 429 ? rateLimitDetail(res.headers) : null };
      }
      // GitHub answers a bad or expired code with 200 and an `error` field.
      const json = (await res.json().catch(() => null)) as Record<string, unknown> | null;
      return { status: res.status, accessToken: typeof json?.access_token === "string" ? json.access_token : null, detail: null };
    } catch (err) {
      return { status: 0, accessToken: null, detail: `error=${err instanceof Error ? err.name : "unknown"}` };
    }
  }
}

export async function exchangeCode(env: AppEnv, body: string): Promise<ExchangeResult> {
  let result: ExchangeResult = { status: 0, accessToken: null, detail: null };
  for (const region of EXCHANGE_REGIONS) {
    const id = env.GITHUB_EXCHANGE.idFromName(`token-${region}`);
    const stub = env.GITHUB_EXCHANGE.get(id, { locationHint: region });
    result = await stub.exchange(body);
    if (result.status !== 429) break;
    console.warn(`github oauth limited region=${region} ${result.detail ?? ""}`);
  }
  return result;
}
[[durable_objects.bindings]]
name = "GITHUB_EXCHANGE"
class_name = "GitHubExchange"

[[migrations]]
tag = "v1"
new_sqlite_classes = ["GitHubExchange"]

This is the older [[migrations]] format, which still works. A new Worker should declare its Durable Object classes with Cloudflare’s newer exports field instead.

A few details carry most of the weight.

The region is in the object’s name. Cloudflare’s docs say location hints are best effort, and only the first get() for a given object respects the hint; after that the object stays where it was created. In the probe, “western North America” turned out to be Dallas. Giving each region its own name means two separate objects, each created once in roughly the right place.

Only a 429 moves on to the second region, with the same code. A 502, a timeout, or a 200 with an error field is final, because the code may already be spent.

There’s no sleep. The second try leaves from somewhere else, and there is never a third. This does not wait out Retry-After, and I’m doing that on purpose: the refusal appears to be about the shared address, not my app’s quota. Capping it at one extra request per sign-in keeps it from turning into a retry storm.

Nothing is stored. The client secret, code, verifier and token live in memory for one call. The object makes no storage calls, and a test checks that.

Errors come back as data. Only an error’s name is kept, because error messages can contain request details.

Only the exchange moved. The two api.github.com calls still run in the Worker. They were never refused, and moving them would add a hop for nothing.

The cost is one Durable Object request per GitHub sign-in, two after a 429.

I considered three other options. Quick direct retries, Garrul’s approach, are simpler, but in my probe one run of five failed four times in a row. Dedicated egress addresses would remove the shared-address problem entirely, but on Cloudflare they’re an Enterprise feature. A third-party sign-in service would move the problem rather than understand it.

The fix merged on November 24 at 14:06.

Testing what you can’t run locally

Location hints have no effect in local tests, so the tests check intent instead: which objects were used, in what order, and that the same request body went to both.

it("tries the second region with the same code and signs in", async () => {
  const log = vi.spyOn(console, "warn").mockImplementation(() => {});
  const bodies = mockLimited([limited({ "retry-after": "300" })]); // the value the probe measured
  const { used, vars } = recordingRegions();
  const res = await callback(await start(vars), vars);
  expect(errorOf(res)).toBeNull();
  expect(bodies).toHaveLength(2);
  expect(new Set(bodies).size).toBe(1); // same code both times
  expect(used).toEqual(["token-wnam", "wnam", "token-enam", "enam"]);
  expect(log.mock.calls).toEqual([
    ["github oauth limited region=wnam retry_after=300 limit=none remaining=none reset=none request_id=no"],
  ]);
});

That log line is a test fixture, not something I captured in production. The other cases: it gives up with github_busy after both regions; it tries only once on a 502; it tries only once when there’s no answer at all, and never logs the error’s message (that test throws an error containing the client secret); secrets placed in response headers never reach the logs; and the object’s storage stays empty.

Where it stands

GitHub sign-in has worked in production since the fix deployed on November 24. Right after the deploy, five sign-ins in a row succeeded. My log watch caught two of those callbacks completing, with no 429s, no second-region tries and no errors. The other three aren’t in the logs, so I can’t say whether any of them needed the second region.

That’s “it has worked since”, not “it’s solved”. The trade-offs are real:

  • Cloudflare doesn’t let you roll a Worker back past a Durable Object migration. Undoing this means a new deploy that keeps the class and its migration, not a one-click rollback.
  • A fixed object adds a network hop for people far from North America. I haven’t measured it.
  • The new path still leaves from shared addresses. The 429s could come back.
  • The whole fix rests on an inference. The logging is there so I can be proved wrong.

What I’d tell myself a week ago

  1. Give 429 its own error path. “Could not reach GitHub” was simply wrong, and it sent me looking in the wrong place.
  2. Log Retry-After and whether a request ID was present before you design a retry. I designed for a header I had never seen.
  3. Tests against a mock show your code handles a case, not that the case happens.
  4. On serverless platforms, the source address is an input you don’t control, and it can be shared.
  5. For one-time credentials, decide per status whether a retry is safe. A 429 and a 502 look alike to a retry loop, and they aren’t.
  6. Ship an off switch, and keep a second way to sign in. They’re what let me take a day to understand the problem instead of rushing a guess.

All writing