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

📚 Interview question

Your CI pipeline fails about one run in ten with different tests each time, and they all pass locally. Developers have started clicking re-run. How do you diagnose the flaky tests, decide what to quarantine, and fix the root causes?

Debugging flaky .NET tests: reproducing with repeat runs and constrained resources, classifying causes (time, ordering, shared state, parallelism, async races, external dependencies), xUnit collections and parallelism, blame-hang diagnostics, quarantine policy and permanent fixes.

Senior Debugging Advanced ci-cd debugging flaky-tests test-parallelism testing xunit

🎯 Key points

  • Measure first: collect test results from every CI run (TRX/JUnit) and rank tests by failure rate; re-run success = flaky, not fixed
  • Reproduce by repeating: loop the test hundreds of times, run with constrained CPU, randomise order, run the whole class or assembly
  • Common causes: wall-clock time, shared static or database state, test order, parallel collections, async races (sleep-based waits), ports and files, external services
  • xUnit runs test collections (classes by default) in parallel; shared fixtures and statics leak across them
  • Diagnostics: ITestOutputHelper logs, --blame-hang-timeout and --blame-crash dumps, Testcontainers logs, Application Insights for the app under test
  • Quarantine with an owner, an issue and a deadline; never blanket automatic retries hiding everything
  • Fix root causes: TimeProvider, per-test data, awaited signals, dynamic ports, isolated containers; add a repeat-run check for new tests

⏱ 30-second 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.

🗣 Full answer (senior)

How I would answer this in an interview

"When people start clicking re-run, the real damage is that a red build no longer means anything, so a genuine regression gets re-run too. My first step is data, not guesses. I make sure every CI run publishes test results, TRX or JUnit, and I pull a report of failures per test over the last few hundred runs. Azure DevOps has flaky-test detection built in; with GitHub Actions I aggregate the reports myself. Usually it's a handful of tests causing most of the pain.

Then I reproduce. 'Passes locally' usually means 'passes on a fast, idle machine, alone'. So I run the test in a loop five hundred times, then the whole class, then the whole assembly with parallelism, on a container limited to two CPUs. For example, at [company] we had [a dozen] tests failing about [8%] of runs. Repetition showed three patterns. Some read DateTime.UtcNow and failed near midnight UTC, which is 11 am in Sydney, so they failed every morning. Some shared a static in-memory cache between two test classes that xUnit ran in parallel. And a few used Task.Delay(200) to wait for a background handler. We fixed them with TimeProvider, by isolating the cache per test, and by awaiting a signal instead of sleeping. Failure rate went from [8%] to under [0.5%] in [two weeks].

The mistake I see is turning on automatic retries for the whole suite. That hides flakiness instead of fixing it, and it hides real intermittent bugs in the product too, like race conditions. I quarantine individual tests, each with an owner and an issue, and the rule is it's fixed or deleted within a sprint. A flaky test is a bug, either in the test or in the code."


Classify the failure

Pattern in the data Likely cause First check
Fails at certain times of day or month Wall-clock time, time zones DateTime.Now / UtcNow usage
Fails only when run with others Shared state, order dependence Statics, shared DB rows, fixtures
Fails more on busy agents Async race, timing assumptions Task.Delay / Thread.Sleep waits
Fails with "address in use" / file locked Fixed ports, shared temp files Hard-coded ports and paths
Hangs then times out Deadlock, unawaited task, missing cancellation --blame-hang-timeout dump
Fails with network errors Real external dependency Calls to real third-party services
Product race condition Genuine concurrency bug Reproduce outside tests

Reproduction techniques

Technique How
Repeat a single test Loop dotnet test --filter "FullyQualifiedName~X" or a [Theory] with many rows
Repeat with neighbours Run the class or assembly repeatedly
Constrain resources docker run --cpus=2 for the test run
Change order Randomise or reverse test order; run classes alone
Turn parallelism off xunit.runner.json "parallelizeTestCollections": false; if it stops failing, it's shared state
Capture hangs dotnet test --blame-hang-timeout 2m --blame-hang-dump-type full

