AI System DesignData and Feature InfrastructureModule 02 — Data and feature infrastructure

Integrating Unreliable Third-Party Data into Latency-Sensitive AI Prediction Systems

Question 38 of 47 · Updated

On this page

Keep unreliable external data off the critical prediction path wherever the business contract permits. Acquire and validate provider observations asynchronously, cache them with their real observation times and explicit validity, isolate provider failures and quotas, and bind each prediction to an approved feature-availability profile. For a request that genuinely needs a live fetch, enforce one end-to-end deadline and reserve time for inference and response. Fail over only to a semantically compatible and authorized source with available capacity. If admissible external evidence is missing, use a separately validated degraded model or abstain; do not fabricate a feature or disguise stale evidence as fresh.

How would you integrate unreliable third-party data providers into a latency-sensitive prediction system?

ASD-015 | Module 02 — Data and feature infrastructure | Learning order 25. Existing RAG deadline/partial-result, LLM retry-storm/circuit-breaker and MLOps feature-freshness lessons establish bounded waiting, retry control and feature-age semantics. Generic API integration and connector-reliability lessons address transport and ownership. Here the architectural objective is external-data dependency isolation coupled to *prediction eligibility*: provider-specific evidence semantics, acquisition versus serving, compatible substitution, availability-dependent model selection and outcome-quality monitoring during outages. ASD-009 covers shared ingestion, ASD-010 snapshot disagreement and ASD-014 model-feature contract coexistence. This design reuses those principles without rebuilding a generic feature store or teaching circuit breakers in isolation. All figures and provider contracts below are hypothetical; the Python fixture was actually executed locally.

1. Begin with the prediction's dependency requirements#

Imagine a delivery ETA and delay-risk service with a 150 ms response objective. Internal data includes order status, road graph, courier position and recent travel history. External vendors provide traffic observations and weather. One vendor occasionally takes several seconds, another has narrow coverage and a strict quota, and both may use a common upstream traffic feed. The service must respond quickly without presenting an estimate based on unsupported or misleading data.

The interview question is not simply how to make HTTP calls reliable. A provider can return HTTP 200 with an old measurement, wrong location, changed units or a missing coverage area. A transport-successful call can still produce invalid model input. Conversely a vendor outage need not prevent every prediction.

Classify each dependency by target, decision purpose and region:

DependencyExampleMissing-data policy
Mandatory authoritative evidenceCurrent road closure eligibility for an actual route commitmentHold the affected action; an ETA model is not proof of route permission
Mandatory for full model onlyCurrent compatible traffic delay featureUse approved local-only model or abstain
Optional under trained contractWeather category with trained unknown representationMark missing explicitly and use the supported profile
Slowly changing enrichmentRoad classificationUse authorized cached evidence within approved age/validity
Unapproved or unsupportedProvider covers only highways but request concerns a local roadDo not use the response for that target

A dependency can be required for one prediction and optional for another. Never decide criticality from the order in which responses arrive. Distinguish prediction availability from business action eligibility: a degraded ETA may be useful for display while route dispatch still needs an independent current closure check. Conversely a product may choose to abstain entirely when that mandatory check is missing.

Define latency percentiles and deadline misses on all eligible requests, full-feature coverage, permitted degraded coverage, abstention rate, valid evidence freshness, prediction error by actual model/profile, and cost per useful prediction. A fast controlled abstention is a useful safety behavior but is not a successful full prediction. Establish acceptable output quality and failure responses with the product and model owners before designing failover.

2. Provider-specific evidence contracts#

Register each provider with its supported product, geography, endpoint, account/quota scope, transport/schema version, business definition and security requirements. A canonical observation envelope should preserve the origin instead of flattening all provider responses into an anonymous number.

Contract fieldWhy it matters
Provider and upstream lineageDiagnose correlated outages and actual evidence source
Entity, tenant/purpose and geographic mappingPrevent wrong-road or unauthorized evidence substitution
Quantity, unit, resolution and methodologyA speed average differs from a delay estimate
Event/observation time and received timeSeparate actual age from cache write time
Source sequence/revision and validity intervalReject superseded, future or expired observations
Coverage and quality statusDistinguish unavailable areas from real zero measurements
Canonical definition and adapter releaseBind the transformation used by inference
License, permitted purpose and retentionDo not cache, redisclose or train on data without authorization
Quota, burst and request-cost semanticsControl offered load and spend

