Skip to content

feat: rate limiting middleware (per-provider token bucket to prevent quota exhaustion) #39

Open

Description

@devops-bda

Wave 3 — Infrastructure

Problem

Provider APIs enforce rate limits (requests/min, tokens/min). When llmrouter sends traffic faster than a provider's quota allows, it gets 429s that the retry middleware then amplifies into cascading backoff storms. A client-side rate limiter prevents quota exhaustion before it happens and reduces unnecessary retries.

Compared to LiteLLM, which has per-key rate limits at the proxy layer, llmrouter needs this as a composable middleware so Go services get the same protection without a sidecar.

Proposed Design

New file middleware/ratelimit.go:

type RateLimiter interface {
    Wait(ctx context.Context) error // blocks until a token is available or ctx is cancelled
}

type TokenBucketOptions struct {
    RequestsPerMinute int
    TokensPerMinute   int // optional; 0 = no token-based limiting
}

func NewTokenBucket(opts TokenBucketOptions) RateLimiter
func NewRateLimitMiddleware(limiter RateLimiter) llmrouter.Middleware
  • NewTokenBucket uses golang.org/x/time/rate (already a transitive dep via google APIs)
  • Token-based limiting uses Usage.TotalTokens from the previous response as an estimate
  • Wait respects context cancellation so timeouts still work correctly
  • Callers can supply a custom RateLimiter (e.g. a distributed Redis-backed limiter)

Composition order

Rate limiter should sit outside retry in the middleware chain: ratelimit → retry → circuitbreaker → timeout → provider. This ensures retries count against the rate limit.

Acceptance Criteria

  • RateLimiter interface and NewTokenBucket implementation
  • NewRateLimitMiddleware wrapping any RateLimiter
  • Context cancellation propagated correctly through Wait
  • Unit tests verifying requests are held when rate is exceeded
  • README example showing correct middleware composition order

Activity

  1. added
    enhancement
    on May 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions