Caching & monitoring

Error handling and 422 codes: Error handling. Platform HTTP errors and retries: Error Handling.

Data freshness

Both ML endpoints return deterministic estimates for a given input set. Results are stable over timescales of days to weeks — the model is retrained periodically, not in real time.

EndpointRecommended TTLCache keyNotes
GET /ml/flight-time24 hoursflighttime:{from}:{to}:{aircraft}Route statistics change rarely; 24 h is safe for most use cases
GET /carbon/estimate1–24 hourscarbon:{dep}:{arr}:{passengers}:{rfi}Shorter TTL if passengers or RFI flag changes frequently in your UI

Route statistics are derived from historical operational data. A 24-hour TTL for flight time is appropriate because block-time norms for a given city pair and aircraft type change only when airlines adjust schedules seasonally.

ML disclosure: Present estimates as historical averages, not real-time forecasts. For flight time, wind and live routing are not modelled. For carbon, estimates follow ICAO Doc 9988 methodology; when include_rfi=true, the figure includes Radiative Forcing Index (~2× base CO₂) and must be disclosed in passenger-facing copy.

import os
import time
import requests

HEADERS = {
    "X-RapidAPI-Key": os.getenv("RAPIDAPI_KEY", "YOUR_RAPIDAPI_KEY"),
    "X-RapidAPI-Host": "skylink-api.p.rapidapi.com",
}
BASE = "https://skylink-api.p.rapidapi.com"

_cache: dict[str, tuple[dict, float]] = {}


def _cached_get(url: str, params: dict, ttl_seconds: int) -> dict | None:
    """In-process TTL cache. Replace with Redis for multi-instance deployments."""
    key = url + str(sorted(params.items()))
    cached = _cache.get(key)
    if cached and time.time() < cached[1]:
        return cached[0]

    r = requests.get(url, headers=HEADERS, params=params, timeout=(10, 15))
    if r.status_code == 404:
        return None
    r.raise_for_status()
    data = r.json()
    _cache[key] = (data, time.time() + ttl_seconds)
    return data


def get_flight_time(
    origin: str, destination: str, aircraft: str | None = None
) -> dict | None:
    """Cached ML flight time estimate. TTL 24 hours."""
    params: dict[str, str] = {"from": origin, "to": destination}
    if aircraft:
        params["aircraft"] = aircraft
    return _cached_get(f"{BASE}/ml/flight-time", params, ttl_seconds=86400)


def get_carbon(
    departure_icao: str,
    arrival_icao: str,
    passengers: int = 1,
    include_rfi: bool = False,
) -> dict | None:
    """Cached carbon estimate. TTL 1 hour (adjust to 24 h for stable routes)."""
    params: dict[str, str | int] = {
        "departure_icao": departure_icao,
        "arrival_icao": arrival_icao,
        "passengers": passengers,
        "include_rfi": str(include_rfi).lower(),
    }
    return _cached_get(f"{BASE}/carbon/estimate", params, ttl_seconds=3600)


if __name__ == "__main__":
    data = get_flight_time("KJFK", "KLAX", aircraft="B738")
    if data:
        print(
            f"Estimated: {data['estimated_hours_display']}  "
            f"(range {data['min_minutes']}–{data['max_minutes']} min)"
        )
        print("Statistical average — wind not modelled.")

    data2 = get_flight_time("KJFK", "KLAX", aircraft="B738")
    print("Cache hit:", data2 is not None)

Rate limits

Every response includes rate limit headers. Monitor X-RateLimit-Requests-Remaining across both endpoints combined — each call to /ml/flight-time and /carbon/estimate counts toward your monthly quota.

HeaderValue
X-RateLimit-Requests-LimitYour plan's monthly request quota
X-RateLimit-Requests-RemainingRequests left this month
X-RateLimit-Requests-ResetSeconds until the quota resets

A 24-hour TTL for flight time reduces ML endpoint calls to one per route per day — important when quota is shared across all API endpoints.

Monitoring

Log on every ML request:

  • endpoint (flight-time or carbon)
  • status_code
  • elapsed_ms
  • quota_remaining (from X-RateLimit-Requests-Remaining)
  • cache_hit (boolean — did the response come from cache?)

Alert on:

  • status = 429 — reduce polling frequency or extend TTLs
  • elapsed_ms > 5000 repeatedly — consider a shorter timeout with a graceful fallback
  • quota_remaining < 200 — approaching monthly limit; extend TTLs or reduce unique route calls

Related: Flight Time · Carbon Emissions · Error handling · Error Handling