For example, provider A reports incremental delay minutes for a named road segment over a specified window. Provider B reports average speed in km/h for a larger road region. It is not enough to multiply or divide until the units match: a delay relative to free-flow requires appropriate distance and baseline speed, and a regional average may not represent the named segment. Only an explicitly evaluated adapter and coverage mapping can establish compatibility. If the secondary provider cannot supply the intended feature, choose another model profile instead of silently substituting its response.

Illustrative normalized observation (not an official schema):

JSON
{ "provider": "traffic-A", "provider_contract": "segment-delay/v3", "canonical_feature": "delay_minutes_5m/v1", "scope": "authorized-region/segment-71", "source_revision": "observation-927", "observed_at": "2026-01-15T10:00:00Z", "received_at": "2026-01-15T10:00:04Z", "valid_until": "2026-01-15T10:01:00Z", "value": 8, "unit": "minute", "coverage": "approved-segment", "adapter_release": "traffic-adapter/r5", "evidence_ref": "restricted-observation-artifact" }

Validate response status, schema, numeric bounds, identity, units, timestamps, coverage, source revision and integrity. A successful response with an invalid timestamp is an invalid observation, not a fresh feature. Keep missing, denied, throttled, timed out, unsupported, malformed, stale and legitimately zero as different states. Raw vendor evidence and feature values are separate artifacts. If a provider changes semantics without updating its schema, freeze the affected adapter/generation until independently reviewed.

3. Architecture: split acquisition from prediction#

Loading diagram…

The acquisition plane runs asynchronous prefetch, subscriptions or scheduled refreshes, provider-specific throttling and validation. The online inference plane reads authorized local and external observations from a nearby store, evaluates their eligibility, and selects a pinned model/profile. A bounded on-demand request may be permitted on a cache miss, but it must not be the default for hot keys with predictable refresh needs. Its budget includes queueing, connection setup, response body limits, parsing, validation and cancellation.

Use separate worker pools, queues and connection budgets for providers and refresh versus foreground work. A stalled weather endpoint must not consume every connection available to traffic or local feature reads. A bounded queue is important: an isolated pool with an unbounded backlog can still consume memory and make all queued work expire. Implement concurrency limits as well as rate limits; one call/s can still create many outstanding calls if each takes a minute. Release local resources on cancellation, and distinguish local cancellation from actual remote cancellation.

Ownership is explicit: provider adapter owner maintains native contract; data owner approves feature semantics, mappings and validity; model owner approves each availability profile; reliability owner controls capacity and incident response; governance owner decides allowed data use. The product decision owner maintains mandatory constraints and approved failure behavior. A central gateway is not a universal permission to combine all providers' data.

4. Asynchronous prefetching and caching: availability is not freshness#

For spatial traffic data, many requests concern the same active road segments. Maintain a hot-key refresh plan driven by authorized demand, provider update cadence, feature sensitivity and quota. Prefer a provider-supported bulk or push feed where it meets the same coverage and evidence contract. Prewarm active regions, coalesce concurrent refreshes for the same scoped key, jitter schedules, and bound cold-key admission.

Cache keys need tenant or lawful sharing scope, geographic/subject identity, provider and canonical definition, adapter version and other validity context. A cross-tenant shared cache is only appropriate for data that can genuinely be shared under the contract; a public-looking road identifier is not sufficient proof. Isolate credentials and purpose. Cache actual observation, source revision, time observed, time received, expiry, source lineage and validation status.

Separate cache eviction TTL from evidence eligibility. Eviction is a storage policy. Prediction validity is a semantic policy. For a simple age-bound feature, effective expiry is the earliest of provider validity end, observation time plus maximum feature age, explicit withdrawal and any other applicable eligibility constraint. A newly written cache entry can already be stale. An HTTP Age or Cache-Control field can help HTTP cache behavior, but does not prove business observation freshness. A 304 response or a successful re-fetch must not reset the event age unless the source contract actually establishes a newer verified observation.

