# How to honor Retry-After without stalling a worker pool

> Turn one 429 into one pause for the whole pool: parse Retry-After in both forms, cap it, hold every worker until it passes, then release the workers one at a time.

Source: https://voxgig.com/howto/honour-retry-after-without-stalling-a-worker-pool

- Audience: api-consumer
- Level: intermediate
- Languages: typescript
- Verified: 2026-11-29
- Published: 2026-11-29

## Short answer

Give the pool one pause gate, an object that holds the earliest time any worker may send. On a 429, parse `Retry-After` as delay-seconds or an HTTP-date, cap it, and move that time forward. Every worker awaits the gate before each request, and the workers it held come back one slot apart. A 429 with no header gets a default wait, and an over-long one raises an alert instead of a silent stall.

---
## You will need

Node 22 or later, and workers in one process that share a quota. Verified 2026-11-29 against
Node 22.23.5. The gate has no dependency. The comparison installs bottleneck, p-queue and
`groq-sdk`, and it runs on Node's
[mock timers](https://nodejs.org/docs/latest-v22.x/api/test.html#class-mocktimers), so a
two-second pause costs no real time. Node 22 prints an experimental warning for that API,
which is why the commands below pass `--no-warnings`.

## Approaches compared

| Approach | When it fits | What it costs you | When to pick something else |
| --- | --- | --- | --- |
| [bottleneck failed event returning a retry delay](https://github.com/SGrondin/bottleneck#retries) | Jobs already go through bottleneck and a per-job wait is acceptable | Only the refused job waits, so nine other jobs reached the API during the pause | One refusal must stop every caller that shares the key |
| [Hand-rolled pool-wide pause gate](https://www.rfc-editor.org/rfc/rfc9110.html#section-10.2.3) | Workers you control, in one process, sharing one quota | About a hundred lines to own, with an HTTP-date parser, a cap and a default | Workers in several processes, which need the pause in a shared store |
| [p-queue pause and start](https://github.com/sindresorhus/p-queue#pause) | Work already runs through one p-queue with a concurrency limit | `start()` released ten requests in one millisecond after the pause | The restart must be spread out without a permanent interval cap |
| [Speakeasy and Stainless generated SDKs](https://www.speakeasy.com/docs/sdks/customize/runtime/retries#respecting-retry-after) | Calls go one at a time through a Speakeasy SDK, or an existing Stainless-generated one | Retry-After is honored per call, so in the `groq-sdk` run nine other calls kept sending | Several concurrent calls share one quota and need one pause |

A per-job retry in bottleneck or a generated SDK costs no code, but the run below shows nine
more requests landing during the pause. p-queue's `pause()` stops the pool for two lines of
code, and it restarts all ten slots at once. The hand-rolled gate avoids both, at the price of
a parser, a cap and an alert that you write and test yourself.

## Hold one earliest-send time for the pool

The gate holds two numbers: `#until`, the earliest time any request may go out, and
`#nextSlot`, the next release time for a worker that the pause held.

```js title="pause-gate.mjs"
  // Await this before every request.
  async ready() {
    while (this.#clock.now() < this.#until) {
      // Held by a pause: take the next release slot after it ends, then check
      // again, because another refusal may have moved the end during the sleep.
      const slot = Math.max(this.#nextSlot, this.#until)
      this.#nextSlot = slot + this.#spacingMs
      await this.#clock.sleep(slot - this.#clock.now())
    }
  }

  // Call this with every 429, and with a 503 that carries Retry-After.
  // Returns the pause it applied, so the caller can log it.
  pause(response) {
    const now = this.#clock.now()
    const header = response.headers.get('retry-after')
    const { form, ms } = parseRetryAfter(header, now)
    let wait = ms ?? this.#defaultMs
    if (wait > this.#maxMs) {
      this.#onCapped({ header, form, requestedMs: wait, appliedMs: this.#maxMs })
      wait = this.#maxMs
    }
    const until = now + wait
    if (until > this.#until) {
      this.#until = until
      this.#nextSlot = until
    }
    return { form, waitMs: wait, until: this.#until }
  }
```

Three choices in that code decide the behavior. A later refusal can extend a pause but never
shorten it, so a stray `Retry-After: 0` cannot reopen the gate early. A worker that waited
takes a slot, so ten held workers come back at `until`, `until + 100` and onward, one per slot.
The cap fires a callback before it clamps, which turns an hour-long header into a log line
somebody reads.

The defaults are a 100 ms spacing, a one-second wait when the header is missing, and a
60-second cap. Set the cap from what your job can tolerate, not from what the API might send.

## Parse both forms of the header

[RFC 9110](https://www.rfc-editor.org/rfc/rfc9110.html#section-10.2.3) defines `Retry-After`
as either delay-seconds, a non-negative integer, or an HTTP-date. Its date section requires a
recipient to accept
[all three HTTP-date formats](https://www.rfc-editor.org/rfc/rfc9110.html#section-5.6.7),
including two obsolete ones.[^1]

```js title="retry-after.mjs"
// Returns the wait in milliseconds and which form the header took:
// 'seconds', 'date', 'missing' or 'invalid'. A date in the past is a wait of zero.
export function parseRetryAfter(value, nowMs) {
  if (value === null || value === undefined) return { form: 'missing', ms: null }
  const text = String(value).trim()
  if (/^\d+$/.test(text)) return { form: 'seconds', ms: Number(text) * 1000 }
  const at = parseHttpDate(text, nowMs)
  if (at === null) return { form: 'invalid', ms: null }
  return { form: 'date', ms: Math.max(0, at - nowMs) }
}
```

`parseHttpDate` matches each format with its own pattern and refuses a date such as 31 February
rather than letting `Date` roll it into March. `1.5` and an ISO 8601 timestamp come back as
`invalid`, so they take the default wait instead of a guess.

## Make every worker wait at the gate

Each worker awaits `ready()` before it sends, and hands any 429 to `pause()` before it retries
the same job. The worker that received the refusal waits at the gate like the others.

```js title="pool.mjs"
  async function worker(id) {
    for (let job = queue.shift(); job !== undefined; job = queue.shift()) {
      for (;;) {
        if (policy === 'gate') await gate.ready()
        const res = await send(job, id)
        if (!RETRYABLE.has(res.status) || (res.status === 503 && !res.headers.has('retry-after'))) {
          results.push({ job, status: res.status })
          break
        }
        if (policy === 'gate') {
          gate.pause(res)
        } else {
          const { ms } = parseRetryAfter(res.headers.get('retry-after'), clock.now())
          await clock.sleep(ms ?? defaultMs)
        }
      }
    }
  }
```

The `sleep` branch is the per-request policy, kept for the comparison.

## Run seven clients against one stand-in

The stand-in API logs every arrival, refuses arrival 25 with `Retry-After: 2`, and refuses
anything else that arrives during those two seconds, as a rate-limited service would. A 200
takes 40 to 69 ms, so the workers drift apart before the refusal.

```bash
node --no-warnings compare.mjs
```

```text output
10 workers, 80 requests; arrival 25 is refused with Retry-After: 2

                                       sent during        first 100 ms after it
client                                 the pause    429s  requests  same ms
per-request sleep                              9      10        19        2
pause gate, 100 ms spacing                     0       1         3        1
bottleneck, failed returns the wait            9      10        18        1
bottleneck, failed sets reservoir 0            1       2        20        1
p-queue, pause inside the task                 0       1        23       10
p-queue, pause after add() resolves            1       2        24       10
groq-sdk 1.6.0, its own retries                9      10        19        2
```

The gate is the only client that kept the pause to a single refusal and also came back
gradually. Its three requests in the first 100 ms all come from the first released worker.

bottleneck's `failed` handler retries one job after the returned delay, and its README says
that job
[keeps its concurrency slot while it waits](https://github.com/SGrondin/bottleneck#retries).
The other nine slots kept working. Setting `reservoir` to zero in the same handler stopped the
pool, but one job got through. That job was still queued when the handler ran, but its slot
check had already started. The check and `updateSettings()` each
[wait one timer turn](https://github.com/SGrondin/bottleneck/blob/v2.19.5/lib/LocalDatastore.js#L90-L101)
before they act, so the check ran before the reservoir changed.

p-queue's `pause()` stops starting tasks and lets running ones finish. Called inside the task, before
it returns, it held the pool completely. Called after `add()` resolved, one more task had
already started. Either way, `start()` launched ten tasks in the same millisecond.

`groq-sdk` is a published SDK [generated with Stainless](https://github.com/groq/groq-typescript),
and it reads `Retry-After` inside each call's own retry loop. The other nine calls never paused.
Stainless [stopped taking signups and creating SDKs](https://www.stainless.com/blog/stainless-is-joining-anthropic/)
in May 2026, so this pattern reaches you only through SDKs it has already generated.
Speakeasy documents the same per-call shape: a generated SDK
[respects the header](https://www.speakeasy.com/docs/sdks/customize/runtime/retries#respecting-retry-after)
while the time it names is still ahead and below the configured maximum elapsed retry time.

## Check it worked

The tests assert on what the stand-in received, not on what the workers believed.

```js title="gate.test.mjs"
test('one 429 pauses the whole pool: nothing is sent until Retry-After has passed', async () => {
  const { api, summary } = await virtualRun('gate')
  assert.equal(summary.refused, 1, 'the API refused exactly one request')
  assert.equal(summary.during, 0, 'no request arrived during the pause')
  assert.equal(api.arrivals.length, JOBS.length + 1, 'every job was served, the refused one twice')
})

test('the pool resumes one worker at a time, 100 ms apart, not in one millisecond', async () => {
  const { api } = await virtualRun('gate')
  const { end } = api.window()
  const firstPerWorker = new Map()
  for (const a of api.arrivals) if (a.t >= end && !firstPerWorker.has(a.worker)) firstPerWorker.set(a.worker, a.t)
  const starts = [...firstPerWorker.values()]
  assert.equal(starts.length, 10)
  assert.deepEqual(starts.map((t) => t - end), [0, 100, 200, 300, 400, 500, 600, 700, 800, 900])
})
```

The suite also parses every header form and runs the per-request policy as a control. One test
repeats the pool over real HTTP on 127.0.0.1 with the real clock, allowing 200 ms for requests
already on the wire.

```bash
node --test --no-warnings gate.test.mjs
```

```text output
1..8
# tests 8
# suites 0
# pass 8
# fail 0
# cancelled 0
# skipped 0
# todo 0
```

`# pass 8` covers the single refusal, the ten staggered restarts, the capped hour, the default
wait for a missing header, and `groq-sdk` behind the gate with its own retries off.

## When it goes wrong

The pool stalls for an hour. A service sent `Retry-After: 3600`, by mistake or by policy, and a
client obeyed it in full. Here the limit actually lifts after two seconds:

```bash
node --no-warnings pitfall.mjs
```

```text output
Retry-After: 3600 on the first response; the limit lifts after 2 s

pause gate, 60 s cap
  alert: Retry-After 3600 asks for 3600 s, capped at 60 s
  second request sent at 60 s, status 200
groq-sdk 1.6.0, maxRetries 2
  second request sent at 3600 s, status 200
```

`groq-sdk` 1.6.0 places
[no upper bound](https://github.com/groq/groq-typescript/blob/v1.6.0/src/client.ts#L612-L618)
on the header, so its `models.list()` call took an hour
of virtual time to resolve. The gate paused for its cap, raised an alert, and found the limit
lifted on its second request.[^2]

A 429 arrives with no `Retry-After` at all. RFC 6585 says a 429
[MAY include the header](https://www.rfc-editor.org/rfc/rfc6585.html#section-4), not that it
must. Treating absence as zero sends the pool straight back into the refusal. The gate takes
`defaultMs`, a second by default, and a test asserts it.

A few requests still land in the pause. They left before the 429 reached the client, so no gate
can recall them. The real HTTP test allows them 200 ms and fails on any request that arrives
after that.

## When not to do this

Do not use an in-process gate when the workers are separate processes or machines. Each process
would hold its own `#until`, and the other processes would keep sending. Put the earliest-send
time in a store they share, and give it the same cap and default.

Do not add a gate around a generated SDK and leave the SDK's own retries on. The SDK sleeps
inside the call and then sends, so the gate never sees the attempt. Set `maxRetries: 0`, pass the
error's headers to `pause()`, as one test does, or accept per-call waits.

Do not build this for a single sequential caller. One worker that sleeps on its own 429 is
already the whole pool, and a per-request sleep with a cap does the same job.

Do not treat the cap as a fix. A capped wait still sends a request the service asked you not to
send, so route the alert to someone who can read the provider's limits.

## Related how-tos

- [Read RateLimit headers and slow down before you get a 429](/howto/read-ratelimit-headers-and-pace-before-429)

- [Share one rate limiter across many workers with Redis](/howto/share-a-rate-limiter-across-workers-with-redis)

- [Choose between 429 and 503 when you throttle a request](/howto/choose-429-or-503-when-throttling)

- [Decide which status codes an SDK should retry](/howto/decide-which-status-codes-an-sdk-retries)

- [Retry a failed API call inside a tool, not in the model](/howto/retry-inside-a-tool-not-in-the-model)

## Last verified

Verified 2026-11-29 against Node 22.23.5, bottleneck 2.19.5, p-queue 10.0.0 and `groq-sdk`
1.6.0. Every output block is what the command preceding it printed, against a stand-in API in
the same process, and `groq-sdk` was given a `fetch` that calls it. Speakeasy was not run,
because it needs an account. Its row is read from its retries documentation. Stainless was not
run either, so its behavior comes from `groq-sdk`, one SDK it generated.

[^1]: The two obsolete formats are the RFC 850 date, with a two-digit year, and the output of
ANSI C's `asctime()`. [Section 5.6.7](https://www.rfc-editor.org/rfc/rfc9110.html#section-5.6.7)
settles the century for the RFC 850 date. A two-digit year that seems to lie more than 50 years ahead
is read as the most recent past year with the same last two digits. The section explains
the trio by noting that servers used three formats before 1995, and it requires senders to emit
only `IMF-fixdate`.

[^2]: An hour is not an unusual figure. The example response in
[RFC 6585](https://www.rfc-editor.org/rfc/rfc6585.html#section-4), the document that defined
429, carries `Retry-After: 3600` and a body explaining that the site allows 50 requests per
hour per logged-in user. The body then ends with a three-word invitation to try again.