Overview
Thehttp_session module provides enterprise-grade HTTP session management for tif1, implementing a thread-safe singleton pattern with aggressive connection pooling, intelligent DNS resolution with DNS-over-HTTPS (DoH) fallback, and comprehensive connection reuse tracking. This infrastructure is critical to tif1’s performance characteristics, enabling high-throughput parallel data fetching while minimizing network overhead.
Why HTTP Session Management Matters
Formula 1 telemetry data consists of thousands of individual data points spread across multiple JSON files on CDN servers. A typical session load might require:- 20-50 HTTP requests for lap data, session metadata, and driver information
- 100-300 HTTP requests for telemetry data when loading all drivers
- 500+ HTTP requests when loading full season data with telemetry
- TCP handshake overhead: 1-3 round trips (50-150ms on typical connections)
- TLS negotiation: 2-4 round trips (100-200ms)
- DNS resolution: 20-100ms per unique hostname
Key Features
- Thread-safe singleton pattern: Single shared session across all threads and requests
- Aggressive connection pooling: Dynamically sized pools based on concurrency settings
- HTTP/2 multiplexing: Multiple requests over single connections (optional)
- HTTP/3 support: QUIC protocol for improved performance (optional)
- DNS-over-HTTPS fallback: Automatic DoH resolver fallback for reliability
- Connection reuse tracking: Comprehensive metrics for monitoring and optimization
- Keep-alive optimization: Configurable timeouts and request limits per connection
- Automatic resource cleanup: Graceful shutdown on process exit
- Zero-trust environment handling: Disabled trust_env for predictable behavior
Core API
get_session
_session_lock) to ensure thread-safe initialization. Once the session is created, subsequent calls return the cached instance without acquiring the lock, making this operation extremely fast in the common case.
Session Lifecycle:
- First call creates the session with optimized settings
- Subsequent calls return the cached instance
- Session persists until process exit or explicit
close_session()call - Automatic cleanup registered via
atexithandler
niquests.Session: Shared session instance configured with:- Dynamic connection pooling based on concurrency settings
- DNS-over-HTTPS fallback resolvers
- HTTP/2 multiplexing (if enabled)
- HTTP/3 support (if not disabled)
- Keep-alive headers with configurable timeouts
- Disabled
trust_envfor predictable behavior
- HTTPAdapter mounted on
https://with custom pool settings - Connection pooling:
pool_connectionsandpool_maxsizedynamically calculated - Keep-alive headers:
Connection: keep-alivewith timeout and max request limits - Resolver fallback: Attempts standard DNS, then Cloudflare DoH, then Google DoH
- Multiplexing: HTTP/2 multiplexing enabled by default for optimal throughput
- First call: 10-50ms (session creation + DNS resolution)
- Subsequent calls: <1μs (cached instance return)
- Memory overhead: ~1-2MB for session + connection pools
- Connection reuse: 80-95% in typical workloads
Configuration changes only take effect before the first
get_session() call. To apply new settings, call close_session() first to reset the singleton, then call get_session() again.close_session
Connection Statistics
get_connection_stats
- Dictionary with connection metrics:
total_requests: Total number of requests madeconnections_reused: Number of requests that reused connectionsconnections_created: Number of connection pools createdreuse_rate: Percentage of requests that reused connections (0-100)
reset_connection_stats
Configuration
The HTTP session is configured via the global config object. Key settings:| Config Key | Type | Default | Description |
|---|---|---|---|
http_multiplexed | bool | True | Enable HTTP/2 multiplexing |
http_disable_http3 | bool | False | Disable HTTP/3 support |
pool_connections | int | Dynamic (min 256) | Number of connection pools (auto-sized based on concurrency) |
pool_maxsize | int | Dynamic (min 512) | Maximum connections per pool (auto-sized, typically 4x pool_connections) |
keepalive_timeout | int | 120 | Keep-alive timeout in seconds |
keepalive_max_requests | int | 1000 | Max requests per connection |
user_agent | str | "tif1/0.2.0 (https://github.com/TracingInsights/tif1)" | User-Agent header |
http_resolvers | list[str] | ["standard", "doh://cloudflare", "doh://google"] | DNS resolvers with DoH fallback |
DNS-over-HTTPS (DoH) Support
The HTTP session automatically falls back to DoH resolvers if standard DNS fails. This improves reliability in restrictive network environments. Default resolver order:- Standard DNS
- Cloudflare DoH (
doh://cloudflare) - Google DoH (
doh://google)
Connection Pooling
The HTTP session uses aggressive connection pooling for maximum performance:- Connection reuse: Keeps connections alive for multiple requests
- Pool sizing: Dynamically sized based on concurrency settings
- Keep-alive: Configurable timeout and max requests per connection
- Thread-safe: Single shared session across all threads
- Eliminates TCP handshake overhead
- Reduces TLS negotiation time
- Improves throughput for parallel requests
- Lowers latency for sequential requests
Advanced Configuration
HTTP/2 Multiplexing
HTTP/2 multiplexing is enabled by default to send multiple requests over a single connection. You can disable it if needed:HTTP/2 multiplexing is enabled by default for optimal performance. Only disable if you experience issues with specific CDN configurations.
Custom pool sizing
Pool sizes are automatically calculated based on concurrency settings. Override only if you have specific requirements:The library automatically sizes connection pools based on
max_workers, max_concurrent_requests, and telemetry_prefetch_max_concurrent_requests settings. Manual override is rarely needed.Keep-Alive Tuning
Adjust keep-alive settings for different network conditions:Troubleshooting
Connection pool exhaustion
If you see connection pool warnings, increase pool size:DNS Resolution Failures
If standard DNS fails, DoH fallback activates automatically. To force DoH:Connection reuse issues
Monitor connection reuse rate to identify issues:Best Practices
- Don’t create multiple sessions: Use the shared session for all requests
- Monitor connection stats: Track reuse rate to optimize performance
- Tune pool size: Match pool size to your concurrency needs
- Use DoH in restrictive networks: Configure DoH resolvers for reliability
- Enable HTTP/2 carefully: Test thoroughly before enabling multiplexing
- Let the library manage cleanup: Session closes automatically on exit
Summary
The http_session module provides:- Shared HTTP session with connection pooling
- DNS-over-HTTPS fallback for reliability
- Connection reuse tracking and statistics
- Configurable pool sizing and keep-alive
- Thread-safe singleton pattern
- Automatic resource cleanup