Suppose an observation is made at 10:00:00, received at 10:00:12 and provider-valid until 10:02:00. The full model allows 60 seconds from observation time. At 10:00:59 the age is 59 seconds; at 10:01:01 it is 61 seconds and invalid for that profile, even if the cache retains it for five minutes. Use a documented inclusive or exclusive boundary. A degraded profile that tolerates age up to 120 seconds needs its own approval and must still obey provider expiry, revocation, licensing and mandatory policy. A grace period is a model/policy property, not a cache workaround.

Negative caching can prevent repeated misses for known unsupported regions or short-lived upstream failures. Use distinct short-lived negative states: timeout is not a proof of no traffic; denied is not a public absence result. Do not use a negative cache to bypass a current permission check. Refresh failures should preserve the previous observation for authorized diagnostic use but must not extend its eligibility.

Refresh capacity worked example#

Assume 12,000 active segment keys refreshed every 30 seconds. With no batching this is 400 requests/s, impossible under an illustrative quota of 120/s. If an approved bulk endpoint returns up to 20 segments per call, ideal offered load is 20 calls/s for full batches. Allow capacity for sparse batches, retries, high-priority refreshes, cold keys and quota sharing; verify whether the provider bills or limits by HTTP request, segment, returned observation or another unit. Batching does not reduce a per-segment quota. Also confirm the provider itself updates often enough; a faster refresh loop cannot make its source observations newer.

Suppose only 3,000 keys are active frequently and a smaller 30-second refresh tier is enough. Single-key polling would be 100/s, leaving only 20/s nominal capacity, before retries. An unbounded request-triggered refresh can exhaust that margin. Use explicit quota reservation and skip low-value refreshes where the model contract supports it. These are hypothetical demand calculations rather than measured vendor limits.

5. End-to-end deadlines and bounded on-demand fetching#

The deadline belongs to the logical prediction request. Do not give each provider a new 150 ms timeout independently. Use a monotonic clock for elapsed time and propagate a remaining-time context through remote calls. Business observation timestamps require a trustworthy wall-clock/event-time policy; do not subtract a provider UTC timestamp from a local monotonic clock.

Illustrative serial budget for a 150 ms objective:

StageAllocated maximum
Ingress/authentication and routing10 ms
Parallel local feature reads and cached observation resolution20 ms
Optional bounded external recovery path40 ms
Validate and assemble vector10 ms
Model execution35 ms
Serialize and return15 ms
Contingency20 ms
Total150 ms

These are engineering allocations, not measured p99s. Parallel stage duration depends on the slowest needed task; adding individual stage p99s does not generally compute end-to-end p99. Measure the actual distribution under representative concurrency and provider failures. A request already late at ingress may skip the optional external recovery path. If an external response arrives too late for the full model but the degraded path can still meet its deadline, use the latter only if approved for the case. If neither can finish within the remaining envelope, return a controlled timeout/abstention rather than launch useless work.

For an optional live fetch at elapsed 30 ms, 120 ms remain. If downstream reserve is 80 ms and provider cap is 40 ms, the fetch may consume at most 40 ms. After 25 ms spent on a failed first attempt, only 15 ms of that external window remains; a second attempt with a 20 ms minimum useful budget should not start. Include retry backoff, connection acquisition and validation in the same budget. Do not merely set a socket read timeout, because DNS/connect/TLS/queue phases can consume the remainder.

Loading diagram…

A response arriving after the request's cutoff cannot alter that already selected prediction. It may populate the authorized cache for future requests if still valid and not superseded, using correct source-revision fencing. Do not let a delayed failure or stale observation overwrite a newer valid cache entry. A historical correction should create new evidence and explicitly affect future or corrected-analysis predictions rather than rewriting original prediction lineage.

6. Provider isolation, circuit breaking, retries and quota control#

These mechanisms have different purposes:

ControlScope and action
DeadlineLimit logical request and child work
BulkheadIsolate connection, worker and queue resources
Rate limiterAdmit requests/units according to upstream quota and cost
Circuit breakerSuppress calls to an unhealthy dependency temporarily
Retry budgetBound repeat attempts across all layers
CoalescingShare identical authorized in-flight refresh work
Load sheddingRefuse optional work before saturation harms prediction

