Vehicle Telemetry GET Endpoint and Safe API Versioning

Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen

Problem Statement

Build the read-side HTTP handler for a multi-tenant commercial vehicle telematics API, and support a non-breaking migration from v1 to v2 as electric vehicles join combustion vans on the same platform.

Vehicles push sensor updates asynchronously into a metric read store (InMemoryTelemetryStore), where each vehicle's latest snapshot carries an integer sequence counter seq (1, 2, 3, ..., or 0 before the first report). Implement TelemetryApi.handle_get(path, query, headers) -> Response to serve GET /v1/vehicles/{vin}/telemetry and GET /v2/vehicles/{vin}/telemetry according to the rules below.

Routing, Authentication, and Input Validation

  • HTTP semantics & header casing: handle_get must be safe and idempotent (purely read-only, never mutating store). Incoming header names are case-insensitive.
  • Exact path matching: Only /v1/vehicles/{vin}/telemetry and /v2/vehicles/{vin}/telemetry are valid routes (the entire path string must match, with no extra segments or trailing newline). Any other path or version returns 404 (not-found).
  • Bearer authentication (checked before input validation): Callers authenticate with Authorization: Bearer <token>, where the "Bearer" scheme name is case-insensitive and <token> is a non-empty key in self.tokens (mapping each token to its fleet_id). Missing, malformed, or unrecognized credentials return 401 (unauthenticated) with header WWW-Authenticate starting with "Bearer" (for example, Bearer realm="fleet-api").
  • VIN format: Check that the raw {vin} path segment is pure ASCII before upper-casing it, then verify that the upper-cased VIN consists of 17 characters from [A-Z0-9] excluding I, O, and Q (ISO 3779). Invalid VINs return 400 (invalid-vin).
  • Unit selection: v1 always serves metric readings and ignores query parameters. v2 requires query["units"] to be either "metric" or "imperial"; missing or unsupported unit strings return 400 (invalid-units).
  • Fleet isolation and missing vehicles: Look up the upper-cased VIN via store.get_vehicle(vin). If the vehicle does not exist or belongs to a different fleet_id, return the identical 404 (vehicle-not-found) so callers cannot probe foreign VINs.
  • Datastore timeout: If store.get_vehicle, store.get_version, or store.get_snapshot raises StoreTimeout, return 503 (telemetry-unavailable) with a positive integer Retry-After header (such as "2").

Error Envelope (Problem Details)

Every 4xx or 5xx response must follow RFC 7807 / RFC 9457 Problem Details: - Headers: Content-Type: application/problem+json and Cache-Control: no-store. - Body: json { "type": "https://api.example.com/problems/<slug>", "title": "<human-readable summary>", "status": 400, "detail": "<specific explanation>", "instance": "<request path>" } where <slug> is "not-found", "unauthenticated", "invalid-vin", "invalid-units", "vehicle-not-found", or "telemetry-unavailable".

Conditional Caching (ETag and 304 Not Modified)

  • Generate a strong quoted ETag (for example, "v2-imperial-1") that varies across API version (1 vs. 2), effective unit system ("metric" vs. "imperial"), and snapshot sequence seq.
  • Query store.get_version(vin) first (0 when registered with no snapshots yet) and compare against If-None-Match using HTTP weak comparison: strip an optional case-sensitive W/ prefix on each candidate, accept comma-separated tag lists, and treat "*" as matching.
  • When If-None-Match matches, immediately return 304 with body = None, ETag, and Cache-Control: private, no-cache without calling store.get_snapshot(vin).
  • On a cache miss, call store.get_snapshot(vin) and recompute ETag from snapshot["seq"] (0 if snapshot is None) so a concurrent write between the two reads never produces a mismatched tag. Include Content-Type: application/json, ETag, Cache-Control: private, no-cache, and — whenever snapshot is not None — Last-Modified formatted as an HTTP GMT date (RFC 7231).

Response Schemas and Contract Evolution (v1 -> v2)

Timestamps use UTC ISO-8601 format "%Y-%m-%dT%H:%M:%SZ". When a registered vehicle has snapshot is None, return 200 with vin (and units in v2) populated and every telemetry reading set to None (no Last-Modified header).

  • v1 payload (legacy metric fields + additive energy_source bridge + sunset headers):
    • Fields: vin, reported_at, odometer_km, fuel_level_percent (level_percent when energy["type"] == "liquid_fuel", or None when "battery"), tire_pressures_kpa, location, and metric energy_source.
    • Every v1 response (200, 304, and 4xx/5xx on /v1/... routes) must attach:
      • Deprecation: V1_DEPRECATION ("@1796083200")
      • Sunset: V1_SUNSET ("Tue, 01 Jun 2027 00:00:00 GMT")
      • Link: includes </v2/vehicles/{raw_vin}/telemetry?units=metric>; rel="successor-version" and a rel="deprecation" link.
  • v2 payload (explicit unit tags + polymorphic energy_source, no fuel_level_percent, no deprecation headers):
    • Fields: vin, units, reported_at, odometer, energy_source, tire_pressures, location.
    • odometer: {"value": <km or mi>, "unit": "km" | "mi"}.
    • energy_source:
      • Battery EV: {"type": "battery", "state_of_charge_percent": <float>}.
      • Combustion vehicle: {"type": "liquid_fuel", "level_percent": <float>, "volume": {"value": <L or gal>, "unit": "L" | "gal"}}.
    • tire_pressures: {"unit": "kPa" | "psi", "front_left": ..., "front_right": ..., "rear_left": ..., "rear_right": ...}.
    • Convert imperial values from stored metric figures using KM_PER_MILE = 1.609344, LITERS_PER_US_GALLON = 3.785411784, and KPA_PER_PSI = 6.894757, rounding converted numbers to 1 decimal place.

Examples

Example 1

Suppose "1FLTWEST000000101" belongs to "fleet-west" (token "tok-west") with one recorded snapshot at 2026-10-14T14:20:00Z: odometer_km = 24510.8, liquid fuel level_percent = 75.0 and volume_l = 47.5, tire_pressures_kpa = {"front_left": 240.0, "front_right": 242.0, "rear_left": 236.0, "rear_right": 238.0}, and location = {"lat": 41.8781, "lon": -87.6298}.

Input:

path    = "/v2/vehicles/1FLTWEST000000101/telemetry"
query   = {"units": "imperial"}
headers = {"Authorization": "Bearer tok-west"}

