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

📚 Interview question

How do you test a distributed .NET system made of several services, queues and databases? What can you test locally and in CI, what can only be tested in production, and how would you run chaos experiments safely?

Testing distributed .NET systems: component tests with real dependencies in containers, .NET Aspire integration tests, contract tests, asserting eventual consistency, fault injection with Polly chaos strategies and Azure Chaos Studio, and testing in production with synthetic monitoring, canaries and feature flags.

Senior Theory Advanced aspire chaos-engineering distributed-systems polly testing testing-in-production

🎯 Key points

  • Test each service as a component with real dependencies (Testcontainers) and fakes for other services; contract tests for the seams
  • Aspire.Hosting.Testing (DistributedApplicationTestingBuilder) runs the whole app model locally or in CI for a few end-to-end journeys
  • Assert eventual consistency by polling with a deadline and a correlation id, never fixed sleeps; test duplicate and out-of-order delivery
  • Exercise failure modes explicitly: slow and failing dependencies, timeouts, network partitions, crashes between commit and publish, poison messages
  • Fault injection: WireMock.Net delays and errors; Polly v8 chaos strategies (AddChaosLatency, AddChaosFault, AddChaosOutcome) behind a switch; Azure Chaos Studio for infrastructure
  • SLOs (for example checkout p95 < 800 ms, error rate < 0.5%) define the steady state, the chaos abort thresholds and the production alerts
  • Observability is the assertion tool in production and during chaos: golden signals, distributed traces and logs correlated per request
  • Test in production safely: synthetic monitoring with test accounts, canaries, feature flags, small blast radius and automatic abort

⏱ 30-second answer

I test a distributed system in layers. Each service gets component tests with its own real dependencies in containers (Testcontainers: SQL Server, Service Bus emulator, Redis) and fakes for other services; contract tests cover the seams between services. A handful of critical journeys run end to end with .NET Aspire's testing host (DistributedApplicationTestingBuilder). Because the system is eventually consistent, assertions poll with a deadline instead of sleeping, and I test duplicate and out-of-order messages. I inject faults deliberately: WireMock.Net delays, Polly v8 chaos strategies. But real scale, network and configuration only exist in production, so I also test in production: synthetic checks, canaries, feature flags, SLO alerts, and chaos experiments with a hypothesis, a small blast radius and an abort switch. The trade-off: no single environment proves everything; confidence comes from combining layers.

🗣 Full answer (senior)

How I would answer this in an interview

"The trap with distributed systems is trying to prove everything with one big end-to-end environment. It's slow, flaky and still doesn't look like production. I split it. Each service is tested as a component: its own database, broker and cache are real, in containers via Testcontainers, and the other services are faked with WireMock.Net or in-process fakes. That's where I test retries, idempotency, duplicate messages and poison messages. The seams between services are covered by contract tests, so I know the shapes still match without deploying everything together.

Then a few critical journeys run end to end. With .NET Aspire I can start the whole app model in a test with DistributedApplicationTestingBuilder, wait for resources to be healthy and drive it over HTTP. Because work flows through queues, assertions poll with a deadline rather than sleeping. And I deliberately inject faults: Polly v8 has chaos strategies, so a pipeline can add latency or faults at a set rate behind a configuration switch, which lets me check timeouts, circuit breakers and fallbacks really work.

But some things only exist in production: real traffic patterns, real network, real configuration and scale. For example, at [company] our [order pipeline] passed every pre-production test, then failed under a [regional network blip] because a retry policy and a lock timeout interacted. So we also test in production carefully: synthetic transactions every minute from Application Insights availability tests, canary releases watched against SLOs, feature flags to turn things off, and chaos experiments. We ran them first in staging, then in production with a small blast radius, a written hypothesis and automatic abort conditions, using Azure Chaos Studio for infrastructure faults. The mistake I see is chaos without observability: if you can't see the steady state, you can't tell whether the experiment hurt anything. You don't test a distributed system once, you keep testing it in every environment it runs in."


What each layer can prove

Layer Proves Can't prove Tools
Unit Logic, including retry/idempotency decisions Wiring, real I/O xUnit, fakes, FakeTimeProvider
Component (one service) Service with its real DB, broker, cache Other services' behaviour Testcontainers, WireMock.Net, WebApplicationFactory
Contract Services agree on interfaces Runtime behaviour together Pact, OpenAPI diff
Local end-to-end Key journeys work together Production scale, network, config .NET Aspire testing
Pre-production chaos / load Resilience under faults and load Real user traffic Azure Chaos Studio, k6, Azure Load Testing
Production Real behaviour Nothing safely without guard rails Synthetic monitoring, canaries, flags, SLOs, chaos