A breaker should be scoped to the actual failure domain, such as provider endpoint, product, region and account/quota partition where relevant. A quota failure for one account is not necessarily a global vendor outage. A transport breaker should distinguish timeout and server overload from invalid credentials or an unsupported request. A separate semantic health gate can withdraw data when values, schema or coverage become unreliable even though transport remains healthy.

Loading diagram…

Use bounded half-open probes and gradual recovery, not a simultaneous retry from every replica. A provider is not ready simply because a health endpoint responded once. Verify representative actual requests, schema validity, observation freshness and required region coverage. A contract invalidation requires appropriate owner approval, not merely elapsed cooldown. If the cache remains eligible while the breaker is open, continue using it within the approved evidence contract.

A single designated layer owns retries and includes hidden SDK retries in its accounting. Retry only failures plausibly transient and repeatable under the provider's semantics. Honor a valid Retry-After hint when applicable; if it exceeds the useful deadline or background refresh limit, defer or skip. Do not retry authorization denial, unsupported coverage or invalid payload unchanged. Background refresh may tolerate bounded exponential backoff with jitter, while a tight foreground deadline often allows zero retries. A read call can still consume paid quota and cause load, even when repeating it is semantically safe.

Use token buckets or a provider-specific quota mechanism at the actual shared account scope. A bucket with sustained rate r and capacity b admits bursts according to its token accounting; distributing independent full-size buckets to ten replicas may multiply the upstream quota tenfold. Coordinate or allocate conservative per-replica shares, accounting for autoscaling and failover. Reserve capacity for critical calls and probes. In a distributed implementation, token acquisition must be atomic or conservatively bounded; reading a quota counter is not reserving a token.

Consider 200 logical provider calls/s and a 10% first-attempt failure rate. If all failed attempts receive one retry, offered attempts rise to 220/s. If quota is 210/s, even one retry per failed call is infeasible without admission control. A global retry allowance of 5% of initial calls limits retries to 10/s under the simplifying steady-state assumption, and real quota must also include other workloads and burst rules. Do not claim this recovers every failure. Track attempts/original calls, successful recovered cases and chargeable units. See the established LLM retry-storm lesson for the general retry amplification and breaker algorithms; here the consequence is lost or delayed feature eligibility, not simply inference backend availability.

7. Failover is a compatibility decision, not a provider ranking#

Approve alternatives by feature contract and intended model use. Evaluate scope and data license, semantic meaning and unit conversions, geographic/time resolution, calibration and accuracy relative to an authoritative reference, freshness, failure correlation, capacity and cost. A provider can be compatible for highway ETA and not for urban turn-by-turn delay.

Candidate evidenceSelection action
Preferred source eligible and within budgetUse approved observation
Preferred source stale, secondary independently eligibleUse approved secondary; retain source identity
Secondary has different measurement meaningReject substitution or choose compatible alternate model
Both eligible but materially disagreeApply validated disagreement policy; investigate/hold when required
Neither eligibleApproved missingness profile, degraded model or abstention
Mandatory evidence unavailableHold affected prediction/action as specified

Deterministic precedence should be defined before seeing scores. One illustrative policy prefers a valid primary observation over a secondary one within the same maximum age, unless a known quality or conflict condition blocks it. Other products may prefer the freshest compatible measurement or a validated fusion model. Do not choose the provider whose value produces the desired decision. Do not average incompatible observations. If multiple providers depend on the same upstream, their failures and errors may be correlated.

For illustration, if two providers each have 98% eligible coverage and their failures are independent, theoretical at-least-one coverage is 1 − 0.02 × 0.02 = 99.96%. If their failures are perfectly correlated, coverage remains 98%. Neither result includes deadline, semantic mapping, quota or geographic scope. Estimate joint outage behavior on aligned cases and perform correlated-failure tests. Two vendor contracts do not guarantee independent resilience.

Switchback needs care: a brief primary recovery should not trigger rapid alternation, cache thrashing or distribution shifts. Use stable preference and measured recovery gates, while preserving per-request eligibility. Record the actual source and model used. When switching back, preserve legitimate secondary observations and do not invalidate unrelated scopes.

8. Prediction profiles: full, degraded and abstention#

