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

📚 Interview question

Flaky tests are blocking releases. How do you find the cause, decide whether to quarantine, and stop new flaky tests from appearing?

A team-level approach to flaky tests in .NET: measuring flakiness from CI test reports, reproducing failures (loops, parallelism, limited CPU, blame options), the common root causes, a visible quarantine with an owner and deadline, and prevention with TimeProvider, banned-API analysers, xUnit analysers and a flaky-rate dashboard.

Senior RealWorldScenario Advanced ci-cd flaky-tests test-reliability testing timeprovider xunit

🎯 Key points

  • Measure first: TRX or JUnit reports per run; flaky = failed then passed on the same commit; track flaky rate per test
  • Reproduce: loop the test (50-200 runs), run it with its neighbours in parallel, limit CPU (docker --cpus=1), --blame-hang-timeout for hangs
  • Usual causes: time (DateTime.Now, Task.Delay waits), shared static or database state, order dependence, parallelism, culture or time zone, real network, unawaited tasks
  • Quarantine visibly: [Trait("Category","Quarantine")] filtered out of the gate but still run and reported; owner, ticket, deadline (e.g. 2 weeks) or delete
  • Automatic retries are a diagnostic, not a fix: retry and report, never silently pass
  • Fix with determinism: TimeProvider/FakeTimeProvider, await signals not sleeps, test-owned data, unique ports
  • Prevent: BannedApiAnalyzers (DateTime.Now, Thread.Sleep in tests), xUnit analysers, review checklist, flaky-rate dashboard and an SLO

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"A flaky test is one that passes and fails on the same code. The real damage isn't the red build, it's that people learn to click re-run and stop trusting failures, including real ones. So I treat it as a reliability problem with data. I publish TRX results from every CI run (dotnet test --logger trx) into Azure DevOps Test Analytics, or a test reporter on GitHub. A test that failed and then passed on the same commit is flagged, and I rank tests by flaky rate. Usually five or six tests cause most of the pain.

For example, at [company] our [service] pipeline was failing about [x]% of runs with no code change. I took the worst offender and ran it 200 times in a loop: it passed every time on its own. Run with its class in parallel on one CPU, it failed about one time in thirty. The cause was a static list shared by two test classes, plus a Thread.Sleep(500) waiting for a background worker that took longer on a loaded agent. We moved the state into a per-test fixture, replaced the sleep with awaiting a TaskCompletionSource signalled by the worker, and used FakeTimeProvider for the timer. Re-runs dropped from [x]% to [y]%.

While a fix is in progress, I quarantine visibly. The test gets [Trait("Category", "Quarantine")], the release gate runs with --filter Category!=Quarantine, and a separate non-blocking job still runs and reports the quarantined tests. Every one has an owner, a ticket and a two-week deadline, after which it's fixed or deleted. The mistake I see is turning on automatic retries and calling it solved. That hides real race conditions that will also happen in production. Then I stop new ones: banned-API analysers for DateTime.Now and Thread.Sleep in test projects, the xUnit analysers, and a flaky-rate number on the team dashboard with a target, say under 1% of runs. Flakiness is a bug in the test or in the product, and both are worth finding."


Root causes and fixes

Cause Typical symptom Fix
Time Fails near midnight, month end or daylight-saving changes; timeouts on slow agents Inject TimeProvider; FakeTimeProvider.Advance in tests
Sleeps as synchronisation Fails only on loaded agents Await a signal (TaskCompletionSource, channel), or poll with a deadline
Shared state (static fields, one database) Fails only when run with other tests Per-test data, fixtures, Respawn or a database per class
Order dependence Passes alone, fails in the suite Each test arranges its own state
Parallelism Fails with more cores or fewer Proper fixture scopes; unique ports and file names
Culture or time zone Fails on one agent image Set culture explicitly; use UTC; test time zones on purpose
Real network or third parties Fails in bursts WireMock.Net, Testcontainers
Unawaited tasks, async void Random exceptions in other tests Await everything; the xUnit analysers flag blocking calls

Quarantine rules

Rule Why
Tagged, not deleted or skipped silently It keeps running and reporting, so you know when it's fixed
Owner + ticket + deadline Quarantine with no deadline becomes permanent lost coverage
Cap, e.g. at most 10 tests Forces fixing over hiding
Product bug found? Fix the product Some "flaky tests" are real races

Production example

A pipeline where about 15% of runs needed a manual re-run (around 40 minutes lost per developer per day) can usually get below 2% within a sprint by fixing the top five flaky tests. The common culprits are time, sleeps and shared state.

