Skip to main content
The async_fetch module provides the underlying async HTTP infrastructure for parallel data fetching. It uses niquests (a modern fork of requests) with HTTP/2 multiplexing for optimal performance.
Most users don’t need to interact with this module directly. The Session class handles async fetching automatically through methods like laps_async() and get_fastest_laps_tels_async().

Core Functions

fetch_json_async

Asynchronously fetch and parse JSON from a CDN with caching, retry logic, and validation. Parameters:
  • year: Season year (e.g., 2025)
  • gp: Grand Prix name (e.g., “Monaco”)
  • session: Session name (e.g., “Race”, “Qualifying”)
  • path: Path to JSON file (e.g., “laps.json”, “drivers.json”)
  • max_retries: Maximum retry attempts. If None, uses global config
  • timeout: Request timeout in seconds. If None, uses global config
  • use_cache: If True, read from cache before network fetch
  • write_cache: If True, persist successful responses to cache
  • validate_payload: If True, run payload validation before returning data
Returns:
  • Parsed JSON data as a dictionary (never None, raises on error)
Raises:
  • NetworkError: If network request fails after all retries
  • DataNotFoundError: If data doesn’t exist (404)
  • InvalidDataError: If JSON parsing or validation fails
Example:

fetch_multiple_async

Fetch multiple JSON files in parallel with optimized batch size and graceful error handling. Parameters:
  • requests: List of (year, gp, session, path) tuples to fetch
  • use_cache: If True, read from cache before network fetch
  • write_cache: If True, persist successful responses to cache
  • validate_payload: If True, run payload validation before returning data
  • max_retries: Maximum retry attempts per request. If None, uses global config
  • timeout: Request timeout in seconds per request. If None, uses global config
  • max_concurrent_requests: Maximum concurrent requests. If None, uses global config (default: 20)
Returns:
  • List of parsed JSON dictionaries or None for failed requests, in the same order as requests
Raises:
  • Does not raise exceptions. Failed requests return None and are logged as warnings
  • DataNotFoundError (404) is silently converted to None
Example:

fetch_with_rate_limit

Execute an async function with rate limiting using a semaphore for concurrency control. Parameters:
  • coro_func: Async function to execute
  • *args: Positional arguments for coro_func
  • semaphore: Optional semaphore for rate limiting. If None, creates one based on max_concurrent_requests config
  • **kwargs: Keyword arguments for coro_func
Returns:
  • Result from coro_func execution
Raises:
  • Any exception raised by coro_func
Example:
This is a utility function for custom concurrency control. Most users should use fetch_multiple_async() which handles rate limiting automatically.

Resource Management

cleanup_resources

Clean up all async resources including HTTP sessions, thread pools, and process pools. Call this when shutting down your application to ensure proper cleanup. Handles cleanup errors gracefully and logs failures without raising. Example:

close_session

Close the shared niquests HTTP session. The session will be recreated on next use.

close_executor

Shut down the thread pool executor used for async operations. The executor will be recreated on next use.

Performance Characteristics

The async fetch system is optimized for:
  • HTTP/2 multiplexing: Single connection for multiple requests
  • Connection pooling: Reuses connections across requests
  • Parallel JSON parsing: Offloads JSON parsing to thread pool
  • Rate limiting: Prevents overwhelming CDN with concurrent requests
  • Automatic retries: Exponential backoff with jitter
Typical performance:
  • Single lap fetch: ~50-100ms
  • 20 driver laps in parallel: ~200-300ms (vs 1-2s sequential)
  • Full session telemetry (20 drivers × 50 laps): ~10-15s (vs 50-100s sequential)

Configuration

Async fetch behavior is controlled by global configuration:

Error Handling

The async fetch system uses a hierarchy of exceptions:

Advanced Usage

Custom concurrency limits

Disable caching for fresh data

Disable validation for performance


Implementation Details

The async fetch system uses niquests with HTTP/2 support, allowing multiple requests to share a single TCP connection. This dramatically reduces latency for parallel requests.
JSON parsing is offloaded to a thread pool executor (or optional process pool for non-telemetry data) to avoid blocking the async event loop. The system uses orjson for fast parsing and can parse multiple responses in parallel. Telemetry payloads use thread-based parsing to avoid cross-process IPC overhead.
A semaphore-based rate limiter ensures no more than max_concurrent_requests requests are in flight simultaneously. This prevents overwhelming the CDN and triggering rate limits. The default is 20 concurrent requests, configurable via global config.
Failed requests are retried with exponential backoff and jitter. The backoff formula is: min(backoff_factor^attempt + random(0, jitter_max), max_delay) seconds, where defaults are backoff_factor=2.0, jitter_max=1.0, and max_delay=60.0. The system also includes circuit breaker logic to prevent cascading failures and special handling for connection pool exhaustion.
Last modified on March 4, 2026