The principal AI-specific design problem is that network resilience cannot by itself repair a model trained on a different input distribution. A missing traffic signal is not zero congestion. Define approved inference profiles before outages.

ProfileEvidence requirementsTraining and evaluation
FullLocal features plus eligible traffic and other required inputFit and test exact feature contract and compatible providers
Missingness-awareSome explicitly supported optional inputs missing with masksTrain with representative missingness; validate actual outage slices
DegradedSeparate local-only ETA/delay model with stable inputsIndependently evaluate calibration, uncertainty, error and coverage
AbstainNo approved profile meets target, mandatory evidence or deadlineTyped response; no fabricated numeric result

A single model with a trained missing-feature representation can be appropriate for some workloads. A separately trained smaller model can be more predictable if large feature groups disappear. The degraded model must predict the same declared target for substitutable outputs, or identify a different target/contract explicitly. Validate downstream consumers and decision thresholds for its uncertainty and error characteristics. Do not treat a degraded score as a full-model calibrated probability without evidence.

Outage missingness is often not random: storms, geographic gaps and vendor overload coincide with traffic conditions where prediction is hardest. Random feature dropout in training is a useful controlled stress test but may not represent real failure patterns. Preserve actual outage contexts, provider availability, observation ages, fallback policy and mature outcomes; build representative evaluation cohorts using availability-aware joins. Include simultaneous failure, stale readings, incompatible revisions, rare regions and time-of-day slices. Evaluate selection policy on all offered cases, not just successful full predictions. When the model must act under uncertain information, validate interval coverage or calibration separately by profile; do not merely multiply uncertainty by an arbitrary outage factor.

Loading diagram…

An output may include prediction ID, target/horizon, actual model and profile, status, source evidence references, input age and validity, fallback reason and uncertainty semantics. Expose relevant degradation to consumers; do not reveal private vendor payloads or credentials. Preserve a typed abstention without pretending that a zero prediction was returned. Current decision policy independently verifies whether it may act on the profile.

9. Worked outage: quantify coverage, not only uptime#

Suppose an invented service handles 100,000 eligible requests in an outage interval. Assume mandatory local requirements and deadline are initially satisfied for these requests.

DispositionCount
Valid cached primary observation82,000
Approved secondary observation10,000
Approved local-only prediction7,000
No approved profile / abstention1,000
Total100,000

Full-model coverage is 92%; numerical prediction coverage is 99%; abstention is 1%. These are mutually exclusive actual result dispositions. A report of 99% availability alone hides the 7% degraded path. Assume, purely illustratively, mature comparable outcomes show mean absolute ETA error of 2.5 minutes on the 92,000 full predictions and 4 minutes on the 7,000 degraded predictions. The pooled MAE among the 99,000 predicted cases is (92,000×2.5 + 7,000×4)/99,000 = approximately 2.606 minutes. This is conditional on predictions being returned; the 1,000 abstentions have no point-error value and must be counted separately. The full and degraded cohorts may differ in difficulty, so the difference of group MAEs is not a causal estimate of switching models. Evaluate paired profiles on eligible cases and audit outage-specific outcomes.

If 800 of the 99,000 numerical predictions missed the actual 150 ms deadline, valid on-time numerical coverage would be 98,200/100,000 = 98.2% under these assumptions. A real system should avoid returning late results as timely successes. Track every dimension: actual response, validity, deadline, profile and outcome. Set explicit stop/containment rules for degraded error or unsupported coverage.

10. Tested implementation: deadline-aware evidence and profile selection#

This standard-library Python fixture isolates the selection logic. Both providers have been preapproved for the same synthetic canonical delay contract. Inputs represent already acquired observations, not HTTP responses. The toy policy checks scope, source/contract, time, expiry and numeric value, prefers valid primary evidence and abstains on conflicting top-ranked same-provider observations. The full and degraded paths reserve 25 and 15 synthetic milliseconds respectively. The separate attempt-budget function caps the permitted duration by remaining deadline after reserve and rejects calls when breaker, quota or attempt count disallows them.

