The flaky-tests story told as a delivery problem: measuring flakiness from CI history, quarantining with an owner and a deadline, fixing the common causes (time, ordering, shared state, async waits), changing the team habit of re-running, and showing release frequency recover.
When flaky tests block releases I treat it as a delivery problem with data, not an annoyance. I pull failure rates per test from CI history, because usually a handful of tests cause most of the red builds. Those go into quarantine with an owner and a deadline: they still run and report, but don't block the release.
Then we fix the causes, which are nearly always time (DateTime.Now instead of TimeProvider), shared state and test order, real network calls, or fixed sleeps. The habit matters as much as the code: no silent re-runs, and the flaky count on the team board. The trade-off: quarantine unblocks releases immediately, but every quarantined test is a hole in your safety net until it's fixed.
"At [company], our main pipeline for [the orders service] was passing first time [about 60%] of the time. People had got used to clicking re-run, so a merge took [over an hour], and twice we [missed a release window] because the build wouldn't go green. Nobody owned it, because every individual failure looked random.
I exported [the last 30 days] of test results from [Azure DevOps Test Analytics] and found that [7 tests out of about 2,400] caused [over 80%] of the failures. I raised that in stand-up with the list, and we agreed a rule: those tests moved to a quarantine category that still runs and reports but doesn't block the merge, each with an owner and a two-week deadline. I took [the three worst] myself. Two used
DateTime.UtcNowand failed around midnight UTC, which is mid-morning in Sydney, so I moved the code toTimeProviderand the tests toFakeTimeProvider. One integration test depended on data left by another; I gave each test class its own database with Testcontainers and Respawn.The harder part was the habit. We agreed that a re-run needed a ticket for the failing test, and I put the flaky count on the team dashboard. Within [a month], first-time pass rate went from [60% to 97%], merge time dropped [from over an hour to about 15 minutes], and we went back to [releasing daily]. What I learned is that flakiness is a team habit as much as a code problem."
| Cause | Symptom | Fix in .NET |
|---|---|---|
| Wall-clock time | Fails at midnight, month end, DST change | Inject TimeProvider; FakeTimeProvider.Advance() in tests |
| Shared state / test order | Passes alone, fails in the full run | Fresh data per test (Respawn, transactions), no static mutable state |
| Parallelism | Fails only on CI agents with more cores | xUnit collections for shared resources, unique names per test |
| Real network / third parties | Fails when a sandbox is down | WireMock.Net or a stub HttpMessageHandler |
| Fixed sleeps | Task.Delay(500) then assert |
Await the operation, or poll with a timeout |
| Environment | Culture, time zone, file paths | Set CultureInfo explicitly; use Path.Combine |
| Rule | Why |
|---|---|
| Still runs, results visible | You keep the signal and see whether the fix worked |
| Owner and a deadline | Otherwise quarantine becomes a graveyard |
| Limit (e.g. max 10 tests) | Forces fixing before adding |
| Delete if not fixed by the deadline and replace with a better test | A test nobody trusts protects nothing |
"[7 of ~2,400] tests caused [80%] of red builds. After a month: first-time pass rate [60% → 97%], median merge time [70 → 15 minutes], releases back to [daily], and the quarantine list stayed under [5] tests for the next [two quarters]."
Checks whether the candidate takes ownership of a shared delivery problem, uses data to focus effort, knows the real causes of flaky .NET tests, and changes team habits so the fix lasts.
Green flags
Red flags
flaky test fails ─► dev re-runs ─► passes ─► "must be flaky"
│ │
└──── real regression fails the same way ◄─┘ (now ignored too)
Once people learn a red build is probably noise, they stop reading failures, and real regressions slip through. Google has published that around 1.5% of its test runs showed flaky results and that a large share of tests had flaked at some point; the problem is normal at scale and needs a process, not heroics.
dorny/test-reporter), or TRX files from dotnet test --logger trx pushed to a database.for i in {1..50}; do dotnet test --filter FullyQualifiedName~X; done), randomise order, run with full parallelism.DateTime.Now/UtcNow and Stopwatch in code under test. Since .NET 8, TimeProvider is the abstraction; Microsoft.Extensions.TimeProvider.Testing gives FakeTimeProvider.async void tests or un-awaited tasks finish after the assertion.Use STAR by default. SOAR works well here because the obstacle ("everyone just re-ran it") is the interesting part. Keep the technical detail to two causes and their fixes; the interviewer will drill down if they want more.
It also answers: "Tell me about improving developer productivity", "Tell me about changing a team habit", "How do you keep a CI pipeline healthy?"
DateTime.UtcNow and rewrite it with FakeTimeProvider.Quarantined trait and a pipeline step that runs those tests without failing the build.[placeholders] for every number and rehearse it in 90 seconds.The key fix for the most common cause, time, is injecting TimeProvider and using FakeTimeProvider in tests.
// Before: depends on the real clock, so it fails near midnight UTC and at month end.
// After: TimeProvider is injected; production uses TimeProvider.System.
namespace Orders;
public sealed record Order(Guid Id, DateTimeOffset PlacedAt);
public sealed class CancellationPolicy(TimeProvider clock)
{
private static readonly TimeSpan Window = TimeSpan.FromHours(24);
public bool CanCancel(Order order) =>
clock.GetUtcNow() - order.PlacedAt < Window;
}
// Program.cs
// builder.Services.AddSingleton(TimeProvider.System);
// builder.Services.AddSingleton<CancellationPolicy>();
// Test: deterministic, no sleeps. Package: Microsoft.Extensions.TimeProvider.Testing
using Microsoft.Extensions.Time.Testing;
using Orders;
using Xunit;
namespace Orders.Tests;
public sealed class CancellationPolicyTests
{
[Fact]
public void Cannot_cancel_after_24_hours()
{
var clock = new FakeTimeProvider(new DateTimeOffset(2026, 3, 31, 23, 30, 0, TimeSpan.Zero));
var policy = new CancellationPolicy(clock);
var order = new Order(Guid.NewGuid(), clock.GetUtcNow());
clock.Advance(TimeSpan.FromHours(25));
Assert.False(policy.CanCancel(order));
}
// Quarantined test: still runs and reports, but a separate pipeline step
// doesn't fail the build. Owner and deadline live in the linked ticket.
[Fact, Trait("Category", "Quarantined")]
public void Legacy_report_export_matches_snapshot() { /* being fixed: [ticket] */ }
}
# VSTest-based dotnet test: the blocking step excludes quarantined tests...
dotnet test --filter "Category!=Quarantined"
# ...and a non-blocking step (continueOnError: true) runs only them, so the signal isn't lost.
dotnet test --filter "Category=Quarantined"
[Fact(Skip = "flaky")] with no owner. Why it is wrong: the test is silently gone forever. Instead: quarantine that still runs, with an owner and a deadline.FakeTimeProvider, call Advance() so timers and Task.Delay(…, timeProvider) fire deterministically.async void test methods or fire-and-forget tasks in the code under test. Why it is wrong: the test can finish (and pass) before the work does, or an exception lands on another test. Instead: return Task from tests, await everything, and expose a way to await background work (e.g. a Channel drained in the test).[Collection].The senior part of this story is taking ownership of a commons problem and changing behaviour, not just code. Measuring first makes the problem undeniable and keeps the effort small (a handful of tests usually cause most failures). Making quarantine visible and time-boxed keeps the safety net honest. Ending with the team's habit changed, and the metric still on the dashboard months later, shows it stuck without you.
Also say what you'd do differently, such as adding a flakiness check to new tests (run new tests 20 times in the PR build) so the problem doesn't come back.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Quarantine with owner and deadline | A few tests cause most failures | Temporary hole in coverage | As a permanent home for tests |
| Auto-retry failed tests | Short-term while fixing, with retries reported | Masks real races | As the only fix |
| Delete and rewrite the test | Test is poorly designed or tests implementation | Effort; brief loss of coverage | Test covers a critical path with no replacement ready |
| Fix the root cause | Always the goal | Engineering time | Never skip it |
Measure first. Collect TRX or JUnit reports from every CI run. A test that fails and then passes on the same commit is flaky. Rank tests by flaky rate.
Reproduce the failure: run the test in a loop (50 to 200 times), run it in parallel with its neighbours, run it on limited CPU, and use --blame-hang-timeout for hangs. The usual causes are time (DateTime.Now, Task.Delay waits), shared state, test order, parallelism, culture or time zone, and real network calls.
Quarantine visibly: tag the test so the release gate filters it out, but keep running and reporting it. Give it an owner, a ticket and a deadline, or delete it.
Prevent new ones with TimeProvider, banned-API analysers, the xUnit analysers and a flaky-rate dashboard. The trade-off is that quarantine unblocks releases but lowers coverage, so it must be temporary.
Inject TimeProvider (registered as TimeProvider.System in DI) instead of calling DateTime.UtcNow or Task.Delay directly. In tests use FakeTimeProvider from Microsoft.Extensions.TimeProvider.Testing: set a start time, call Advance to move time forward, and timers, delays and PeriodicTimer created from it fire deterministically with no real waiting. Test the boundaries (exactly at expiry, one tick either side), keep business time in UTC, and cover daylight-saving rules with a fake local time zone.
How to tell it (STAR)
**S:** At [company], our [orders service] pipeline passed first time only [about 60%] of the time, merges took [over an hour], and we'd missed [two release windows]. **T:** Nobody owned it, so I took it on. **A:** I exported [30 days] of results and showed the team that [7 of 2,400] tests caused [80%] of failures. We agreed to quarantine them with owners and a two-week deadline. I fixed the three worst: two depended on the real clock, so I moved them to TimeProvider, and one shared data with another test class, so I gave each class its own database. I also proposed that re-runs need a ticket and put the flaky count on our dashboard. **R:** Within [a month], first-time pass rate went from [60% to 97%], merges took [about 15 minutes], and we were back to [daily releases].
Last updated 23 Nov 2026.