End-to-End Reliability Loop for Fleet Telemetry Ingestion

Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen

Prompt

You own production reliability and release engineering for an always-on connected-fleet ingestion tier. Connected cars stream continuous status packets (GPS coordinates, battery state of charge, fault codes) into your service, which validates each payload's schema, queries a separate vehicle-attributes service for enrichment fields, and commits the resulting record into a primary operational store.

Without coordinated safeguards, either a struggling enrichment service or a buggy code push can stall worker pools, drop incoming vehicle packets, and flood on-call engineers with redundant pages. Design one cohesive production architecture that ties together downstream fault isolation, symptom-driven observability, rollback-safe database evolution, and automated progressive delivery.

Scope & Expectations

  • Downstream fault isolation & circuit breaking: Define timeouts, retry limits, and the exact Closed, Open, and Half-Open state machine (trip conditions, cool-down windows, probe rules, HTTP status handling, and degraded-mode fallback behavior) protecting calls to the vehicle-attributes service.
  • SLIs, SLOs, and low-noise alerting: Specify 2–3 concrete Service Level Indicators and rolling objectives for the pipeline, clearly distinguishing urgent user-impacting conditions that page an engineer from diagnostic signals routed to tickets or dashboards.
  • Rollback-safe database evolution: Walk through how multi-step expand-and-contract migrations decouple table changes from application binaries so rolling back code never corrupts stored rows or breaks live queries.
  • Progressive CI/CD & automated rollback gates: Outline a canary or blue/green deployment pipeline specifying concrete metric comparisons against a fair control baseline and the exact triggers that automatically halt and revert a bad rollout before full promotion.

