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

πŸ“š Interview question

What makes a system distributed? Explain the fallacies of distributed computing, and give a .NET example of code that breaks because it believes one of them.

What a distributed system is, the eight fallacies of distributed computing, and how each shows up as a concrete bug in .NET services that call each other over the network.

Beginner Theory Beginner distributed-systems fallacies httpclient latency networking resilience

🎯 Key points

  • Distributed = components on separate machines that coordinate only by sending messages over a network
  • No shared memory and no shared clock: each node only knows what messages tell it
  • The eight fallacies (Deutsch/Gosling): reliable network, zero latency, infinite bandwidth, secure network, unchanging topology, one administrator, zero transport cost, homogeneous network
  • A remote call is not a method call: it can be slow, fail, or succeed without you knowing
  • Concrete .NET bugs: relying on HttpClient's default 100 s timeout (still the default in .NET 10), calls in a loop, stale DNS, unencrypted internal traffic
  • Mitigations: timeouts and idempotent retries (Microsoft.Extensions.Http.Resilience), batching, async messaging (Azure Service Bus), TLS plus managed identities, service discovery
  • Microservices and Kubernetes multiply the fallacies: more hops, moving pods, more teams
  • Trade-off: distribution buys independent scaling and deployment, at the cost of handling failure explicitly

⏱ 30-second answer

A system is distributed when its parts run on different machines and coordinate only by sending messages over a network: there is no shared memory and no shared clock. That changes everything, because a remote call can be slow, fail, or succeed without you finding out. The fallacies of distributed computing are eight assumptions developers make that are false: the network is reliable, latency is zero, bandwidth is infinite, the network is secure, topology doesn't change, there is one administrator, transport cost is zero and the network is homogeneous. In .NET they show up as an HttpClient call with no sensible timeout, a downstream call inside a foreach, or a cached IP address that goes stale. The trade-off: distribution buys independent scaling and deployment, and you pay for it by handling failure in every call.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"A distributed system is a set of components on different machines that cooperate only by passing messages over a network. There's no shared memory, so one node can't just read another's state, and there's no shared clock, so they can't even agree exactly on when something happened. Everything a node knows about the others comes from messages that may arrive late, out of order, twice or never.

The fallacies of distributed computing, from Peter Deutsch and James Gosling at Sun, list the assumptions that make code look fine on a laptop and fail in production: the network is reliable, latency is zero, bandwidth is infinite, the network is secure, topology doesn't change, there is one administrator, transport cost is zero, and the network is homogeneous. In .NET the classic one is treating await client.GetAsync(...) as if it were a local method call. HttpClient has a default timeout of 100 seconds, so a slow dependency holds a request open for 100 seconds unless you set a real timeout. Another is calling a pricing service once per basket line in a loop: 40 lines at 20 ms each is 800 ms of pure waiting.

The mistake I see is people adding microservices and then writing calls between them as if they were in-process. My rule is simple: every remote call gets a timeout, a decision about retries, and a plan for what the user sees when it fails."


The eight fallacies and how they bite in .NET

Fallacy What really happens Typical .NET bug What you do instead
The network is reliable Packets drop, connections reset, services restart No retry, or a retry on a non-idempotent POST Timeouts, retries with backoff, idempotency keys
Latency is zero 0.5–2 ms inside an Azure region, 10–15 ms Sydney↔Melbourne, ~150 ms to the US Calls in a loop (N+1 over HTTP) Batch endpoints, parallel calls with a limit
Bandwidth is infinite Payloads cost time, especially on mobile Returning the whole entity graph Projection, pagination, compression
The network is secure Internal traffic can be sniffed or spoofed Plain HTTP between services, no auth TLS everywhere, managed identities, zero trust
Topology doesn't change Pods move, IPs change, DNS changes A singleton HttpClient that never refreshes DNS PooledConnectionLifetime, service discovery
There is one administrator Different teams and providers change things Assuming you control the firewall or the gateway Contracts, runbooks, observability across teams
Transport cost is zero Serialisation, TLS and egress cost CPU and money JSON serialising huge objects per call Smaller contracts, gRPC where it fits
The network is homogeneous Different OSes, proxies, MTUs, protocols Assuming HTTP/2 everywhere Negotiate protocols, test through real proxies

