DEV Community

Cover image for Token Bucket Algorithm
Jayant
Jayant

Posted on

1 1 1 1 1

Token Bucket Algorithm

These Algo. typically used as Rate limiting Algorithm.
It is used to control amount of data or number of requests that can be proccessed in a given time period.

Token Bucket Algo

WORKING :

  • Token are added to the Bucket at a fixed rate.
  • The Bucket has a Max. Capacity, it can't hold more tokens than that.
  • When a Request came, the Bucket is checked for number of token available
    • If req. tokens are available then remove that tokens from the bucket and process the request.
    • If no token are available, the request is rejected or pushed to a retry queue.

IMPLEMENTATION :

Token Bucket can be implemented in respect to user or application.
Means either we can use it rate limit the user, that a certain user can only make 10req/sec.
or we can use it to rate limit the application, that a certain application can only make 10req/sec.

class TokenBucket{
    private refillRate:number;  // no of token added to the bucket per second
    private capacity:number;
    private Bucket: number;
    private lastRefillTime: number;

    constructor(refillRate:number,capacity:number){
        this.refillRate = refillRate;
        this.capacity = capacity;
        this.Bucket = capacity;
        this.lastRefillTime = Date.now();
    }

    public refill(){
        const time = Date.now();
        const diff = time - this.lastRefillTime;
        const tokensToAdd = Math.floor(diff* this.refillRate);
        this.Bucket = min(this.capacity, this.Bucket+tokensToAdd);
        this.lastRefillTime = time;
    }

    public allowRequest(){
        // Update the Bucket with tokens
        refill();

        if(this.Bucket >= 1){
            this.Bucket = this.Bucket - 1;
            return true;
        }

        return false;
    }
}
Enter fullscreen mode Exit fullscreen mode

Example : LIMITING REQUESTS PER SECOND FOR USER IN NESTJS

Token Bucket Algo

FLOW

Client ──> NestJS API (Producer)
               └── always send to RabbitMQ  (free or premium queue)

Worker (Consumer)
    └── Pull from queue(s)
        └── Check Redis token bucket
            ├──  Allowed  process job
            └──  Not allowed  requeue with delay

Enter fullscreen mode Exit fullscreen mode

Heroku

Save time with this productivity hack.

See how Heroku MCP Server connects tools like Cursor to Heroku, so you can build, deploy, and manage apps—right from your editor.

Learn More

Top comments (0)

Build gen AI apps that run anywhere with MongoDB Atlas

Build gen AI apps that run anywhere with MongoDB Atlas

MongoDB Atlas bundles vector search and a flexible document model so developers can build, scale, and run gen AI apps without juggling multiple databases. From LLM to semantic search, Atlas streamlines AI architecture. Start free today.

Start Free

👋 Kindness is contagious

Take a moment to explore this thoughtful article, beloved by the supportive DEV Community. Coders of every background are invited to share and elevate our collective know-how.

A heartfelt "thank you" can brighten someone's day—leave your appreciation below!

On DEV, sharing knowledge smooths our journey and tightens our community bonds. Enjoyed this? A quick thank you to the author is hugely appreciated.

Okay