API Connections / Handling rate limits and errors

Handling rate limits and errors Advanced

Every API sometimes says no. Knowing what the error codes mean, and how to retry politely, keeps a bot working day after day.

What you'll learn

  • What common status codes mean
  • How to retry with backoff
  • Keeping a log

Before you start

1. Read the status code

2. Retry with backoff

  1. Only retry 429 and 5xx errors (and network timeouts).
  2. Wait before retrying, and wait longer each time (for example 1, 2, 4, 8 seconds). This is backoff.
  3. If the response has a Retry-After or rate-limit header, follow it.
  4. Give up after a few tries and report the failure.
Screenshot: A log showing a 429 response followed by a successful retry.

3. Refresh tokens automatically

If a 401 comes from an expired OAuth token, get a fresh one and try once more.

4. Log failures

Write down the time, request, status and message. A log makes problems easy to spot.

Ideas to try

  • Daily report bot.
    Review my script and add retries with backoff for 429 and 5xx errors.
  • Debugging.
    My calls fail with 403. Using the API docs, list the permissions I might be missing.
  • Monitoring.
    When the nightly sync fails three times, message me instead of retrying forever.
  • Learning.
    Explain the rate limit for this API using its official docs.

Tips

  • Never retry a 400-level error (except 429) unchanged; it will fail again.
  • Don't retry actions that charge money unless you're sure they didn't go through.
  • Keep secrets out of logs.

Facts about the Grok Bot app come from Cursor's official Grok Bot documentation. See MDN: HTTP status codes. Menus and services change; if something looks different, check the official docs or ask your bot.