🔍 What the interviewer is checking

Checks whether the candidate can lead a systematic, data-driven response to flaky tests at team level, not just fix a single test.

Green flags

  • Measures flakiness from CI reports (same-commit fail-then-pass) before acting.
  • Has concrete reproduction techniques: loops, neighbours, limited CPU, blame dumps.
  • Names the root causes and deterministic fixes (TimeProvider, signals, fixtures, WireMock.Net).
  • Uses a visible quarantine with an owner and deadline, and adds prevention (analysers, dashboard, target).

Red flags

  • "Just add retries" or "increase the timeout".
  • Skips or deletes tests silently.
  • Never considers that the flakiness could be a real product race.

📚 Learn in depth

1. What "flaky" really means

A test is a function of code, test data, environment and timing. When only the code is fixed, any variation in the other three can change the result.

result = f(code, data, environment, timing)
          fixed   shared?  agent CPU,  thread scheduling,
                  order?   culture,    clock, network
                           time zone

Flakiness is non-determinism you didn't control. The fix is always to take control of the varying input, not to retry.

2. Detecting it

  • Reports: dotnet test --logger "trx" (or JUnit through a logger package) per run, published to Azure DevOps (Test Analytics shows pass rate per test and can flag flaky tests) or to a GitHub test reporter action.
  • Same-commit signal: failed then passed on the same SHA is the cleanest definition.
  • Trend: flaky rate per test over 14 to 30 days, top-N list in the team's weekly review.

3. Reproducing it

  1. Loop alone: for i in $(seq 200); do dotnet test --filter "FullyQualifiedName~OrderWorkerTests" || break; done.
  2. Loop with neighbours: run the whole class or collection, because shared state only shows with company.
  3. Starve the CPU: docker run --cpus=1 ..., or run two suites at once. Timing bugs appear quickly.
  4. Hangs: dotnet test --blame-hang-timeout 2m collects a dump of the hung test host. Open it with dotnet-dump analyze and run clrstack -all.
  5. Change environment: set TZ=Australia/Sydney, or a different culture, and fake the date to the October or April daylight-saving change.

4. Fixing it with determinism

  • Time: inject TimeProvider (built into .NET 8 and later). In tests, FakeTimeProvider.Advance(TimeSpan) fires due timers and completes Task.Delay(delay, timeProvider) straight away.
  • Background work: expose a completion signal, or poll with a short interval and a hard deadline. Never use a fixed sleep.
  • State: test-owned data, the right fixture scope, unique resource names (ports, temp folders, queue names).
  • External services: WireMock.Net for HTTP, Testcontainers for databases and brokers.

5. Preventing it

  • Microsoft.CodeAnalysis.BannedApiAnalyzers with a BannedSymbols.txt in test projects: P:System.DateTime.Now, P:System.DateTime.UtcNow, M:System.Threading.Thread.Sleep(System.Int32).
  • xUnit analysers (shipped with xUnit): xUnit1031 flags blocking task operations in tests, and others catch async void tests and bad fixture use.
  • Review checklist: no sleeps, no wall-clock time, no shared statics, no real network.
  • A target: flaky rate below 1% of runs, visible on the dashboard. What gets measured gets fixed.

Try it yourself

  1. Write a test that waits for a BackgroundService with Thread.Sleep(100). Run it 200 times under --cpus=1 and count the failures.
  2. Rewrite it with a TaskCompletionSource signal and FakeTimeProvider, then rerun the loop.
  3. Add BannedApiAnalyzers to a test project and ban DateTime.Now. Fix what lights up.
  4. Publish TRX from your pipeline and build a query for tests that failed then passed on the same commit.
  5. Use --blame-hang-timeout on a deliberately deadlocked test and find the deadlock in the dump.

💻 Code

A flaky test (sleep plus wall-clock time) and its deterministic rewrite (xUnit v3, FakeTimeProvider).

#nullable enable
using Microsoft.Extensions.Time.Testing;
using Xunit;

namespace Orders.Tests;

// ----- Code under test: expires unpaid orders after 30 minutes -----
public sealed class OrderExpiryWorker(TimeProvider clock)
{
    private readonly TaskCompletionSource _firstSweep = new(TaskCreationOptions.RunContinuationsAsynchronously);
    public List<Guid> Expired { get; } = [];
    public Task FirstSweepCompleted => _firstSweep.Task; // a signal tests can await