Quarantine policy

Rule Why
Quarantine per test, never per suite Keeps the rest of the signal
Owner, issue link and deadline Prevents a permanent graveyard
Quarantined tests still run and report You can see when they are fixed
Fix or delete within a sprint Flaky coverage is worse than honest absence

Production example

A [120-developer] .NET monorepo had a [9%] pipeline failure rate from flaky tests and an average of [1.6] re-runs per PR. Ranking by failure rate showed [14] tests caused [90%] of it. After fixing time, shared-state and sleep-based waits, the flaky failure rate fell below [0.5%] and median PR time to merge dropped by [40] minutes.

🔍 What the interviewer is checking

Checks whether the candidate debugs flaky tests systematically from data, knows the common technical causes in .NET test suites, and sets a quarantine policy that keeps the build trustworthy.

Green flags

  • Starts with failure-rate data across runs, then reproduces by repetition and constrained resources
  • Names causes precisely: time, shared static/database state, xUnit parallel collections, sleep-based waits, external services
  • Uses --blame-hang-timeout, test output logging and Testcontainers logs
  • Quarantine with owner and deadline; rejects blanket retries; considers that the product may have a real race

Red flags

  • "Just add retries" or "increase the delay"
  • Blames the CI agents without reproducing
  • No policy, so quarantined tests are forgotten

📚 Learn in depth

1. Why tests become flaky

A test is deterministic only if everything it depends on is controlled. Flakiness comes from anything uncontrolled:

           +--------------------+
           |      the test      |
           +---------+----------+
                     |
   +--------+--------+---------+-----------+------------+
   |        |        |         |           |            |
 clock   threads   shared    order     resources    network
         /timing   state                (ports,       (real
                  (statics,              files,      services)
                   DB rows)              CPU)

The fix is always to bring one of those under control.

2. How xUnit runs tests in parallel

In xUnit (v2 and v3), each test class is a test collection by default. Collections run in parallel; tests inside a collection run sequentially. Consequences:

  • Two classes touching the same static field, file, or database rows race.
  • [Collection("Database")] on several classes puts them in one collection so they run sequentially and can share an ICollectionFixture<T>.
  • IClassFixture<T> is created once per class; mutable state inside it leaks between that class's tests.
  • A new instance of the test class is created for every test, so instance fields are safe; statics are not.

NUnit and MSTest default to no parallelism unless configured ([Parallelizable], [assembly: Parallelize]), so moving frameworks can expose hidden shared state.

3. Async races

test:      trigger -> sleep(200ms) -> assert
product:   trigger -> queue -> (busy agent: 350 ms) -> handled

The sleep encodes a guess about scheduling. On a loaded agent the guess is wrong. Replace with an awaited signal (TaskCompletionSource, channel) or a polling assertion with a timeout for genuinely eventual systems.

4. Time

DateTime.UtcNow.Date changes at 10 or 11 am in Sydney, so a test comparing "today" computed twice can fail during that second. Month-end, leap days and daylight-saving changes produce rare failures. Inject TimeProvider; use FakeTimeProvider in tests.

5. Shared external resources

  • Databases: tests sharing rows; use unique keys per test, Respawn, or a database per collection with Testcontainers.
  • Ports: WebApplicationFactory uses an in-memory TestServer (no port). If you need Kestrel, bind to port 0 and read the assigned port.
  • Files: use Path.GetTempFileName() or a per-test directory, never a fixed path.
  • Containers: slow container start under load causes timeouts; use Testcontainers' wait strategies rather than fixed delays.