Step-by-step walkthrough

  1. Frame the architecture and its core durability rule

    Start by sketching the path each vehicle event takes and stating the one invariant the system must never violate:

    vehicles --HTTPS--> load balancer --> ingestion service --+--> primary datastore
                                             |  1. validate   |
                                             |  2. enrich ----+--> metadata service (external)
                                             |                |
                                             +--> enrichment-retry queue --> backfill worker
                                             +--> dead-letter queue (schema-invalid events)
    
    • The core rule — zero lost accepted events: Metadata enrichment (looking up vehicle trim, fleet owner, or firmware) is helpful context, whereas saving telemetry is mission-critical. If the metadata microservice slows down or crashes, enrichment may be delayed, but ingestion must never block or drop valid events.
    • Concrete baseline assumptions: When healthy, the metadata service answers with median (p50) latency 8 ms and 99th-percentile (p99) latency 40 ms. Vehicle metadata changes rarely, and vehicles buffer events locally and retry on transient network errors, sending a unique event_id per event so our datastore performs an idempotent write (saving the same event_id twice produces only one stored row). Malformed payloads go to a dead-letter queue (DLQ) (a quarantine queue for invalid payloads so engineers can inspect bad firmware formats without blocking valid traffic).
  2. Layer timeouts, bounded retries, bulkheads, and caching before the breaker

    A circuit breaker is the last line of defense against a failing dependency; four lightweight guards protect threads and latency on every call first:

    1. Timeouts: Enforce a 50 ms TCP connect timeout, a 100 ms per-attempt read timeout (2.5x the healthy 40 ms p99, cutting off hung sockets so threads never stall indefinitely), and a 250 ms total enrichment budget.
    2. Bounded retries with jitter: Retry at most once after 20–50 ms of jitter (a small random delay so thousands of callers do not retry on the exact same millisecond), only on connection errors or HTTP 502 / 503 / 504, and only while a retry budget (capping retries at <= 10% of total metadata calls per pod) allows it. Without a retry budget, a struggling dependency gets hit with 2x load right as it is failing.
    3. Bulkhead isolation: Limit each ingestion pod to at most 64 concurrent metadata calls — a bulkhead (a concurrency cap named after watertight ship compartments so one slow dependency cannot flood every worker thread). By Little's Law (in_flight = arrival_rate * latency), 1,000 calls/s takes 10 concurrent slots at 10 ms latency, jumping to 100 slots at 100 ms timeouts; calls beyond 64 skip straight to fallback.
    4. VIN cache with stale fallback: Keep an in-memory LRU cache (evicting least-recently-used entries when full) keyed by vehicle VIN with a 10-minute TTL (time-to-live, jittered +/- 20%), retaining expired entries up to 24 hours for emergency stale reads, plus request coalescing (sharing one in-flight lookup if ten events from the same VIN arrive simultaneously).

    Classify HTTP responses carefully: 5xx, 429 Too Many Requests, and timeouts count as downstream failures; 404 Not Found ("unknown VIN") is a valid business response cached briefly as a negative entry; 400 Bad Request means our client code sent a malformed request and triggers a bug alert rather than tripping the circuit breaker.

  3. Specify the circuit breaker states, thresholds, and fallback path

    A circuit breaker is a state machine modeled after an electrical breaker that automatically stops calling a broken service so both sides stay alive:

                >= 50% failures across >= 20 calls in 10 s
      CLOSED ------------------------------------------------> OPEN
        ^                                                        |  fail fast for 30 s (+ 0..5 s jitter)
        |  5 of 5 probes succeed                                 v
        +--------------------------------------------------- HALF-OPEN
             any probe fails -> back to OPEN, cool-down doubles (30 -> 60 -> 120 s, capped at 300 s)
    
    • Closed (normal): Calls proceed normally; outcomes are tracked in a 10-second sliding window per pod. Requiring at least 20 calls prevents 1–2 unlucky errors at 3 AM from tripping the breaker.
    • Open (tripped): Calls fail fast in memory (0 ms network wait) and jump straight to fallback for 30 s plus 0–5 s random jitter, giving the metadata service breathing room to recover.
    • Half-Open (probing): Exactly 5 probe calls are allowed through while all other traffic continues using the fallback. If all 5 succeed, reset cool-down to 30 s and return to Closed; if any probe fails, return immediately to Open with doubled cool-down (up to 300 s).

    Fallback behavior (whenever Open, bulkhead-rejected, or timed out): 1. If a stale VIN entry (<= 24 h old) exists in cache, attach it with enrichment_status = "stale" and record its age. 2. Otherwise write the validated raw event to the primary datastore with enrichment_status = "pending" and enqueue (event_id, vin) onto the enrichment-retry queue for a rate-limited background backfill worker. 3. Return 202 Accepted to the vehicle once the primary datastore write commits (202 rather than 201 communicates "durably accepted, background enrichment may still be pending"); return 400 on schema failure (copied to DLQ), 429 with Retry-After on per-VIN abuse, and 503 with Retry-After only if the primary datastore itself cannot persist the event.

    import random
    import time
    from collections import deque
    
    
    class CircuitBreaker:
        """Per-pod sliding-window circuit breaker (caller synchronizes if shared across threads)."""
    
        def __init__(self, clock=time.monotonic, window_s=10.0, min_calls=20, failure_rate=0.5,
                     cooldown_s=30.0, max_cooldown_s=300.0, probes=5):
            self.clock = clock
            self.window_s = window_s
            self.min_calls = min_calls
            self.failure_rate = failure_rate
            self.base_cooldown_s = cooldown_s
            self.cooldown_s = cooldown_s
            self.max_cooldown_s = max_cooldown_s
            self.probes = probes
            self.state = "closed"
            self.calls = deque()  # deque of (timestamp, succeeded_bool) inside the 10s window
            self.open_until = 0.0
            self.probes_started = 0
            self.probes_ok = 0
    
        def allow(self) -> bool:
            """Return True to call metadata service, or False to jump straight to fallback."""
            if self.state == "open":
                if self.clock() < self.open_until:
                    return False
                self.state = "half_open"
                self.probes_started = 0
                self.probes_ok = 0
            if self.state == "half_open":
                if self.probes_started >= self.probes:
                    return False
                self.probes_started += 1
            return True
    
        def record(self, ok: bool) -> None:
            """Record whether an allowed call succeeded (`False` on timeout, 5xx, or 429)."""
            now = self.clock()
            if self.state == "open":
                return
            if self.state == "half_open":
                if not ok:
                    self._open(now, min(self.cooldown_s * 2, self.max_cooldown_s))
                    return
                self.probes_ok += 1
                if self.probes_ok == self.probes:
                    self.state = "closed"
                    self.calls.clear()
                    self.cooldown_s = self.base_cooldown_s
                return
            self.calls.append((now, ok))
            while self.calls[0][0] < now - self.window_s:
                self.calls.popleft()
            failures = sum(1 for _, good in self.calls if not good)
            if len(self.calls) >= self.min_calls and failures >= self.failure_rate * len(self.calls):
                self._open(now, self.cooldown_s)
    
        def _open(self, now: float, cooldown_s: float) -> None:
            self.state = "open"
            self.cooldown_s = cooldown_s
            # Add 0..5s jitter so fleet pods do not enter Half-Open on the exact same instant
            self.open_until = now + cooldown_s + random.uniform(0, 5)
            self.calls.clear()
    
  4. Define SLIs, SLOs, and burn-rate paging vs ticket diagnostics

    An SLI (Service Level Indicator) measures user-visible health as good_events / valid_events, and an SLO (Service Level Objective) sets the target percentage over a rolling 30-day window:

    SLI                       Definition of a "good event"                                 30-day SLO
    1. Ingestion availability Valid non-4xx telemetry request answered 2xx within 1,000 ms  99.9%
    2. End-to-end freshness   Accepted event queryable in the primary read store <= 30 s    99.5%
    3. Enrichment completion  Accepted event has fresh/backfilled metadata within 15 min    99.0%
    

    Measure availability at the load balancer (capturing crashes where ingestion pods cannot emit metrics), measure freshness both per event (visible_at - accepted_at) and via a synthetic canary vehicle sending one probe every 10 s, and run a 1-minute reconciliation check verifying every 202 event_id exists in storage.

    A 99.9% 30-day SLO grants an error budget (allowed failure allowance) of 0.1% = 43.2 minutes (30 * 24 * 60 * 0.001). Alert on multi-window burn rate (how fast the error budget is being consumed relative to a 1x steady pace; 14.4x on 99.9% means an error rate >= 1.44%):

    Severity   Burn rate   Long window   Short window   30-day budget spent
    PAGE       14.4x       1 hour        5 min          2% in 1 hour
    PAGE       6.0x        6 hours       30 min         5% in 6 hours
    TICKET     1.0x        3 days        6 hours        10% in 3 days
    
    • High-severity PAGE (wakes an engineer — user-visible harm happening now): Fast burn (14.4x or 6x) on Ingestion Availability or Freshness, any 202-vs-stored data-loss mismatch across 2 consecutive minutes, or 3 consecutive failed synthetic probes (> 60 s, catching silent blackholes during low night traffic). Requiring both long and short windows to exceed the threshold makes pages fire quickly and auto-resolve within minutes of recovery.
    • Low-severity TICKET or dashboard (causes and early warnings — zero alert fatigue): Circuit breaker Open while Availability and 15-minute Enrichment SLOs remain green (the fallback is working as designed!), enrichment-retry queue depth trending upward, VIN cache hit rate dropping, single-pod restarts, CPU > 80%, or DLQ spikes isolated to one vehicle firmware version.
  5. Decouple database changes with expand and contract

    To make code rollbacks instant and safe, follow expand and contract (a multi-phase migration pattern where every code release is compatible with both the database schema before it and the schema right after it, and migrations never ship bundled inside the same artifact as code that depends on them).

    Concrete trace for migrating odometer_miles (NOT NULL) to odometer_km:

    Phase  Change shipped                                          Safe to roll code back one step?
    E1     Expand DB: ADD COLUMN odometer_km DOUBLE PRECISION NULL Yes — current code ignores new NULL column
    R1     Deploy v1: dual-write miles & km; still read miles      Yes — v0 still reads/writes miles
    B      Backfill: batch-update NULL odometer_km rows            Idempotent (`WHERE odometer_km IS NULL`)
    R2     Deploy v2: read km (fallback to miles); dual-write both Yes — v1 still finds miles written by v2!
    E2     Expand DB: ALTER COLUMN odometer_miles DROP NOT NULL    Yes — allows omitting miles next
    R3     Deploy v3: read km and write ONLY km                    Yes to v2 (reads km); never jump back to v1
    C1     Contract DB (days later): snapshot + DROP odometer_miles One-way cleanup after v3 is proven stable
    

    Operational database safeguards (e.g., PostgreSQL): run CREATE INDEX CONCURRENTLY so index builds never block telemetry writes, set SET lock_timeout = '2s' with retry loops on ALTER TABLE statements (otherwise an ALTER waiting behind one slow analytics query blocks every subsequent read and write in a lock queue), throttle backfills to 10,000-row primary-key batches while watching replication lag, and never run destructive DROP down-migrations inside automated rollbacks.

  6. Wire CI/CD, matched-baseline canary gates, and automated rollback

    git merge
      -> CI: unit tests + metadata contract tests + migration linter (blocks DROP/RENAME with code)
             + build immutable container image tagged by commit SHA + security scan
      -> Staging: deploy image + integration suite + replay 1 hour of anonymized vehicle traffic
      -> Prod Expand Job: apply additive schema migration (if any) before touching app pods
      -> Canary 5% (30 min): spin up 5% new pods AND a fresh 5% baseline on the current version
      -> Canary 25% (30 min): repeat automated metric comparison
      -> Prod 100%: shift full traffic; keep warm old-version pods at 0% traffic for 1 hour
    

    Always compare the 5% canary against a same-age 5% baseline spun up at the exact same moment on the old version: comparing against the existing 95% fleet is unfair because old pods have warm VIN caches and pooled connections, and checking global metrics dilutes a 10% canary failure down to a tiny 0.5 percentage point (pp) (5% * 10%) blip. Evaluate 1-minute buckets (>= 500 requests/min):

    Canary vs Matched Baseline Metric            Automated Action Trigger
    HTTP 5xx error rate                          (canary - baseline) > 0.5 pp AND > 2x baseline for 3 min -> ABORT
    Ingestion p95 / p99 latency                  canary > 1.2x baseline AND > baseline + 20 ms for 3 min -> ABORT
    Schema 400 / DLQ reject rate                 canary > baseline + 0.1 pp for 3 min (bad schema rule)  -> ABORT
    Metadata fallback rate or breaker state      canary breaker Open while baseline Closed, or +1.0 pp 3m -> ABORT
    Datastore write errors / reconciliation gap  any excess over baseline in 1 min                        -> ABORT NOW
    Pod crash-loops / OOM (out-of-memory) kills  any occurrence                                           -> ABORT NOW
    CPU or RSS memory per request                > 1.25x baseline                                         -> HOLD & alert
    

    When an abort triggers, the controller shifts canary traffic weight to 0% in seconds, quarantines one canary pod off-traffic with heap/logs preserved for debugging, marks the commit SHA failed so CI/CD cannot re-promote it, and creates an engineering ticket (paging only if an SLO actually burned). Because only expand migrations ran beforehand, zero database rollback is needed.

  7. Trace how all four pieces work together during a bad deploy

    Walk through a realistic failure to see why these four layers form one closed loop:

    1. The bug: An engineer accidentally changes the metadata client timeout from 100 ms to 30 ms. CI and staging pass because the lightly loaded staging metadata service responds in 8 ms.
    2. Resilience holds the line at 5% canary: Production metadata has a healthy p99 of 40 ms, so the slowest 3% of uncached metadata calls on the canary now time out at 30 ms. Instead of failing vehicle requests, those 3% hit the VIN stale cache or enqueue to enrichment-retry, returning 202 Accepted with zero lost events. The circuit breaker stays Closed (3% < 50%), which is right because the metadata service itself is healthy.
    3. Canary gate catches what global metrics miss: Globally, 3% of 5% traffic is just 0.15 pp — invisible on a fleet-wide graph. Comparing the canary directly against the matched 5% baseline immediately flags a +3.0 pp fallback-rate delta (> +1.0 pp threshold) for 3 consecutive minutes and drains canary traffic back to 0%.
    4. Calm monitoring + clean rollback: Because Availability (99.9%) and 15-minute Enrichment (99.0%) never breached their burn-rate budgets, nobody gets paged at 2 AM — a ticket opens with the canary diff report while the backfill worker drains the tiny retry queue, and the old release keeps running cleanly over the expand-only database schema.