Distributed behaviours worth testing explicitly

Behaviour How to test
Duplicate message delivery Deliver the same message twice; assert one effect
Out-of-order messages Deliver v2 before v1; assert final state
Dependency slow WireMock.Net delay or Polly chaos latency; assert timeout and fallback
Dependency down Fault injection; assert circuit opens and recovers
Poison message Message that always throws; assert dead-lettered after N attempts
Crash between DB commit and publish Kill after commit; assert outbox republishes

Production example

After adding component tests for duplicate delivery and a monthly chaos experiment (inject 2 s latency into the inventory API for 10% of calls in production for 10 minutes), the team found a missing timeout on one HttpClient that would have exhausted the thread pool. The experiment aborted automatically when p95 latency crossed [800 ms], affected about [0.5%] of requests for [3] minutes, and the fix shipped before a real incident.

🔍 What the interviewer is checking

Checks whether the candidate has a layered, realistic test strategy for distributed systems, including eventual consistency, fault injection and safe testing in production.

Green flags

  • Component tests with real dependencies plus contract tests, and only a few end-to-end journeys
  • Polls with deadlines for eventual consistency; tests duplicate and out-of-order delivery
  • Fault injection with WireMock.Net, Polly chaos strategies or Azure Chaos Studio
  • Chaos with steady state, hypothesis, blast radius and abort conditions; synthetic monitoring and canaries

Red flags

  • "We test it all in staging"
  • Sleeps in tests for asynchronous effects
  • Chaos in production without observability or abort criteria

📚 Learn in depth

1. Why distributed systems need a different test strategy

A distributed system has partial failure, asynchronous communication and independent deployment. That introduces behaviours a monolith doesn't have:

Orders API --HTTP--> Payments API
     |
     +--publish--> [Service Bus] --deliver (at least once)--> Shipping worker --> Shipping DB
  • Messages can arrive twice, late or out of order.
  • A call can time out after the other side did the work.
  • Each service can be on a different version.
  • Data is eventually consistent: a read straight after a write may not see it.

Tests must either control these conditions (component tests) or observe them in reality (production).

2. Component tests with real dependencies

Testcontainers starts real SQL Server, Redis, RabbitMQ, Kafka or the Azure Service Bus emulator in Docker for the test run. The service runs in-process with WebApplicationFactory; other services are faked at the HTTP boundary with WireMock.Net. This catches serialisation, transaction and broker-configuration bugs that in-memory fakes hide, and stays fast enough for every PR.

3. .NET Aspire for local end-to-end

Aspire.Hosting.Testing starts the AppHost model (projects, containers, connection strings) inside a test:

DistributedApplicationTestingBuilder.CreateAsync<Projects.Shop_AppHost>()
   -> BuildAsync() -> StartAsync()
   -> ResourceNotifications.WaitForResourceHealthyAsync("orders-api")
   -> CreateHttpClient("orders-api")    (service discovery resolves the address)

That makes a real multi-service journey runnable on a laptop or CI agent with Docker. Keep these few (5–15 journeys): they are slower and broader than component tests.

4. Asserting eventual consistency

Replace await Task.Delay(5000) with polling: check every 100–250 ms until the condition holds or a deadline passes, then fail with the last observed state. Use a correlation id so you check your order, not any order. Distributed tracing (OpenTelemetry) lets tests and humans see where a message stopped.

5. Fault injection

  • At the HTTP boundary in tests: WireMock.Net with WithDelay and fault responses.
  • Inside the app: Polly v8 (Polly.Core 8.3+) chaos strategies, AddChaosLatency, AddChaosFault, AddChaosOutcome and AddChaosBehavior, added to a resilience pipeline with an InjectionRate and an EnabledGenerator driven by configuration, so you can switch them on in staging or for a slice of production traffic.
  • Infrastructure: Azure Chaos Studio experiments (VM shutdown, AKS pod kill via Chaos Mesh, network latency, Key Vault deny, Cosmos DB failover) with defined targets and durations.

6. Testing in production