6. Diagnostics

  • ITestOutputHelper (xUnit) or TestContext.Current.TestOutputHelper in v3 captures logs per test; route ILogger to it so the app's logs appear with the failure.
  • dotnet test --blame-hang-timeout 2m kills a hung test host and collects a dump plus the sequence of tests that ran; --blame-crash does the same for crashes. Open with dotnet-dump analyze (clrstack -all) or Visual Studio.
  • Test result history: Azure DevOps Test Analytics flags flaky tests; for GitHub Actions, publish JUnit results and aggregate them (for example in a dashboard or a scheduled job).

7. Retries: where they belong

Microsoft.Testing.Platform has a retry extension and many CI systems can re-run failed tests. Used narrowly (a quarantined test, a known infrastructure blip with tracking) it is pragmatic. Used globally it turns a 10% flaky test into a green build and hides product race conditions. Always record the retry so the data still shows the flake.

Try it yourself

  1. Write two test classes that both modify a static list; run them together repeatedly and watch them race; fix with [Collection] or by removing the static.
  2. Write a test that sleeps 100 ms for a background task that takes 50–150 ms; loop it 500 times; replace the sleep with a TaskCompletionSource.
  3. Run a test suite inside docker run --cpus=1 and compare failure rates.
  4. Add --blame-hang-timeout 30s and write a test that deadlocks with .Result; open the dump and find the blocked thread.
  5. Export the last 200 CI runs' test results and rank tests by failure rate.

💻 Code

Three typical flaky tests and their fixes, in one xUnit v3 file with the code under test.

// Shop/FlakySources.cs  (code under test)
namespace Shop;

public sealed class PriceCache
{
    // FLAKY CAUSE 1 (before): public static readonly Dictionary<string, decimal> Prices = new();
    // Shared across parallel test classes. Fixed: instance state, one cache per test.
    private readonly Dictionary<string, decimal> _prices = new();
    public void Set(string sku, decimal price) => _prices[sku] = price;
    public int Count => _prices.Count;
}

public sealed class DailyReport(TimeProvider time)
{
    // FLAKY CAUSE 2 (before): DateTime.UtcNow.Date read twice could cross midnight UTC (10-11 am Sydney).
    public string FileName() => $"report-{time.GetUtcNow():yyyy-MM-dd}.csv";
}

public sealed class OrderEvents
{
    public event Func<Guid, Task>? OrderPlaced;

    // Fire-and-forget dispatch, like many in-process event buses.
    public void Publish(Guid orderId) => _ = Task.Run(() => OrderPlaced?.Invoke(orderId) ?? Task.CompletedTask);
}
// Shop.Tests/FlakyFixedTests.cs
using Microsoft.Extensions.Time.Testing;
using Shop;
using Xunit;

namespace Shop.Tests;

public sealed class PriceCacheTests
{
    [Fact]
    public void Set_AddsOneEntry()
    {
        var cache = new PriceCache(); // new instance per test: nothing shared with other classes
        cache.Set("SKU-1", 9.95m);
        Assert.Equal(1, cache.Count);
    }
}

public sealed class DailyReportTests
{
    [Fact]
    public void FileName_UsesUtcDate()
    {
        // Controlled clock, set one second before midnight UTC: the old version failed here.
        var time = new FakeTimeProvider(new DateTimeOffset(2026, 11, 21, 23, 59, 59, TimeSpan.Zero));
        Assert.Equal("report-2026-11-21.csv", new DailyReport(time).FileName());
    }
}

public sealed class OrderEventsTests
{
    [Fact]
    public async Task Publish_InvokesHandler()
    {
        var events = new OrderEvents();
        var handled = new TaskCompletionSource<Guid>(TaskCreationOptions.RunContinuationsAsynchronously);
        events.OrderPlaced += id => { handled.TrySetResult(id); return Task.CompletedTask; };
        var orderId = Guid.NewGuid();

        events.Publish(orderId);

        // FLAKY CAUSE 3 (before): await Task.Delay(200); Assert.True(called);
        // Fixed: await the effect, with a real-time guard so a bug fails rather than hangs.
        var received = await handled.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
        Assert.Equal(orderId, received);
    }
}
// xunit.runner.json: temporarily turn off parallel collections to confirm a shared-state diagnosis.
{
  "$schema": "https://xunit.net/schema/current/xunit.runner.schema.json",
  "parallelizeTestCollections": false
}
# Reproduce: loop one test 500 times on 2 CPUs and count failures; capture a dump if it hangs.
for i in $(seq 1 500); do
  docker run --rm --cpus=2 -v "$PWD":/src -w /src mcr.microsoft.com/dotnet/sdk:10.0 \
    dotnet test --filter "FullyQualifiedName~OrderEventsTests" --blame-hang-timeout 2m || echo FAIL >> fails.txt
