Overview
Thetiming middleware adds Server-Timing headers to responses, allowing you to measure and report server-side performance metrics. These metrics are visible in browser DevTools.
Installation
Quick Start
Examples
Basic Usage
Track Custom Metrics
Using Start/Stop Pattern
Using Track Helper
Multiple Metrics
API Reference
Functions
Response Header Format
Viewing in Browser
Open DevTools → Network → Select request → Timing tab to see:- Total server processing time
- Individual metric breakdowns
- Descriptions for each metric
Technical Details
Implementation Architecture
The timing middleware uses a context-based storage mechanism to track performance metrics throughout the request lifecycle.Core Components
-
timingData Structure
- Thread-safe metric storage using
sync.Mutex - Tracks request start time
- Maintains a slice of custom metrics
- Thread-safe metric storage using
-
Context Integration
- Uses typed context key for type-safe storage
- Stores timing data in request context
- Enables metric collection across handler chain
-
Metric Recording
- Metrics stored as
{name, duration, description}tuples - Total duration calculated from request start time
- All durations converted to milliseconds (microseconds/1000)
- Metrics stored as
Header Generation
The middleware builds the Server-Timing header after handler execution:- Total time is always included first
- Custom metrics appended in order of addition
- Format:
name;dur=<ms>;desc="<description>" - Multiple metrics joined with
,separator
Thread Safety
All metric operations are protected by mutex locks:Add()acquires lock before appending metrics- Header generation locks before reading metrics
- Safe for concurrent metric recording
Best Practices
- Track database queries, cache lookups, and external API calls
- Use descriptive names for metrics
- Add descriptions for clarity
- Keep metric names short and consistent
- Use the Start/Stop pattern for cleaner code