Overview
Themirror middleware duplicates requests to one or more target servers for traffic shadowing, testing, and analysis. Mirrored requests run asynchronously and donβt affect the original response.
Installation
Quick Start
Configuration
| Option | Type | Default | Description |
|---|---|---|---|
Targets | []Target | - | Mirror target URLs |
Timeout | time.Duration | 5s | Timeout for mirrored requests |
Async | bool | true | Run mirror requests asynchronously |
CopyBody | bool | true | Copy request body |
OnError | func(string, error) | - | Error callback |
OnSuccess | func(string, *http.Response) | - | Success callback |
Examples
Single Target
Multiple Targets
Percentage-Based Mirroring
Custom Timeout
Synchronous Mirroring
Error Handling
Success Callback
Response Comparison
Route-Specific Mirroring
Canary Testing
A/B Testing Analysis
Skip Body for GET Requests
Target Structure
Helper Functions
Mirrored Request Headers
Each mirrored request includes:- All original headers
X-Mirrored-From: <original-host>
API Reference
Use Cases
- Shadow Testing: Test new versions with production traffic
- Load Testing: Send copies to test infrastructure
- Analytics: Duplicate to analytics services
- Backup: Sync to backup systems
- Canary Deployment: Route small percentage to canary
Technical Details
Implementation Architecture
The mirror middleware is built with the following core components:-
Request Cloning: The middleware reads the original request body (if
CopyBodyis enabled) and stores it in memory to allow multiple sends without consuming the original request stream. -
HTTP Client: A dedicated
http.Clientis created with the configured timeout and redirect policy (http.ErrUseLastResponseto prevent following redirects). - Percentage-Based Sampling: Uses a simple counter-based modulo operation to determine whether to mirror a request based on the configured percentage (e.g., 50% mirrors every other request).
-
Asynchronous Execution: When
Asyncis true (default), mirrored requests are executed in separate goroutines, ensuring zero impact on the main request latency.
Request Flow
- Original request arrives at the middleware
- If
CopyBodyis enabled and body exists, read body into memory and restore it to the original request - For each target:
- Check percentage threshold using counter-based sampling
- If threshold met, execute mirror request (async or sync based on configuration)
- Continue to next middleware/handler with original request unchanged
Mirror Request Details
Each mirrored request includes:- All original HTTP headers copied verbatim
X-Mirrored-Fromheader set to original request host- Same HTTP method as original request
- Same request URI (path + query string) appended to target base URL
- Request body (if
CopyBodyis enabled)
Performance Characteristics
- Async mode: Zero latency impact on original request (default)
- Sync mode: Adds mirror request latency to original request processing
- Memory overhead: Proportional to request body size when
CopyBodyis enabled - Goroutine cost: One goroutine per target per mirrored request in async mode
Error Handling
- Mirror failures never affect the original request/response
- Errors are silently ignored unless
OnErrorcallback is provided - HTTP client respects the configured timeout to prevent hanging requests
- Response bodies are properly closed to prevent resource leaks
Best Practices
- Use async mode (default) to avoid latency
- Set appropriate timeouts
- Monitor error rates on mirror targets
- Use percentage-based mirroring for gradual rollouts
- Log and compare responses for validation
- Donβt mirror to targets with side effects (unless intended)
Testing
The mirror middleware includes comprehensive test coverage for all features:| Test Case | Description | Expected Behavior |
|---|---|---|
| TestNew | Basic mirror functionality with single target | Request is successfully mirrored to target server |
| TestWithOptions_Async | Asynchronous mirroring behavior | Original response returns immediately without waiting for mirror completion |
| TestWithOptions_Percentage | Percentage-based traffic sampling | Approximately 50% of requests are mirrored when percentage is set to 50 |
| TestWithOptions_MultipleTargets | Mirroring to multiple targets simultaneously | All configured targets receive mirrored requests |
| TestWithOptions_OnError | Error callback invocation | OnError callback is called when mirror request fails |
| TestWithOptions_OnSuccess | Success callback invocation | OnSuccess callback is called with response when mirror succeeds |
| TestWithOptions_MirroredHeader | X-Mirrored-From header injection | Mirror request includes X-Mirrored-From header with original host |
| TestPercentage | Percentage helper function | Returns Target with correct URL and percentage values |
| TestWithOptions_CopyBody | Request body copying enabled | Mirror request receives the same body as original request |
| TestWithOptions_NoCopyBody | Request body copying disabled | Mirror request is sent without body content |
| TestNew_MultipleTargets | Multiple targets via New() helper | All targets receive mirrored requests with async execution |