How-to › Make calls that survive failure

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.

Audience
API consumer
Level
intermediate
Topic
Set and respect rate limits
Languages
TypeScript
Verified

One of your ten workers gets a 429 with Retry-After: 2 and sleeps for two seconds. The other nine never hear about it, so they keep sending into the refusal, collect a 429 each, and sleep on nine separate timers. The API asked the client for two seconds of quiet and received nine more requests instead.

What you get

You will end up with a gate that turns one 429 into one pause for the whole pool and restarts the workers 100 ms apart. This is for you if several workers share one API key and its quota.

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, 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

ApproachWhen it fitsWhat it costs youWhen to pick something else
bottleneck failed event returning a retry delayJobs already go through bottleneck and a per-job wait is acceptableOnly the refused job waits, so nine other jobs reached the API during the pauseOne refusal must stop every caller that shares the key
Hand-rolled pool-wide pause gateWorkers you control, in one process, sharing one quotaAbout a hundred lines to own, with an HTTP-date parser, a cap and a defaultWorkers in several processes, which need the pause in a shared store
p-queue pause and startWork already runs through one p-queue with a concurrency limitstart() released ten requests in one millisecond after the pauseThe restart must be spread out without a permanent interval cap
Speakeasy and Stainless generated SDKsCalls go one at a time through a Speakeasy SDK, or an existing Stainless-generated oneRetry-After is honored per call, so in the groq-sdk run nine other calls kept sendingSeveral 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.

  // 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 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, including two obsolete ones.1

// 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.

  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.

node --no-warnings compare.mjs
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. 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 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, 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 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 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.

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.

node --test --no-warnings gate.test.mjs
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:

node --no-warnings pitfall.mjs
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 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, 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.

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.

Footnotes

  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 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. ↩︎ Back to text

  2. An hour is not an unusual figure. The example response in RFC 6585, 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. ↩︎ Back to text

Read this page as markdown · All how-to guides

Generate the client instead of writing it#

Retries, timeouts, pagination and auth are the same problems in every client. Voxgig generates them from your OpenAPI description, in 23 languages, from one model.

Listen to Fireside, the Voxgig podcast

Since 2018, Richard Rodger has talked with developer advocates, event organizers, and the people who build developer-facing companies about the specifics of the work.