Back to Snippets
CODE

Throttle API Requests

Description

Prevents excessive API calls by throttling requests to specified rate limit

Code

/**
 * Throttle API requests with rate limiting
 * @param fn Async function to throttle
 * @param limit Maximum requests per minute
 * @returns Throttled async function
 */
function throttleApiRequests<T extends (...args: any[]) => Promise<any>>(
  fn: T,
  limit = 60 // 60 requests per minute (1 per second)
): T {
  const requestTimes: number[] = [];
  const interval = 60000 / limit; // Milliseconds between requests

  return async function(this: ThisParameterType<T>, ...args: Parameters<T>) {
    const now = Date.now();
    
    // Remove timestamps older than 1 minute
    requestTimes.filter(time => now - time < 60000);
    
    if (requestTimes.length >= limit) {
      const oldestRequest = requestTimes[0];
      const waitTime = interval - (now - oldestRequest);
      
      if (waitTime > 0) {
        await new Promise(resolve => setTimeout(resolve, waitTime));
      }
    }
    
    requestTimes.push(Date.now());
    return fn.apply(this, args);
  } as T;
}

// Usage Example
const fetchData = throttleApiRequests(async (url: string) => {
  const response = await fetch(url);
  return response.json();
}, 30); // 30 requests per minute

// Safe to call multiple times - will be throttled automatically
fetchData('https://api.example.com/data');
fetchData('https://api.example.com/data');
fetchData('https://api.example.com/data');

Usage

Critical for applications consuming APIs with rate limits, preventing 429 Too Many Requests errors

Tags

APIThrottleRate LimitingPerformance