Technique What it gives
Synthetic monitoring (Application Insights standard availability tests, scripted journeys) Detects broken journeys before users report them
Canary / progressive delivery New version gets a small share; compare error rate and latency
Feature flags (Azure App Configuration) Turn code on for staff or a percentage; switch off without redeploy
Dark launch / shadow traffic New path receives copies of real requests; responses discarded
SLOs and burn-rate alerts Objective signal that a change hurt users

Synthetic transactions must use clearly marked test accounts and data that can't trigger real payments, emails or deliveries.

7. Chaos engineering principles

  1. Define the steady state with metrics (orders per minute, p95 latency, error rate).
  2. Write a hypothesis: "if inventory latency rises to 2 s for 10% of calls, checkout p95 stays under 800 ms because of the timeout and fallback".
  3. Limit the blast radius: one region, a percentage, a short duration.
  4. Define abort conditions: automatic stop when an SLO burn rate crosses a threshold.
  5. Run in pre-production first, then production during business hours with people watching.
  6. Fix what you find and automate the experiment so it runs regularly.

Try it yourself

  1. Write a component test that delivers the same Service Bus message twice (emulator in Testcontainers) and asserts one row is written.
  2. Create an Aspire AppHost with two projects and write one DistributedApplicationTestingBuilder test for a journey across both.
  3. Add a Polly chaos latency strategy behind a configuration flag and verify your timeout and fallback with it on.
  4. Write a polling assertion helper and replace a Task.Delay in an existing test.
  5. Draft a chaos experiment document: steady state, hypothesis, blast radius, abort conditions and rollback.

💻 Code

An Aspire end-to-end journey with a polling assertion, plus a Polly v8 chaos strategy switched on by configuration.

// Shop.EndToEndTests/CheckoutJourneyTests.cs
using System.Net.Http.Json;
using Aspire.Hosting;
using Aspire.Hosting.Testing;
using Xunit;

namespace Shop.EndToEndTests;

public sealed record PlaceOrder(string Sku, int Quantity);
public sealed record OrderCreated(Guid OrderId);
public sealed record Shipment(Guid OrderId, string Status);

public sealed class CheckoutJourneyTests
{
    [Fact]
    public async Task PlacedOrder_IsEventuallyShipped()
    {
        var ct = TestContext.Current.CancellationToken;

        // Starts every project and container in the AppHost (APIs, worker, SQL Server, Service Bus emulator).
        var builder = await DistributedApplicationTestingBuilder.CreateAsync<Projects.Shop_AppHost>(ct);
        await using var app = await builder.BuildAsync(ct);
        await app.StartAsync(ct);
        await app.ResourceNotifications.WaitForResourceHealthyAsync("orders-api", ct);
        await app.ResourceNotifications.WaitForResourceHealthyAsync("shipping-api", ct);

        var orders = app.CreateHttpClient("orders-api");
        var shipping = app.CreateHttpClient("shipping-api");

        var response = await orders.PostAsJsonAsync("/orders", new PlaceOrder("SKU-1", 2), ct);
        response.EnsureSuccessStatusCode();
        var created = await response.Content.ReadFromJsonAsync<OrderCreated>(ct);

        // Eventual consistency: poll with a deadline instead of sleeping.
        var shipment = await Eventually.Async(
            () => shipping.GetFromJsonAsync<Shipment?>($"/shipments/{created!.OrderId}", ct),
            s => s is { Status: "ReadyToShip" },
            TimeSpan.FromSeconds(30), ct);

        Assert.Equal(created!.OrderId, shipment!.OrderId);
    }
}

public static class Eventually
{
    public static async Task<T> Async<T>(Func<Task<T>> probe, Func<T, bool> done, TimeSpan timeout, CancellationToken ct)
    {
        using var deadline = CancellationTokenSource.CreateLinkedTokenSource(ct);
        deadline.CancelAfter(timeout);
        T last = default!;
        while (!deadline.IsCancellationRequested)
        {
            try
            {
                last = await probe();
                if (done(last)) return last;
            }
            catch (HttpRequestException) { /* not there yet (e.g. 404); keep polling */ }

            await Task.Delay(TimeSpan.FromMilliseconds(250), CancellationToken.None);
        }
        throw new TimeoutException($"Condition not met within {timeout}. Last value: {last}");
    }
}
// Orders.Api/Program.cs: chaos strategies in the resilience pipeline, off unless configuration enables them.
using Microsoft.Extensions.Options;
using Polly;
using Polly.Simmy;
using Polly.Simmy.Latency;

