ctw / ctw-middleware-responsetime
This PSR-15 middleware adds an X-Response-Time in milliseconds to the Response header.
Installs: 124
Dependents: 0
Suggesters: 0
Security: 0
Stars: 1
Watchers: 1
Forks: 0
Open Issues: 0
pkg:composer/ctw/ctw-middleware-responsetime
Requires
- php: ^8.3
- ctw/ctw-middleware: ^4.0
- psr/container: ^1.0 || ^2.0
Requires (Dev)
- ctw/ctw-qa: ^5.0
- phpunit/phpunit: ^12.0
- symfony/var-dumper: ^7.0
README
PSR-15 middleware that adds an X-Response-Time header showing request processing duration in milliseconds.
Introduction
Why This Library Exists
Understanding how long your application takes to process requests is essential for performance monitoring and optimization. While external tools can measure total response time, they include network latency. Measuring at the application level provides the true processing time.
This middleware adds an X-Response-Time header to every response showing:
- Processing duration: Time from request arrival to response generation
- Millisecond precision: Three decimal places for accurate measurement
- Consistent format: Standardized header for easy parsing by monitoring tools
- Zero overhead: Uses PHP's native
microtime()for minimal performance impact
Problems This Library Solves
- Invisible performance: Without timing data, slow requests go unnoticed
- External tool inaccuracy: Network-based measurements include latency, not just processing time
- Manual instrumentation: Adding timing code to every handler is tedious and error-prone
- Inconsistent measurement: Different timing implementations across the application
- Missing production visibility: Development profilers aren't available in production
Where to Use This Library
- Performance monitoring: Track response times across your application
- SLA verification: Ensure responses meet required time thresholds
- Debugging slowness: Quickly identify slow requests from response headers
- Load testing: Analyze response time distribution under load
- Client-side monitoring: JavaScript can read the header for real-user monitoring
- Log correlation: Include response time in access logs for analysis
Design Goals
- High precision: Milliseconds with three decimal places (microsecond resolution)
- Accurate timing: Uses
REQUEST_TIME_FLOATas start time for precision - Standard format:
X.XXX msformat is human-readable and parseable - Minimal overhead: Simple subtraction and header addition
- Universal application: Works for HTML, JSON, and all response types
Requirements
- PHP 8.3 or higher
- ctw/ctw-middleware ^4.0
Installation
Install by adding the package as a Composer requirement:
composer require ctw/ctw-middleware-responsetime
Usage Examples
Basic Pipeline Registration (Mezzio)
use Ctw\Middleware\ResponseTimeMiddleware\ResponseTimeMiddleware; // In config/pipeline.php - place early in the pipeline for accurate timing $app->pipe(ResponseTimeMiddleware::class);
ConfigProvider Registration
// config/config.php return [ // ... \Ctw\Middleware\ResponseTimeMiddleware\ConfigProvider::class, ];
Response Header Output
HTTP/1.1 200 OK Content-Type: text/html; charset=UTF-8 X-Response-Time: 45.123 ms
Inspecting with cURL
curl -I https://example.com/ # Response includes: # X-Response-Time: 45.123 ms
Inspecting in Browser DevTools
- Open Developer Tools (F12)
- Navigate to the Network tab
- Select a request
- View Response Headers
- Look for
X-Response-Time
Header Format
| Component | Description |
|---|---|
| Value | Processing time in milliseconds |
| Precision | Three decimal places (microsecond resolution) |
| Format | X.XXX ms |
| Example | 45.123 ms |
Timing Calculation
The middleware calculates response time as:
Response Time = (end_time - start_time) × 1000
Where:
start_time=$_SERVER['REQUEST_TIME_FLOAT'](request arrival)end_time=microtime(true)(response generation complete)
Use Cases
Log Analysis
# Extract response times from access logs grep "X-Response-Time" /var/log/nginx/access.log | awk '{print $NF}'
Performance Alerting
// Client-side monitoring const responseTime = parseFloat( response.headers.get('X-Response-Time') ); if (responseTime > 1000) { console.warn('Slow response:', responseTime, 'ms'); }
Load Testing
# Apache Bench with response time analysis ab -n 1000 -c 10 https://example.com/ | grep "Time per request"