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
| Option | Type | Default | Description |
|---|---|---|---|
Max | int | Required | Max connections |
ErrorHandler | func(*mizu.Ctx) error | 503 | Custom error handler |
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
Testing
The maxconns middleware includes comprehensive test coverage for all major scenarios:| Test Case | Description | Expected Behavior |
|---|---|---|
TestNew | Concurrent requests exceeding max limit | Accepts up to max connections, rejects excess with 503 |
TestWithOptions_PerIP | Multiple concurrent requests from same IP with PerIP limit | Only allows configured number per IP, rejects others |
TestWithOptions_CustomErrorHandler | Custom error handler with Max=0 | Uses custom handler returning custom status/response |
TestPerIP | Sequential requests with PerIP limit | Sequential requests succeed as connections are released |
TestGlobal | Global limit using Global() helper | Request succeeds within global limit |
TestCounter | Counter type for monitoring | Counter tracks current connections and exposes metrics |
TestRetryAfterHeader | Rejected request header validation | Sets βRetry-After: 60β header on 503 responses |