    public async Task RunAsync(IReadOnlyDictionary<Guid, DateTimeOffset> unpaidSince, CancellationToken ct)
    {
        using var timer = new PeriodicTimer(TimeSpan.FromMinutes(1), clock);
        while (await timer.WaitForNextTickAsync(ct))
        {
            var now = clock.GetUtcNow();
            foreach (var (id, since) in unpaidSince)
                if (now - since >= TimeSpan.FromMinutes(30) && !Expired.Contains(id))
                    Expired.Add(id);
            _firstSweep.TrySetResult();
        }
    }
}

public sealed class OrderExpiryWorkerTests
{
    // FLAKY (kept as a comment): real clock and a sleep.
    // It depends on agent speed and would need to wait 30 real minutes to be meaningful.
    //   var worker = new OrderExpiryWorker(TimeProvider.System);
    //   _ = worker.RunAsync(orders, ct);
    //   Thread.Sleep(1500);
    //   Assert.Contains(id, worker.Expired);

    [Fact]
    public async Task Unpaid_order_expires_after_30_minutes()
    {
        var ct = TestContext.Current.CancellationToken;
        var clock = new FakeTimeProvider(new DateTimeOffset(2026, 11, 21, 0, 0, 0, TimeSpan.Zero));
        var id = Guid.NewGuid();
        var orders = new Dictionary<Guid, DateTimeOffset> { [id] = clock.GetUtcNow() };
        var worker = new OrderExpiryWorker(clock);

        using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
        var run = worker.RunAsync(orders, cts.Token);

        clock.Advance(TimeSpan.FromMinutes(31)); // fires the timer: no waiting in real time
        await worker.FirstSweepCompleted.WaitAsync(TimeSpan.FromSeconds(5), ct); // signal, with a safety deadline

        Assert.Contains(id, worker.Expired);

        await cts.CancelAsync();
        await Assert.ThrowsAnyAsync<OperationCanceledException>(() => run);
    }
}
# BannedSymbols.txt in the test project (Microsoft.CodeAnalysis.BannedApiAnalyzers)
P:System.DateTime.Now;Use TimeProvider / FakeTimeProvider
P:System.DateTime.UtcNow;Use TimeProvider / FakeTimeProvider
M:System.Threading.Thread.Sleep(System.Int32);Await a signal instead of sleeping
# Release gate skips quarantined tests; a separate non-blocking job still runs them
dotnet test --filter "Category!=Quarantine" --logger trx --blame-hang-timeout 5m
dotnet test --filter "Category=Quarantine" --logger trx || true

⚠ Common mistakes

  • Mistake: Turning on automatic retries and calling the problem solved. Why it is wrong: It hides real race conditions that will also happen in production, and the suite gets slower. Instead: Retry only to detect and report flakiness, and fix the cause.
  • Mistake: Marking tests Skip with no owner or deadline. Why it is wrong: The coverage is gone for good and nobody notices. Instead: Use a visible quarantine trait that is still run and reported, with a ticket and an expiry.
  • Mistake: Making a sleep longer to fix a timing failure. Why it is wrong: The test gets slower and still fails on a slower agent. Instead: Await a signal, or use FakeTimeProvider.
  • Mistake: Reproducing only by running the test alone in the IDE. Why it is wrong: Shared-state and parallelism bugs only appear with neighbours or under load. Instead: Loop it with its class, under limited CPU.
  • Mistake: Assuming the test is wrong and the product is right. Why it is wrong: Some flaky tests expose real races, such as a double-processed message. Instead: Read the failure as a possible product bug first.
  • Mistake: Having no metric. Why it is wrong: Flakiness creeps back and nobody can tell whether it's getting better. Instead: Track flaky rate per test and per pipeline on a dashboard, with a target.
  • Mistake: Using DateTime.Now and culture-dependent formatting in tests. Why it is wrong: They fail at midnight, around daylight-saving changes or on agents with a different locale. Instead: Use TimeProvider, UTC and an explicit culture, enforced with BannedApiAnalyzers.

🏛 Senior insight: trade-offs

Flaky tests are a trust problem before they are a technical one. Once people re-run by reflex, real failures get re-run too, and the suite stops protecting releases. My approach is to make flakiness visible (a number on the dashboard), make it someone's job (an owner per quarantined test), and make the right fix the easy one (TimeProvider, fixtures, WireMock.Net, analysers). I'd also put a cap on quarantine, so it can't become a dumping ground.

