Overview
Themaxconns middleware limits the maximum number of concurrent connections to protect server resources.
Use it when you need:
- Connection limiting
- Resource protection
- DoS mitigation
Installation
Quick Start
Configuration
Options
Examples
Basic Limit
Custom Error
With Monitoring
API Reference
Functions
Technical Details
Implementation Architecture
The maxconns middleware uses atomic operations and mutexes to safely manage concurrent connections: Global Connection Tracking:- Uses
atomic.LoadInt64andatomic.AddInt64for lock-free global connection counting - Atomic operations ensure thread-safe increments/decrements without mutex overhead
- Counter is incremented before processing and decremented via defer after completion
- Maintains a
map[string]intfor per-IP connection counts - Protected by
sync.RWMutexto allow concurrent reads with exclusive writes - IP addresses extracted from
X-Forwarded-For,X-Real-IP, orRemoteAddrheaders - Map entries automatically cleaned up when IP count reaches zero
- Check global limit using atomic load operation
- If PerIP enabled, check IP-specific limit under read lock
- Increment both counters (atomic for global, locked for per-IP)
- Process request through handler chain
- Decrement counters via defer (guarantees cleanup even on errors)
- When
Max <= 0, middleware immediately rejects all requests - Optimized fast path that bypasses counter management
- Default response: 503 Service Unavailable with βRetry-After: 60β header
- Custom error handlers can be configured via Options
- Error handler receives full context for custom responses
Key Components
Counter Type:- Provides observable connection metrics
- Exposes
Current()andMax()methods for monitoring - Can be used standalone for custom monitoring solutions
Global(max): Alias forNew(max)for semantic clarityPerIP(max): Convenience function setting per-IP limit with high global max (1,000,000)getClientIP(): Extracts client IP from standard proxy headers
Best Practices
- Set based on server capacity
- Monitor connection counts
- Use with rate limiting
- Return appropriate error response