Rate Limiting: Comprehensive Guide to Token Bucket, Leaky Bucket, and MikroTik Queue Burst
“Rate limiting seems trivial — 'limit to 100 per minute, done'. But every decision inside is a trade-off between protecting systems and degrading user experience. Here is how to choose based on mathematics, not guesswork.”
Table of Contents
1 Why Rate Limiting Exists
Every system has finite capacity: uplink bandwidth, database connection pools, requests per second processed by CPU. Rate limiting is the mechanism that ensures resource consumption does not exceed established operational thresholds.
There are four distinct motivations, and distinguishing them is critical because each dictates a different optimal algorithm:
Preventing server outages caused by traffic spikes. What matters here is an absolute hard ceiling — no spikes should ever breach system capacity.
A single client must not consume shared capacity intended for all subscribers. In WISP / community networks, one user pulling 24/7 torrents should not degrade speeds for 30 neighboring subscribers.
When calling third-party APIs billed per request, or managing ISP upstream FUP quotas, rate limiting acts as a financial brake keeping operational expenses bounded.
Restricting login attempts, mass sign-ups, or OTP dispatches to mitigate brute force attacks, credential stuffing, and spam bots.
2 Core Vocabulary
Before exploring algorithms, these four core concepts must be clear, as they are frequently conflated in daily practice and router configurations:
| Term | Meaning & Definition | Real-World Example |
|---|---|---|
| Rate (r) | Permitted long-term average throughput | 10 requests/sec, 5 Mbps |
| Burst (b) | Maximum volume consumable in a short surge above standard rate | 50 concurrent requests, 20 Mbps (2 seconds) |
| Quota | Absolute cumulative volume over an extended epoch | 500 GB/month, 10,000 requests/day |
| Window | Time window across which counters reset or evaluate | per second, per minute, per hour |
3 Rate Limiting Algorithms
3.1 Fixed Window Counter
The simplest approach. Partition time into discrete windows (e.g. per minute), increment a counter per window, and reject requests when the limit is exceeded.
key = user_id + ":" + floor(now / 60)
count = INCR(key)
if count == 1: EXPIRE(key, 60)
if count > limit: REJECT
3.2 Sliding Window Log
Store timestamps of every incoming request. When a new request arrives, prune all timestamps older than the rolling window, then count the remainder.
ZREMRANGEBYSCORE key 0 (now - window)
count = ZCARD key
if count < limit: ZADD key now now
else: REJECT
3.3 Sliding Window Counter
An elegant hybrid compromise. Track counters for both the current and preceding window, interpolating linearly based on the current window elapsed time:
estimated = current_count + previous_count × (1 − position_in_window)
Example: Limit 100/min. Previous window had 80 requests, current window has 30 requests, and we are at second 15 (25% elapsed):
estimated = 30 + 80 × (1 − 0.25) = 30 + 60 = 90 (90 < 100, accepted).
3.4 Leaky Bucket
Imagine a bucket with a small hole at the bottom. Requests enter the bucket (queue) and leak out to processing at a constant, smooth rate. If the bucket overflows, new requests are dropped.
- Constant, Smooth Output: Regardless of incoming burstiness, output traffic is perfectly regulated (ideal for egress traffic shaping).
- No Bursts on Output: Traffic bursts are buffered in the queue and leaked slowly. Users experience this as latency, not immediate rejection.
3.5 Token Bucket
A bucket is filled continuously with tokens at rate r tokens/second, up to a maximum bucket capacity b. Each request consumes tokens matching its cost. If tokens are insufficient, the request is rejected or queued.
tokens = min(b, tokens + (now − last_refill) × r)
last_refill = now
if tokens >= cost:
tokens −= cost
ALLOW
else:
REJECT
Lazy Evaluation: No background timers or crons needed. Tokens are calculated lazily upon request arrival from timestamp deltas. Requires only 2 variables per client (tokens and last_refill).
4 Token Bucket Mathematics
This is where mathematical modeling proves decisive, because parameter interactions are often counter-intuitive.
4.1 Maximum Burst Duration (T_burst)
If the bucket is full (b tokens) and the client sends at rate R greater than refill rate r:
Example: b = 100 tokens, r = 10 tokens/s. Client bursts at R = 50 req/s:
T_burst = 100 / (50 − 10) = 2.5 seconds (125 requests processed).
4.2 Recovery Time (T_recovery)
After the bucket is completely drained, the time required to replenish back to capacity b:
Example: 100 / 10 = 10 seconds. For a full 2.5 second burst, the client must remain idle for 10 seconds to restore full capacity.
4.3 Calculating Retry-After
When a request is rejected due to insufficient tokens, the duration the client must wait before retrying:
This value should be transmitted in HTTP headers to prevent blind client retries.
4.4 Sizing Capacity from Requirements
If a user needs 200 concurrent requests upon loading a complex dashboard, with steady-state usage of 5 req/s:
Is 40 seconds recovery too long? Increase r, but be aware steady-state bandwidth consumption will rise accordingly.
Experiment with bucket size and client demand rates using our real-time simulation canvas.
5 Burst in Network Engineering (MikroTik RouterOS)
Burst implementation in MikroTik RouterOS differs from pure token bucket algorithms, which is a frequent source of confusion among network engineers and ISP operators. MikroTik relies on four core parameters:
burst-time is NOT how long the burst lasts! RouterOS computes the moving average over the past burst-time by dividing it into 16 sampling intervals. Once the rolling average exceeds burst-threshold, throughput is throttled back to max-limit.
Actual MikroTik Burst Duration Formula:
Practical ISP Field Scenario
RouterOS CLI/queue simple add name="subscriber-01" target=192.168.10.5/32 max-limit=2M/2M burst-limit=8M/8M burst-threshold=1M/1M burst-time=16s/16s
Calculation: T_burst = (1 × 16) / 8 = 2 seconds.
The subscriber experiences 8 Mbps for the initial 2 seconds — sufficient to render web portals or video playback start instantaneously — before smoothly settling at 2 Mbps. This creates a perception of "lightning-fast internet" without congesting upstream links!
Inspect the 16-slice moving average curve and generate ready-to-use RouterOS scripts directly.
6 Distributed Rate Limiting
The calculations above assume a single instance. When scaling an application across multiple instances behind a load balancer, in-memory counters lack shared state. Across 4 instances with a 100/min limit, a client could slip through up to 400 req/min.
Approach 1: Atomic Centralized Counter (Redis + Lua)
Token bucket operations must be atomic to eliminate race conditions. Use this production-tested Lua script:
-- KEYS[1] = bucket key
-- ARGV[1] = capacity (b)
-- ARGV[2] = refill rate (r, tokens/second)
-- ARGV[3] = cost
-- ARGV[4] = current time (seconds)
-- ARGV[5] = TTL
local tokens = tonumber(redis.call("HGET", KEYS[1], "tokens")) or tonumber(ARGV[1])
local last = tonumber(redis.call("HGET", KEYS[1], "ts")) or tonumber(ARGV[4])
local delta = math.max(0, tonumber(ARGV[4]) - last)
tokens = math.min(tonumber(ARGV[1]), tokens + delta * tonumber(ARGV[2]))
if tokens < tonumber(ARGV[3]) then
return 0
end
tokens = tokens - tonumber(ARGV[3])
redis.call("HSET", KEYS[1], "tokens", tokens, "ts", ARGV[4])
redis.call("EXPIRE", KEYS[1], ARGV[5])
return 1
Approach 2: Partitioned Quota
Divide the overall limit by instance count (e.g. 4 instances = 25/min per node). Zero network coordination overhead, but unequal if traffic distribution across nodes is uneven.
Approach 3: Hybrid Batching
Instances decrement local memory counters and sync batched deltas to Redis periodically (e.g. every 100 ms). Optimal balance between low latency and accuracy at massive scale.
7 Client Communication
Robust rate limiting never operates silently. Communicate remaining quotas using standardized HTTP response headers:
HTTP/1.1 429 Too Many Requests
RateLimit-Limit: 100
RateLimit-Remaining: 0
RateLimit-Reset: 47
Retry-After: 12
Client Strategy: Exponential Backoff with Jitter
On client applications, implement backoff with randomized jitter to prevent the catastrophic Thundering Herd problem:
delay = min(max_delay, base × 2^attempt) × (0.5 + random() × 0.5)
Without jitter randomization, thousands of throttled clients will retry simultaneously at second 12 — creating repetitive tidal waves of load.
8 Common Pitfalls & Mistakes
Hundreds of corporate or mobile ISP users share a single public IP via CGNAT. Throttling by IP can inadvertently lock out an entire enterprise. Prefer API keys / user session tokens.
Heavy analytical reporting queries consuming 3 seconds of CPU should not cost the same token weight as a Redis cached balance check. Apply differentiated cost values.
PDF generation endpoints may be seldom invoked, but 100 concurrent triggers will exhaust server CPU pools immediately if left unthrottled.
Surges in HTTP 429 responses are telemetry alerts: they might signal client app bugs, DDoS activity, or that limits are overly restrictive for legitimate workflows.
9 Choosing Parameters from Data, Not Guesswork
Never set rate limits arbitrarily. Follow this 5-stage data-driven methodology:
r around legitimate P99 usage.b slightly above this crest.b / r. If recovery is too sluggish and users suffer repeated drops, scale up r.10 Conclusion & Key Recommendations
Rate limiting appears straightforward, but every parameter tuning is an architectural trade-off between infrastructure resilience and user experience. Token bucket remains dominant because it is the sole algorithm decoupling steady-state rate from temporary surge tolerance.
Software Engineering, Backend Architecture & Telecommunications Specialist. This guide bridges mathematical traffic shaping theory with real-world production practices across MikroTik routers and modern APIs.