📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What is partial failure in a distributed system? Your service calls another service and the call times out: did the other service do the work? Explain why you can't know, and what that means for how you write the calling code.

Partial failure and the unknown outcome of a timed-out remote call: why the caller can't tell what happened, and how timeouts, idempotency, status checks and reconciliation make calling code safe.

Junior Theory Intermediate distributed-systems httpclient idempotency partial-failure retries timeouts

🎯 Key points

  • Partial failure: some components fail while others keep working, and nobody has a global view
  • A timeout means the outcome is unknown, not that the operation failed
  • Four possibilities: request lost, server crashed before or after the work, response lost, still running
  • Retrying blindly can duplicate side effects (double charge, duplicate order)
  • Make operations idempotent or send an idempotency key so a retry is safe
  • Otherwise query the outcome (GET by client-generated id) before retrying
  • Reconciliation jobs catch what slips through
  • Cancellation in .NET stops waiting; it does not undo work on the other side

⏱ 30-second answer

Partial failure means part of a distributed system fails while the rest keeps running, and no single node can see the whole picture. The sharpest example is a timeout: when your call to the payments service times out, the request might have been lost, the service might have crashed before or after charging the card, the response might have been lost, or it might still be running. A timeout means the outcome is unknown, not that it failed. So calling code must be written for the unknown: make the operation idempotent (or send an idempotency key) so a retry can't do the work twice, or look up the outcome by a client-generated id before retrying, and run reconciliation for anything left in doubt. The trade-off is extra design work on every write that crosses the network.

🗣 Full answer (senior)

How I would answer this in an interview

"Partial failure is what makes distributed systems hard. In one process, things either work or throw. Across a network, one part can fail while others carry on, and the caller only sees silence. When my call to another service times out, there are four possibilities: my request never arrived, the service crashed before doing the work, it did the work and crashed or the response got lost, or it's still running and just slow. From the caller's side all four look identical. So a timeout is not a failure; it's an unknown outcome.

That changes how I write the calling code. If the operation is naturally idempotent, like setting an address or a PUT of a whole resource, I can simply retry. If it isn't, like charging a card or creating an order, I generate an id on the client side and send it as an idempotency key, so the server can recognise the retry and return the first result instead of charging again. Where I can't do that, I check the outcome first, for example GET /payments/{myId}, before trying again. And in .NET it's worth remembering that cancelling a CancellationToken only stops my waiting; it doesn't undo anything on the other side.

The mistake I see is code that catches TaskCanceledException, logs 'payment failed' and tells the user to try again, which is exactly how customers get charged twice. Treat every timeout on a write as 'maybe it happened'."


What a timeout can mean

Case Did the work happen? Is a blind retry safe?
Request lost on the way No Yes
Server crashed before the work No Yes
Server did the work, then crashed or the response was lost Yes No: duplicate
Server is still working (slow) Not yet, but it will No: duplicate or race

Ways to handle the unknown

Technique How When it fits
Naturally idempotent operation PUT full state, "set status = Shipped" Updates you can repeat
Idempotency key Client sends a unique key; server stores the result per key Payments, order creation
Client-generated id Client picks the order id; server rejects a duplicate insert Creating resources
Status check before retry GET the resource by its id APIs without idempotency support
Reconciliation Batch job compares both sides Money, stock; the final safety net

Production example

An order service called a payment provider with a 5-second timeout and, on timeout, told the user the payment failed. During a provider slowdown about 0.4% of payments actually succeeded after the timeout, and users who clicked Pay again were charged twice. Sending the order id as the provider's idempotency key and showing "we're confirming your payment" on timeout took duplicate charges to zero.

🔍 What the interviewer is checking

Checks whether the candidate understands that a timeout means an unknown outcome and knows the standard ways to make calling code safe.

Green flags

  • Lists the possible cases behind a timeout, including "done but response lost".
  • Brings up idempotency keys and a stable client-generated id.
  • Knows that client cancellation doesn't undo server work.
  • Mentions reconciliation for money.

Red flags

  • "It timed out, so it failed; just retry."
  • Thinks a longer timeout solves the problem.
  • Never considers duplicates.

📚 Learn in depth

1. The two generals problem in one diagram

