JavaScript

Rate Limiter (Token Bucket)

by @admin
9h ago
Apr 28, 2026
Public
Implements a token-bucket rate limiter that allows a burst of calls up to a maximum capacity, then replenishes tokens at a steady rate. Useful for throttling outbound API requests, user-facing actions, or any operation where you need to allow occasional bursts without exceeding a sustained rate.
JavaScript
function createRateLimiter(maxTokens = 10, refillRate = 1, refillInterval = 1000) {
  let tokens = maxTokens;
  setInterval(() => { tokens = Math.min(maxTokens, tokens + refillRate); }, refillInterval);

  return function consume(count = 1) {
    if (tokens >= count) {
      tokens -= count;
      return true;
    }
    return false;
  };
}

// Usage
const allowed = createRateLimiter(5, 1, 1000); // 5 burst, +1/sec

for (let i = 0; i < 8; i++) {
  console.log(`Request ${i + 1}:`, allowed() ? 'OK' : 'RATE LIMITED');
}
// First 5: OK, next 3: RATE LIMITED
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.