I measure success by the re-run rate of the release pipeline and the median time to green. If those improve, the team's trust in the suite comes back.

Option When it fits Cost When not to
Fix immediately Cause is clear (sleep, time, shared static) An hour or two Never skip it when the cause is known
Visible quarantine Cause unknown and releases are blocked Temporary coverage loss; tracking No owner or deadline available
Retry and report Detection phase, to measure flaky rate Slower runs; can hide races As a permanent "fix"
Delete the test Low value, duplicated by better tests Lost coverage It guards a critical path

🔗 Follow-ups the interviewer may ask

  1. When: Candidate identifies shared state between test classes as the cause. Why: Checks they know xUnit fixture scopes and isolation.
    How to answer

    Wrap the resource in a fixture that implements IAsyncLifetime, so the container starts once in InitializeAsync and is removed in DisposeAsync. Then pick the sharing scope:

    • IClassFixture<T>: one instance per test class.
    • ICollectionFixture<T> with [CollectionDefinition]: one instance for every class in the collection, and those classes run serially.
    • xUnit v3 assembly fixture ([assembly: AssemblyFixture(typeof(T))]): one instance for the whole run, with tests still running in parallel, so the fixture must be thread-safe.

    Share the resource, not the state. Each test creates its own rows with unique keys, or you reset the database between tests with Respawn. Respawn is a small library that deletes data in foreign-key order and keeps the schema. The trade-off is that a wider scope gives a faster suite, but one test can leak data into another.

  2. When: Candidate mentions shared seed data causing order-dependent failures. Why: Checks their test data isolation strategy.
    How to answer

    Choose the data strategy per test level:

    • Unit tests: test data builders with valid defaults, so each test states only the field it cares about.
    • Integration tests: every test creates its own rows with unique keys, and the database is reset with Respawn. No test relies on another test's data.
    • End-to-end and UAT: synthetic data seeded from code, for example Bogus with a fixed seed so runs repeat, and versioned in git.

    Build edge cases in on purpose: Unicode names, boundary amounts, Australian daylight-saving changes. Never copy production PII into lower environments. Under the Privacy Act 1988 (APP 11), a test copy is still personal information you must protect, and a leak can be a notifiable data breach. The trade-off is that synthetic data takes effort to make realistic, but it removes a whole class of privacy risk.

🛠 Real-world problems: how you handle them

Release pipeline blocked by tests that only failed on loaded CI agents
Situation
A [service] with about [n] tests ran on shared Azure DevOps agents. Around [x]% of release runs failed and passed on re-run, and the team had started re-running by reflex, including once on a real regression.
Signals
Pass rate per test in Azure DevOps Test Analytics below 98% for five tests; the same commit failing then passing; failures clustered at busy times on the agent pool; developers reporting about [time] lost per day to re-runs.
Investigation
Ranked tests by fail-then-pass rate over 30 days. Looped the top test 200 times alone (all passed), then with its class under docker --cpus=1 (about 1 in 30 failed). Found Thread.Sleep waits for a BackgroundService, DateTime.UtcNow in an expiry check and a static list shared between two classes. Used --blame-hang-timeout to capture a dump for one hanging test and found an unawaited task.
Resolution
Immediate: moved the five tests to a visible quarantine trait with owners and a two-week deadline, so releases were unblocked while the tests still ran in a non-blocking job. Real fix: injected TimeProvider and used FakeTimeProvider, replaced sleeps with completion signals, moved shared state into fixtures, and awaited the stray task. All five were back in the gate within [n] days.
Prevention
BannedApiAnalyzers in all test projects (DateTime.Now/UtcNow, Thread.Sleep), xUnit analysers as errors, a review checklist item, a quarantine cap of 10 tests, and a flaky-rate panel on the team dashboard with a target of under 1% of runs.

How to tell it (STAR)

**S:** Our release pipeline failed on about [x]% of runs with no code change, and people had started re-running without looking. One real regression slipped through that way. **T:** I took ownership of getting the suite trustworthy again without blocking releases. **A:** I ranked tests by fail-then-pass rate, reproduced the worst ones by looping them with their neighbours on one CPU, and found sleeps, wall-clock time and shared statics. I quarantined five tests visibly with owners and deadlines, fixed them with TimeProvider, completion signals and fixtures, and added banned-API analysers and a flaky-rate dashboard. **R:** Re-runs dropped from [x]% to [y]%, median time to green fell by [n] minutes, and quarantine has stayed under [n] tests since.

↩ Usually asked after

More in .NET Testing Tools

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me