Caching & Rate Limits
HTTP caching headers, ETag conditional requests, rate limit handling, and Retry-After
Skills taught: api.cache-control, api.etag, api.rate-limit-headers, api.retry-after
HTTP caching and rate limit handling
// ── Reading rate limit headers ──
async function apiFetch(url) {
const res = await fetch(url);
// Log rate limit info on every response
const remaining = Number(res.headers.get('x-ratelimit-remaining'));
const limit = Number(res.headers.get('x-ratelimit-limit'));
const resetAt = Number(res.headers.get('x-ratelimit-reset')); // Unix timestamp
if (!isNaN(remaining)) {
console.log(`Rate limit: ${remaining}/${limit} remaining`);
if (remaining < 10) {
const resetIn = Math.ceil((resetAt * 1000 - Date.now()) / 1000);
console.warn(`Warning: only ${remaining} requests left, resets in ${resetIn}s`);
}
}
if (res.status === 429) {
const retryAfter = Number(res.headers.get('retry-after')) || 60;
throw new RateLimitError(`Rate limited. Retry after ${retryAfter}s`, retryAfter);
}
return res;
}
// ── ETag conditional request ──
const cache = new Map(); // url → { etag, data }
async function fetchWithETag(url) {
const cached = cache.get(url);
const headers = {};
if (cached?.etag) headers['If-None-Match'] = cached.etag;
const res = await fetch(url, { headers });
if (res.status === 304) {
// Not modified — use cached data, saved bandwidth!
console.log('Cache hit (304 Not Modified)');
return cached.data;
}
const data = await res.json();
const etag = res.headers.get('etag');
if (etag) cache.set(url, { etag, data });
return data;
}
// ── Client-side rate limiter ──
class RateLimiter {
constructor(requestsPerSecond) {
this.interval = 1000 / requestsPerSecond;
this.lastCall = 0;
}
async throttle() {
const wait = this.interval - (Date.now() - this.lastCall);
if (wait > 0) await new Promise(r => setTimeout(r, wait));
this.lastCall = Date.now();
}
}
// 5 requests per second max:
const limiter = new RateLimiter(5);
async function throttledFetch(url) {
await limiter.throttle();
return fetch(url);
}
Frequently Asked Questions
How do I know if an API has rate limits and what they are?
Check the API documentation — it usually specifies limits per endpoint (e.g. '60 requests/minute for free tier'). At runtime, check response headers: X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset. Not all APIs use the same header names — GitHub uses X-RateLimit-*, Stripe uses separate docs. When you get a 429 response, always check the Retry-After header before retrying. Some APIs use a sliding window (track last N seconds), others use fixed windows (reset every hour at :00).