Overview
Thethrottle middleware limits the number of concurrent requests being processed, ensuring your application doesn’t get overwhelmed by too many simultaneous operations.
Use it when you need:
- Limit concurrent request processing
- Prevent resource exhaustion
- Control server load
- Queue requests during high traffic
Installation
Quick Start
Configuration
Options
Examples
Simple Throttle
With Backlog
With Timeout
No Backlog (Immediate Rejection)
With OnThrottle Callback
API Reference
Functions
Technical Details
Implementation
The throttle middleware uses a semaphore-based approach to control concurrency:-
Semaphore: A buffered channel (
chan struct{}) acts as a semaphore with capacity equal to theLimit. Each slot represents permission to process one request concurrently. -
Request Flow:
- When a request arrives, the middleware attempts to acquire a slot from the semaphore (non-blocking)
- If a slot is available immediately, the request proceeds
- If no slot is available, the request checks the backlog capacity
-
Backlog Queue:
- A counter tracks the number of requests waiting for a slot
- If backlog capacity is reached, new requests are rejected immediately with
503 Service Unavailable - Requests in the backlog wait with a timeout for a slot to become available
-
Timeout Handling:
- Waiting requests use
time.NewTimerwith the configuredTimeout - Three exit conditions: slot acquired, timeout reached, or request context cancelled
- On timeout or cancellation, the backlog counter is decremented
- Waiting requests use
-
Thread Safety: A
sync.Mutexprotects the backlog counter to prevent race conditions.
Default Values
Limit: 100 concurrent requestsBacklog: 1000 waiting requestsTimeout: 30 seconds
Error Responses
503 Service Unavailablewith “service busy” - backlog capacity exceeded503 Service Unavailablewith “request timeout” - timeout waiting for slot
Throttle vs Rate Limit
Best Practices
- Use for upstream service protection
- Set reasonable wait timeouts
- Monitor queue depths
- Combine with rate limiting for full control
- Set
BacklogSet: truewhen usingBacklog: 0to disable queueing - Use
OnThrottlecallback for monitoring and metrics collection