Orders service                 Payments service
     |  POST /charge (A$120)  -->   |
     |                              |  charge card  ✔
     |       <-- 200 OK --- X       |  (response lost)
     |  ... 5 s timeout ...         |
     |  ??? did it charge?          |

No amount of extra acknowledgements fixes this: the last message can always be lost. This is why distributed systems can't guarantee that both sides know the outcome at the same time, and instead make repeated attempts harmless.

2. Why the failure is "partial"

In a single process a crash takes everything down together. In a distributed system:

  • The payments service may be healthy for other callers but slow for you.
  • One replica may be down while others are fine.
  • The network between two zones may be broken while each zone works.

No node has a global view, so each must decide based on local information and timeouts.

3. What .NET actually does on a timeout

  • HttpClient throws TaskCanceledException (with an inner TimeoutException since .NET 5) when its Timeout passes.
  • The client closes or abandons the connection; the server may never notice and keeps processing.
  • ASP.NET Core on the server side exposes HttpContext.RequestAborted, which fires when the client disconnects, but most handlers don't check it after they've started a database write, and they shouldn't half-undo work anyway.

So client cancellation stops waiting. It doesn't roll anything back.

4. Making retries safe

Idempotency means doing the operation once or many times has the same effect.

Attempt 1: POST /payments  Idempotency-Key: ord-981  -> server charges, stores result under ord-981, response lost
Attempt 2: POST /payments  Idempotency-Key: ord-981  -> server finds ord-981, returns stored result, no new charge

The key must come from the client and stay the same across retries. Generating a new GUID per attempt defeats it.

5. The final safety net: reconciliation

Even with idempotency, some outcomes stay in doubt (for example, a provider outage lasting longer than your retry window). A scheduled reconciliation job compares your records with the other side's (the provider's settlement report, the warehouse's stock) and fixes or flags mismatches. For money, this is not optional.

Try it yourself

  1. Build two minimal APIs: the server sleeps 3 seconds then writes a row; the client calls it with a 1-second timeout. Check the database after the client reports failure.
  2. Add an Idempotency-Key header and a unique index on it in the server's table; retry the client three times and confirm only one row exists.
  3. Log HttpContext.RequestAborted.IsCancellationRequested on the server after the client times out.
  4. Write a tiny reconciliation query that finds orders marked PaymentUnknown older than 15 minutes.

💻 Code

Calling a payment service when the outcome of a timeout is unknown: a stable idempotency key, a status check, and an explicit "unknown" state.

namespace Orders;

public enum PaymentOutcome { Succeeded, Declined, Unknown }

public sealed record ChargeRequest(Guid OrderId, decimal Amount);
public sealed record ChargeResult(string Status);

public sealed class PaymentsClient(HttpClient http, ILogger<PaymentsClient> logger)
{
    public async Task<PaymentOutcome> ChargeAsync(ChargeRequest request, CancellationToken ct)
    {
        // The key is derived from the order, so every retry carries the SAME key
        using var message = new HttpRequestMessage(HttpMethod.Post, "/payments")
        {
            Content = JsonContent.Create(request)
        };
        message.Headers.Add("Idempotency-Key", $"order-{request.OrderId}");

        try
        {
            using var response = await http.SendAsync(message, ct);
            var result = await response.Content.ReadFromJsonAsync<ChargeResult>(ct);
            return result?.Status == "succeeded" ? PaymentOutcome.Succeeded : PaymentOutcome.Declined;
        }
        catch (TaskCanceledException) when (!ct.IsCancellationRequested)
        {
            // Timeout: the charge MAY have happened. Don't report failure.
            logger.LogWarning("Payment for {OrderId} timed out; outcome unknown", request.OrderId);
            return await CheckStatusAsync(request.OrderId, ct);
        }
    }

    private async Task<PaymentOutcome> CheckStatusAsync(Guid orderId, CancellationToken ct)
    {
        try
        {
            var result = await http.GetFromJsonAsync<ChargeResult>($"/payments/by-order/{orderId}", ct);
            return result?.Status switch
            {
                "succeeded" => PaymentOutcome.Succeeded,
                "declined" => PaymentOutcome.Declined,
                _ => PaymentOutcome.Unknown
            };
        }
        catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException)
        {
            return PaymentOutcome.Unknown; // a reconciliation job resolves it later
        }
    }
}

