Howwise RSS
Trading Software8 min read

API Rate Limit 429 Retry in Python: A Safe Client Design

Short answer

For an api rate limit 429 retry in Python, layer a token bucket that throttles before sending, a Retry-After-aware backoff with jitter, caching, and client order IDs so a retried order POST never creates a duplicate.

Key takeaways
  • A 429 means slow down; a 418 on Binance means an IP ban, so stop all requests until Retry-After has passed.
  • Throttle proactively with a token bucket set to about 80% of the published limit, and pause it globally when a 429 arrives.
  • Use full jitter backoff, delay = random(0, min(cap, base*2^attempt)), and sleep for the max of that and Retry-After.
  • Retry GETs freely, but for order POSTs generate the client order ID once, reuse it, and query by that ID before resubmitting.
  • Cut calls with TTL caches, on-disk bar storage, in-flight dedupe and WebSocket streams instead of polling.

What do 429, 418, 403 and 5xx actually mean?

A 429 Too Many Requests means you exceeded a quota and the server is refusing work for now. It is the only status that explicitly says slow down, and it is safe to retry after waiting.

Binance escalates. Breaching a limit returns 429. If you keep sending after that, the IP gets a 418, a temporary ban whose length grows with repeated violations, from about two minutes up to three days. When you see 418, stop sending entirely and wait out the Retry-After value. Probing during a ban extends it.

A 403 is often a WAF or CDN block (sometimes a rate-based one) or a permissions problem, so retrying rarely helps. 5xx errors are server-side faults and are retryable for reads, but for orders they are ambiguous, as covered below.

StatusMeaningRetry?Action
429Quota exceededYes, after waitingHonor Retry-After, pause shared limiter
418 (Binance)IP banned after repeated 429sNot until ban endsHalt all traffic, wait Retry-After, then reduce rate
400 / 401 / 422Bad request, bad auth, rejected orderNoFix the request; log it
403Forbidden or WAF blockNoCheck keys, IP allowlist, permissions
500 / 502 / 503 / 504Server or gateway faultReads yes; orders reconcile firstBackoff with jitter
Timeout / resetUnknown outcomeReads yes; orders reconcile firstQuery by client ID

How do I read the provider's rate-limit signals?

Retry-After is the one standard header. It is either an integer number of seconds or an HTTP-date, and a robust client parses both.

X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset are conventions, not a standard, and semantics differ. Reset may be an epoch timestamp at one provider and seconds remaining at another, so a value of 30 versus 1731500000 must be interpreted per provider. An IETF draft defines RateLimit headers, but adoption is uneven.

Binance reports consumption in X-MBX-USED-WEIGHT-1M (and X-MBX-ORDER-COUNT-* for orders). Limits are weight-based: each endpoint costs a different number of weight units, and the limits themselves are listed in the rateLimits field of exchangeInfo.

Limit typeExampleImplication
Requests per time windowAlpaca trading API, 200 requests/min per accountSimple count bucket
Weight-basedBinance REQUEST_WEIGHT per IP per minuteCost per call varies by endpoint and parameters
Order countBinance ORDERS per 10s and per daySeparate bucket for order endpoints
Per IP vs per keyIP for Binance market data, key or account for many brokersKey the limiter by the right identity
WebSocketConnection count and subscriptions per connection, message rateMultiplex streams, avoid reconnect storms
Tip: Prefer WebSocket streams over polling for prices, order updates and fills. One subscription replaces thousands of REST calls, but reconnect loops count against connection limits, so back off on reconnects too.

How do I build a token bucket rate limiter in Python?

A token bucket holds up to capacity tokens (the allowed burst) and refills at rate tokens per second. Each request spends tokens equal to its cost. If tokens are short, the caller waits for the exact deficit.

Compare alternatives. A fixed window counter resets at boundaries, so a client can send a full quota at the end of one window and again at the start of the next, doubling the burst. A leaky bucket smooths output to a constant rate but allows no burst. A token bucket permits controlled bursts and is the easiest to make weight-aware.

Set rate to about 80% of the published limit. Clocks, network jitter and other processes sharing the IP make exact-limit operation fragile. The version below is thread-safe and asyncio-safe, with a pause() method used by the retry layer.

import time, threading, asyncio