Local call vs remote call

Local method call Remote call
Latency Nanoseconds Milliseconds to seconds
Failure Exception, or it worked Worked, failed, or unknown
Partial results No Yes (the other side may have done the work)
Ordering Program order Messages can reorder or duplicate

Production example

A checkout API called a pricing service once per basket line. In Australia East this cost about 2 ms per call, so nobody noticed until a promotion pushed baskets to 60 lines and the pricing service slowed to 50 ms per call: checkout p95 went from 300 ms to over 3 seconds. Replacing the loop with one batch call and setting a 2-second per-attempt timeout brought p95 back to 350 ms.

πŸ” What the interviewer is checking

Checks whether the candidate understands that remote calls are fundamentally different from local ones and can turn the fallacies into concrete engineering habits.

Green flags

  • Defines distributed in terms of message passing, no shared memory and no shared clock.
  • Names several fallacies and ties each to a real bug or fix.
  • Mentions timeouts, idempotent retries and batching unprompted.
  • Knows realistic latency numbers.

Red flags

  • Recites the list with no examples.
  • Thinks a retry policy alone makes a call reliable.
  • Treats internal networks as trusted.

πŸ“š Learn in depth

1. Why "distributed" is a different world

Inside one process, a method call either returns or throws, and memory is shared. Across machines you only have messages:

Service A                         Service B
   |  ---- request ---------->      |
   |         (may be lost)          |  does the work (or not)
   |  <--- response ----------      |
   |         (may be lost)          |

If A sees no response, it can't tell whether the request was lost, B crashed before doing the work, B did the work and crashed, or the response was lost. That ambiguity is the root of almost every distributed systems technique: timeouts, retries, idempotency, consensus.

2. No shared clock

Every machine has its own clock, kept roughly in sync by NTP or the cloud host. Clocks drift and can jump. So "event X happened before event Y" can't be decided reliably from timestamps written on different machines. This is why distributed systems use sequence numbers, versions and logical clocks for ordering.

3. The fallacies, with numbers

  • Latency: a call within one Azure region is roughly 0.5–2 ms of network round trip; between Australia East (Sydney) and Australia Southeast (Melbourne) about 10–15 ms; Sydney to US West about 150 ms. Ten sequential calls across regions is over a second before any work happens.
  • Bandwidth: a 2 MB JSON response over a 5 Mbit/s mobile link takes over 3 seconds just to transfer.
  • Reliability: in a large fleet, something is always failing: a node restarts, a load balancer drains, a connection resets.
  • Topology: in Kubernetes, pod IPs change on every deployment. A client that resolved DNS once and kept the connection forever keeps talking to a dead or wrong address.

4. How .NET helps and where it doesn't

  • HttpClient + IHttpClientFactory manage connection pools; SocketsHttpHandler.PooledConnectionLifetime recycles connections so DNS changes are picked up.
  • Microsoft.Extensions.Http.Resilience (AddStandardResilienceHandler) adds total and per-attempt timeouts, retries with jitter and a circuit breaker on top of Polly v8.
  • CancellationToken lets you stop work when the caller has gone.
  • What .NET can't do for you: decide whether an operation is safe to retry, or what the user should see when a dependency is down. Those are design decisions.

5. Why we still distribute

Distribution buys independent deployment, independent scaling, fault isolation and team autonomy. You pay with latency, partial failure and harder debugging. A modular monolith avoids most of the fallacies until you really need to split.

