Inferensys

Glossary

Token Bucket Algorithm

A traffic shaping algorithm that controls data transmission by maintaining a fixed-capacity bucket of tokens consumed per request, enabling controlled bursts up to a defined limit.
Data scientist building training data pipeline on laptop, data preprocessing visible, technical workspace.
TRAFFIC SHAPING

What is Token Bucket Algorithm?

The token bucket algorithm is a traffic shaping mechanism that controls data transmission by maintaining a fixed-capacity bucket of tokens, where each token authorizes the transmission of a defined unit of data, and tokens are replenished at a constant rate to permit controlled bursts up to the bucket's depth.

The token bucket algorithm operates by adding tokens to a conceptual bucket at a fixed refill rate, typically measured in tokens per second. Each incoming request must consume an equivalent number of tokens from the bucket to proceed. If sufficient tokens are unavailable, the request is either queued, delayed, or discarded outright. The bucket has a maximum capacity that limits the size of an allowable burst, preventing unbounded accumulation of unused transmission credit.

This algorithm is distinct from a leaky bucket because it permits bursty traffic rather than smoothing it to a constant output rate. It is widely implemented in packet-switched networks, API gateways, and rate limiters to enforce service-level agreements. By decoupling the arrival rate from the service rate, the token bucket provides a precise mechanism for enforcing both a sustained average throughput and a peak burst size.

TRAFFIC SHAPING MECHANISM

Key Characteristics

The token bucket algorithm is a fundamental traffic policing mechanism that allows for controlled bursts while enforcing a long-term average rate. It is widely used in network engineering and API gateways to mitigate scraping.

01

Core Mechanism: Tokens as Transmission Rights

The algorithm uses a conceptual bucket that holds tokens. Tokens are added at a fixed fill rate (e.g., 10 tokens per second) up to a maximum bucket capacity (e.g., 50 tokens). To transmit a packet or process a request, a number of tokens equal to the packet size or request cost must be removed from the bucket. If insufficient tokens are available, the request is either queued or dropped, enforcing the rate limit.

02

Burst Tolerance vs. Sustained Rate

Unlike a simple leaky bucket, the token bucket explicitly decouples the sustained rate from the burst size.

  • Sustained Rate: Defined by the token fill rate. Over a long period, the average traffic cannot exceed this rate.
  • Burst Size: Defined by the bucket capacity. A sender can transmit a burst of traffic up to the bucket's full capacity instantaneously, as long as tokens have been accumulated during idle periods. This makes it ideal for TCP traffic, which is inherently bursty.
03

Implementation in Web Scraping Mitigation

In API gateways and Web Application Firewalls (WAFs), the token bucket is used to enforce per-client rate limits.

  • Keying: A bucket is assigned per IP address, API key, or session token.
  • Cost: A single HTTP request typically costs 1 token, but expensive endpoints (e.g., search queries) can cost more.
  • Penalty: When a scraper exceeds the burst limit, the gateway returns a 429 Too Many Requests status code, often paired with a Retry-After header. This prevents automated scripts from exhausting server resources while allowing legitimate user bursts.
04

Algorithmic Logic and State

The algorithm requires maintaining minimal state per client: current token count and last refill timestamp. The logic is executed on every request:

  1. Refill: Calculate elapsed time since the last check. Add elapsed_time * fill_rate tokens, capping at the maximum bucket size.
  2. Consume: Check if current_tokens >= request_cost. If yes, subtract the cost and allow the request. If no, deny the request. This calculation is O(1) and memory-efficient, making it suitable for high-throughput edge functions and reverse proxies.
05

Comparison with Leaky Bucket

The token bucket is often contrasted with the leaky bucket algorithm:

  • Leaky Bucket: Processes requests at a constant, fixed rate, smoothing out bursts completely by queuing them. It enforces a rigid output rate regardless of the input burst pattern.
  • Token Bucket: Allows instantaneous bursts up to the bucket size while enforcing a long-term average rate. It does not smooth traffic but limits the total volume over time. For scraping mitigation, the token bucket is preferred because it does not introduce artificial latency for legitimate users during short, high-activity periods.
06

Distributed Rate Limiting

In a distributed system with multiple API gateway instances, a centralized state store is required to maintain a global token bucket. Redis is commonly used for this purpose. A naive implementation can suffer from race conditions. The Generic Cell Rate Algorithm (GCRA), often implemented via sorted sets or atomic Lua scripts in Redis, provides a formalized, race-condition-free method for calculating token availability in a distributed environment without requiring constant bucket state synchronization.

TRAFFIC SHAPING COMPARISON

Token Bucket vs. Leaky Bucket Algorithm

A technical comparison of two fundamental rate-limiting algorithms used in network traffic shaping and API gateway enforcement.

FeatureToken BucketLeaky Bucket

Core Mechanism

Tokens accumulate at a fixed rate in a bucket with a maximum capacity; each request consumes one or more tokens

Requests enter a queue (bucket) and are processed at a constant, fixed rate regardless of burst traffic

Burst Handling

Idle Behavior

Accumulates tokens up to bucket capacity, allowing future bursts

Queue drains completely; no credit accumulated for future use

Output Pattern

Bursty with configurable maximum burst size

Smooth, constant-rate output with no bursts

Queue Behavior

No queue; excess requests are rejected immediately when tokens are depleted

Queue-based; excess requests are queued until capacity is reached, then dropped

Traffic Shaping vs. Policing

Traffic policing: allows bursts but enforces a long-term average rate

Traffic shaping: smooths traffic to a strict constant rate

Memory Usage

Low: requires only a token counter and timestamp

Higher: requires queue storage proportional to burst size

Use Case

API rate limiting, short-lived traffic spikes, user-facing services

Streaming media, constant-bitrate applications, ISP traffic shaping

Implementation Complexity

Moderate: requires timer for token replenishment and atomic counter operations

Moderate: requires queue management and timer-based dequeue operations

Starvation Risk

Low: tokens replenish predictably; no request is permanently blocked

Moderate: slow consumers may experience sustained queuing delays

Configurable Parameters

Token rate (r), bucket capacity (b)

Output rate (r), queue size (q)

RFC Reference

RFC 2697 (Single Rate Three Color Marker)

Generic Cell Rate Algorithm (GCRA) per ATM Forum specifications

TRAFFIC SHAPING

Frequently Asked Questions

Explore the mechanics of the token bucket algorithm, a foundational traffic shaping mechanism used to enforce rate limits while permitting controlled bursts of activity.

The Token Bucket Algorithm is a traffic shaping mechanism that controls the rate of data transmission or request processing by maintaining a conceptual bucket that holds tokens. Tokens are added to the bucket at a fixed, configurable rate, and the bucket has a maximum capacity. To process a request or transmit a packet, a specific number of tokens must be removed from the bucket. If the bucket contains enough tokens, the action is permitted and the tokens are consumed. If the bucket is empty, the action is either delayed until tokens become available or rejected outright. This mechanism allows for controlled bursts of traffic up to the bucket's maximum capacity while enforcing a long-term average rate, making it ideal for smoothing out traffic spikes without starving legitimate users.

Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.