class TokenBucket:
    def __init__(self, rate, capacity):
        self.rate, self.capacity = rate, capacity   # tokens/sec, burst
        self.tokens = capacity
        self.ts = time.monotonic()
        self.blocked_until = 0.0
        self._lock = threading.Lock()

    def _reserve(self, cost=1):
        """Return seconds to wait before this request may be sent."""
        with self._lock:
            now = time.monotonic()
            self.tokens = min(self.capacity,
                              self.tokens + (now - self.ts) * self.rate)
            self.ts = now
            self.tokens -= cost          # may go negative = queued debt
            wait = max(0.0, -self.tokens / self.rate)
            return max(wait, self.blocked_until - now)

    def pause(self, seconds):            # call on 429/418 with Retry-After
        with self._lock:
            self.blocked_until = max(self.blocked_until,
                                     time.monotonic() + seconds)

    def acquire(self, cost=1):           # sync
        time.sleep(self._reserve(cost))

    async def aacquire(self, cost=1):    # asyncio
        await asyncio.sleep(self._reserve(cost))

# Binance-style: 6000 weight/min published -> use ~80%
bucket = TokenBucket(rate=6000 * 0.8 / 60, capacity=20)

How do I handle an API rate limit 429 retry in Python with Retry-After and jitter?

Without jitter, many clients that hit a limit at the same moment all retry at the same moment, and fail together again (a thundering herd). Full jitter spreads them out: delay = random(0, min(cap, base * 2^attempt)).

Then take the max of that delay and Retry-After, because the server's instruction is a floor. Also pause the shared bucket, otherwise other threads keep sending while one sleeps.

Retry 429, 502, 503, 504 and connection timeouts. Never blindly retry 400, 401, 403 or order rejections, since the answer will not change.

import random, time, email.utils, requests

RETRY_STATUS = {429, 502, 503, 504}

def parse_retry_after(v):
    if not v: return 0.0
    if v.isdigit(): return float(v)
    dt = email.utils.parsedate_to_datetime(v)       # HTTP-date form
    return max(0.0, dt.timestamp() - time.time())

def get(session, url, bucket, cost=1, max_attempts=6,
        base=0.5, cap=30, deadline=120, **kw):
    start = time.monotonic()
    for attempt in range(max_attempts):
        bucket.acquire(cost)
        try:
            r = session.get(url, timeout=(3.05, 10), **kw)
        except (requests.ConnectionError, requests.Timeout):
            r = None
        if r is not None and r.status_code == 418:
            bucket.pause(parse_retry_after(r.headers.get('Retry-After')))
            raise RuntimeError('IP banned, halting')
        if r is not None and r.status_code not in RETRY_STATUS:
            return r
        ra = parse_retry_after(r.headers.get('Retry-After')) if r else 0
        delay = max(ra, random.uniform(0, min(cap, base * 2 ** attempt)))
        if time.monotonic() - start + delay > deadline:
            break
        if r is not None and r.status_code == 429:
            bucket.pause(delay)        # global pause, not just this call
        time.sleep(delay)
    raise RuntimeError('retries exhausted')
Warning: Treat 418 as a hard stop, not a retryable status. The helper above checks for 418 before anything else and raises; also remove 418 from any generic library retry list, or the client will keep hammering a banned IP and lengthen the ban.

What do requests, httpx and ccxt already do for me?

With requests, mount an HTTPAdapter carrying urllib3 Retry. Its respect_retry_after_header defaults to True and applies to 413, 429 and 503. Its allowed_methods default excludes POST, which is correct for orders. Older urllib3 backoff has no jitter; newer 2.x releases add a backoff_jitter parameter, so confirm your installed version. It also cannot pause a shared limiter, so it complements a bucket rather than replacing it.

httpx supports only connection-level retries in its transport (retries=N), not status-based ones, so wrap calls with tenacity or the custom loop above. aiohttp has no built-in retry; use the same wrapper with await bucket.aacquire().

ccxt has enableRateLimit (on by default in current versions) and a rateLimit value in milliseconds between calls. Its throttler handles per-call cost for many exchanges, but it is per exchange instance, so two processes each get their own budget. Do not run several instances against one IP without a shared limit.

from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

retry = Retry(total=5, backoff_factor=0.5,
              status_forcelist=[429, 502, 503, 504],
              respect_retry_after_header=True,
              allowed_methods=frozenset(['GET', 'HEAD', 'DELETE']))
s = requests.Session()
s.mount('https://', HTTPAdapter(max_retries=retry))

How do I avoid duplicate orders when retrying an order request?

A timeout on an order POST does not mean it failed. The server may have accepted and filled it, and only the response was lost. Blind retry then creates a second order. Binance can even return a 503 saying execution status is unknown.

