Skip to main content

Overview

The http_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
Without proper connection management, each request would incur:
  • 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
The http_session module eliminates most of this overhead through connection reuse, achieving 80-95% connection reuse rates in typical workloads. This translates to 5-10x faster data loading compared to naive HTTP implementations.

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

Retrieve or create the shared HTTP session using a thread-safe singleton pattern. This function implements double-checked locking to ensure only one session instance exists across all threads while minimizing lock contention. Thread Safety: The function uses a module-level lock (_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:
  1. First call creates the session with optimized settings
  2. Subsequent calls return the cached instance
  3. Session persists until process exit or explicit close_session() call
  4. Automatic cleanup registered via atexit handler
Returns:
  • 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_env for predictable behavior
Implementation Details: The session is configured with:
  • HTTPAdapter mounted on https:// with custom pool settings
  • Connection pooling: pool_connections and pool_maxsize dynamically calculated
  • Keep-alive headers: Connection: keep-alive with 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
Performance Characteristics:
  • 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
Example:
Advanced Usage:
This is an internal API. Most users don’t need to interact with the HTTP session directly. The library handles all HTTP requests automatically through Session.load() and related methods.
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

Close the shared HTTP session and cleanup resources. Called automatically on exit. Example:

Connection Statistics

get_connection_stats

Get current connection pool statistics for monitoring and debugging. Returns:
  • Dictionary with connection metrics:
    • total_requests: Total number of requests made
    • connections_reused: Number of requests that reused connections
    • connections_created: Number of connection pools created
    • reuse_rate: Percentage of requests that reused connections (0-100)
Example:

reset_connection_stats

Reset connection statistics. Useful for testing or benchmarking. Example:

Configuration

The HTTP session is configured via the global config object. Key settings: Example:

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:
  1. Standard DNS
  2. Cloudflare DoH (doh://cloudflare)
  3. Google DoH (doh://google)
Custom resolvers:

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
Performance benefits:
  • Eliminates TCP handshake overhead
  • Reduces TLS negotiation time
  • Improves throughput for parallel requests
  • Lowers latency for sequential requests
Example monitoring:

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

  1. Don’t create multiple sessions: Use the shared session for all requests
  2. Monitor connection stats: Track reuse rate to optimize performance
  3. Tune pool size: Match pool size to your concurrency needs
  4. Use DoH in restrictive networks: Configure DoH resolvers for reliability
  5. Enable HTTP/2 carefully: Test thoroughly before enabling multiplexing
  6. 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
This infrastructure enables high-performance data fetching with minimal latency.
Last modified on May 8, 2026