DEV Community

Yasser Elgammal
Yasser Elgammal

Posted on

Introducing a Rate Limiter Library for Go

In modern backend systems, rate limiting is essential.

Without it, APIs are exposed to abuse, resource exhaustion, and unfair usage.

That’s why I built a production-ready, thread-safe rate limiter library in Go, based on the Token Bucket algorithm.


Why Token Bucket?

I chose the Token Bucket algorithm because it:

  • Allows controlled bursts of traffic
  • Provides smooth request flow
  • Is widely used in production systems
  • Is simple to understand and reason about

Each client gets a bucket of tokens that refills over time.

Requests consume tokens — once the bucket is empty, requests are rejected.


Library Highlights

This library focuses on correctness and simplicity:

  • Production-ready & thread-safe
  • Token Bucket algorithm with burst support
  • Fast in-memory storage
  • Detailed rate limit results (remaining, retry-after, reset time)
  • Extensive unit tests and race-condition testing
  • Optional cleanup for stale entries

Quick Example

config := limiter.Config{
    Rate:     10,
    Duration: time.Second,
    Burst:    20,
}

store := store.NewMemoryStore(5 * time.Minute)
rateLimiter, _ := limiter.NewTokenBucket(config, store)

if rateLimiter.Allow("user123") {
    fmt.Println("Request allowed")
}
Enter fullscreen mode Exit fullscreen mode

With just a few lines, you get a reliable rate limiter ready for production.


Perfect For

  • REST APIs
  • Go microservices
  • Public-facing services
  • Internal tools

Anything that needs fair and controlled request handling.


Open Source

The project is open source under the MIT license and open for contributions.

GitHub:

https://github.com/yasserelgammal/rate-limiter

If you find it useful, feel free to leave a ⭐️

It really helps support open-source work.

Top comments (0)