PYTHON
from dataclasses import dataclass, replace from math import isfinite @dataclass(frozen=True) class Reading: scope: str provider: str contract: str observed: int received: int expires: int value: float def usable(r, scope, now, max_age, approved): return (r.scope == scope and (r.provider, r.contract) in approved and r.observed <= r.received <= now < r.expires and now - r.observed <= max_age and type(r.value) in (int, float) and isfinite(r.value) and 0 <= r.value <= 120) def choose(scope, now, deadline, readings, local_ready, mandatory_ready): # All times share a synthetic clock; reserve 25 ms for full inference. if not mandatory_ready or not local_ready: return 'ABSTAIN', None remaining = deadline - now if remaining < 15: return 'ABSTAIN', None approved = {('primary', 'delay/v1'), ('secondary', 'delay/v1')} candidates = [r for r in readings if usable(r, scope, now, 60, approved)] if candidates and remaining >= 25: # Fixed precedence, then observation and receipt time within provider. ranked = sorted(candidates, key=lambda r: (r.provider != 'primary', -r.observed, -r.received)) best = ranked[0] tied = [r for r in ranked if (r.provider, r.observed, r.received) == (best.provider, best.observed, best.received)] if any(r != best for r in tied): return 'ABSTAIN', None return 'FULL', best return 'DEGRADED', None def attempt_budget(now, deadline, reserve, cap, attempts_left, quota, breaker_open): if breaker_open or attempts_left <= 0 or quota <= 0: return 0 return max(0, min(cap, deadline - now - reserve)) p = Reading('a/route', 'primary', 'delay/v1', 50, 55, 130, 8) s = Reading('a/route', 'secondary', 'delay/v1', 60, 65, 140, 9) def run(rows=(p,s), now=100, deadline=140, local=True, mandatory=True): return choose('a/route',now,deadline,rows,local,mandatory) assert run() == ('FULL',p) assert run((s,p)) == run() assert run((replace(p,observed=30),s)) == ('FULL',s) assert run((replace(p,contract='speed/v2'),s)) == ('FULL',s) assert run((replace(p,scope='b/route'),)) == ('DEGRADED',None) assert run((replace(p,received=101),)) == ('DEGRADED',None) assert run((replace(p,expires=100),)) == ('DEGRADED',None) assert run((replace(p,value=float('nan')),)) == ('DEGRADED',None) assert run((replace(p,value=True),)) == ('DEGRADED',None) assert run((replace(p,value=121),)) == ('DEGRADED',None) assert run((p,replace(p,value=10))) == ('ABSTAIN',None) assert run((p,p)) == ('FULL',p) assert run(deadline=125) == ('FULL',p) assert run(deadline=124) == ('DEGRADED',None) assert run(deadline=115) == ('DEGRADED',None) assert run(deadline=114) == ('ABSTAIN',None) assert run(local=False) == ('ABSTAIN',None) assert run(mandatory=False) == ('ABSTAIN',None) assert run(()) == ('DEGRADED',None) assert attempt_budget(100,180,25,40,1,1,False) == 40 assert attempt_budget(140,180,25,40,1,1,False) == 15 assert attempt_budget(155,180,25,40,1,1,False) == 0 assert attempt_budget(100,180,25,40,0,1,False) == 0 assert attempt_budget(100,180,25,40,1,0,False) == 0 assert attempt_budget(100,180,25,40,1,1,True) == 0 print('25 checks passed')

Observed execution on Python 3.13.5:

25 checks passed

The 25 assertions cover provider precedence and input-order invariance, stale primary failover, incompatible semantic contract, scope mismatch, future receipt, exclusive expiry, NaN/Boolean/out-of-range input, conflicting same-ranked observations, duplicate identical evidence, exact full/degraded deadline thresholds, missing local or mandatory input, no external observations, and remaining-time, retry-count, quota and breaker limits. Exact locally executed code MD5 excluding its terminal newline: 60ae6bcfa7cfb9b65ff841461df412c3.

