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

📚 Interview question

Tell me about a time flaky tests were blocking releases. How did the team end up there, what did you personally do to find the causes and unblock releases, how did you get people to stop just re-running the pipeline, and what changed afterwards?

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.

Mid-Level RealWorldScenario Intermediate ci-cd flaky-tests real-world star-story test-reliability timeprovider

🎯 Key points

  • Measure first: failure rate per test from CI history (Azure DevOps Test Analytics, GitHub Actions results)
  • Quarantine with an owner and a deadline, never just [Skip] forever
  • Common causes: code reading the real clock, test order and shared state, parallel test collections, un-awaited async work, real network, fixed sleeps
  • Fixes: inject TimeProvider (FakeTimeProvider in tests), isolated data per test (Testcontainers, Respawn), await or poll with timeouts
  • Test infrastructure through DI: swap clocks, HTTP handlers and databases in WebApplicationFactory
  • Change the habit and the culture: no silent re-runs, flaky count on the team board, fixing flakiness counts as real work
  • Result with numbers: pipeline pass rate, release frequency, time lost to re-runs

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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.UtcNow and failed around midnight UTC, which is mid-morning in Sydney, so I moved the code to TimeProvider and the tests to FakeTimeProvider. 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."


Causes and fixes

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

Quarantine rules that work

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

Production example

"[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]."

🔍 What the interviewer is checking

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

  • Measured failure rates per test before fixing
  • Quarantine with owner and deadline, not silent skips
  • Names specific causes and fixes (TimeProvider, isolated data, no sleeps)
  • Changed the re-run habit and kept the metric visible
  • Result in pass rate, merge time or release frequency

Red flags

  • "We just added retries"
  • Skipped tests permanently
  • No numbers, or blames the original authors

📚 Learn in depth

1. What the interviewer is really assessing

  • Ownership of a shared problem nobody owns (the tragedy of the commons in CI).
  • Evidence over anecdote: did you measure, or just fix the test that annoyed you most?
  • Technical depth: do you know the real causes of non-determinism in .NET tests?
  • Changing team behaviour: re-running is rational for one person and harmful for the team.

2. Why flaky tests are worse than no tests

 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.

3. Measuring flakiness

  • Definition: a test that both passes and fails on the same commit.
  • Sources: Azure DevOps Test Analytics / flaky test detection, GitHub Actions test reports (e.g. via dorny/test-reporter), or TRX files from dotnet test --logger trx pushed to a database.
  • Metric: failure rate per test over 14–30 days, sorted. Fix the top of the list (Pareto).
  • Reproduce: run the suspect test in a loop (for i in {1..50}; do dotnet test --filter FullyQualifiedName~X; done), randomise order, run with full parallelism.

4. The usual .NET culprits

  • DateTime.Now/UtcNow and Stopwatch in code under test. Since .NET 8, TimeProvider is the abstraction; Microsoft.Extensions.TimeProvider.Testing gives FakeTimeProvider.
  • xUnit runs test collections in parallel by default; tests in different classes that share a database or a static field will race.
  • async void tests or un-awaited tasks finish after the assertion.
  • Integration tests that share one database and rely on row counts or IDs.

5. Telling the story (STAR, CAR, SOAR)

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.

6. Reusing the story

It also answers: "Tell me about improving developer productivity", "Tell me about changing a team habit", "How do you keep a CI pipeline healthy?"

Try it yourself

  1. Export 30 days of test results from your CI and rank tests by failure rate.
  2. Find a test using DateTime.UtcNow and rewrite it with FakeTimeProvider.
  3. Run your suite three times with randomised order and compare results.
  4. Add a Quarantined trait and a pipeline step that runs those tests without failing the build.
  5. Write your STAR story with [placeholders] for every number and rehearse it in 90 seconds.

💻 Code

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"

⚠ Common mistakes

  • Mistake: Telling it as "I fixed some flaky tests". Why it is wrong: misses the delivery impact and your ownership. Instead: open with what it cost (release windows missed, merge time) and end with what came back.
  • Mistake: Adding automatic retries to the test runner as the fix. Why it is wrong: hides real race conditions, some of which are production bugs. Instead: retries only as a temporary, visible measure while the root cause is fixed.
  • Mistake: [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.
  • Mistake: Replacing a sleep with a longer sleep. Why it is wrong: slower and still flaky on a busy agent. Instead: await the operation, or poll with a timeout; with FakeTimeProvider, call Advance() so timers and Task.Delay(…, timeProvider) fire deterministically.
  • Mistake: 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).
  • Mistake: Ignoring that xUnit runs test collections in parallel. Why it is wrong: two classes sharing a database, file or static field race only on multi-core CI agents. Instead: isolate state per test, or put shared-resource tests in one [Collection].
  • Mistake: Blaming whoever wrote the tests. Why it is wrong: sounds negative and ignores the system that allowed it. Instead: describe the habit and how the team changed it.
  • Mistake: "We" throughout. Why it is wrong: hides what you did. Instead: "I exported the data, I proposed the rule, I fixed the three worst".
  • Mistake: Drowning a non-technical interviewer in xUnit detail, or giving no number in the result. Why it is wrong: they can't score it. Instead: "the pipeline went from passing 6 times in 10 to almost every time, and we went back to daily releases".

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions quarantine or the causes of the flaky tests. Why: Checks the technical playbook for diagnosing and quarantining flaky tests in depth.
    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 mentions tests failing around midnight, month end or with timeouts. Why: Checks that they can make time-dependent code testable with TimeProvider.
    How to answer

    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.

🛠 Real-world problems: how you handle them

Seven flaky tests holding up every release
Situation
[Company]'s [orders service], [~2,400 tests] in [Azure DevOps / GitHub Actions], [N] developers merging [~20 PRs] a day; releases planned [daily] but often slipping.
Signals
First-time pipeline pass rate [~60%]; re-run button used [dozens of times] a week; median merge time [over an hour]; [two] missed release windows in a month; developers saying 'just re-run it' in chat.
Investigation
Exported [30 days] of test results (Test Analytics / TRX) and ranked tests by failure rate on the same commit; [7 tests] caused [80%+] of failures. Reproduced locally by looping each test and randomising order. Ruled out agent capacity (failures didn't correlate with agent pool) and the database server (no errors in its logs). Causes: two tests used DateTime.UtcNow near midnight UTC, one relied on data from another test class, others used fixed Task.Delay waits.
Resolution
Immediately: moved the 7 tests to a Quarantined trait that runs in a non-blocking step, each with an owner and a two-week deadline. Then: TimeProvider in the code with FakeTimeProvider in tests; a database per test class with Testcontainers and Respawn; replaced sleeps with awaited operations and polling with timeouts.
Prevention
A rule that a re-run needs a ticket for the failing test; flaky count and first-time pass rate on the team dashboard; quarantine capped at [10] tests; new tests run [20] times in the PR build; banned-API analyser rule for DateTime.Now in domain code.

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].

More in Delivery and People

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me