Skip to main content

Overview

The ratelimit middleware implements token bucket rate limiting to control request rates. It protects your application from abuse, ensures fair usage, and prevents resource exhaustion. Use it when you need:
  • API rate limiting
  • Protection against brute force attacks
  • Fair usage enforcement
  • Resource protection

Installation

Quick Start

Configuration

Options

Examples

Basic Rate Limiting

Custom Rate and Interval

With Burst

Rate Limit by API Key

Rate Limit by User

Skip Certain Requests

Custom Error Handler

Disable Headers

Different Limits for Different Routes

Tiered Rate Limits

Custom Store

Response Headers

When Headers is enabled (default), these headers are included:

API Reference

Functions

Store Interface

RateLimitInfo

Token Bucket Algorithm

The middleware uses the token bucket algorithm:
  1. Bucket starts full with Burst tokens
  2. Requests consume one token
  3. Tokens refill at Rate per Interval
  4. Burst allows temporary spikes

Technical Details

The rate limit middleware implements the token bucket algorithm, a sophisticated approach for managing request rates with support for burst traffic. The implementation details are as follows:

Token Bucket Implementation

The algorithm maintains a bucket of tokens for each rate limit key:
  1. Initialization: Each bucket starts with Burst tokens (default equals Rate)
  2. Token Consumption: Each request consumes exactly one token from the bucket
  3. Token Refill: Tokens are added continuously based on elapsed time:
    • Refill rate: Rate / Interval tokens per second
    • Formula: tokensToAdd = (Rate * elapsedSeconds) / intervalSeconds
  4. Capacity Limit: Bucket capacity is capped at Burst tokens to prevent unlimited accumulation
  5. Request Decision: Request is allowed if bucket has at least 1 token available

In-Memory Store

The default MemoryStore provides:
  • Thread Safety: Uses sync.Mutex for concurrent access protection
  • Per-Key Tracking: Maintains separate buckets for each key (IP, user ID, API key, etc.)
  • Automatic Cleanup: Background goroutine removes stale buckets after 10 minutes of inactivity
  • Fractional Tokens: Uses float64 for precise token calculations during refills

Rate Limit Information

For each request, the middleware calculates and returns:
  • Limit: Maximum requests allowed per interval (from Rate option)
  • Remaining: Current token count (floored to nearest integer)
  • Reset: Timestamp when bucket will be full again (current time + Interval)

Best Practices

  • Set reasonable limits based on expected usage
  • Use different limits for different endpoints
  • Include rate limit headers for client awareness
  • Monitor rate limit hits for tuning
  • Consider user tiers for fair access

Testing

The rate limit middleware includes comprehensive test coverage for all functionality: