Inferensys

Glossary

Token Bucket Algorithm

A rate-limiting algorithm that uses a fixed-capacity bucket of tokens refilled at a constant rate to control the throughput of requests, allowing for short bursts of traffic.
Control room desk with laptops and a large orchestration network display.
RATE LIMITING

What is Token Bucket Algorithm?

The token bucket algorithm is a traffic shaping mechanism that controls the rate and burstiness of data transmission or request processing by managing a virtual bucket of tokens.

The token bucket algorithm is a rate-limiting mechanism that uses a fixed-capacity bucket filled with tokens at a constant refill rate to govern throughput. Each request or packet consumes one or more tokens from the bucket; if insufficient tokens are available, the request is delayed or discarded. This model permits short bursts of traffic up to the bucket's capacity while enforcing a long-term average rate defined by the token replenishment speed.

In real-time fraud scoring pipelines, the algorithm is essential for implementing velocity checks and protecting downstream services from overload. Unlike a fixed-window counter, the token bucket smooths traffic by allowing unused tokens to accumulate, accommodating legitimate transaction spikes without violating system constraints. It is commonly implemented in API gateways and stream processors to enforce service-level agreements on P99 latency.

RATE LIMITING MECHANICS

Key Features of the Token Bucket Algorithm

The token bucket algorithm is a fundamental rate-limiting pattern that controls throughput by managing a fixed-capacity bucket of tokens replenished at a constant rate, enabling controlled bursts while enforcing long-term rate limits.

01

Token Replenishment Rate

Tokens are added to the bucket at a fixed, configurable rate—typically measured in tokens per second. This replenishment rate defines the sustained throughput the system will support over time. For example, a rate of 100 tokens/second means the system can process an average of 100 requests per second over the long term. The refill is typically implemented using a leaky bucket integrator that calculates elapsed time since the last request and adds the proportional number of tokens, ensuring smooth, continuous replenishment without requiring a background thread.

100 req/s
Typical Sustained Rate
02

Burst Capacity

The bucket has a maximum capacity that allows it to accumulate unused tokens up to a ceiling. This enables the algorithm to tolerate short bursts of traffic that temporarily exceed the sustained rate. For instance, with a capacity of 500 tokens and a refill rate of 100 tokens/second, the system can handle a burst of 500 requests instantly, then settle back to 100 requests/second. Once the bucket is empty, requests are either throttled (rejected with HTTP 429) or queued until tokens become available. This property is critical for handling traffic spikes without overwhelming downstream services.

500 tokens
Example Burst Capacity
03

Per-Key Isolation

In production fraud detection pipelines, token buckets are typically instantiated per unique key—such as an API key, user ID, IP address, or merchant ID. This ensures that one abusive client cannot exhaust the rate limit for all others. Each key maintains its own independent bucket state, including current token count and last refill timestamp. This isolation is essential for velocity checks in financial systems, where you might limit a single card to 5 authorization attempts per minute while allowing the overall payment gateway to process thousands of transactions per second.

5/min
Per-Card Velocity Limit
04

Memory-Efficient State Management

Token bucket state is lightweight—typically just a token count and a last access timestamp per key. This makes the algorithm highly suitable for in-memory stores like Redis or local caches. For high-throughput systems processing millions of keys, an LRU eviction policy can prune inactive buckets to prevent memory exhaustion. The constant-time O(1) complexity for both token consumption and refill calculations ensures the algorithm adds negligible latency to the critical path of real-time transaction authorization, often executing in microseconds.

O(1)
Time Complexity
< 1 µs
Per-Check Latency
05

Distributed Rate Limiting

In horizontally scaled fraud detection services, a single token bucket must be shared across multiple instances to enforce a global rate limit. This is achieved using distributed counters in systems like Redis with Lua scripting for atomicity. The INCRBY and EXPIRE commands can implement a sliding window approximation, while a more precise token bucket requires a compare-and-swap pattern to atomically deduct tokens. For financial authorization flows, eventual consistency is often acceptable, trading perfect accuracy for sub-millisecond read latency from local replicas.

99.9%
Consistency Target
06

Integration with Backpressure

When the token bucket is empty, the system must decide how to handle excess requests. Common strategies include immediate rejection with a 429 Too Many Requests response, queuing with a timeout, or graceful degradation to a fallback service. In financial fraud pipelines, immediate rejection is preferred to maintain deterministic latency guarantees. The token bucket can also feed into a circuit breaker pattern—if the bucket remains empty for an extended period, the circuit opens to protect downstream systems from sustained overload, triggering alerts for operations teams.

429
HTTP Status on Throttle
RATE LIMITING COMPARISON

Token Bucket vs. Leaky Bucket Algorithm

A technical comparison of the two foundational traffic-shaping algorithms used in real-time fraud scoring pipelines to control throughput and manage burst traffic.

FeatureToken BucketLeaky Bucket

Core Mechanism

Tokens added at fixed rate; bucket holds up to max capacity

Requests added to queue; processed at fixed rate

Burst Handling

Output Pattern

Bursty, allows short traffic spikes