The fix is a client order ID generated once, before the first attempt, and reused on every retry: Binance newClientOrderId, Alpaca client_order_id, ccxt params clientOrderId (exchange-specific key mapping applies), IBKR orderRef (with permId assigned by IBKR). Where an Idempotency-Key header is supported, use it the same way.

On an ambiguous failure, query the order by client ID before resubmitting. A duplicate-ID rejection (Binance error -2010 'Duplicate order sent', Alpaca 422 on non-unique client_order_id) should be handled as 'look it up', not as a failure. Cancels are naturally idempotent: repeating one ends in the same state, though the second may return an 'unknown order' error to be treated as success.

  1. Generate client_id = uuid4().hex once, before any network call.
  2. Send the POST with that ID and a total deadline (for example 15 s).
  3. On 2xx, done. On a definite 4xx rejection, stop and surface it.
  4. On timeout, reset or 5xx, wait with jitter, then GET the order by client ID.
  5. If found, adopt its state. If not found (not-found response), resubmit with the same ID.
  6. If the deadline has passed, do not resubmit; alert so a stale order is never placed late.
import uuid, time, random

def place_order(api, bucket, payload, deadline=15):
    cid = uuid.uuid4().hex[:32]            # created ONCE
    payload = {**payload, 'newClientOrderId': cid}
    end = time.monotonic() + deadline
    attempt = 0
    while time.monotonic() < end:
        bucket.acquire(cost=1)
        try:
            r = api.post('/order', payload, timeout=5)
            if r.ok: return r.json()
            if r.status_code == 429:
                bucket.pause(parse_retry_after(r.headers.get('Retry-After')))
            elif r.status_code < 500 and not is_duplicate(r):
                raise OrderRejected(r.text)       # definite: do not retry
        except (requests.ConnectionError, requests.Timeout):
            pass
        time.sleep(random.uniform(0, min(5, 0.3 * 2 ** attempt)))
        attempt += 1
        found = api.lookup_by_client_id(cid)      # reconcile first
        if found: return found
    raise OrderUnknown(cid)       # human or reconciler decides
Warning: Never regenerate the client ID inside the retry loop. A new ID on each attempt turns every ambiguous timeout into a potential duplicate order.

How do I cut API calls and verify the client works?

Cache reference data such as symbols, exchange info and instrument lists with a TTL of hours. Store historical bars on disk (Parquet or SQLite) keyed by symbol and timeframe, and request only the missing range after the last stored timestamp. Dedupe identical in-flight requests so ten tasks asking for the same quote share one call. Use batch endpoints (multi-symbol snapshots) and conditional requests with ETag and If-None-Match, since a 304 often costs less quota or none.

Log remaining quota from headers (for example X-MBX-USED-WEIGHT-1M) and count 429s per endpoint. Add a circuit breaker: after N consecutive failures, open for a cooldown and fail fast instead of queueing more requests.

Across processes, an in-memory bucket is not shared. Use Redis with an atomic Lua script that implements the same refill math, or a single local proxy process that owns the limiter.

Test with a local mock server that returns 429 with Retry-After: 2 on the first calls, then 200. Assert that the elapsed time is at least 2 seconds, that all threads paused, and that an order timeout results in exactly one order on the mock.

Common questions

Why do I still get 429 when my script is under the published limit?

Limits are often shared: other scripts, a second ccxt instance or another machine on the same IP or key consume the same quota. Weighted endpoints can also cost far more than one unit, and fixed-window counters penalize bursts at window edges. Read the used-weight header and size your bucket from observed usage.

Should I retry a 418 or 403?

No. A 418 is an IP ban, so all traffic must stop until the Retry-After time, and retrying extends it. A 403 reflects a permission or firewall decision, which waiting will not usually change.

Is urllib3 Retry enough for a trading client?

It handles status-based retries with Retry-After for reads, but it does not throttle proactively, does not pause other threads, and does nothing about order idempotency. Use it as the transport layer beneath a token bucket and a reconcile-based order path.

How big should the token bucket burst capacity be?

Match the smallest window the provider enforces, for example per-second or per-10-second order limits, and keep it low, often a handful of requests. A large capacity lets a freshly started script send a burst that trips a short-window limit even when the per-minute average is fine.

Do WebSocket connections have rate limits too?

Yes. Providers cap connections per IP, subscriptions per connection and incoming message rate, and they can disconnect or ban clients that reconnect in a tight loop. Apply jittered backoff to reconnects and combine streams on one connection.

Related topics:rate limitingpythonbinance apiretryorder idempotency