Launch-Time Data Gatherer with Partial Failure Tolerance
System DesignModel answerLast updated
Design an async service that merges four backend calls into one app-startup response, aborting on a critical failure and degrading gracefully on optional ones, within a fixed latency budget.
Context
A consumer mobile app makes one startup call, GET /v1/bootstrap?user_id={userId}, to load everything it needs for its first screen. If this call is slow or breaks, users feel it immediately. You are asked to design the service layer behind that endpoint.
The service gathers data from four internal backends:
- Profile service (critical): name, email, default delivery address.
- Active order service (optional): live status of any order in progress.
- Cart service (optional): items saved in the cart but not yet submitted.
- Experiment service (optional): feature flags and UI variants.
What to deliver
1. Contracts and interface
Define the response model and the aggregator class. Each of the four sections of the response must carry a status (SUCCESS, DEGRADED, or FAILED) plus either its payload or a fallback, and an optional error code. Use the following skeleton, or something equivalent:
class SectionStatus(Enum):
SUCCESS = "SUCCESS"
DEGRADED = "DEGRADED"
FAILED = "FAILED"
@dataclass
class AggregatedSection:
status: SectionStatus
data: Optional[Dict[str, Any]] = None
error_code: Optional[str] = None
@dataclass
class BootstrapResponse:
user_id: str
profile: AggregatedSection
active_order: AggregatedSection
cart: AggregatedSection
experiment_flags: AggregatedSection
class BootstrapAggregator:
def __init__(self, profile_client, order_client, cart_client,
experiment_client, timeout_ms: int = 300): ...
async def get_bootstrap_data(self, user_id: str) -> BootstrapResponse: ...
2. Failure rules
- If the profile call fails for any reason (timeout, 5xx, unauthenticated), the whole request fails with a suitable error such as 502 or 504.
- If any optional call times out or errors, the section is marked
DEGRADED(with a safe default) orFAILED, and the overall response is still HTTP 200. - All four calls run concurrently. Enforce both a per-call timeout and an overall deadline (default 300 ms).
3. Operational concerns
Explain or implement:
- What happens when the client disconnects before the response is ready.
- How the experiment section should fall back: a static local config, or an empty result.
- What logging, metrics, and alerts would reveal downstream trouble before users report it.
Example
If the active order service times out while everything else succeeds, the response is HTTP 200 with profile, cart and experiment_flags marked SUCCESS, and active_order shaped like:
{ "status": "DEGRADED", "data": null, "error_code": "DOWNSTREAM_TIMEOUT" }
Walk through your design, including the code for the aggregator, its complexity, and the trade-offs you made.
Hints
Hint 1
Think of the request as one must-have call plus three nice-to-have calls sharing a single time budget. Start all four at once so total latency is about the slowest call, not the sum.
Hint 2
Do not just gather everything and look at the results afterwards. Watch for the profile task finishing (or failing) as tasks complete, so a critical failure can cancel the rest immediately instead of waiting for the full deadline.
Hint 3
For each optional section, pick the fallback that cannot mislead the user. An empty cart says the items vanished, while an all-features-off flag set is a safe default. Also make sure a cleanup block cancels unfinished tasks on every exit path, including client disconnect.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core idea
Model the endpoint as one critical dependency and three optional enrichments, all sharing one latency budget.
- Fan out immediately. Launch all four calls as concurrent tasks. Wall-clock time is roughly the slowest call, capped by the deadline.
- Two layers of timeout. Each call has its own timeout (for example profile 250 ms, order 200 ms, cart 200 ms, experiments 150 ms), and each is capped by the global deadline (300 ms). Per-call limits stop one slow service from consuming the whole budget. The global deadline bounds what the user waits.
- Fail fast on the critical call. Wait with
asyncio.wait(tasks, timeout=remaining, return_when=FIRST_COMPLETED)in a loop. Every time something completes, check the profile task. If it failed, cancel everything else and raise immediately. A profile failure at 20 ms returns at about 20 ms, not 300 ms. - Turn optional outcomes into data, not exceptions. A helper converts each optional task into an
AggregatedSection. Exceptions from optional calls are read only inside that helper, so they can never change the HTTP status.
Status semantics
SUCCESS: live data returned.DEGRADED: a transient problem (timeout, deadline hit) or a safe fallback was served. The client may retry or poll.FAILED: a hard error and no usable data. The client hides the module.
Choosing fallbacks
A fallback must never lie to the user.
- Experiments: serve a static, conservative local config with every new feature off (control variants). Returning
{}is worse because the client's behavior on missing flags is undefined, and it may flip users between variants inconsistently. Mark itDEGRADEDso analytics can exclude those sessions from experiment results. - Cart: do not return an empty cart, since it suggests the user's items disappeared. Return
data: nullwithDEGRADEDso the client shows "couldn't load cart" or falls back to its local cache. - Active order: return
nullwith a status. The client can poll the tracking endpoint separately.
Code sketch
import asyncio, logging
logger = logging.getLogger("bootstrap")
LOCAL_DEFAULT_FLAGS = {"new_checkout_flow": False}
PER_CALL_MS = {"profile": 250, "active_order": 200, "cart": 200, "experiment_flags": 150}
class BootstrapError(Exception):
def __init__(self, http_status, error_code):
super().__init__(error_code)
self.http_status, self.error_code = http_status, error_code
class UnauthenticatedError(Exception): pass
class BootstrapAggregator:
def __init__(self, profile_client, order_client, cart_client,
experiment_client, timeout_ms=300):
self._c = {"profile": profile_client, "active_order": order_client,
"cart": cart_client, "experiment_flags": experiment_client}
self._deadline_s = timeout_ms / 1000
async def _call(self, name, user_id):
loop = asyncio.get_running_loop(); t0 = loop.time(); outcome = "ok"
try:
budget = min(PER_CALL_MS[name] / 1000, self._deadline_s)
return await asyncio.wait_for(self._c[name].fetch(user_id), budget)
except asyncio.TimeoutError: outcome = "timeout"; raise
except asyncio.CancelledError: outcome = "cancelled"; raise
except Exception: outcome = "error"; raise
finally:
logger.info("downstream_call", extra={
"dependency": name, "outcome": outcome,
"latency_ms": round((loop.time() - t0) * 1000, 1)})
async def get_bootstrap_data(self, user_id):
loop = asyncio.get_running_loop()
deadline = loop.time() + self._deadline_s
tasks = {n: asyncio.create_task(self._call(n, user_id)) for n in self._c}
try:
pending = set(tasks.values())
while pending:
remaining = deadline - loop.time()
if remaining <= 0: break
done, pending = await asyncio.wait(
pending, timeout=remaining,
return_when=asyncio.FIRST_COMPLETED)
p = tasks["profile"]
if p in done and p.exception() is not None:
raise self._critical_error(p.exception())
if p in done and not pending - {p}:
pass
p = tasks["profile"]
if not p.done():
raise BootstrapError(504, "PROFILE_TIMEOUT")
if p.exception() is not None:
raise self._critical_error(p.exception())
return BootstrapResponse(
user_id=user_id,
profile=AggregatedSection(SectionStatus.SUCCESS, p.result()),
active_order=self._section(tasks["active_order"]),
cart=self._section(tasks["cart"]),
experiment_flags=self._section(
tasks["experiment_flags"], fallback=LOCAL_DEFAULT_FLAGS))
finally:
for t in tasks.values():
if not t.done(): t.cancel()
await asyncio.gather(*tasks.values(), return_exceptions=True)
@staticmethod
def _critical_error(exc):
if isinstance(exc, asyncio.TimeoutError): return BootstrapError(504, "PROFILE_TIMEOUT")
if isinstance(exc, UnauthenticatedError): return BootstrapError(401, "UNAUTHENTICATED")
return BootstrapError(502, "PROFILE_UNAVAILABLE")
@staticmethod
def _section(task, fallback=None):
if not task.done():
return AggregatedSection(SectionStatus.DEGRADED, fallback, "DEADLINE_EXCEEDED")
if task.cancelled():
return AggregatedSection(SectionStatus.DEGRADED, fallback, "CANCELLED")
exc = task.exception()
if exc is None:
return AggregatedSection(SectionStatus.SUCCESS, task.result())
if isinstance(exc, asyncio.TimeoutError):
return AggregatedSection(SectionStatus.DEGRADED, fallback, "DOWNSTREAM_TIMEOUT")
return AggregatedSection(SectionStatus.FAILED, fallback, "DOWNSTREAM_ERROR")
The final gather(..., return_exceptions=True) in finally also marks exceptions as retrieved, so asyncio does not warn about unobserved task errors.
Why it is correct
- Bounded latency: every wait uses
remaining = deadline - now, and every call is wrapped inwait_for. Nothing waits past the budget apart from scheduling jitter. - Early abort: the profile task is inspected each time any task completes.
- Isolation: optional exceptions are consumed only in
_section, which always returns a section object. - No leaked work: the
finallyblock cancels unfinished tasks on every path (success, critical failure, caller cancellation).
Complexity
- Time: wall-clock is O(min(T_global, max_i T_i)); CPU is O(k) for k dependencies (k = 4).
- Space: O(k) tasks plus response payloads.
Edge cases
- Client disconnects: the framework cancels the handler, so
CancelledErrorsurfaces at ourawait. Thefinallyblock cancels the child tasks, which closes their HTTP/gRPC calls and propagates cancellation downstream. Re-raise it, never swallow it, and log it asclient_cancelledrather than as an error so alerts stay clean. - Profile succeeds, deadline fires before optional calls finish: those sections become
DEGRADED / DEADLINE_EXCEEDED, still HTTP 200. - Profile pending at the deadline: return 504
PROFILE_TIMEOUT. - Unauthenticated profile: return 401, not 502, because the client must re-login rather than retry.
- Hidden dependency: parallel fetch only works if optional services need nothing but
user_id. If cart needed the address from the profile, that call would have to wait for it.
Observability
- Metrics per dependency: latency histogram (p50/p95/p99), outcome counter (ok, timeout, error, cancelled), and a counter of sections served as
DEGRADEDorFAILED. - Endpoint metrics: overall latency, HTTP status distribution, and the fraction of responses with at least one degraded section.
- Logs: structured, with a request ID, dependency, outcome and latency. Sample the successes and keep all failures.
- Alerts: page on profile error or timeout rate above a threshold (for example 2% over 5 minutes) and on bootstrap p99 approaching the deadline. Warn (ticket or chat) when an optional dependency's degraded rate rises, for example above 5%, since it is not user-blocking but signals trouble early. Use burn-rate alerts against an SLO such as 99.9% of bootstraps returning 200 within 400 ms.
- Synthetic probes that call the endpoint from outside catch problems even during low traffic.
Trade-offs and extensions
- A circuit breaker per optional dependency skips calls to a service that is clearly down, saving the budget and avoiding load on a recovering service.
- Retries are risky inside a 300 ms budget. Allow at most one hedged request for idempotent reads, and only if budget remains.
- Short-lived caching of experiment configs (stale-while-revalidate) is often a better fallback than a static default.
Common mistakes
- Using a plain
gatherand checking the profile only at the end, which wastes time after a critical failure. - Applying only a global timeout, so one slow call starves the rest.
- Returning an empty cart or
{}flags as if they were real data. - Swallowing
CancelledError, or forgetting to cancel child tasks on exit. - Treating a 401 from the profile service as a retryable 502.