Intuition & how it works

Picture a vehicle telematics ingestion pipeline like an emergency-room triage desk (ingestion service) that checks a patient's ID band (schema validation), calls a records clerk down the hall for non-urgent background info (metadata microservice), and saves the chart (primary datastore). Even if the records clerk's phone line dies or a newly deployed triage script has a bug, you never lose an arriving patient's chart: a circuit breaker (an automatic safety switch modeled after an electrical breaker) cuts off calls to a failing dependency and falls back to cached records or a background retry queue, SLI/SLO monitoring (measuring user-visible success rates against an allowed error budget) pages humans only when real symptoms degrade, expand and contract database migrations keep old and new code working side by side, and an automated canary deployment tests every new build on a 5% slice of live traffic against a matched baseline before full rollout.

Without this integrated loop, naive designs fail catastrophically: calling the metadata service synchronously with long timeouts and unbounded retries lets one slow downstream pod tie up every ingestion thread, trigger a retry storm, drop vehicle events, and fire dozens of noisy alerts at once. Worse, bundling a DROP or RENAME COLUMN database migration inside the same deployment artifact makes rolling back a faulty release impossible because the previous code crashes against the altered table.

Trace a concrete 4-step example when a faulty build lowers the metadata timeout from 100 ms to 30 ms (while healthy metadata p99 latency is 40 ms): 1. Canary traffic (5%, say 1,000 events/min): Roughly 3% (30 calls/min) of metadata lookups take 31–40 ms and time out on the canary. 2. Fallback prevents data loss: Instead of returning 500 to vehicles, the ingestion pod serves stale cached VIN metadata or writes enrichment_status = "pending" to the primary datastore, pushes those 30 IDs onto the retry queue, and returns 202 Accepted. The circuit breaker stays Closed (3% failures is well below its 50% trip threshold). 3. Matched-baseline check catches the regression: Across the whole fleet, 3% of 5% is a tiny 0.15 percentage point (pp) (arithmetic difference between percentages) shift, which global alerts would miss. Comparing the 5% canary against a same-age 5% baseline immediately detects a +3.0 pp jump in metadata fallback rate (> +1.0 pp gate for 3 consecutive minutes). 4. Zero-downtime rollback: Traffic shifts back to 0% canary in seconds with no human page (no user-facing SLO burned) and zero database rollback (only additive expand migrations ran before code deploy).

