100% FREE • NO LOGIN REQUIRED

Token Bucket Simulator

Leverage Token Bucket (RouterOS v6.35+) using the bucket & marbles analogy for minimal CPU overhead without burst ceilings, ideal for lower-spec routers.

Penggunaan Token Bucket
6 times
Privacy Guarantee
Zero-Logs • Protected
Last Active
01 Oct 2026
Quick Presets: Citraweb Research (#297) & Field Scenarios

Token Bucket Parameters

Mbps
10.0
1.0 (Light) 10.0 (Citraweb) 20.0 30.0 (Large)
Mbps
Simulate actual download speed requested by client.
Total Bucket Capacity
10 Mbits
1.25 MB tokens
Bucket Depletion Time
10.0s
Until tokens depleted
Speed Status
BONUS AKTIF
Klien dapat 2M (kemudian 1M)
Bucket Emptying Simulation (Token Drain Curve)
Ready-to-Use MikroTik RouterOS Scripts

                
In-Depth Technical Guide & Article

Panduan Analogi Ember & Kelereng (HTB Token Bucket) MikroTik

Master the underlying theory, mathematical formulas, and best practices for production deployment.

Buka Semua Panduan

Traditional Queue Burst

RouterOS calculates the client's average data usage over a moving time window called Burst Time, divided into 16 sampling intervals.

  • Strict Upper Ceiling: Client will never exceed burst-limit.
  • Duration Formula: T = (Threshold × Time) / Burst-Limit.
  • CPU Overhead: Requires continuous 16-slice moving average computations per active queue.
  • Best Use Case: Commercial Hotspot & PPPoE tiers with definite, strictly enforced peak rates.

Token Bucket (Hierarchical Token Bucket)

Introduced in RouterOS v6.35+. Uses a bucket holding tokens analogy where total capacity is determined by the bucket-size parameter.

  • No Upper Bound: Client can drain tokens as fast as link capacity allows without burst-limit restrictions.
  • Simple & Lightweight: Requires only 1 parameter (bucket-size).
  • Super Low CPU Overhead: Ideal for routers with constrained CPU resources (e.g. RB750/hEX series).
  • Best Use Case: ISPs with thousands of subscribers desiring flexible bursts without overloading router CPU.
Characteristic Conventional Queue Burst Token Bucket (v6.35+)
Maximum Burst Ceiling Strictly capped by burst-limit Uncapped (limited only by physical link capacity)
Router CPU Utilization Moderate - High (continuous 16-slice sampling) Very Low (simple token arithmetic)
Configuration Parameters 3 parameters: Threshold, Limit, Time 1 parameter: bucket-size
Queue Tree Support Supported Supported
Hotspot/PPPoE Profile Support Native rate-limit attribute format Configured via Queue Scripts / Parent Queues
Technical Analysis & References refer to Citraweb Solusi Teknologi (#297) & MikroTik RouterOS HTB Documentation.
Read Citraweb Article #297
Technical Deep Dive Networking & Backend 8 Min Read

Rate Limiting: Comprehensive Guide to Token Bucket, Leaky Bucket, and MikroTik Queue Burst

MY
Written by Makarius Yuwono
• September 19, 2026 • Rate Limiting, MikroTik, API, Traffic Shaping

“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.”

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:

Capacity Protection

Preventing server outages caused by traffic spikes. What matters here is an absolute hard ceiling — no spikes should ever breach system capacity.

Fair Share Among Users

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.

Cost Control

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.

Anti-Abuse

Restricting login attempts, mass sign-ups, or OTP dispatches to mitigate brute force attacks, credential stuffing, and spam bots.

Core Distinction: The first motivation demands rigid boundaries. The second demands flexibility — users who are typically quiet should be permitted to burst briefly at high speeds. This difference is what gave birth to the concept of burst.

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
Key Insight: Rate and burst are complementary dimensions, not substitutes. Rate governs long-term behavior; burst governs short-term elasticity. A system with only rate feels stiff and sluggish. A system with only burst provides zero long-term protection.

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
Pros: Minimal memory (single counter per user), easy to reason about, trivial to implement in Redis.
Fatal Flaw (Window Boundary): A user can transmit 100 requests at second 59 and 100 requests at second 61, exposing the server to 200 requests within 2 seconds (2x the intended limit).

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
Pros: Perfect mathematical precision, completely free of window boundary surges.
Cons: Linear memory growth. A 10,000/hour limit requires storing 10,000 timestamps per active user, making RAM requirements unsustainable at scale.

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).

Industry Standard: Memory overhead is merely two integers per client with very high practical accuracy. This is the default recommendation for modern API backends.

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:

T_burst = b / (R − 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:

T_recovery = b / r

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:

Retry_After = (cost − available_tokens) / r

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:

r = 5 | b = 200 | Recovery = 200 / 5 = 40 seconds

Is 40 seconds recovery too long? Increase r, but be aware steady-state bandwidth consumption will rise accordingly.

Test Token Bucket Visually

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:

max-limit Normal maximum speed (MIR) when burst is inactive.
burst-limit Peak speed granted while burst bonus is active.
burst-threshold Average consumption threshold that triggers/revokes burst.
burst-time Moving average calculation window (NOT burst duration!).
The #1 Misconception in MikroTik: 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:

T_burst = (burst-threshold × burst-time) / burst-limit
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!

Test This 2M / 8M Preset in Our Calculator

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

Rate Limiting Solely by IP Address

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.

Uniform Cost Across All Endpoints

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.

Neglecting Rare but Expensive Endpoints

PDF generation endpoints may be seldom invoked, but 100 concurrent triggers will exhaust server CPU pools immediately if left unthrottled.

Ignoring 429 Rejection Metrics

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:

1
Measure First: Deploy rate limiters in audit/shadow mode (telemetry logging only, zero drops) for 3–7 days.
2
Extract Percentiles: Evaluate P95 and P99 traffic rates per user. Set steady-state rate r around legitimate P99 usage.
3
Size Burst from Real Workflows: Identify the largest legitimate burst (e.g. initial dashboard hydration requiring 40 endpoints). Set capacity b slightly above this crest.
4
Validate Recovery Time: Check ratio b / r. If recovery is too sluggish and users suffer repeated drops, scale up r.
5
Monitor and Iterate: Continuously monitor 429 error ratios in monitoring dashboards. Adaptively relax limits if legitimate clients are impacted.

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.

Key Takeaway: Limits that are overly strict harm legitimate subscribers; limits that are overly generous fail to safeguard services. The ideal equilibrium is established through telemetry data, never guesswork.
MY
Makarius Yuwono

Software Engineering, Backend Architecture & Telecommunications Specialist. This guide bridges mathematical traffic shaping theory with real-world production practices across MikroTik routers and modern APIs.

Bermanfaat untuk Pekerjaan Jaringan?

Share This Free Tool With Your Network

Help fellow network engineers, ISP technicians, and WISP operators with these free MikroTik utilities.

MikRam Hotspot & Billing ISP

Otomatiskan Billing & Isolir Pelanggan MikroTik Anda

Tidak perlu lagi repot copy-paste skrip secara manual. MikRam menyinkronkan profil bandwidth, voucher hotspot, PPPoE, dan pembayaran otomatis dengan WhatsApp gateway & payment gateway resmi.