Overview
Theconcurrency middleware limits the number of requests processed in parallel, preventing resource exhaustion and ensuring stable performance.
Use it when you need:
- Limit CPU-intensive operations
- Control database connection usage
- Prevent memory exhaustion
Installation
Quick Start
Configuration
Options
Examples
Basic Limit
Custom Error
Per-Route Limits
API Reference
Functions
Technical Details
The concurrency middleware uses Goβs buffered channels as semaphores to control concurrent request processing:Implementation Mechanisms
- Semaphore Pattern: Uses a buffered channel with capacity equal to the maximum concurrent requests limit
- Non-blocking Acquisition: The default
New()andWithOptions()useselectwithdefaultto immediately reject requests when at capacity - Blocking Acquisition: The
Blocking()variant blocks requests until a slot becomes available - Context-aware: The
WithContext()variant respects context cancellation while waiting for a slot
Core Components
- Options struct: Configures maximum concurrent requests and custom error handling
- Semaphore channel: Controls access to the handler based on the configured limit
- Deferred release: Ensures semaphore slots are released even if the handler panics
- Retry-After header: Automatically set to β1β second when requests are rejected
Behavior Patterns
- Zero or negative limit: Immediately rejects all requests with 503 Service Unavailable
- Default error response: Returns 503 with βServer at capacityβ message
- Custom error handler: Allows full control over rejection response format and status code
Best Practices
- Set limits based on resource capacity
- Monitor concurrent request counts
- Use different limits for different workloads
- Combine with timeout for hung requests