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.
Glossary
Token Bucket Algorithm

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.
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.
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.
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.
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.
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-Afterheader. This prevents automated scripts from exhausting server resources while allowing legitimate user bursts.
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:
- Refill: Calculate elapsed time since the last check. Add
elapsed_time * fill_ratetokens, capping at the maximum bucket size. - 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.
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.
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.
Token Bucket vs. Leaky Bucket Algorithm
A technical comparison of two fundamental rate-limiting algorithms used in network traffic shaping and API gateway enforcement.
| Feature | Token Bucket | Leaky 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 |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
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.
Related Terms
The Token Bucket Algorithm is a foundational mechanism for controlling data flow. These related concepts define the broader ecosystem of rate limiting, bot mitigation, and traffic management.

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.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us