Output:

status  = 200
headers = {
  "Content-Type": "application/json",
  "ETag": "\"v2-imperial-1\"",
  "Cache-Control": "private, no-cache",
  "Last-Modified": "Wed, 14 Oct 2026 14:20:00 GMT"
}
body = {
  "vin": "1FLTWEST000000101",
  "units": "imperial",
  "reported_at": "2026-10-14T14:20:00Z",
  "odometer": {"value": 15230.3, "unit": "mi"},
  "energy_source": {
    "type": "liquid_fuel",
    "level_percent": 75.0,
    "volume": {"value": 12.5, "unit": "gal"}
  },
  "tire_pressures": {
    "unit": "psi",
    "front_left": 34.8, "front_right": 35.1,
    "rear_left": 34.2,  "rear_right": 34.5
  },
  "location": {"lat": 41.8781, "lon": -87.6298}
}

Walk-through: Dividing 24510.8 / 1.609344 gives 15230.305... -> 15230.3 mi, 47.5 / 3.785411784 gives 12.548... -> 12.5 gal, and 240.0 / 6.894757 gives 34.809... -> 34.8 psi. Repeating the identical call with If-None-Match: "v2-imperial-1" returns status = 304 and body = None without calling get_snapshot.

Example 2

Suppose "1FLTWEST000000202" is a battery electric van in "fleet-west" reported at 2026-10-14T14:05:00Z with odometer_km = 18400.0 and energy = {"type": "battery", "state_of_charge_percent": 68.5}.

Input:

path    = "/v1/vehicles/1FLTWEST000000202/telemetry"
query   = {}
headers = {"Authorization": "Bearer tok-west"}

Output:

status  = 200
headers includes Deprecation="@1796083200", Sunset="Tue, 01 Jun 2027 00:00:00 GMT", Link="</v2/vehicles/1FLTWEST000000202/telemetry?units=metric>; rel=\"successor-version\", ..."
body    = {
  "vin": "1FLTWEST000000202",
  "reported_at": "2026-10-14T14:05:00Z",
  "odometer_km": 18400.0,
  "fuel_level_percent": None,
  "tire_pressures_kpa": {"front_left": 255.0, "front_right": 255.0, "rear_left": 250.0, "rear_right": 250.0},
  "location": {"lat": 47.6062, "lon": -122.3321},
  "energy_source": {"type": "battery", "state_of_charge_percent": 68.5}
}

Walk-through: Legacy v1 callers keep receiving fuel_level_percent (None because an EV has no fuel tank) alongside the additive energy_source object and RFC 8594 sunset headers.

Example 3

Input:

1) handle_get("/v2/vehicles/bad/telemetry", {"units": "metric"}, {})
2) handle_get("/v2/vehicles/1FLTWEST00000010O/telemetry", {"units": "metric"}, {"Authorization": "Bearer tok-west"})

Output:

1) status = 401, Content-Type = "application/problem+json", body["type"] ends with "/unauthenticated"
2) status = 400, Content-Type = "application/problem+json", body["type"] ends with "/invalid-vin"

Walk-through: Call 1 lacks credentials and is rejected with 401 before inspecting the malformed VIN. Call 2 authenticates cleanly and fails VIN validation with 400 because letter O is disallowed in ISO 3779 VINs.

Constraints

  • Use only the Python standard library and keep all class, method, and constant names in starter.py unchanged.
  • handle_get must execute in O(1) time and O(1) extra space per request (excluding the small header map) and must never modify self.store.
  • Snapshot tire_pressures_kpa always contains the four keys "front_left", "front_right", "rear_left", and "rear_right", and reported_at is a timezone-aware UTC datetime.