The fixture deliberately uses one synthetic clock and a 60-unit age bound, not the real-world 60-second business example above. It assumes trusted, normalized metadata and ready flags. Real code needs a monotonic deadline clock distinct from validated observation/availability timestamps, authenticated identities and provider provenance, explicit source revisions, current policy, coverage and integrity checks. It does not execute models, real deadlines, asynchronous tasks, network calls, cancellation, cache writes or external effects. The budget function is not a limiter or breaker implementation: quota and attempts are inputs, not atomic reservations, and a caller must account for backoff and useful minimum attempt time. The selector checks only conflicts tied at the top rank; it does not detect all conflicts across history or between providers. It checks observation validity at selection, not guaranteed validity at a later decision or inference completion. The synthetic reserve is an admission estimate, not a latency guarantee; deployed code must enforce an actual deadline and revalidate evidence where required. Local-ready and mandatory-ready booleans stand in for independent protected checks. Production must return exact model/profile and reason provenance, not just a tuple. A degraded path may be appropriate only if explicitly approved for the request context. No real quality, security, concurrency or provider behavior is established by this test.

For n candidate observations, the fixture filters and sorts in O(n log n) time and O(n) space. With fixed provider precedence, a production selector could retain only the best eligible observation and relevant conflict evidence per approved provider in a linear scan. The performance issue in practice is network and shared resource delay, not sorting a small number of observations.

11. Cost, scalability and security#

At 2,000 prediction requests/s, suppose the cache returns admissible external evidence for 95% and only 2% of *all* requests invoke an authorized live provider fetch. That is 40 live calls/s. If background acquisition consumes 60 calls/s, the total initial rate is 100/s. A 10% extra-attempt budget on these calls gives 110 attempts/s under a steady illustrative workload, leaving 10/s against a hypothetical 120/s quota. This is before probes and other account users; reserve additional margin or reduce admission. Without caching, one external fetch per prediction would offer 2,000/s. Neither cache hit ratio nor reduced calls alone proves eligible freshness or quality.

Suppose a provider charges a fictional $0.002 per call and average chargeable traffic is 100/s all day. That is 8.64 million calls/day and $17,280/day, before other charges. A reduced average of 20/s is 1.728 million calls/day and $3,456/day, a modeled difference of $13,824/day. These are hypothetical prices and volume assumptions, not actual vendor pricing. If billing is per returned unit or minimum commitment rather than call, the arithmetic changes. Optimize cost per on-time eligible prediction under quality and coverage gates, not cheapest source at all costs.

Apply per-tenant and per-purpose quotas, budget alerts and hard authorized spending limits. Coalesce only equivalent requests with compatible permission and output semantics. Partition storage by appropriate region and scope; use regional caches and bounded bulk refreshes. Account for replicated cache costs, cache stampedes after restart, hot-key skew and cross-region failure. Failover capacity must be reserved or dynamically admitted, not assumed. A shared external provider can have correlated latency across regions.

Vendor integration is also a trust boundary. Use allowlisted destinations, protected scoped credentials, TLS verification, bounded payload parsing, safe handling of redirects and provider errors, secret rotation and minimal outbound data. Do not transmit raw customer identifiers or location details beyond approved necessity. A returned URL or text field is untrusted and does not authorize a new fetch, tool action or change of provider. Review license and retention for cache, historical replay, model training and cross-region transfer; these are distinct permitted purposes. Enforce current access independently of a cached response. Deletion/revocation must invalidate affected cached and derived evidence under the actual requirements. Do not claim compliance from an architectural diagram.

12. Monitoring and incident recovery#

SignalWhat it detects
Provider attempts, status, p50/p95/p99 and timeoutTransport and queue health
Quota utilization, 429, retry amplification and spendAdmission pressure
Breaker state, probe validity and recovery rampsFailure containment and switchback
Valid observation coverage, age and expiry by scopeActual feature eligibility
Schema, semantic and geographic mapping failuresInvalid evidence despite HTTP success
Cache eligible-hit rate, refresh lag and coalesced workAcquisition effectiveness
Full/degraded/abstain and actual provider mixProduct-level exposure
On-time valid prediction coverage and profile-specific outcome errorEnd-to-end service quality
Same-target provider differences and shared outage correlationSubstitution safety
Orphan calls and late-result rejectionDeadline and cancellation behavior
Permission or lineage violationsTrust boundary integrity

