You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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:
typeRateLimiterinterface {
Wait(ctx context.Context) error// blocks until a token is available or ctx is cancelled
}
typeTokenBucketOptionsstruct {
RequestsPerMinuteintTokensPerMinuteint// optional; 0 = no token-based limiting
}
funcNewTokenBucket(optsTokenBucketOptions) RateLimiterfuncNewRateLimitMiddleware(limiterRateLimiter) 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