Learning center

How should a GitHub API client wait out a rate limit?

Wait until the time GitHub names, because a generic retry policy gives up minutes into a limit that can last up to an hour. For a primary limit that time is the x-ratelimit-reset header. For a secondary limit it is retry-after when present, and otherwise at least a minute, growing on each repeat. A client that treats either as an ordinary transient error spends its attempts in seconds, and a client that treats the 403 as a permission error does not retry at all.

Two limits, one status code#

GitHub enforces two kinds of REST rate limit, and its rate limit documentation describes how each one answers:

  • Primary limit. A budget of requests per hour, for example at least 5,000 for a GitHub App installation. When it runs out, GitHub returns 403 or 429 with x-ratelimit-remaining: 0, and "you should not retry your request until after the time specified by the x-ratelimit-reset header", given in UTC epoch seconds. That reset can be up to an hour away.
  • Secondary limit. Limits on concurrency, requests per minute to one endpoint, and content creation, some of them undisclosed. GitHub returns 403 or 429 with a message saying a secondary rate limit was exceeded. If retry-after is present, wait that many seconds. If x-ratelimit-remaining is 0, wait for the reset. "Otherwise, wait for at least one minute before retrying", and if it keeps failing, wait "an exponentially increasing amount of time between retries".

The best practices page adds the consequence of ignoring both: "Continuing to make requests while you are rate limited may result in the banning of your integration."

The hard part is the 403. The same status means "this token may not do that", which no retry will fix. A client must tell the two apart from the headers and the message before it decides anything.

The mismatch with a generic retry policy#

A typical retry policy for transient errors starts at one second and doubles: 1, 2, 4 and so on to 128 seconds across eight retries after the first request. That adds up to 255 seconds, a little over four minutes. It suits a dropped connection or a brief 503. Against a primary limit whose reset is 30 minutes away, all eight retries hit the same limit, each one counts as another request while limited, and the job fails for good about four minutes in, with 26 minutes of the limit left.

Many HTTP clients also put 403 on their list of permanent errors. Under that rule the first secondary-limit response ends the operation outright, even though waiting a minute would have let it through.

The lab#

The lab applies GitHub's rules, in the documented order, to four responses, and compares them with the generic policy. It needs Docker and runs in seconds.

import random

NOW = 1_796_200_000  # a fixed clock, in epoch seconds


def rate_limit_wait(status, headers, body, attempt, now=NOW):
    """Seconds to wait before retrying, or None if this is not a rate limit.
    Follows GitHub's 'Exceeding the rate limit' rules in order."""
    if status not in (403, 429):
        return None
    h = {k.lower(): v for k, v in headers.items()}
    if "retry-after" in h:
        return int(h["retry-after"])
    if h.get("x-ratelimit-remaining") == "0":
        return max(0, int(h["x-ratelimit-reset"]) - now)
    if status == 429 or "secondary rate limit" in body.lower():
        base = 60 * 2 ** attempt                 # 60 s, then exponential
        return base + random.uniform(0, base / 4)
    return None                                  # a 403 for permissions


def generic_backoff(retries=8, first=1.0):
    """A typical transient-error policy: 1 s doubling, eight retries."""
    return [first * 2 ** i for i in range(retries)]


cases = [
    ("primary limit", 403,
     {"x-ratelimit-remaining": "0", "x-ratelimit-reset": str(NOW + 1800)},
     "API rate limit exceeded for installation."),
    ("secondary, retry-after", 403, {"retry-after": "60"},
     "You have exceeded a secondary rate limit."),
    ("secondary, no headers", 403, {},
     "You have exceeded a secondary rate limit."),
    ("permission denied", 403, {"x-ratelimit-remaining": "4211"},
     "Resource not accessible by integration"),
]
random.seed(7)
for name, status, headers, body in cases:
    w = rate_limit_wait(status, headers, body, attempt=0)
    print(f"{name:24} -> {'not a rate limit' if w is None else f'wait {w:.0f} s'}")

delays = generic_backoff()
print(f"generic policy: {len(delays)} retries, {sum(delays):.0f} s in total")

Save it as wait.py in an empty directory and run it:

docker run --rm --name pl-c-ratelimit -v "$PWD":/lab:ro -w /lab python:3 python -I wait.py
primary limit            -> wait 1800 s
secondary, retry-after   -> wait 60 s
secondary, no headers    -> wait 65 s
permission denied        -> not a rate limit
generic policy: 8 retries, 255 s in total

The primary limit needs a 30-minute wait, seven times longer than the generic policy's whole budget. The secondary limit without headers still gets a minute, plus jitter. The permission error is left for the caller to fail on, because waiting will not change it.

The message match is a heuristic. GitHub documents the condition, not an exact string, so check the wording your client receives and keep the 429 path, which needs no match.

Wait without holding a worker#

A 30-minute sleep inside a request handler or a worker thread holds a connection, a slot and often a lock for nothing, and a deploy in the meantime loses the wait. Record the wait instead. A job runner can store "not due before" with the reset time and a reason such as GITHUB_RATE_LIMIT, release the worker, and pick the job up after the reset. The reason makes the stall visible in dashboards as a rate limit and not a hang.

A retried write must converge when it runs again, since the first attempt may have succeeded partly before the limit hit. Find the branch, pull request or comment you created last time before creating another one. The guide to a third-party 429 or 503 covers telling your quota from the provider's outage. GitHub also asks integrations to make requests serially and to wait at least one second between POST, PATCH, PUT and DELETE requests, which keeps many secondary limits from firing at all.

What happened in production#

In the production case behind this guide, the code that opens fix pull requests, replies on review threads and updates a pull request's body converted GitHub errors through local copies of one helper. Those copies dropped the wait GitHub named and the marker that identified a rate limit. A rate limit therefore became an ordinary transient error: eight attempts in about four minutes, then permanent failure, against a limit that lasts up to an hour. The body update was worse. It checked for a plain success status, so the first secondary-limit 403 failed the run with no retry.

After the fix, every one of those paths uses the shared conversion. A rate limit makes the run wait with the reason recorded and GitHub's reset as its earliest next attempt. The test covers both cases: a primary-limit 403 naming a reset 30 minutes away leaves the run waiting and not due before that time, and a secondary-limit 403 with no rate-limit headers now waits instead of failing.

Where this came from#

Proofline found this in its own fix pull request and reply writes and shipped the fix in its production release of 19 November 2026. The eight attempts in about four minutes in What happened in production were that client's retry budget before the change. Proofline reviews GitHub pull requests; new organizations get one calendar month of hosted code review without a cloud connection. Start a free GitHub review ยท Eligibility and fair-use terms

Questions#

Does GitHub return 403 or 429 for a rate limit?

Either. The documentation says both primary and secondary limits answer with 403 or 429, so a client must check the headers and message on a 403 before it treats the response as a permission error.

Can I check whether I am close to a secondary limit?

No. GitHub states there is no way to check its status. Pace writes, avoid concurrent requests per token, and handle the response when it comes.

Should a client call GET /rate_limit before each request?

No. It does not count against the primary limit but can count against the secondary one. Read the x-ratelimit-* headers on the responses you already get.

One month of free code review.

New organizations get one calendar month of hosted code review for private and public GitHub repositories. No card or cloud connection required. Eligibility and fair-use terms.

Start free with GitHub

Related reading