Key points

  • Durability before enrichment: Accepted telemetry is never dropped; when metadata degrades, serve stale VIN cache (<= 24 h) or commit enrichment_status = "pending" (202 Accepted) and backfill asynchronously.
  • Defense in depth on downstream calls: Combine a 100 ms per-attempt timeout, at most 1 jittered retry capped by a 10% retry budget, a 64-call per-pod bulkhead concurrency cap, and an in-memory LRU cache (10 min jittered TTL + request coalescing) in front of the circuit breaker (Closed -> Open at >= 50% failures over >= 20 calls in 10 s, 30 s jittered cool-down with exponential backoff up to 300 s, 5/5 successful Half-Open probes to close).
  • Response classification: Count timeouts, 5xx, and 429 as dependency failures; cache 404 briefly as "unknown VIN"; alert on 400 as a caller bug without tripping the breaker.
  • Symptom-based SLOs and multi-window burn rates: Track Availability (99.9% <= 1 s), Read Freshness (99.5% <= 30 s), Enrichment Completeness (99.0% <= 15 min), and 1-minute 202-vs-stored reconciliation. Page on fast burn rates (14.4x over 1h/5m, 6x over 6h/30m); route component causes (like an open breaker while SLOs hold) to tickets.
  • Expand-and-contract migrations: Ship additive schema changes (ADD COLUMN NULL, CREATE INDEX CONCURRENTLY with lock_timeout) as a separate pre-deploy step, transition through dual-write and backfill releases so every version rolls back cleanly by one step, and run destructive DROP COLUMN steps days later.
  • Canary verification against a same-age baseline: Compare 5% canary pods against fresh 5% baseline pods (fair cache warmth, zero 20x dilution), aborting after 3 consecutive bad 1-minute intervals on error/latency/fallback/DLQ deltas and immediately on crashes or data-loss signals.

