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.
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.
"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."
| 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 |
| 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 |
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.
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
Red flags
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
Tests must either control these conditions (component tests) or observe them in reality (production).
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.
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.
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.
WithDelay and fault responses.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.| 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.
DistributedApplicationTestingBuilder test for a journey across both.Task.Delay in an existing test.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);
}
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.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.
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.
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.
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.
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.
Last updated 23 Nov 2026.