Handling 429 Rate Limits: Retry-After and Back-off in Python
Every plan has a daily request limit that resets at UTC midnight. When a key hits it, the API answers 429 with a Retry-After header holding the seconds until the reset. Retrying immediately cannot help, because the counter does not reset until then.
A wrapper that respects the header
import httpx
API = "https://bharatstockapi.com"
HEADERS = {"X-API-Key": "bsk_live_..."} # your key from the dashboard
import time
def get(path, params=None, max_wait=60):
r = httpx.get(f"{API}{path}", headers=HEADERS, params=params, timeout=30)
if r.status_code == 429:
wait = int(r.headers.get("Retry-After", "0"))
if wait <= max_wait:
time.sleep(wait)
r = httpx.get(f"{API}{path}", headers=HEADERS, params=params, timeout=30)
else:
raise RuntimeError(f"Daily limit reached; resets in {wait}s")
r.raise_for_status()
return r.json()Spend fewer requests
- Use batch quotes instead of one call per ticker.
- Use
page_sizeat its maximum so history is a call or two, not dozens. - Cache end-of-day responses locally. They do not change until the next close.
- The official SDK already retries with back-off on a 429. It cannot wait out a daily limit, so a long
Retry-Afterstill surfaces as an error.
Plan limits are on the pricing page.