Smoothed, constant rate

Queue Behavior

No queue; excess requests rejected immediately

Queue with fixed depth; overflow discarded

State Required

Token count and last refill timestamp

Queue depth and drain rate

Memory Overhead

Low

Higher due to queued request storage

Use Case in Fraud Pipelines

Velocity checks allowing burst of legitimate rapid purchases

Strict upstream rate limiting to protect downstream scoring engines

P99 Latency Impact

Variable, spikes during bursts

Predictable, bounded by queue depth

RATE LIMITING & VELOCITY CHECKS

Applications in Financial Fraud Detection

The token bucket algorithm is a foundational mechanism in real-time fraud scoring pipelines, enabling precise control over transaction throughput while accommodating legitimate bursts. Its deterministic, low-overhead design makes it ideal for enforcing velocity checks at the network edge before transactions reach downstream ML models.

01

Velocity Check Enforcement

Token buckets directly implement velocity checks by tracking the rate of specific attributes—such as card numbers, IP addresses, or device fingerprints—over configurable time windows. Each transaction consumes a token; when the bucket empties, subsequent requests are throttled or flagged.

  • Card velocity: Limit attempts per PAN per minute to block card testing attacks
  • IP velocity: Restrict transactions from a single IP to detect bot-driven enumeration
  • Account velocity: Cap login or transfer attempts per user session

A bucket configured with a capacity of 10 tokens and a refill rate of 1 token per second allows a burst of 10 immediate transactions, then sustains a steady 1 TPS rate.

< 1 ms
Per-request overhead
O(1)
Algorithmic complexity
03

Burst Tolerance for Legitimate Traffic

Unlike a fixed window counter, the token bucket's burst capacity parameter allows short spikes of legitimate activity without triggering false positives. This is critical during flash sales, payroll processing windows, or mobile wallet top-up surges.

  • Capacity (burst size) defines the maximum instantaneous transaction rate tolerated
  • Refill rate defines the sustained average rate the system enforces over time
  • The ratio of capacity to refill rate determines how long a burst can be sustained

A fraud analyst might configure a bucket with capacity=100 and refill=10/s, permitting a 10-second burst of 100 transactions before throttling to the steady 10 TPS rate—accommodating genuine customer behavior while capping abuse.

04

Multi-Tier Token Bucket Hierarchies

Sophisticated fraud pipelines apply nested token buckets at multiple granularities to catch distributed attacks that respect per-entity limits but exceed aggregate thresholds.

  • Tier 1 — Merchant-level: Limit total transactions per merchant per second
  • Tier 2 — IP-level: Limit transactions from a single IP across all merchants
  • Tier 3 — PAN-level: Limit attempts per card number globally

A transaction must pass all tiers to proceed. An attacker rotating through 100 stolen cards from a single IP would pass Tier 3 checks but be blocked by Tier 2. This layered defense catches both card testing and credential stuffing patterns simultaneously.

05

Integration with Feature Stores

Token bucket counters serve as real-time features fed into online inference models. The current bucket depth—how many tokens remain—becomes a numerical feature indicating how close a transaction is to the velocity limit.

  • Feature: card_token_bucket_depth (0.0 to 1.0, normalized)
  • Feature: ip_token_bucket_exhausted (boolean flag)
  • Feature: time_since_last_refill_ms (milliseconds)

These features are computed in the hot path and served via a feature store with sub-millisecond latency, allowing gradient-boosted models to weigh velocity signals alongside behavioral biometrics and device fingerprinting scores.

06

Backpressure and Graceful Degradation

When downstream fraud scoring services experience latency spikes, token buckets act as a backpressure mechanism to prevent cascading failures. By throttling inbound transactions at the API gateway, the system protects the scoring engine from overload.

  • Circuit breaker integration: When the scoring service returns 5xx errors, the bucket refill rate is dynamically reduced
  • Graceful degradation: Exhausted buckets route transactions to a static rules engine instead of the ML model
  • Dead letter queues: Transactions that exceed retry budgets are persisted for asynchronous reprocessing

This pattern implements the bulkhead pattern from resilience engineering, isolating failures and ensuring the payments authorization flow remains operational even during partial outages.

TOKEN BUCKET ALGORITHM

Frequently Asked Questions

Explore the mechanics, configurations, and implementation patterns of the token bucket algorithm, a foundational rate-limiting technique used in real-time fraud scoring pipelines to control throughput and manage burst traffic.

The token bucket algorithm is a rate-limiting mechanism that controls the throughput of requests by using a conceptual bucket that holds tokens. The bucket has a fixed maximum capacity and is refilled with tokens at a constant, configurable rate. To process a request, a token must be removed from the bucket; if the bucket is empty, the request is throttled or rejected. This model allows for short bursts of traffic up to the bucket's capacity while enforcing a long-term average rate defined by the refill speed. For example, a bucket with a capacity of 100 tokens and a refill rate of 10 tokens per second can handle a sustained load of 10 requests per second, but can also accommodate an instantaneous burst of 100 requests, after which the system must wait for tokens to regenerate.

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.