var builder = WebApplication.CreateBuilder(args);
builder.Services.Configure<ChaosSettings>(builder.Configuration.GetSection("Chaos"));

builder.Services.AddHttpClient<InventoryClient>(c => c.BaseAddress = new Uri("https+http://inventory-api"))
    .AddResilienceHandler("inventory", (pipeline, context) =>
    {
        var chaos = context.ServiceProvider.GetRequiredService<IOptionsMonitor<ChaosSettings>>();

        pipeline.AddTimeout(TimeSpan.FromSeconds(2)); // what the experiment is meant to prove works

        // Inner strategy: injected latency happens 'inside' the timeout, like a slow dependency.
        pipeline.AddChaosLatency(new ChaosLatencyStrategyOptions
        {
            Latency = TimeSpan.FromSeconds(5),
            InjectionRateGenerator = _ => ValueTask.FromResult(chaos.CurrentValue.LatencyRate),
            EnabledGenerator = _ => ValueTask.FromResult(chaos.CurrentValue.Enabled)
        });
    });

var app = builder.Build();
app.Run();

public sealed class ChaosSettings
{
    public bool Enabled { get; set; }          // switched on per environment via Azure App Configuration
    public double LatencyRate { get; set; } = 0.1;
}

public sealed class InventoryClient(HttpClient http)
{
    public Task<int> GetStockAsync(string sku, CancellationToken ct) =>
        http.GetFromJsonAsync<int>($"/stock/{sku}", ct);
}

⚠ Common mistakes

  • Mistake: Relying on one shared end-to-end environment as the main test. Why it is wrong: slow, flaky, couples every team's releases and still differs from production. Instead: component and contract tests per service, a few end-to-end journeys, plus production checks.
  • Mistake: Task.Delay(5000) before asserting an asynchronous effect. Why it is wrong: slow when the system is fast and flaky when it's slow. Instead: poll with a deadline and a correlation id.
  • Mistake: Faking the broker or database with in-memory versions in integration tests. Why it is wrong: misses serialisation, transaction, lock and broker-configuration bugs. Instead: real dependencies in Testcontainers (including the Service Bus emulator).
  • Mistake: Never testing duplicate or out-of-order messages, or a network partition between a service and its broker. Why it is wrong: at-least-once delivery and partial failure guarantee these happen in production. Instead: explicit tests that deliver twice, out of order, and cut the connection mid-operation (for example pausing the broker container).
  • Mistake: Running chaos experiments without defined steady-state metrics or abort conditions. Why it is wrong: you can't tell whether users were hurt, and the experiment can become an outage. Instead: before starting, agree what observers watch: the SLO metrics for the affected journeys (request rate, error rate, p95/p99 latency), saturation (thread-pool queue length, CPU, connection pools), queue depth and dead-letter count, and the circuit-breaker state; set automatic abort thresholds on them.
  • Mistake: Starting chaos in production. Why it is wrong: unknown weaknesses hit real users. Instead: run in pre-production first, then small and supervised in production.
  • Mistake: Synthetic production tests that use real accounts or trigger real side effects. Why it is wrong: real charges, emails or deliveries, and polluted business metrics. Instead: marked test tenants and accounts, excluded from analytics and payments.
  • Mistake: Treating testing in production as a replacement for pre-production testing. Why it is wrong: finds problems after users are exposed. Instead: layer it on top, behind flags and canaries.

🏛 Senior insight: trade-offs

The senior shift is from "prove it works before release" to "build confidence continuously in every environment". Pre-production tests are good at deterministic behaviour (logic, contracts, idempotency, failure handling you can simulate). Production is the only place with real traffic, scale, configuration and network, so you design for safe exposure (flags, canaries), observe against SLOs and experiment deliberately. Each layer covers what the others can't, and none is enough alone.

The organisational part matters too: chaos experiments need agreement from the service owners and on-call, a calendar, and a clear rollback. Start with game days in staging, earn trust, then automate. And because observability is how you assert in production, distributed tracing and good metrics are prerequisites, not extras.

Technique When it fits Cost When not to
Component tests + Testcontainers Every service, every PR Docker in CI, a few minutes Never skip
Contract tests Independently deployed services Broker and states One deployable
Aspire end-to-end A few critical journeys Slower, broad failures As the main test layer
Chaos in pre-production Before relying on resilience policies Environment and time Without observability
Chaos in production Mature teams with SLOs and abort automation Some user risk Early-stage systems, peak trading periods
Canary + SLO gates Any frequent deployment Traffic routing and metrics Tiny user bases (no statistical signal)

