API Rate Limiter & Token Bucket Algorithm Simulator

Simulate API rate limiting across Token Bucket, Leaky Bucket, and Sliding Window algorithms. Model burst capacity, HTTP 429 throttling, and calculate Retry-After headers.

📁 Developer🔒 100% Free & Private⚡ Instant Output
Quick Overview & Direct Answer

API Rate Limiting & Token Bucket Algorithm Simulator: Free API Rate Limiting & Token Bucket Algorithm Simulator tool: simulate API rate limiting across Token Bucket, Leaky Bucket, Fixed Window, and Sliding.

Primary Use Code debugging, syntax validation, encoding/decoding, API payload inspection
Input Formats Code snippets, JSON, XML, SQL, regex expressions, data structures
Output Format Formatted code, validation feedback, generated hashes, AST trees
Processing Mode 100% Client-Side JavaScript Engine
Access Tier Free, unlimited, no sign-up needed

Rate Limiting Parameters

Tokens added per second
Max tokens bucket can hold

Incoming Client Traffic Spike Simulation

Simultaneous calls dispatched at t = 0
Weight per API call

Simulation Results & Throttling Status

Requests Accepted (200 OK)
15 Calls
Processed immediately
Throttled (429 Too Many)
10 Calls
40.0% rejected
HTTP Retry-After Header
10 Seconds
Until next call allowed
Full Bucket Recovery
15.0 Seconds
Time to reach max burst
Rate Limit Exceeded: A burst of 25 calls exhausted the 15-token capacity. 10 requests were rejected with HTTP 429 Too Many Requests.

Standard IETF HTTP Response Headers

HTTP/1.1 429 Too Many Requests Content-Type: application/json Retry-After: 10 RateLimit-Limit: 60 RateLimit-Remaining: 0 RateLimit-Reset: 10

Algorithm Comparison & Storage Tradeoffs

Algorithm Burst Handling Memory per Client CPU Cost in Redis Boundary Spike Vulnerability

The Architectural Role of API Rate Limiting

In distributed web systems, API rate limiting is a fundamental resilience pattern. Unchecked inbound traffic exposes backend services to Denial-of-Service (DoS) attacks, brute-force credential stuffing, API scraping, and the "noisy neighbor" problem in multi-tenant SaaS environments.

Rate limiting controls the consumption of server resources by tracking incoming client request rates (typically keyed by Client IP, API Key, or JWT User ID) and applying throttling mechanisms once a pre-established threshold is crossed. Rejected requests receive a standardized HTTP 429 Too Many Requests status code, informing client software to pause transmission.

Deep Dive into the Core Rate Limiting Algorithms

1. The Token Bucket Algorithm

The Token Bucket algorithm is the industry standard for REST and GraphQL APIs (used by Stripe, AWS, and GitHub). It models a bucket with maximum capacity $B$ that continuously receives tokens at a refill rate $r$ tokens per second:

Token Bucket State Transition Equations

$$text{Tokens}_{text{new}} = min left( B, , text{Tokens}_{text{old}} + (t_{text{now}} - t_{text{last}}) times r right)$$

$$text{If } text{Tokens}_{text{new}} ge text{Cost}: quad text{Accept Request}, quad text{Tokens}_{text{remaining}} = text{Tokens}_{text{new}} - text{Cost}$$

$$text{If } text{Tokens}_{text{new}} < text{Cost}: quad text{Reject (HTTP 429)}, quad text{Retry-After} = leftlceil frac{text{Cost} - text{Tokens}_{text{new}}}{r} rightrceil$$

Key Advantage: The Token Bucket allows brief, legitimate bursts of traffic (up to $B$ requests) while guaranteeing that over longer time horizons, the sustained throughput never exceeds $r$ requests per second.

2. The Leaky Bucket Algorithm

Unlike the Token Bucket which permits instantaneous bursts, the Leaky Bucket algorithm enforces a strictly constant, smoothed outflow rate. Incoming requests enter a FIFO queue (the bucket). The bucket leaks requests at a steady rate $r$. If incoming requests arrive faster than the leak rate, the bucket fills; once the queue capacity is reached, new requests overflow and are dropped immediately.