Try it yourself

  1. Write a console app that calls https://httpbin.org/delay/10 with the default HttpClient and time it, then set Timeout = TimeSpan.FromSeconds(2) and catch the TaskCanceledException.
  2. Call a local endpoint 50 times in a loop, then in one batch call; compare total time with a Stopwatch.
  3. Use tc (Linux) or a tool like Toxiproxy in Docker to add 50 ms latency and 5% packet loss between two containers, and watch what your service does.
  4. Run nslookup on a Kubernetes service before and after a rollout and note the changing pod IPs behind a headless service.

πŸ’» Code

A remote call that respects the fallacies: a typed client with a timeout and the standard resilience handler, compared with the naive version.

// Program.cs
using Microsoft.Extensions.Http.Resilience;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddHttpClient<PricingClient>(c =>
    {
        c.BaseAddress = new Uri("https://pricing.internal"); // TLS even inside the network
    })
    // Total timeout, per-attempt timeout, retries with jitter, circuit breaker
    .AddStandardResilienceHandler(o =>
    {
        o.AttemptTimeout.Timeout = TimeSpan.FromSeconds(2);
        o.TotalRequestTimeout.Timeout = TimeSpan.FromSeconds(6);
    });

var app = builder.Build();
app.MapPost("/basket/price", async (BasketDto basket, PricingClient pricing, CancellationToken ct) =>
    Results.Ok(await pricing.PriceAsync(basket.Skus, ct)));
app.Run();

public sealed record BasketDto(IReadOnlyList<string> Skus);
namespace Checkout;

public sealed record Price(string Sku, decimal Amount);

public sealed class PricingClient(HttpClient http)
{
    // Naive: one network round trip per SKU ("latency is zero")
    public async Task<List<Price>> PriceOneByOneAsync(IEnumerable<string> skus, CancellationToken ct)
    {
        var prices = new List<Price>();
        foreach (var sku in skus)
            prices.Add((await http.GetFromJsonAsync<Price>($"/prices/{sku}", ct))!);
        return prices;
    }

    // Better: one round trip for the whole basket
    public async Task<IReadOnlyList<Price>> PriceAsync(IReadOnlyList<string> skus, CancellationToken ct)
    {
        using var response = await http.PostAsJsonAsync("/prices/batch", skus, ct);
        response.EnsureSuccessStatusCode();
        return (await response.Content.ReadFromJsonAsync<List<Price>>(ct))!;
    }
}

⚠ Common mistakes

  • Mistake: Treating a remote call like a local method call. Why it is wrong: it can be slow, fail, or succeed without a response, and local-call habits ignore all three. Instead: give every remote call a timeout, a retry decision and a failure path.
  • Mistake: Relying on HttpClient's default 100-second timeout. Why it is wrong: one slow dependency holds requests and threads open far longer than any user will wait. Instead: set per-attempt and total timeouts that fit your latency budget.
  • Mistake: Calling another service inside a loop. Why it is wrong: round trips add up linearly; 50 calls at 20 ms is a second of waiting. Instead: batch, or run calls in parallel with a concurrency limit.
  • Mistake: Sending plain HTTP between internal services. Why it is wrong: "the network is secure" is a fallacy; internal traffic can be intercepted, and the ACSC's guidance assumes breach. Instead: TLS everywhere plus service-to-service authentication (managed identities, mTLS).
  • Mistake: Creating a singleton HttpClient with default settings and keeping connections forever. Why it is wrong: it never re-resolves DNS, so it keeps talking to old addresses after topology changes. Instead: use IHttpClientFactory or set PooledConnectionLifetime.
  • Mistake: Retrying every failure automatically. Why it is wrong: retrying a non-idempotent POST can charge a customer twice. Instead: retry only idempotent operations or those protected by idempotency keys.
  • Mistake: Testing only on a laptop where all services run locally. Why it is wrong: local calls have near-zero latency and never drop, so the fallacies stay hidden. Instead: inject latency and faults in tests (Toxiproxy, Azure Chaos Studio).

πŸ› Senior insight: trade-offs