done
wc -l fails.txt

⚠ Common mistakes

  • Mistake: Enabling automatic retries for the whole test suite. Why it is wrong: flakiness disappears from view, and so do real intermittent product bugs. Instead: retry only quarantined tests, record every retry, and fix the cause.
  • Mistake: Debugging from a single failed run. Why it is wrong: one failure doesn't show the pattern (time of day, neighbours, agent type). Instead: collect results from every run and rank tests by failure rate.
  • Mistake: Concluding "it passes locally, so it's the CI agent". Why it is wrong: local runs are fast, idle and often run the test alone, hiding races and shared state. Instead: reproduce with loops, constrained CPU and the full assembly.
  • Mistake: Increasing Task.Delay from 200 ms to 2 seconds. Why it is wrong: the suite gets slower and the race still exists. Instead: await a signal or poll with a timeout.
  • Mistake: Static fields or shared rows used by several test classes. Why it is wrong: xUnit runs classes in parallel, so they race. Instead: per-test instances and data, or a shared [Collection] when sharing is intended.
  • Mistake: Quarantining without an owner or deadline. Why it is wrong: quarantine becomes a graveyard of silent untested behaviour. Instead: issue, owner, and fix-or-delete within a sprint.
  • Mistake: Assuming the test is wrong. Why it is wrong: some flaky tests are correctly exposing a race condition in the product. Instead: check whether the failure could happen in production before "fixing" the test.
  • Mistake: Calling real third-party APIs from CI tests. Why it is wrong: their latency and outages become your flakiness. Instead: WireMock.Net or fakes in CI; a separate, non-blocking contract or smoke check against the real service.

🏛 Senior insight: trade-offs

Flakiness is an organisational problem as much as a technical one. Each flaky test teaches the team to ignore red builds, and that cost compounds: reviewers stop looking at failures, real regressions get re-run into green. The senior response is to make flakiness visible (a failure-rate report everyone can see), give it an owner, set a policy (quarantine with a deadline, no global retries), and then fix the handful of tests causing most of the pain.

I also prevent new ones: a repeat-run job for new or changed tests (run them 50–200 times before merge or nightly), analyser rules against DateTime.Now and blocking waits, and a testing guideline that bans sleep-based waits. That moves the cost from incident to review.

Response When it fits Cost When not to
Fix the root cause Always the goal Engineer time Never skip it
Quarantine one test Cause not found within a day Temporary lost coverage Without owner and deadline
Narrow, recorded retry Known infrastructure blip being worked on Hides some signal As a permanent global setting
Delete the test Low-value test, costly to fix Lost coverage Tests guarding critical paths
Repeat-run gate for new tests Large suites with recurring flakiness CI minutes Tiny suites