3. Fixed Window vs Sliding Window Counter

Algorithm Mechanism Pros Cons
Fixed Window Counter Divides time into discrete blocks (e.g. 12:00:00 to 12:01:00) with a simple counter Extremely simple; requires single integer key in Redis (INCR) Severe Boundary Spike: Traffic clustered at boundary edges permits $2times$ the limit
Sliding Log Stores a sorted set of every request timestamp within the past window 100% mathematically precise; zero boundary edge flaws Memory Intensive: Storing thousands of timestamps per user causes massive Redis RAM bloat
Sliding Window Counter Blends the previous window's counter with the current window using an elapsed time weighting factor Prevents boundary spikes; stores only 2 integer counters per client Approximation (assumes uniform distribution in previous window)

The Sliding Window Counter Formulation

To eliminate the boundary spike of Fixed Windows without incurring the heavy memory footprint of Sliding Logs, Cloudflare and Kong popularize the Sliding Window Counter approximation:

Sliding Window Estimation Formula

$$text{Requests in Window} = text{Counter}_{text{current}} + text{Counter}_{text{previous}} times (1 - text{Fractional Time Elapsed})$$

Example: Window is 60 seconds. Currently at second 15 ($25%$ elapsed into current window). Previous window had 100 requests; current window has 20 requests:

$$text{Estimated Rate} = 20 + 100 times (1 - 0.25) = 20 + 75 = mathbf{95text{ requests}}$$

This approach requires storing only two numbers per user (previous count and current count), achieving 99.9% accuracy with virtually zero Redis memory overhead.

Production Redis Lua Script Implementation

Implementing an atomic Token Bucket in Redis using Lua eliminates race conditions across distributed API gateway instances:

-- Redis Lua Script: Atomic Token Bucket local key = KEYS[1] local capacity = tonumber(ARGV[1]) local refill_rate = tonumber(ARGV[2]) local cost = tonumber(ARGV[3]) local now = tonumber(ARGV[4]) local data = redis.call('HMGET', key, 'tokens', 'last_updated') local tokens = tonumber(data[1]) local last_updated = tonumber(data[2]) if tokens == nil then tokens = capacity last_updated = now else local delta = math.max(0, now - last_updated) tokens = math.min(capacity, tokens + delta * refill_rate) last_updated = now end if tokens >= cost then tokens = tokens - cost redis.call('HMSET', key, 'tokens', tokens, 'last_updated', last_updated) redis.call('EXPIRE', key, math.ceil(capacity / refill_rate)) return {1, tokens, 0} -- Allowed: {status, remaining, retry_after} else local retry_after = math.ceil((cost - tokens) / refill_rate) return {0, tokens, retry_after} -- Throttled: {status, remaining, retry_after} end

Frequently Asked Questions

The Token Bucket algorithm accumulates tokens at a constant rate up to a maximum bucket capacity, allowing short bursts of traffic up to the burst limit to be processed immediately with zero delay. In contrast, the Leaky Bucket algorithm processes incoming requests at a strictly constant, smoothed outflow rate, queuing excess requests in a buffer or discarding them once the buffer fills, making it ideal for traffic shaping rather than bursty API endpoints.

The Fixed Window Counter resets its request counter at fixed time intervals (e.g. at the start of every minute). If a client transmits its maximum limit (e.g. 100 requests) in the final 5 seconds of minute 1, and another 100 requests in the first 5 seconds of minute 2, the system accepts 200 requests within a 10-second window—twice the intended limit. The Sliding Window Counter algorithm prevents this by weighting the previous window's count by the overlap percentage.

Under the Token Bucket model, when a request arrives and the available token count is less than the required cost, the server calculates how long it will take for enough tokens to regenerate: Retry-After = ceil((Required Tokens - Current Tokens) / Refill Rate). The header indicates to the client how many seconds it must pause before retrying.

A Token Bucket requires reading the current token balance, computing the tokens generated since the last timestamp, checking if sufficient tokens exist, decrementing the balance, and updating the timestamp. Executing these steps as separate Redis commands creates a race condition in high-concurrency environments. Encapsulating the logic in an atomic Redis Lua script ensures thread-safe, linear execution without distributed locks.