Step-by-step walkthrough

  1. Understand the resource, its clients, and the read model

    Before picking URLs or status codes, pin down what the endpoint actually reads and who calls it:

    • The resource is the latest known state of a single vehicle, stored in a fast backend read model (a database table or key-value store that keeps one latest-snapshot row per vehicle). A GET request never radios the car over the cellular network; instead, vehicles push updates asynchronously through an ingestion pipeline, and GET reads the latest saved snapshot.
    • Three client groups call this endpoint with very different upgrade speeds:
      • Mobile apps: run over lossy cellular links, poll frequently while a screen is open, and stay on old app versions for months when users delay updates.
      • External partner integrations: belong to other companies, move slowly, and require months of advance deprecation notice.
      • Internal fleet dashboards: controlled by our own team and easy to redeploy.
    • Authentication and tenant isolation: every caller presents a bearer token (an opaque credential sent in the Authorization: Bearer <token> header) mapped to one fleet. A caller may only read vehicles belonging to its own fleet.
      [Vehicle modem]
            |  periodic telemetry reports (write path)
            v
      [Ingestion service] ---> updates latest snapshot & increments seq (1, 2, 3, ...)
                                        |
                                        v
                           +----------------------------+
                           | Read Model (keyed by VIN)  |
                           |  vehicles[vin]  -> fleet   |
                           |  snapshots[vin] -> seq, .. |
                           +----------------------------+
                                        ^
                                        |  read-only lookups (GET path)
                                 [TelemetryApi]
                                        ^
                                        |  GET /v{1,2}/vehicles/{vin}/telemetry
                    [Mobile Apps / Partner Systems / Fleet Dashboards]
    
  2. Design the v1 GET contract and guarantee safety and idempotency

    In HTTP, two guarantees make GET reliable across retries, proxies, and flaky mobile networks:

    • Safe means the request is purely read-only from the client's perspective: calling it must not alter any server state that clients can observe. For example, a GET must never wake up the car's cellular modem to demand a fresh reading (which drains the vehicle's 12V battery) or increment a visible counter. Server-side access logs and metrics are fine.
    • Idempotent means sending the identical request five times in a row has the exact same effect on server state as sending it once. Every safe method is automatically idempotent. Note that idempotency is about side effects on the server, not frozen output: if the car reports a new odometer reading between two GET calls, the second call may return the newer reading and still be idempotent.

    Our v1 request and 200 OK response look like this:

    GET /v1/vehicles/1FLTWEST000000101/telemetry
    Authorization: Bearer tok-west
    Accept: application/json
    If-None-Match: "v1-metric-6"                  (optional, from an earlier poll)
    
    200 OK
    Content-Type: application/json
    ETag: "v1-metric-7"
    Last-Modified: Wed, 14 Oct 2026 14:20:00 GMT
    Cache-Control: private, no-cache
    
    {
      "vin": "1FLTWEST000000101",
      "reported_at": "2026-10-14T14:20:00Z",
      "odometer_km": 24510.8,
      "fuel_level_percent": 75.0,
      "tire_pressures_kpa": {
        "front_left": 240.0, "front_right": 242.0,
        "rear_left": 236.0,  "rear_right": 238.0
      },
      "location": {"lat": 41.8781, "lon": -87.6298},
      "energy_source": {
        "type": "liquid_fuel",
        "level_percent": 75.0,
        "volume": {"value": 47.5, "unit": "L"}
      }
    }
    

    Key design choices in v1: - The VIN (Vehicle Identification Number) sits in the URL path because it uniquely identifies the vehicle, while telemetry names the sub-resource. - reported_at records when the vehicle measured the data in UTC (ISO 8601 format ending in Z), not when our server answered, so dashboards can show "Updated 2 minutes ago". - From day one, our API documentation states that clients must ignore unknown JSON fields. That single rule lets us add new fields later without breaking existing parsers.

  3. Make polling cheap with ETags and conditional GETs

    If a mobile dashboard polls every 5 seconds while a parked car reports once every 5 minutes, 59 out of 60 polls ask for unchanged data. Reading and serializing the full telemetry row every 5 seconds wastes database I/O and cellular data. We eliminate both costs with HTTP conditional requests:

    1. ETag (entity tag): a short version stamp for a specific representation, such as "v2-imperial-7". Whenever ingestion writes a new snapshot for a vehicle, it increments an integer sequence number seq. Including the API version (v1 or v2) and unit system (metric or imperial) in the ETag is essential because switching from metric to imperial changes the JSON bytes even when seq has not changed.
    2. If-None-Match and 304 Not Modified: on the next poll, the client sends If-None-Match: "v2-imperial-7". Our handler checks store.get_version(vin) (a tiny integer counter, often cached in memory or Redis). When the tag matches, we immediately return 304 Not Modified with an empty body — without loading the full snapshot from the datastore.
    3. Cache-Control: private, no-cache: private forbids shared CDNs or corporate proxies from caching one fleet's response and accidentally serving it to another caller; no-cache instructs the client's local cache to keep the response but revalidate it via If-None-Match before reusing it.
    4. Last-Modified: formatted from reported_at when telemetry exists. Because HTTP timestamps only have 1-second resolution (two updates in the same second share one timestamp), ETag is our primary validator.

    One subtle race condition is easy to miss if get_version and get_snapshot are separate reads:

      Client (no If-None-Match)          Handler                         Ingestion
      -------------------------          -------                         ---------
      GET /v2/.../telemetry     ------>  get_version(vin) -> seq = 1
                                                                         record() -> seq = 2!
                                         get_snapshot(vin) -> seq = 2
                                <------  200 OK
                                         Body has seq 2 data (24600.0 km)
                                         ETag MUST be "v2-metric-2" (from snapshot["seq"]),
                                         NOT "v2-metric-1" (from the earlier get_version)!
    

    Always compute the 200 OK response's ETag from snapshot["seq"] inside the loaded snapshot so the tag strictly describes the body returned.

  4. Standardize errors with Problem Details and strict check ordering

    Instead of inventing ad-hoc error shapes like {"err": "..."}, we follow RFC 7807 (updated as RFC 9457, Problem Details for HTTP APIs): every error returns Content-Type: application/problem+json, Cache-Control: no-store, and five standard fields (type, title, status, detail, instance) so client code can branch reliably on the machine-readable type URI rather than parsing English text.

    Scenario                               Status  Problem type slug       Extra headers / behavior
    -------------------------------------  ------  ----------------------  ------------------------------------
    Unknown URL path or API version        404     not-found               Checked first with regex fullmatch
    Missing, malformed, or unknown token   401     unauthenticated         WWW-Authenticate: Bearer realm=...
    Malformed VIN (length, I/O/Q, Unicode) 400     invalid-vin             Checked only AFTER authentication
    v2 missing or invalid ?units=...       400     invalid-units           v1 ignores units (always metric)
    Unknown VIN, OR another fleet's VIN    404     vehicle-not-found       Identical 404 prevents VIN probing
    Vehicle registered, zero reports yet   200     (not an error)          Readings null, ETag seq=0, no Last-Modified
    Downstream telemetry store timeout     503     telemetry-unavailable   Retry-After: 2
    

    Four defensive engineering rules govern how we order and write these checks: - Authenticate before validating inputs: an unauthenticated caller gets 401 even on /v2/vehicles/bad/telemetry, learning nothing about our validation rules or which vehicles exist. - Return 404 (not 403) for another fleet's VIN: returning 403 Forbidden would confirm to a competitor that a specific 17-character VIN is registered on our platform. - Check raw_vin.isascii() before .upper(): in Python, Unicode letters like Latin small long s ("ſ") convert to ASCII "S" under .upper(), and German "ß" converts to "SS". Checking isascii() first ensures non-ASCII characters never sneak past [A-HJ-NPR-Z0-9]{17}. Similarly, re.fullmatch rejects a trailing newline \n that re.match with $ would allow. - Treat "never reported yet" as 200 OK with null readings: a newly registered truck sitting on a factory lot is a valid resource whose current telemetry state is empty, not a broken request. Returning 200 with seq = 0 lets dashboards show "Awaiting first report" and use 304 caching immediately.

  5. Evolve from v1 to v2 safely without breaking clients

    Adding electric vehicles (EVs) introduces two contract changes: replacing fuel_level_percent with a polymorphic energy_source object (an object whose fields depend on a "type" tag, either "battery" or "liquid_fuel"), and requiring a caller-chosen unit system (units=metric|imperial). Deleting a field and adding a required parameter are breaking changes, so we roll them out in three phases:

    1. Additive bridge in v1: keep fuel_level_percent (null for battery EVs) and add energy_source alongside it in v1. Older mobile clients ignore the new energy_source key, while actively maintained clients can already read EV state of charge.
    2. Launch /v2/ for breaking changes: in /v2/vehicles/{vin}/telemetry?units=metric|imperial, units is required, fuel_level_percent is removed, and every physical quantity carries its unit ({"value": 15230.3, "unit": "mi"}) instead of baking _km or _kpa into field names.
    3. Why URI path versioning (/v1/, /v2/): putting the major version in the URL path makes version traffic immediately visible in API gateway logs, monitoring dashboards, and curl tests, and URL-keyed caches keep versions apart without needing Vary: Accept headers. Both versions run inside one service against the same metric read model, differing only in their serializer function.

    During a 6-month deprecation window (2026-12-01 to 2027-06-01), every v1 response carries standard deprecation headers alongside partner emails and per-token v1 traffic dashboards:

    Deprecation: @1796083200                                      (Unix timestamp for 2026-12-01T00:00:00Z)
    Sunset: Tue, 01 Jun 2027 00:00:00 GMT                         (RFC 8594 removal date)
    Link: </v2/vehicles/{vin}/telemetry?units=metric>; rel="successor-version",
          <https://api.example.com/docs/migrate-telemetry-v1-to-v2>; rel="deprecation"
    
  6. Code the Problem Details, bearer token, and ETag helpers

    Let's start writing the clean helper functions that encapsulate HTTP formatting and header parsing: - _problem builds every error envelope identically with application/problem+json and Cache-Control: no-store. - _bearer_token splits "Authorization: Bearer <token>" case-insensitively on the scheme name while rejecting missing spaces or empty tokens like "Bearer ". - etag_matches implements HTTP weak comparison for If-None-Match: a W/ prefix on either side is ignored, * matches any representation, and comma-separated tag lists are checked item by item.

    from typing import Dict, Optional
    
    PROBLEM_BASE = "https://api.example.com/problems/"
    
    
    class Response:
        def __init__(self, status: int, headers: Dict[str, str], body: Optional[dict]):
            self.status = status
            self.headers = headers
            self.body = body
    
    
    def _problem(status: int, slug: str, title: str, detail: str, instance: str) -> Response:
        """Build an RFC 7807 / RFC 9457 Problem Details error response."""
        body = {
            "type": PROBLEM_BASE + slug,
            "title": title,
            "status": status,
            "detail": detail,
            "instance": instance,
        }
        # Error responses use application/problem+json and must not be cached.
        headers = {
            "Content-Type": "application/problem+json",
            "Cache-Control": "no-store",
        }
        return Response(status, headers, body)
    
    
    def _bearer_token(headers: Dict[str, str]) -> Optional[str]:
        """Extract the token from 'Authorization: Bearer <token>' (case-insensitive scheme)."""
        auth_value = headers.get("authorization", "").strip()
        scheme, separator, raw_token = auth_value.partition(" ")
        # Require an explicit space and a non-empty token so bare "Bearer" is rejected.
        if scheme.lower() != "bearer" or separator == "":
            return None
        token = raw_token.strip()
        if not token:
            return None
        return token
    
    
    def make_etag(api_version: int, units: str, seq: int) -> str:
        """Build a strong quoted ETag specific to (api_version, units, seq)."""
        # Including api_version and units prevents a cached metric ETag from matching an imperial request.
        return f'"v{api_version}-{units}-{seq}"'
    
    
    def _strip_weak_prefix(tag: str) -> str:
        """Strip the case-sensitive HTTP weak validator prefix 'W/' if present."""
        if tag.startswith("W/"):
            return tag[2:]
        return tag
    
    
    def etag_matches(if_none_match: Optional[str], current_etag: str) -> bool:
        """Evaluate If-None-Match using HTTP weak comparison rules."""
        if if_none_match is None:
            return False
        if if_none_match.strip() == "*":
            return True
        target = _strip_weak_prefix(current_etag)
        # Clients may send a comma-separated list of cached ETags, e.g. '"old", W/"v2-metric-3"'.
        for raw_candidate in if_none_match.split(","):
            candidate = _strip_weak_prefix(raw_candidate.strip())
            if candidate == target:
                return True
        return False
    
  7. Code the v1 and v2 representation serializers

    Our datastore keeps every physical measurement once in metric units (km, L, kPa) so ingestion never worries about display preferences. Supporting v1 and v2 in parallel only requires two pure serializer functions (body_v1 and body_v2).

    For imperial requests in v2, we divide by the exact conversion factor (1.609344 km/mi, 3.785411784 L/gal, 6.894757 kPa/psi) and round to 1 decimal place: - Odometer: 24510.8 / 1.609344 = 15230.305... -> 15230.3 mi - Tank volume: 47.5 / 3.785411784 = 12.548... -> 12.5 gal - Front-left tire: 240.0 / 6.894757 = 34.809... -> 34.8 psi

    from typing import Optional
    
    KM_PER_MILE = 1.609344
    KPA_PER_PSI = 6.894757
    LITERS_PER_US_GALLON = 3.785411784
    
    
    def _measure(
        value_metric: float,
        units: str,
        metric_unit: str,
        imperial_unit: str,
        per_imperial: float,
    ) -> dict:
        """Format a metric reading as {'value': ..., 'unit': ...} in metric or imperial units."""
        if units == "metric":
            return {"value": value_metric, "unit": metric_unit}
        # Convert from stored metric units on the fly and round imperial output to 1 decimal place.
        converted_value = round(value_metric / per_imperial, 1)
        return {"value": converted_value, "unit": imperial_unit}
    
    
    def _energy_source(energy: dict, units: str) -> dict:
        """Build the polymorphic energy_source object using 'type' as the discriminator."""
        if energy["type"] == "battery":
            return {
                "type": "battery",
                "state_of_charge_percent": energy["state_of_charge_percent"],
            }
        return {
            "type": "liquid_fuel",
            "level_percent": energy["level_percent"],
            "volume": _measure(energy["volume_l"], units, "L", "gal", LITERS_PER_US_GALLON),
        }
    
    
    def body_v1(vin: str, snapshot: Optional[dict]) -> dict:
        """Serialize v1: legacy metric fields plus the additive energy_source field."""
        if snapshot is None:
            return {
                "vin": vin,
                "reported_at": None,
                "odometer_km": None,
                "fuel_level_percent": None,
                "tire_pressures_kpa": None,
                "location": None,
                "energy_source": None,
            }
    
        energy = snapshot["energy"]
        # Battery EVs have no liquid fuel tank, so legacy fuel_level_percent is null while energy_source carries SoC.
        if energy["type"] == "liquid_fuel":
            fuel_level = energy["level_percent"]
        else:
            fuel_level = None
    
        return {
            "vin": vin,
            "reported_at": snapshot["reported_at"].strftime("%Y-%m-%dT%H:%M:%SZ"),
            "odometer_km": snapshot["odometer_km"],
            "fuel_level_percent": fuel_level,
            "tire_pressures_kpa": dict(snapshot["tire_pressures_kpa"]),
            "location": dict(snapshot["location"]),
            "energy_source": _energy_source(energy, "metric"),
        }
    
    
    def body_v2(vin: str, snapshot: Optional[dict], units: str) -> dict:
        """Serialize v2: unit-tagged measurements and polymorphic energy_source (no fuel_level_percent)."""
        if snapshot is None:
            return {
                "vin": vin,
                "units": units,
                "reported_at": None,
                "odometer": None,
                "energy_source": None,
                "tire_pressures": None,
                "location": None,
            }
    
        if units == "metric":
            tire_unit = "kPa"
        else:
            tire_unit = "psi"
    
        tires: dict = {"unit": tire_unit}
        for wheel, pressure_kpa in snapshot["tire_pressures_kpa"].items():
            if units == "metric":
                tires[wheel] = pressure_kpa
            else:
                tires[wheel] = round(pressure_kpa / KPA_PER_PSI, 1)
    
        return {
            "vin": vin,
            "units": units,
            "reported_at": snapshot["reported_at"].strftime("%Y-%m-%dT%H:%M:%SZ"),
            "odometer": _measure(snapshot["odometer_km"], units, "km", "mi", KM_PER_MILE),
            "energy_source": _energy_source(snapshot["energy"], units),
            "tire_pressures": tires,
            "location": dict(snapshot["location"]),
        }
    
  8. Code the TelemetryApi handler and trace a polling session

    TelemetryApi.handle_get enforces the exact validation order: route match -> header normalization -> bearer authentication -> ASCII VIN check -> v2 units check -> datastore lookup (wrapped in try ... except StoreTimeout) -> If-None-Match short-circuit -> snapshot serialization. Attaching the v1 deprecation headers at the end of handle_get guarantees every v1 response (200, 304, or 4xx/5xx) announces the sunset schedule.

    Let's trace four requests for 1FLTWEST000000101 (seq = 1, 24510.8 km):

    Poll 1: GET /v2/vehicles/1FLTWEST000000101/telemetry?units=imperial
            -> No If-None-Match. Loads snapshot (seq=1).
            -> Returns 200 OK, odometer 15230.3 mi, ETag: "v2-imperial-1" (snapshot_reads = 1).
    
    Poll 2: GET /v2/vehicles/1FLTWEST000000101/telemetry?units=imperial
            Header: If-None-Match: "v2-imperial-1"
            -> get_version() returns 1 -> current_etag == "v2-imperial-1" -> match!
            -> Returns 304 Not Modified, body=None (snapshot_reads still 1!).
    
    Update: Vehicle reports odometer_km = 24525.0 -> ingestion sets seq = 2.
    
    Poll 3: GET /v2/vehicles/1FLTWEST000000101/telemetry?units=imperial
            Header: If-None-Match: "v2-imperial-1"
            -> get_version() returns 2 -> "v2-imperial-2" != "v2-imperial-1" -> cache miss.
            -> Loads snapshot (seq=2), returns 200 OK with ETag: "v2-imperial-2".
    
    Legacy: Old mobile app calls GET /v1/vehicles/1FLTWEST000000101/telemetry
            -> Returns 200 OK with odometer_km=24525.0, fuel_level_percent=75.0, energy_source,
               plus Deprecation, Sunset, and Link headers pointing to /v2/.
    
  9. Complete solution

    Putting the store, Problem Details helpers, representations, and TelemetryApi handler together gives the complete implementation:

    from typing import Dict, Optional
    from email.utils import format_datetime
    import re
    
    # A standard 17-character VIN uses digits and capital ASCII letters except I, O, and Q
    # (excluded by ISO 3779 because they look like 1 and 0).
    VIN_PATTERN = re.compile(r"[A-HJ-NPR-Z0-9]{17}")
    PATH_PATTERN = re.compile(r"/v([12])/vehicles/([^/]+)/telemetry")
    PROBLEM_BASE = "https://api.example.com/problems/"
    
    KM_PER_MILE = 1.609344
    KPA_PER_PSI = 6.894757
    LITERS_PER_US_GALLON = 3.785411784
    
    # v1 is deprecated starting 2026-12-01T00:00:00Z and removed on 2027-06-01T00:00:00Z.
    V1_DEPRECATION = "@1796083200"
    V1_SUNSET = "Tue, 01 Jun 2027 00:00:00 GMT"
    V1_MIGRATION_DOC = "https://api.example.com/docs/migrate-telemetry-v1-to-v2"
    
    
    class StoreTimeout(Exception):
        """The telemetry datastore did not answer in time."""
    
    
    class InMemoryTelemetryStore:
        """Read model: one latest snapshot per vehicle. Readings are stored in metric units.
    
        A snapshot looks like {"seq": 3, "reported_at": datetime (UTC), "odometer_km": 48211.3,
        "energy": {"type": "liquid_fuel", "level_percent": 62.5, "volume_l": 31.3}
               or {"type": "battery", "state_of_charge_percent": 80.0},
        "tire_pressures_kpa": {"front_left": 230.0, ...}, "location": {"lat": ..., "lon": ...}}.
        """
    
        def __init__(self):
            # vehicles: maps VIN -> {"fleet_id": "fleet-a"}
            self.vehicles: Dict[str, dict] = {}
            # snapshots: maps VIN -> latest metric telemetry dict including monotonic int "seq"
            self.snapshots: Dict[str, dict] = {}
    
        def add_vehicle(self, vin: str, fleet_id: str) -> None:
            self.vehicles[vin] = {"fleet_id": fleet_id}
    
        def record(self, vin: str, snapshot: dict) -> None:
            """The ingestion write path (never called by GET). Bumps the version number."""
            old = self.snapshots.get(vin)
            stored = dict(snapshot)
            if old is None:
                stored["seq"] = 1
            else:
                stored["seq"] = old["seq"] + 1
            self.snapshots[vin] = stored
    
        def get_vehicle(self, vin: str) -> Optional[dict]:
            return self.vehicles.get(vin)
    
        def get_version(self, vin: str) -> int:
            """Cheap lookup of the latest seq (0 = nothing reported yet)."""
            snapshot = self.snapshots.get(vin)
            if snapshot is None:
                return 0
            return snapshot["seq"]
    
        def get_snapshot(self, vin: str) -> Optional[dict]:
            return self.snapshots.get(vin)
    
    
    class Response:
        def __init__(self, status: int, headers: Dict[str, str], body: Optional[dict]):
            self.status = status
            self.headers = headers
            self.body = body
    
    
    def _problem(status: int, slug: str, title: str, detail: str, instance: str) -> Response:
        """Build an RFC 7807 / RFC 9457 Problem Details error response."""
        body = {
            "type": PROBLEM_BASE + slug,
            "title": title,
            "status": status,
            "detail": detail,
            "instance": instance,
        }
        # Error responses use application/problem+json and must not be cached.
        headers = {
            "Content-Type": "application/problem+json",
            "Cache-Control": "no-store",
        }
        return Response(status, headers, body)
    
    
    def _bearer_token(headers: Dict[str, str]) -> Optional[str]:
        """Extract the token from 'Authorization: Bearer <token>' (case-insensitive scheme)."""
        auth_value = headers.get("authorization", "").strip()
        scheme, separator, raw_token = auth_value.partition(" ")
        # Require an explicit space and a non-empty token so bare "Bearer" is rejected.
        if scheme.lower() != "bearer" or separator == "":
            return None
        token = raw_token.strip()
        if not token:
            return None
        return token
    
    
    def make_etag(api_version: int, units: str, seq: int) -> str:
        """Build a strong quoted ETag specific to (api_version, units, seq)."""
        # Including api_version and units prevents a cached metric ETag from matching an imperial request.
        return f'"v{api_version}-{units}-{seq}"'
    
    
    def _strip_weak_prefix(tag: str) -> str:
        """Strip the case-sensitive HTTP weak validator prefix 'W/' if present."""
        if tag.startswith("W/"):
            return tag[2:]
        return tag
    
    
    def etag_matches(if_none_match: Optional[str], current_etag: str) -> bool:
        """Evaluate If-None-Match using HTTP weak comparison rules."""
        if if_none_match is None:
            return False
        if if_none_match.strip() == "*":
            return True
        target = _strip_weak_prefix(current_etag)
        # Clients may send a comma-separated list of cached ETags, e.g. '"old", W/"v2-metric-3"'.
        for raw_candidate in if_none_match.split(","):
            candidate = _strip_weak_prefix(raw_candidate.strip())
            if candidate == target:
                return True
        return False
    
    
    def _measure(
        value_metric: float,
        units: str,
        metric_unit: str,
        imperial_unit: str,
        per_imperial: float,
    ) -> dict:
        """Format a metric reading as {'value': ..., 'unit': ...} in metric or imperial units."""
        if units == "metric":
            return {"value": value_metric, "unit": metric_unit}
        # Convert from stored metric units on the fly and round imperial output to 1 decimal place.
        converted_value = round(value_metric / per_imperial, 1)
        return {"value": converted_value, "unit": imperial_unit}
    
    
    def _energy_source(energy: dict, units: str) -> dict:
        """Build the polymorphic energy_source object using 'type' as the discriminator."""
        if energy["type"] == "battery":
            return {
                "type": "battery",
                "state_of_charge_percent": energy["state_of_charge_percent"],
            }
        return {
            "type": "liquid_fuel",
            "level_percent": energy["level_percent"],
            "volume": _measure(energy["volume_l"], units, "L", "gal", LITERS_PER_US_GALLON),
        }
    
    
    def body_v1(vin: str, snapshot: Optional[dict]) -> dict:
        """Serialize v1: legacy metric fields plus the additive energy_source field."""
        if snapshot is None:
            return {
                "vin": vin,
                "reported_at": None,
                "odometer_km": None,
                "fuel_level_percent": None,
                "tire_pressures_kpa": None,
                "location": None,
                "energy_source": None,
            }
    
        energy = snapshot["energy"]
        # Battery EVs have no liquid fuel tank, so legacy fuel_level_percent is null while energy_source carries SoC.
        if energy["type"] == "liquid_fuel":
            fuel_level = energy["level_percent"]
        else:
            fuel_level = None
    
        return {
            "vin": vin,
            "reported_at": snapshot["reported_at"].strftime("%Y-%m-%dT%H:%M:%SZ"),
            "odometer_km": snapshot["odometer_km"],
            "fuel_level_percent": fuel_level,
            "tire_pressures_kpa": dict(snapshot["tire_pressures_kpa"]),
            "location": dict(snapshot["location"]),
            "energy_source": _energy_source(energy, "metric"),
        }
    
    
    def body_v2(vin: str, snapshot: Optional[dict], units: str) -> dict:
        """Serialize v2: unit-tagged measurements and polymorphic energy_source (no fuel_level_percent)."""
        if snapshot is None:
            return {
                "vin": vin,
                "units": units,
                "reported_at": None,
                "odometer": None,
                "energy_source": None,
                "tire_pressures": None,
                "location": None,
            }
    
        if units == "metric":
            tire_unit = "kPa"
        else:
            tire_unit = "psi"
    
        tires: dict = {"unit": tire_unit}
        for wheel, pressure_kpa in snapshot["tire_pressures_kpa"].items():
            if units == "metric":
                tires[wheel] = pressure_kpa
            else:
                tires[wheel] = round(pressure_kpa / KPA_PER_PSI, 1)
    
        return {
            "vin": vin,
            "units": units,
            "reported_at": snapshot["reported_at"].strftime("%Y-%m-%dT%H:%M:%SZ"),
            "odometer": _measure(snapshot["odometer_km"], units, "km", "mi", KM_PER_MILE),
            "energy_source": _energy_source(snapshot["energy"], units),
            "tire_pressures": tires,
            "location": dict(snapshot["location"]),
        }
    
    
    class TelemetryApi:
        """GET /v{1,2}/vehicles/{vin}/telemetry. tokens maps a bearer token to the caller's fleet id."""
    
        def __init__(self, store, tokens: Dict[str, str]):
            self.store = store
            self.tokens = tokens
    
        def handle_get(self, path: str, query: Dict[str, str], headers: Dict[str, str]) -> Response:
            """Read-only GET handler: never mutates server state (safe and idempotent)."""
            # Phase 1: Match the entire URL path; fullmatch rejects trailing newlines or extra segments.
            match = PATH_PATTERN.fullmatch(path)
            if match is None:
                return _problem(404, "not-found", "Not Found", "no such resource", path)
    
            api_version = int(match.group(1))
            raw_vin = match.group(2)
            response = self._get(api_version, raw_vin, path, query, headers)
    
            # Phase 9: Attach sunset and migration headers to every v1 response (200, 304, and errors).
            if api_version == 1:
                response.headers["Deprecation"] = V1_DEPRECATION
                response.headers["Sunset"] = V1_SUNSET
                successor = path.replace("/v1/", "/v2/", 1) + "?units=metric"
                response.headers["Link"] = (
                    f'<{successor}>; rel="successor-version", '
                    f'<{V1_MIGRATION_DOC}>; rel="deprecation"'
                )
            return response
    
        def _get(
            self,
            api_version: int,
            raw_vin: str,
            path: str,
            query: Dict[str, str],
            headers: Dict[str, str],
        ) -> Response:
            # Phase 2: Normalize request header names to lowercase because HTTP header names are case-insensitive.
            normalized_headers: Dict[str, str] = {}
            for name, value in headers.items():
                normalized_headers[name.lower()] = value
    
            # Phase 3: Authenticate before validating inputs so anonymous callers cannot probe VINs.
            token = _bearer_token(normalized_headers)
            if token is None or token not in self.tokens:
                response = _problem(
                    401,
                    "unauthenticated",
                    "Unauthenticated",
                    "send a valid bearer token",
                    path,
                )
                response.headers["WWW-Authenticate"] = 'Bearer realm="fleet-api"'
                return response
            fleet_id = self.tokens[token]
    
            # Phase 4: Check isascii() BEFORE upper(), because Unicode letters like 'ſ' upper-case to 'S'.
            vin = raw_vin.upper()
            if not raw_vin.isascii() or VIN_PATTERN.fullmatch(vin) is None:
                return _problem(
                    400,
                    "invalid-vin",
                    "Invalid VIN",
                    "a VIN has 17 characters: digits and letters except I, O and Q",
                    path,
                )
    
            # Phase 5: v1 is always metric; v2 requires an explicit 'units' query parameter.
            units = "metric"
            if api_version == 2:
                units = query.get("units", "")
                if units not in ("metric", "imperial"):
                    return _problem(
                        400,
                        "invalid-units",
                        "Invalid units",
                        "query parameter units must be 'metric' or 'imperial'",
                        path,
                    )
    
            # Phase 6: Read vehicle metadata and handle conditional caching, catching datastore timeouts.
            try:
                vehicle = self.store.get_vehicle(vin)
                # Return the exact same 404 for another fleet's vehicle so callers cannot enumerate foreign VINs.
                if vehicle is None or vehicle["fleet_id"] != fleet_id:
                    return _problem(
                        404,
                        "vehicle-not-found",
                        "Vehicle not found",
                        f"no vehicle {vin} in your fleet",
                        path,
                    )
    
                # Phase 7: Check the cheap version counter first so a 304 skips loading the full snapshot.
                current_etag = make_etag(api_version, units, self.store.get_version(vin))
                if etag_matches(normalized_headers.get("if-none-match"), current_etag):
                    return Response(
                        304,
                        {"ETag": current_etag, "Cache-Control": "private, no-cache"},
                        None,
                    )
    
                # Phase 8: Cache miss — load the full telemetry snapshot.
                snapshot = self.store.get_snapshot(vin)
            except StoreTimeout:
                response = _problem(
                    503,
                    "telemetry-unavailable",
                    "Telemetry temporarily unavailable",
                    "the telemetry store did not answer in time; retry shortly",
                    path,
                )
                response.headers["Retry-After"] = "2"
                return response
    
            # Recompute ETag from snapshot["seq"] so a report arriving between get_version and get_snapshot stays consistent.
            if snapshot is None:
                snapshot_seq = 0
            else:
                snapshot_seq = snapshot["seq"]
    
            response_headers = {
                "Content-Type": "application/json",
                "ETag": make_etag(api_version, units, snapshot_seq),
                "Cache-Control": "private, no-cache",
            }
            if snapshot is not None:
                response_headers["Last-Modified"] = format_datetime(
                    snapshot["reported_at"], usegmt=True
                )
    
            if api_version == 1:
                body = body_v1(vin, snapshot)
            else:
                body = body_v2(vin, snapshot, units)
            return Response(200, response_headers, body)
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of this API like a dispatch status board hanging in a fleet garage. Trucks radio their latest mileage and fuel or battery readings to a clerk who updates each truck's card on the board and stamps a sequence number (#1, #2, #3) in the corner. When a mobile app or dispatcher checks a truck (GET), they only read the card on the board — they never radio the truck directly — making the read both safe (it changes no observable state on the server or vehicle) and idempotent (repeating the identical read has the same server-side effect as doing it once). Better yet, a dispatcher who remembers "last time I saw stamp #3 in miles" can ask "did anything change since v2-imperial-3?" using an ETag (a short version identifier attached to a specific HTTP response) and receive an instant "no change" nod (304 Not Modified) without the clerk opening the truck's full file.

A naive implementation fails on three fronts at production scale. First, querying the vehicle live on GET drains its battery and violates HTTP safety, while reading and serializing the full database record on every 5-second poll wastes most database I/O on unchanged vehicles. Second, returning unstructured errors or validating inputs before checking credentials lets anonymous callers probe which VINs exist. Third, deleting fuel_level_percent or making units mandatory inside v1 immediately crashes older mobile app versions still running on drivers' phones.

Here is how our single metric read model and dual v1/v2 serializers handle four requests for vehicle 1FLTWEST000000101 (stored once at seq = 1, 24510.8 km, 47.5 L fuel): 1. First v2 poll (?units=imperial): no If-None-Match header is sent, so the handler loads snapshot seq = 1, converts 24510.8 km to 15230.3 mi and 47.5 L to 12.5 gal, and returns 200 OK with ETag: "v2-imperial-1". 2. Five seconds later (If-None-Match: "v2-imperial-1"): the handler checks the lightweight version counter (seq = 1), sees "v2-imperial-1" matches, and returns 304 Not Modified with no body and zero full snapshot reads. 3. Van reports 24525.0 km (seq becomes 2): the next poll sends "v2-imperial-1", sees a mismatch against "v2-imperial-2", loads the new snapshot, and returns 200 OK with ETag: "v2-imperial-2". 4. Legacy v1 mobile client polls /v1/...: the same handler formats the metric v1 payload (including both legacy fuel_level_percent and the additive polymorphic energy_source object whose structure switches on a "type" field) and attaches Deprecation, Sunset, and Link headers guiding developers to v2.

Complexity

  • Time: O(1) per request. Routing uses a fixed-length regular expression, header normalization loops over the small set of HTTP request headers H, authentication and store lookups (get_vehicle, get_version, get_snapshot) are O(1) dictionary/key lookups by token or 17-character VIN, and serialization formats a fixed number of telemetry fields (O(1)). On a 304 Not Modified hit, snapshot loading and JSON serialization are skipped completely.
  • Space: O(1) per request (plus O(H) for normalized request headers), because the handler builds one small fixed-schema response dictionary and stores zero state between requests. In the backing store, memory grows linearly as O(V) with the number of registered vehicles V because only the single latest snapshot per vehicle is retained.

Edge cases

  • VIN validation traps: VINs of 16 or 18 characters, containing I, O, or Q, containing punctuation, ending in a newline \n, or containing Unicode lookalikes ("ſ".upper() == "S", "ß".upper() == "SS") all return 400 (invalid-vin), while valid lowercase ASCII VINs are upper-cased and accepted.
  • Case-insensitive HTTP headers and auth scheme: header names like if-none-match or AUTHORIZATION and scheme casing like bearer tok-west work identically, while empty tokens ("Bearer" or "Bearer ") return 401 with WWW-Authenticate.
  • Weak and multi-value If-None-Match: weak tags (W/"v2-metric-1"), comma-separated tag lists ("old", "v2-metric-1"), and wildcard * all trigger 304 Not Modified.
  • Registered vehicle with zero telemetry reports: returns 200 OK with null reading fields, ETag at seq = 0, and no Last-Modified header, so 304 polling works even before a new vehicle's first trip.
  • Battery EV on legacy v1: fuel_level_percent is null rather than a fake 0 or 68.5, while the additive energy_source field carries {"type": "battery", "state_of_charge_percent": 68.5}.
  • Cross-fleet VIN probing: requesting a valid VIN owned by another fleet returns the exact same 404 (vehicle-not-found) as an unknown VIN, never 403.
  • Concurrent write between version check and snapshot read: recomputing the 200 OK response's ETag from snapshot["seq"] guarantees the returned tag always matches the returned body.

Common mistakes

  • Computing ETag by hashing the serialized JSON body: hashing saves cellular bandwidth on a 304, but the server still had to query the database and serialize the JSON on every 5-second poll. Using a lightweight seq counter saves both bandwidth and database reads.
  • Sharing one ETag across versions or unit systems: if "seq-1" were used everywhere, a client switching from ?units=metric to ?units=imperial would receive 304 Not Modified and display kilometers labeled as miles.
  • Returning Cache-Control: public on authenticated fleet data: a shared proxy or CDN could serve Fleet A's vehicle location to Fleet B. Always mark token-scoped responses private (and errors no-store).
  • Validating the VIN before authenticating: returning 400 on bad VINs and 401 on valid-looking VINs leaks input rules and lets unauthenticated scripts probe endpoints.
  • Using re.match with ^...$ instead of re.fullmatch: in Python regexes, $ matches immediately before a trailing \n, letting "1FLTWEST000000101\n" slip past validation.
  • Breaking v1 in place: removing fuel_level_percent or requiring ?units= on /v1/ breaks deployed mobile apps that cannot be updated overnight.

Alternative approaches

  • Media-type content negotiation (Accept: application/vnd.fleet.telemetry.v2+json): keeps a single URL /vehicles/{vin}/telemetry across versions, which aligns strictly with classic REST theory, at the cost of requiring Vary: Accept on every cache, hiding versions from URL access logs, and needing a fallback version when Accept is omitted.
  • Short freshness window (Cache-Control: private, max-age=5): when vehicles report at most every 30 seconds, allowing clients to reuse a response locally for 5 seconds eliminates even the 304 round-trip, trading up to 5 seconds of extra client-side staleness for lower request rate.
  • 404 with a distinct telemetry-not-reported Problem Details type: defensible if clients prefer treating "never reported" as an error branch, provided it uses a distinct type URI from vehicle-not-found.

Follow-up questions

  • How would you add sparse field selection (such as ?fields=odometer,location) so mobile callers transfer fewer bytes without corrupting cached ETags? Validate the comma-separated field names against an explicit allowlist per API version (returning 400 on unknown names so client typos fail loudly rather than silently dropping fields), while always keeping core identifiers vin and reported_at. Because ?fields=... changes the serialized JSON bytes, canonicalize the requested subset (sort and deduplicate names, e.g., location,odometer) and include that canonical string inside make_etag so partial and full payloads never collide on 304. Over mobile networks, enabling HTTP compression (Content-Encoding: gzip or br) often trims more bytes than field filtering on small payloads, so combine both.
  • Suppose tens of thousands of open dashboards refresh every 5 seconds; how do conditional requests and tiered rate limits keep the datastore healthy? Conditional requests absorb most database reads first: if vehicles report every 30 seconds, 5 out of 6 refreshes match the in-memory seq counter and return 304 without touching the snapshot table (turning 20,000 requests/sec from 100,000 active screens into roughly 3,300 snapshot reads/sec). At the API gateway, enforce two token-bucket rate limits (a counter that refills steadily up to a burst ceiling, rejecting excess calls with 429 Too Many Requests and a Retry-After header): a tight limit per (token, vin) (such as 1 req/sec sustained, burst 5) to block runaway retry loops targeting a single vehicle, plus a broader fleet-wide quota per token scaled to fleet size. Longer term, migrate live dispatch screens from tight polling to server push via Server-Sent Events (SSE) (a one-way HTTP stream pushing updates as they arrive) or WebSockets.
  • If vehicles publish raw sensor packets into an append-only stream such as Kafka, how would you project and maintain the per-vehicle snapshot store? Partition the ingestion topic by vin so every packet for a given vehicle lands in order at one stream consumer, which upserts a single latest-snapshot row per vin in a low-latency key-value store. To guard against duplicate or out-of-order cellular packets, compare incoming reported_at (or modem sequence numbers) against the stored record and increment seq only when stored readings actually advance — otherwise duplicate deliveries would bump ETag and force every poller to re-download identical JSON. Track consumer lag (how far behind the log head the projector is) as your staleness metric, and enable log compaction (retaining at least the latest record per key) so the snapshot store can be rebuilt rapidly if lost.

Follow-up questions

Similar questions

More Generalmotors interview questions

All 5 Generalmotors questions →