Aggregating Three Upstream Services with Graceful Degradation
System DesignModel answerLast updated
Design a startup endpoint that resolves a user's internal ID, fans out to two dependent services, and still returns useful data when optional services fail or run slowly.
Startup Profile Endpoint
You are building a backend endpoint that a client app calls on launch. It receives a user_id and assembles one response from three existing internal services. You may assume mock versions of these services exist, but their exact wire formats are not specified beyond the fields listed below.
Upstream services
| Service | Input | Relevant output |
|---|---|---|
| Consumer | user_id | user information, including consumer_id and roles |
| Payment | consumer_id | default card, available gift-card credit |
| Address | consumer_id | formatted address, first name, last name |
Rules
user_idandconsumer_idare different identifiers. Payment and Address must be called withconsumer_id, never withuser_id.- If Consumer fails, the whole request may fail with HTTP 500.
- If Payment or Address fails, the endpoint must still return everything that was obtained successfully (including Consumer data).
- When Address succeeds, the response must contain the first name and last name, not only the formatted address.
What to deliver
Describe and justify:
- The order of upstream calls and which ones can run concurrently.
- The shape of the response, including how a missing section is represented.
- How you handle HTTP status codes, malformed payloads, and timeouts.
- The tests that would prove the behavior is correct.
Also list the clarifying questions you would ask before building it, and state the assumptions you make when they are unanswered. If you write code, keep it short and focus on the orchestration logic.
Hints
Hint 1
Draw the dependency graph first: which call produces the input needed by the other two? That tells you what must be sequential and what can be parallel.
Hint 2
Think about how a client can tell the difference between 'balance is 0' and 'we could not find out the balance'. Your response contract should make that distinction explicit.
Hint 3
Give the request an overall deadline and derive each upstream timeout from the time remaining, rather than using fixed independent timeouts that could add up beyond the budget.
Hint 4
For tests, use fakes that record the arguments they receive. A test that fails if Payment is called with `user_id` will catch the most likely bug.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
1. Call sequence
The data dependency is a simple two-stage graph:
user_id -> Consumer -> consumer_id -> { Payment, Address }
- Stage 1: call Consumer with
user_id. Nothing else can start becauseconsumer_idis unknown. This is the critical dependency, so a failure here ends the request with HTTP 500 (or 404 if Consumer explicitly says the user does not exist, if we confirm that distinction). - Stage 2: call Payment and Address concurrently using
consumer_id. They are independent, so total latency is roughlylatency(Consumer) + max(latency(Payment), latency(Address))rather than the sum of all three.
The most common bug is passing user_id to the stage 2 services. Because both IDs are often strings or integers, this fails silently in mocks. Name the variables distinctly and test for it.
2. Response contract
Return HTTP 200 with a body where each optional section is either populated or marked unavailable:
{
"user": { "user_id": "u1", "consumer_id": "c9", "roles": ["customer"] },
"payment": {
"default_card": { "...": "..." },
"gift_card_credit": 0
},
"address": {
"formatted": "1 Main St, Springfield",
"first_name": "Ada",
"last_name": "Lovelace"
},
"errors": { "payment": "timeout" }
}
Design choices:
- Do not substitute defaults for missing data. If Payment fails, do not return
gift_card_credit: 0. A real zero and an unknown balance mean different things, and a client might block a purchase or hide a feature based on the wrong one. Usenull(or omit the key) plus an entry inerrors/unavailable. - Keep a machine-readable reason (
timeout,upstream_5xx,not_found,invalid_payload) so the client or dashboards can react without parsing messages. - Always include
first_nameandlast_nameunderaddresswhen Address succeeds. Map fields explicitly rather than passing through the upstream object, so schema drift upstream does not leak or drop fields.
If the client needs to distinguish "this user has no address" from "address service is down", treat a 404 from Address as address: null with no error, and treat 5xx/timeouts as address: null with an error entry.
3. HTTP, parsing and timeouts
- Status handling: treat 2xx as success. For Consumer, 404 is "unknown user" (client error), while 5xx, timeouts and connection errors are 500/502. For Payment and Address, 404 usually means "no data" (not an error), whereas 5xx, 429 and transport errors mean "temporarily unavailable". Confirm this mapping with the owning teams.
- Validate payloads: a 200 with a missing
consumer_idis still a Consumer failure. A 200 from Payment with the wrong type for credit should becomeinvalid_payload, not an exception that kills the whole response. Wrap each optional call so any exception is converted into an error entry. - Deadline budget: set an overall deadline (for example 800 ms for a launch call). Give Consumer a slice (say 300 ms) and stage 2 whatever remains, with each optional call capped by the remaining time. Never let a slow optional service push the response past the budget.
- Retries: only retry if the operation is idempotent (these are reads, so usually safe), at most once, with a short jittered delay, and only if the remaining deadline allows it. Retrying Consumer once is reasonable because it is the critical path; retrying optional calls is often not worth the latency. Avoid retry storms: respect 429 and consider a circuit breaker if an upstream is consistently failing.
4. Sketch
async def bootstrap(user_id, deadline):
try:
consumer = await consumer_client.get(user_id, timeout=deadline.slice(0.4))
consumer_id = consumer["consumer_id"]
roles = consumer["roles"]
except Exception:
raise HTTPError(500)
async def safe(name, coro):
try:
return name, await coro, None
except NotFound:
return name, None, None
except Exception as e:
return name, None, classify(e)
results = await asyncio.gather(
safe("payment", payment_client.get(consumer_id, timeout=deadline.remaining())),
safe("address", address_client.get(consumer_id, timeout=deadline.remaining())),
)
body = {"user": {"user_id": user_id, "consumer_id": consumer_id, "roles": roles},
"payment": None, "address": None, "errors": {}}
for name, data, err in results:
if err:
body["errors"][name] = err
elif data is not None:
body[name] = map_fields(name, data)
return 200, body
map_fields("address", data) returns formatted, first_name and last_name explicitly.
Complexity is trivial; the real cost is latency and the number of upstream calls (three per request, one sequential hop before the parallel pair).
Tests
Use fake clients that record their arguments and can be told to succeed, return an error status, return garbage, or hang.
- Happy path: all succeed; the response has user, payment, address, and first/last name.
- Correct identifiers: Payment and Address fakes assert they received
consumer_id, anduser_iddiffers from it in the fixture. - Consumer failure: 5xx, timeout and malformed body each yield 500; Payment and Address are not called.
- Payment fails: user and address still returned; payment marked unavailable with a reason.
- Address fails: user and payment still returned.
- Both optional fail: 200 with only user data and two error entries.
- Zero vs unknown: a real
gift_card_creditof 0 is returned as 0; a failure is returned as null plus an error. - Timeouts: a hanging optional service makes the total response time stay within the deadline.
- Bad payloads: missing fields, wrong types and an empty body are handled without a crash.
- Concurrency: with both stage 2 fakes delayed by 200 ms, total time is near 200 ms, not 400 ms.
Common mistakes
- Using
user_idfor downstream calls. - Returning a default balance of 0 when Payment fails.
- Failing the whole request on an optional service error, or catching exceptions so broadly that Consumer failures are hidden.
- Calling Payment and Address sequentially.
- Per-call timeouts that sum to more than the overall budget.
- Dropping the first and last name when mapping the address.
- Retrying without checking idempotency or remaining time.
Clarifying questions to raise
- Which statuses mean "no data" versus "temporarily unavailable" for each upstream?
- Should unavailable sections be omitted, null, or structured errors?
- What are the total and per-call deadlines?
- Is retrying safe, and is there room in the deadline for it?