Best Practices

How to Handle API Rate Limits Like a Pro

Learn strategies for handling rate limits gracefully: exponential backoff, request queuing, and caching.

Rate limits protect APIs from abuse, but they can be frustrating for developers. Here's how to handle them gracefully.

1. Exponential Backoff

When you hit a 429 error, wait and retry with increasing delays:

async function fetchWithRetry(url, options, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    const res = await fetch(url, options)
    if (res.status !== 429) return res
    const wait = Math.pow(2, i) * 1000
    await new Promise(r => setTimeout(r, wait))
  }
  throw new Error('Rate limited after max retries')
}

2. Check Rate Limit Headers

Most APIs return rate limit info in response headers:

curl -v https://freeapitools.dev/api/v1/weather?city=Tokyo 2>&1 | grep -i rate
# X-RateLimit-Limit: 100
# X-RateLimit-Remaining: 95
# X-RateLimit-Reset: 1706745600

3. Request Queuing

For high-volume applications, implement a request queue that respects rate limits automatically.

4. Caching

Cache responses to avoid unnecessary API calls. Use ETags and conditional requests when supported.

Summary

Handling rate limits well makes your application more resilient. Combine exponential backoff with caching for the best results.

Ready to Start Building?

Get your free API key and access all the APIs mentioned in this article.

Get Free API Key →