Common mistakes

  • Missing timeouts or unbounded retries: Allows one slow downstream service to exhaust all ingestion worker threads and multiply traffic onto a struggling dependency.
  • Misconfigured circuit breakers: Tripping on client 400/404 responses, omitting a minimum-call threshold (so 1 failure out of 2 quiet-hour calls opens the breaker), or omitting cool-down jitter (so every pod probes simultaneously).
  • Failing vehicle ingestion when optional enrichment fails: Returning 5xx or dropping telemetry instead of persisting raw events and backfilling metadata asynchronously.
  • Paging on internal causes instead of user-facing SLO burn: Waking on-call engineers for transient CPU spikes, single pod restarts, or an open circuit breaker whose fallback is keeping all SLOs green.
  • Coupling destructive schema changes with code deploys: Renaming or dropping columns in the same release as application code so rolling back the binary immediately triggers SQL errors.
  • Evaluating canaries against fleet-wide averages: At 5% traffic weight, even a 10% error rate on the canary raises global errors by just 0.5 pp, hiding broken builds inside normal traffic noise.

Follow-up questions

  • Once a tripped circuit breaker probes healthy and closes again, how do you prevent expired caches and queued retries from overwhelming the recovered dependency? Right when the breaker closes, thousands of VIN cache entries whose 10-minute TTLs expired during the outage look expired across every pod at once — risking a cache stampede (a sudden wall of simultaneous cache-miss lookups) on top of the enrichment-retry backlog draining into the newly recovered metadata service. Prevent re-tripping the breaker in three ways: ramp live cache-miss traffic gradually over 60 s (10% -> 100%, serving stale cache for the remainder), use per-VIN request coalescing plus +/- 20% TTL jitter so expirations spread out, and throttle the backfill worker with a token bucket (a rate limiter that dispenses a fixed number of call permits per second, e.g., <= 15–20% of metadata capacity) that automatically pauses whenever any breaker reopens.
  • Suppose a canary build maintains clean error and latency numbers over a 30-minute bake, yet consumes 15% more RAM than control pods—what automated rules decide between promoting and rolling back? Evaluate the memory slope after initial cache warm-up rather than the static 15% offset alone, because a legitimate new cache plateaus whereas a memory leak climbs steadily toward an OOM kill (when the operating system forcibly terminates a container that exceeds its RAM limit). Fit a linear trend over minutes 15..30 on both canary and matched baseline: abort automatically if any OOM kill occurs, GC p99 pause exceeds 1.5x baseline, or projected time to hit 90% of the container limit is under 24 hours (for example, in a 2 GiB container, 1.15 GiB growing at 5 MiB/min hits 1.8 GiB in (1.8 - 1.15) * 1024 / 5 ≈ 133 minutes -> abort). Proceed with an extended 2-hour bake at 25% if the slope has flattened (~0 MiB/min delta vs baseline) and steady-state RSS sits safely below 70% of the container limit.
  • How must your rollback playbook change when the service is a stateful event-stream consumer rather than a stateless synchronous HTTP tier? Rolling back stateless HTTP pods is a near-instant load-balancer weight shift, whereas rolling back Kafka workers triggers a partition rebalance (reassigning topic partitions across consumer instances; use cooperative sticky rebalancing so unaffected partitions do not pause) and does not undo offsets already committed by the faulty build. To recover bad writes, stop or roll back the consumer group, rewind committed offsets to the pre-deploy timestamp (--reset-offsets --to-datetime), and replay events through idempotent event_id upserts (or isolate canaries first using a shadow consumer group writing to a shadow table). Furthermore, any messages the canary emitted to downstream topics stay permanently in the log, so message schemas in your schema registry must follow backward/forward compatibility (expand and contract for events) so rolled-back consumers can still deserialize them.

Follow-up questions

Similar questions

More Generalmotors interview questions

All 5 Generalmotors questions →