Avoid metric labels containing sensitive customer IDs or exact private route details. Use aggregate scope classes and restricted correlation traces. Trace logical prediction ID, selected profile, provider attempts, evidence identity, observed/received/decision times, adapter and model releases, deadline consumption, cancellation and fallback reason. Reconcile recorded outcomes with actual exposed predictions, not desired routing flags. Provider outage should not automatically be diagnosed as model drift; profile mix and cohort difficulty may have changed.

Incident runbook: contain unhealthy or semantically invalid provider scope; stop new optional calls or open the relevant breaker; protect mandatory local checks and healthy dependencies; verify actual cache eligibility; activate only approved secondary/degraded profiles; assess real output coverage and mature outcomes; identify affected evidence revisions and downstream actions; investigate provider with contract owners; test recovery through bounded probes and fresh observations; gradually restore normal routing; reconcile corrected data and affected decisions separately. If no safe profile remains, abstain rather than extend age or substitute an unsupported source. Document recovery evidence and unresolved limitations.

13. Production acceptance tests#

Test scenarioRequired result
Provider never responds or DNS/TLS stallsDeadline includes connection/queue stages; local resources released
429 and Retry-After exceeds remaining timeSkip/defer; no unbounded foreground retry
Many replicas retry togetherShared quota and retry budget enforced
Same provider fails for one account/regionCorrectly scoped isolation
HTTP 200 contains stale or wrong-unit dataNo eligible full-model feature
Cache entry recently written from old observationActual observation age still enforced
Late response after a newer revisionCannot regress current cache or past prediction
Secondary has incompatible scope or contractReject substitution
Both vendors share outageSafe degraded profile or abstain; no cascading backup overload
Mandatory local evidence missingNo unauthorized output/action
Candidate full model would miss deadlineUse approved timely alternative or abstain
Provider license/permission revokedBlock current use and follow retention policy
Outage affects hard cases disproportionatelyProfile-specific and cohort-aware evaluation
Simultaneous cache miss burstBounded refresh and no provider stampede

Use real async client and server simulators with controlled delays, malformed bodies, rate limits, partial reads and cancellation-resistant remote work. Measure actual wall-clock and monotonic timing, outstanding sockets/tasks, quota reservations and queue saturation. Test concurrency, distributed limiter/breaker behavior and real cache fencing. Verify raw-to-canonical semantic mapping with independent reference cases and compare actual full/degraded model behavior on representative mature outcomes and correlated failures. Conduct controlled canaries, load tests and security review against the real deployment. The local fixture is not evidence of these end-to-end properties.

14. Interview-ready answer#

I would first classify third-party inputs by target semantics and criticality, including which are mandatory for business action and which only improve a particular model. I would register provider contracts with scope, units, observation/availability times, coverage, quotas and permitted use. I would separate asynchronous acquisition and validation from online prediction, prefetch hot keys into scoped versioned caches and check actual data validity rather than cache write age.

For unavoidable foreground calls I would propagate one deadline, reserve time for scoring, isolate provider connections and queues, enforce a shared quota and bounded retry policy, and use scoped circuit breakers with controlled recovery. I would approve secondary sources only when their evidence is semantically compatible, fresh and authorized, and avoid assuming independent failure. The inference router would select the exact approved full or degraded profile based on actual input eligibility and time, or abstain when mandatory evidence or an approved model is unavailable. I would preserve source/model provenance and validate model quality and calibration under realistic, nonrandom outages. Finally I would measure valid on-time prediction coverage, actual provider/profile mix, fallback quality, quota and cost, and test the entire path under correlated failure and recovery.

The key trade-off is not simply availability versus latency. It is on-time access to admissible evidence and a model whose behavior is validated for the evidence actually present.

References and research transparency#

Authorized offline research exception applied. References identify established reliability patterns, protocol specifications, feature-engineering guidance, provenance and security frameworks. Live reference availability and current contents, and the current Supabase changelog, were not verified. Four standard triple-backtick Mermaid diagrams received structural review; parser execution and frontend rendering were not tested. The exact Python fixture was executed locally on Python 3.13.5 with 25 assertions passing. No actual third-party provider, network timeout, asynchronous integration, production model, load benchmark, distributed quota, security assessment or real outage was exercised. All capacity, latency, price and outcome scenarios are hypothetical.

Related questions

Explore other topics:Forward Deployed EngineeringMachine LearningMLOpsPython