I measure success by escaped defects, change failure rate and time to detect, not by the number of end-to-end tests.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions testing fallbacks or degraded modes Why: Checks they can prove fallbacks work before a real outage.
    How to answer

    Fallbacks are code paths that only run during incidents, so they rot unless exercised. I inject faults in a test environment with Polly v8 chaos strategies (AddChaosFault, AddChaosLatency, AddChaosOutcome) or Azure Chaos Studio. Then I assert that the page renders, the right metric increments and the user message appears. I add integration tests that make the dependency return 503 or hang, and run a game day each quarter where on-call flips the kill switches. Success means core flows stay within their SLO while the dependency is down.

  2. When: Candidate mentions end-to-end tests being flaky Why: Checks they can diagnose and fix flakiness rather than accept it.
    How to answer

    Flaky tests are a measurement problem first. I collect results from every CI run (TRX or JUnit reports) and rank tests by failure rate, so I know which tests flake and how often; a pass on re-run means flaky, not fixed. Then I reproduce by repetition: run the suspect test or class hundreds of times, on a constrained agent, in random order. The causes are nearly always one of a few: wall-clock time, shared state (statics, a shared database row), test order, parallelism across xUnit collections, async races with sleep-based waits, or a real external dependency. Diagnostics come from ITestOutputHelper logs and --blame-hang-timeout dumps. Tests I can't fix quickly get quarantined with an owner, an issue and a deadline, never blanket retries. The trade-off: a few days of focused work versus a team that has stopped trusting red builds.

  3. When: Candidate mentions at-least-once delivery or duplicate messages Why: Checks they can turn a distributed-systems guarantee into a concrete, deterministic test.
    How to answer

    Idempotency needs a duplicate-detection mechanism: a stable message id (or business key) recorded in an inbox table with a unique constraint, in the same transaction as the business change. Test it against a real broker or emulator and the real database in Testcontainers. Sequential duplicates: publish the same message twice with the same message id, wait until both deliveries are processed, then assert exactly one business effect (one row in the payments table, one outbox event) and one inbox record. Concurrent duplicates: deliver both copies at once (or call the handler from two tasks released by the same gate) to exercise the race where both pass an "already processed?" check; only the unique constraint or a lock makes that safe, and the losing copy must complete without error rather than dead-lettering. Also assert side effects downstream (published events, notifications) happened once.

🛠 Real-world problems: how you handle them

Chaos experiment found a missing timeout before a real outage
Situation
An [e-commerce] platform of [eight] .NET services on AKS in Australia East had resilience policies on most HttpClients, but they had never been exercised. A major sale event was [six weeks] away.
Signals
No incidents yet, but a review found inconsistent timeout settings, and the team couldn't say what happened to checkout if the inventory API slowed down.
Investigation
I defined steady state from Application Insights (checkout p95 under 800 ms, error rate under 0.5%) and wrote a hypothesis: 2 s inventory latency for 10% of calls would leave checkout within SLO because of the 2 s timeout and cached-stock fallback. We added Polly chaos latency behind an App Configuration flag and ran it in staging first, where it showed checkout p95 jumping to 6 s.
Resolution
Tracing showed one HttpClient registered without the resilience handler, so calls waited for the default 100-second timeout and thread-pool queueing built up. We fixed the registration, re-ran in staging (p95 stayed at 640 ms), then ran the same experiment in production for 10 minutes at 10% with automatic abort at p95 > 800 ms. It held.
Prevention
Made the chaos experiment a monthly automated run in staging and quarterly in production; added an architecture test that every typed HttpClient has a resilience handler; added component tests with WireMock.Net delays for each downstream dependency.

How to tell it (STAR)

**S:** At [company], six weeks before our biggest sale, nobody could say what checkout would do if the inventory API slowed down. **T:** I was asked to prove our resilience policies actually worked. **A:** I defined steady state and a hypothesis, added Polly chaos latency behind a feature flag, and ran it in staging first. Checkout p95 jumped to 6 seconds, and tracing showed one HttpClient had no resilience handler at all. We fixed it, re-ran in staging, then ran a 10-minute production experiment at 10% with automatic abort. **R:** p95 stayed at [640 ms], the sale ran without a checkout incident, and an architecture test now stops any new HttpClient shipping without a resilience handler.

↩ Usually asked after

More in Senior Testing Topics

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me