The fallacies aren't trivia; they're a checklist for code review. Every time a design adds a network hop, I ask four questions: what is the timeout, is it safe to retry, what happens to the user when it fails, and how much latency does it add to the critical path. If nobody can answer, the hop is not ready.

Cloud-native architectures make the fallacies more relevant, not less. A request that touched one monolith now crosses an API gateway, three microservices, a service mesh sidecar and a managed database, each a place where latency, failure and security assumptions break. The senior response is architectural, not just a retry policy:

  • Reliability: keep synchronous call chains short (two hops on the request path is a good limit), and move work that can finish later onto Azure Service Bus queues, where the broker absorbs outages and retries.
  • Latency and bandwidth: design coarse-grained contracts (batch endpoints, a backend for frontend), use gRPC with HTTP/2 between internal services when payload size and serialisation cost matter, and keep chatty calls inside one service.
  • Security: assume breach (ACSC guidance, zero trust). Use TLS everywhere, managed identities and Entra ID tokens for service-to-service authentication, or mTLS from a service mesh, never "it's inside the VNet".
  • Topology: let the platform resolve addresses (Kubernetes Services, .NET Aspire service discovery, Azure Container Apps ingress) and recycle connections with PooledConnectionLifetime.
  • Administrators: write contracts and runbooks as if another team will change things tomorrow, because they will.

The other senior move is knowing when not to distribute. A lot of pain comes from splitting a system before the team needs independent deployment or scaling.

Option When it fits Cost When not to
In-process call (modular monolith) One team, shared release cadence Coupled deployment Parts need very different scaling or ownership
Synchronous remote call (HTTP/gRPC) Caller needs the answer now Latency, partial failure, cascading outages Long chains of calls on the request path
Asynchronous message (Service Bus) Work can finish later Eventual consistency, duplicate handling User needs an immediate, consistent answer

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate mentions round trips adding up or chatty calls. Why: Checks the numbers behind the "latency is zero" fallacy.
    How to answer
    • Latency: how long one thing takes, such as one round trip or one request (ms). Bounded by distance (light in fibre travels roughly 200 km per ms) plus queuing and processing.
    • Bandwidth: the maximum data rate of a link (Mbit/s, Gbit/s). The width of the pipe.
    • Throughput: what you actually achieve (requests/s or MB/s). Limited by bandwidth, latency, windows, concurrency and the slowest component.

    For most APIs, latency Γ— number of round trips dominates, not bandwidth. A request that makes 50 sequential database calls at 2 ms RTT spends 100 ms on the network; move the database to another region at 30 ms RTT and it spends 1.5 s. Fix it by reducing round trips (batching, joins, fewer chatty calls), moving compute near data, caching, and parallelising independent calls.

  2. When: Candidate says the network is unreliable. Why: Checks understanding of partial failure, the core consequence of the fallacies.
    How to 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.

  3. When: Candidate mentions retries. Why: Checks how the candidate turns "the network is unreliable" into a safe retry policy.
    How to answer

    Retry handles transient faults: a network blip, 503, 429 or a timeout that will probably succeed if you try again shortly.

    • What to retry: 5xx, 408, 429 (honour Retry-After), connection errors and timeouts. Never retry 400, 401, 403, 404, 409 or validation failures.
    • How: exponential backoff with jitter, so thousands of clients don't retry in lockstep. Cap the attempts, and keep the whole thing inside a total timeout.
    • Safety: retry only idempotent operations. For POST, use an idempotency key or disable retries for unsafe methods.

    The danger is amplification: retries at the API, service and client layers multiply, which creates a retry storm against a recovering dependency. Retry at one layer and pair it with a circuit breaker.

    In .NET 10 it's Polly v8 (AddRetry) or AddStandardResilienceHandler (3 retries, exponential, jitter, 2 s base). The trade-off is higher success rates against extra load and latency.

More in Distributed Systems Core Concepts

Last updated 23 Nov 2026.

🌐 Sangam's Webring

βͺ Previous 🏠 Main Next ⏩
πŸ’¬ Chat with me