I measure it by flaky failure rate per run, re-runs per PR and the size of the quarantine list over time.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate talks about policy, quarantine and preventing new flaky tests Why: Checks they can turn the debugging into a lasting team process.
    How to 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.

  2. When: Candidate identifies wall-clock time as a cause Why: Checks they can fix time-dependent tests properly with TimeProvider and FakeTimeProvider.
    How to answer

    I inject TimeProvider instead of reading DateTime.UtcNow. It is the built-in clock abstraction since .NET 8: GetUtcNow(), GetTimestamp(), CreateTimer() and LocalTimeZone. Production registers TimeProvider.System; tests use FakeTimeProvider from Microsoft.Extensions.TimeProvider.Testing, where I call SetUtcNow or Advance(TimeSpan.FromDays(14)) to move virtual time instantly. Timers and delays also take the provider (Task.Delay(delay, time, ct), new PeriodicTimer(period, time)), so a one-hour schedule is tested in milliseconds.

    • Test the boundary: just before, exactly at, just after.
    • Advance fires timers synchronously but continuations may run on another thread, so await a signal from a fake, not Thread.Sleep.

    The trade-off: one more constructor parameter, in exchange for tests that are fast, deterministic and independent of the day they run.

  3. When: Candidate identifies sleep-based waits or async races Why: Checks they know how to synchronise async tests on signals rather than delays.
    How to answer

    Async tests should be async Task methods that await the code under test; blocking with .Result or .Wait() hides exceptions inside AggregateException and can deadlock, and async void can't be awaited at all. I test cancellation by cancelling a token and asserting with Assert.ThrowsAnyAsync<OperationCanceledException> (which also catches TaskCanceledException). For background work I never sleep: fakes signal through a TaskCompletionSource or Channel, and the test awaits that signal. Every async test has a guard timeout linked to xUnit v3's TestContext.Current.CancellationToken, so a bug fails in seconds instead of hanging the pipeline. For a BackgroundService, I call StartAsync, feed the channel, await the effect, then StopAsync.

    The trade-off: slightly more test plumbing (gated fakes, signals) in exchange for tests that are deterministic on any CI agent.

🛠 Real-world problems: how you handle them

One CI run in eleven failed, mostly in the morning
Situation
A [120-developer] .NET 10 monorepo ran [6,000] tests per PR in GitHub Actions. About [9%] of runs failed on different tests, and developers averaged [1.6] re-runs per PR. Two real regressions had been re-run into green in the previous month.
Signals
Failures clustered between 10 and 11 am Sydney time; failing tests changed from run to run; the same tests always passed when run alone locally; some runs hung until the 60-minute job timeout.
Investigation
I published JUnit results from every run and aggregated 300 runs: [14] tests caused [90%] of failures. Looping each 500 times in a 2-CPU container reproduced 11 of them. Four compared `DateTime.UtcNow.Date` values and failed across midnight UTC (the morning cluster). Five shared a static cache between two classes that xUnit ran in parallel; turning off `parallelizeTestCollections` made them pass, confirming it. Two used `Task.Delay(200)` to wait for a background handler. The hangs, captured with `--blame-hang-timeout`, showed a `.Result` deadlock in a test helper.
Resolution
Immediate: quarantined the 14 tests with issues and owners, and set the job timeout to 20 minutes with blame dumps. Fix: introduced `TimeProvider` with `FakeTimeProvider`, removed the static cache, replaced sleeps with awaited signals, and made the helper async. Flaky failure rate fell below [0.5%] and the quarantine list was empty in [two weeks].
Prevention
Added a nightly job that repeats new or changed tests 200 times, banned `DateTime.Now`/`UtcNow` in domain code with BannedApiAnalyzers, enabled the xUnit analysers (including xUnit1031) as errors, and published a weekly flaky-test report.

How to tell it (STAR)

**S:** At [company], about one CI run in eleven failed on random tests and people had got used to re-running; two real regressions slipped through that way in a month. **T:** I took ownership of getting the build trustworthy again. **A:** I aggregated results from 300 runs and found 14 tests caused 90% of failures, quarantined them with owners, then reproduced them by looping in a throttled container. The causes were midnight-UTC date comparisons, a static cache shared across parallel classes, sleep-based waits and a `.Result` deadlock. We fixed each and added a nightly repeat-run check plus analyser rules. **R:** Flaky failures dropped from [9%] to under [0.5%], re-runs per PR fell from [1.6] to [0.1], and the quarantine list was empty in two weeks.

↩ Usually asked after

More in Senior Testing Topics

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me