⚠ Common mistakes

  • Mistake: Treating a timeout as a failure and telling the user to try again. Why it is wrong: the work may already have happened, so the retry duplicates it. Instead: record the outcome as unknown, check status, and retry only with an idempotency key.
  • Mistake: Generating a new idempotency key for each attempt. Why it is wrong: the server sees every retry as a new request. Instead: derive the key from the business operation (order id) and reuse it.
  • Mistake: Believing that cancelling the CancellationToken undoes the remote work. Why it is wrong: cancellation stops the client waiting; the server may carry on. Instead: design for the server finishing after you gave up.
  • Mistake: Retrying non-idempotent POSTs in a generic resilience handler. Why it is wrong: the standard handler retries on timeouts and 5xx, which duplicates side effects. Instead: disable retries for unsafe calls or make them idempotent first.
  • Mistake: Setting a very long timeout to "avoid" partial failure. Why it is wrong: the outcome is still unknown when it eventually fires, and meanwhile requests pile up. Instead: use a timeout that fits the latency budget and handle the unknown.
  • Mistake: No reconciliation for money or stock. Why it is wrong: some outcomes stay in doubt beyond any retry window. Instead: schedule a job that compares both sides and flags mismatches.

🏛 Senior insight: trade-offs

I treat "unknown" as a first-class state in the domain model: PaymentPending or PaymentUnknown, with a timestamp, a resolver and an alert if it stays unresolved too long. Once that state exists, the UI can be honest ("we're confirming your payment") and support can see what's in doubt.

The cost of idempotency is real but small: a unique key, a table, and a little discipline. The cost of skipping it is double charges, angry customers and, for payments, a lot of manual refunds.

Approach When it fits Cost When not to
Blind retry Reads and naturally idempotent writes None Any write with side effects
Idempotency key Payments, orders, any create Key storage, TTL Server doesn't support it (use status check)
Status check, then retry Third-party APIs without keys Extra call, race window High-volume paths where races matter
Reconciliation Money, stock, anything audited Batch job, reports Never skip it for money

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions idempotency keys. Why: Checks the server side of the idempotency key the candidate proposed.
    How to answer

    The client sends a unique Idempotency-Key (usually a UUID) with a non-idempotent request and reuses it on every retry. The server atomically claims the key with a unique constraint on (client, key), stores a fingerprint of the request, executes the operation and saves the response. A retry with the same key and body gets the stored response replayed; a request still in progress gets 409 Conflict; the same key with a different body gets 422. Ideally the business write and the idempotency record commit in one transaction, so a crash can't leave a charge without a record. Keys expire after a published window, often 24 hours. The trade-off is an extra write per request and storage, in exchange for making POST safe to retry.

  2. When: Candidate talks about setting timeouts. Why: Checks how timeouts should be chosen and layered across the call chain.
    How to answer

    A timeout is a budget, and budgets must shrink as you go inward. The client's timeout is the largest; the API's own request timeout (the .NET 8+ request timeouts middleware, which cancels HttpContext.RequestAborted) is smaller; each outbound call gets a per-attempt timeout inside its retries and a total timeout outside them (the standard resilience handler defaults to 10 s and 30 s, while raw HttpClient.Timeout is 100 s); SQL gets a command timeout (30 s by default) plus the CancellationToken. One token flows from the request to every call so abandoned work stops. The trade-off: short timeouts fail fast and protect threads but cut off legitimately slow work, so slow operations should become async (202 plus a status resource) rather than get longer timeouts.

  3. When: Candidate says the operation must be idempotent. Why: Checks depth on the core tool for handling partial failure.
    How to answer

    An operation is idempotent if doing it once or many times leaves the system in the same state. It's the core tool because distributed systems produce duplicates all the time: clients retry after timeouts, brokers deliver at least once, users double-click. You get it in two ways. Some operations are naturally idempotent: 'set status to Shipped', a PUT of the full resource, an upsert by a natural key. The rest need deduplication: the caller sends a unique idempotency key (or the broker supplies a message id), and the service records it under a unique constraint in the same transaction as the business change, so a repeat is detected and answered with the stored result. The trade-off is storage and a little complexity, against duplicate charges, orders and emails.

↩ Usually asked after

More in Distributed Systems Core Concepts

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me