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

📚 Interview question

Your .NET solution's CI test stage has grown to 35 minutes and developers are batching changes to avoid it. How would you redesign the test suite and pipeline so pull requests get fast feedback without losing confidence? Cover parallelism, test splitting, containers and what runs on every PR versus later.

Covers making a .NET test suite fast in CI: measuring where time goes, xUnit parallelism, sharding across agents, container reuse, test selection, and deciding what runs on every PR, on merge and nightly.

Senior Architecture Advanced azure-pipelines ci-cd github-actions test-parallelism testcontainers testing

🎯 Key points

  • Measure first: per-test and per-project timings from TRX or JUnit reports, find the slowest 5% of tests
  • Tier the suite: PR gate (fast, deterministic), on-merge (full integration), nightly (load, mutation, E2E)
  • xUnit parallelises test collections; make tests isolated so parallelism is safe
  • Start containers once per run or collection and reset data with Respawn, not per test
  • Replace sleeps with FakeTimeProvider (Microsoft.Extensions.TimeProvider.Testing) and awaitable signals
  • Shard across CI agents by project or by timing (matrix jobs, Azure Pipelines parallel jobs)
  • Build once and run tests with --no-build; cache NuGet packages and Docker images
  • Quarantine flaky tests out of the gate with an owner and deadline; track p90 gate time, flake rate and escaped defects over time

⏱ 30-second answer

I'd start by measuring: per-test timings from the test reports usually show that a few slow tests, container start-ups and serial execution dominate.

Then I tier the suite: the PR gate runs fast, deterministic tests (unit plus API integration with shared containers) in under 10 minutes; the full integration and contract suite runs on merge; load tests, mutation testing and long E2E runs go nightly.

To make each tier fast: build once, cache NuGet and Docker images, run xUnit collections in parallel, start containers once per run and reset with Respawn, and shard across agents by timing. For big repos, test affected projects only on PRs.

The trade-off: some bugs are caught after merge instead of before, so main must stay releasable with quick reverts.

🗣 Full answer (senior)

How I would answer this in an interview

"First I'd measure rather than guess. I'd pull the TRX or JUnit results from the last few weeks of runs and sort tests by duration, and look at the pipeline timeline: restore, build, container start, test execution, publish. In my experience the time is rarely spread evenly: a handful of tests with Task.Delay or polling, a container started per test class, and projects running one after another usually account for most of it.

For example, at [company] our test stage hit [about 35 minutes]. The fixes, in order of payoff, were: build once and run dotnet test --no-build; one SQL Server container per test run via an assembly-level fixture with Respawn between tests instead of a container per class, which alone saved [about 12 minutes]; making test collections safe to run in parallel by giving each collection its own database; replacing sleeps with FakeTimeProvider; and splitting the suite into [four] shards across agents, balanced by historical timings. The PR gate dropped to [about 8 minutes].

Then I decide what runs where. Every PR: compile with warnings as errors, unit tests, API integration tests with real SQL Server, contract tests for anything other teams consume. On merge to main: the full suite, including slower integration paths, then deploy to a test environment and run smoke tests. Nightly: load tests with k6 or Azure Load Testing, Stryker.NET mutation runs, browser E2E. Flaky tests are quarantined out of the gate within a day, with an owner. The mistake I see is making the pipeline faster by deleting the integration tests, which just moves the cost to production. Fast feedback comes from structure, not from testing less."


Where the time usually goes

Cause Typical cost Fix
Rebuilding per test project Minutes Build once, dotnet test --no-build
Container per test class 5–15 s each Assembly or collection fixture; Respawn
Serial collections Linear in test count Isolated data, xUnit parallel collections
Sleeps and polling Seconds per test FakeTimeProvider, awaitable signals
No caching 1–3 min restore and image pulls NuGet cache, pre-pulled or cached images
One agent Whole suite serial Matrix or parallel jobs, timing-based sharding

What runs when

Stage Runs Budget Blocks
PR gate Build, analysers, unit, API integration (containers), contract < 10 min Merge
On merge to main Full suite, deploy to test env, smoke tests < 20 min Release
Nightly Load, soak, Stryker.NET, browser E2E, dependency scans Hours OK Creates tickets
Pre-release Smoke in staging (Australia East), synthetic checks Minutes Production deploy

Splitting strategies

Strategy How Trade-off
By project Matrix job per test project Simple; uneven if one project is huge
By timing Split test list by historical duration Balanced; needs timing data
Affected only Run tests for projects changed (e.g. dotnet-affected) on PRs Fast in monorepos; full run on main still needed

Production example

After the changes, [our] PR gate went from [35] to [8] minutes across [4] shards, the merge stage ran the full [3,200] tests in [14] minutes, and the number of PRs per developer per week rose from [about 3] to [about 6] because nobody was batching changes any more.

🔍 What the interviewer is checking

Checks whether the candidate can design a test pipeline that balances speed, cost and confidence, starting from measurement.

Green flags

  • Measures first, from test reports and the pipeline timeline
  • Tiers the suite with a time budget per stage
  • Knows xUnit collection parallelism and the isolation it needs
  • Shares containers and resets data instead of restarting
  • Handles flaky tests with quarantine and ownership

Red flags

  • "Just run fewer tests" or delete integration tests
  • Parallelism without isolation
  • Automatic retries hiding flakiness

📚 Learn in depth

1. Measure the pipeline as a system

restore ─▶ build ─▶ [start containers] ─▶ run tests ─▶ publish results
  1-3m      2-5m        0.5-15m             5-25m         <1m

Optimise the biggest box first. Test reports (--logger trx with VSTest, or the TRX/JUnit report extensions with Microsoft.Testing.Platform) give per-test durations; the CI timeline gives the rest.

2. How xUnit parallelism works

xUnit groups tests into collections. By default each test class is its own collection, and collections run in parallel up to maxParallelThreads (default: number of logical processors). Tests inside one collection run serially.

Assembly
 ├─ Collection A (class 1)  ── runs in parallel with ──┐
 ├─ Collection B (class 2)  ──                          │
 └─ Collection "db" (classes 3,4,5 share a DB) ── serial inside

So parallelism is only safe when collections don't share mutable state: static fields, one database, files, ports. Giving each collection its own database name on one SQL Server container keeps parallelism and isolation. Across test assemblies, dotnet test runs projects in parallel too.

3. Containers: pay once

A SQL Server container takes several seconds to start and needs ~2 GB of memory. Patterns, from cheapest to most isolated:

Pattern Starts Isolation
Assembly fixture (xUnit v3 AssemblyFixture) Once per assembly Reset with Respawn
Collection fixture Once per collection Database per collection
Class fixture Once per class Strong, slow

Testcontainers' reuse mode keeps containers between local runs, but it is meant for developer machines, not CI.

4. Sharding across agents

Split the test list into N roughly equal buckets by historical duration (greedy bin-packing), run each on its own agent, then merge results. GitHub Actions does this with a matrix and --filter; Azure Pipelines offers parallel jobs and test slicing in the VSTest task. More shards cost more agent minutes and more build overhead per shard, so beyond 4–8 the returns usually fall.

5. Test selection

In large solutions, run tests only for changed projects and their dependants on PRs (build a project graph from ProjectReferences; tools like dotnet-affected do this). Always run everything on main to catch what selection missed.

6. Keep the gate trustworthy

A fast gate that is flaky is worse than a slow one. Track flake rate (tests that fail then pass on retry), quarantine with a tag or trait excluded from the gate, assign an owner, and fix or delete within a set period.

Try it yourself

  1. Export a TRX file from your last CI run and list the 20 slowest tests.
  2. Move a per-class container to a collection or assembly fixture and time the suite.
  3. Turn on parallel collections and find the tests that start failing: they share state.
  4. Split your suite into two matrix shards with --filter and compare wall-clock time and total agent minutes.
  5. Replace one Task.Delay in a test with FakeTimeProvider.Advance and measure the gain.

💻 Code

A sharded GitHub Actions workflow, plus xUnit configuration and traits used to tier the suite.

# .github/workflows/pr.yml
name: pr
on: pull_request
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-dotnet@v4
        with: { dotnet-version: '10.0.x', cache: true, cache-dependency-path: '**/packages.lock.json' }
      - run: dotnet build -c Release -warnaserror
      - uses: actions/upload-artifact@v4
        with: { name: build, path: '**/bin/Release/**' }

  test:
    needs: build
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        shard: [Unit, Api, Data, Contracts]   # balanced by historical timings
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-dotnet@v4
        with: { dotnet-version: '10.0.x' }
      - uses: actions/download-artifact@v4
        with: { name: build }
      - run: docker pull mcr.microsoft.com/mssql/server:2022-latest   # overlaps with restore on later steps
        if: matrix.shard == 'Api' || matrix.shard == 'Data'
      # Quarantined and nightly-only tests are excluded from the PR gate
      - run: >
          dotnet test -c Release --no-build
          --filter "Shard=${{ matrix.shard }}&Category!=Quarantine&Category!=Nightly"
          --logger trx --results-directory TestResults
      - uses: actions/upload-artifact@v4
        if: always()
        with: { name: results-${{ matrix.shard }}, path: TestResults }
// xunit.runner.json in each test project
{
  "parallelizeTestCollections": true,
  "maxParallelThreads": "default"
}
#nullable enable
namespace Orders.Tests;

using Xunit;

// Traits drive the filters above; one convention for the whole solution
public sealed class PricingTests
{
    [Fact, Trait("Shard", "Unit")]
    public void Discount_Applies_From200() => Assert.Equal(180m, Pricing.Discount(200m));

    [Fact, Trait("Shard", "Unit"), Trait("Category", "Nightly")]
    public void Discount_PropertyBased_10kCases()
    {
        // Expensive exhaustive check: valuable, but not on every PR
        for (var cents = 0; cents < 10_000; cents++)
        {
            var amount = cents / 100m * 50;
            Assert.True(Pricing.Discount(amount) <= amount);
        }
    }
}

public static class Pricing
{
    public static decimal Discount(decimal subtotal) => subtotal >= 200m ? subtotal * 0.9m : subtotal;
}

⚠ Common mistakes

  • Mistake: Speeding up CI by deleting or skipping integration tests. Why it is wrong: The bugs those tests caught now reach production. Instead: Make them cheap: shared containers, Respawn, parallel collections.
  • Mistake: Optimising without measuring. Why it is wrong: Effort goes to the wrong stage. Instead: Sort tests by duration from TRX reports and look at the pipeline timeline.
  • Mistake: Turning on parallelism without isolating state. Why it is wrong: Shared databases, statics and files cause random failures. Instead: Database per collection, no static mutable state, unique temp paths.
  • Mistake: Rebuilding in every test job. Why it is wrong: Build time is paid N times. Instead: Build once, share artefacts, --no-build.
  • Mistake: Sharding into many tiny jobs. Why it is wrong: Per-job overhead (checkout, restore, container pull) dominates and costs more agent minutes. Instead: 2–8 shards balanced by timing.
  • Mistake: Retrying failed tests automatically and ignoring it. Why it is wrong: Flakiness hides real race conditions. Instead: Report retries, quarantine with an owner, fix the cause.
  • Mistake: Affected-only testing on main as well as PRs. Why it is wrong: Selection misses indirect dependencies (config, shared files). Instead: Full run on every merge to main.
  • Mistake: Putting load tests and Stryker.NET in the PR gate. Why it is wrong: They take long and are noisy. Instead: Nightly, with results tracked over time.

🏛 Senior insight: trade-offs

The senior framing is that CI time is a product metric for the engineering team: it drives batch size, and batch size drives risk. Smaller, more frequent changes mean faster time to market, easier reviews, smaller blast radius and quicker rollback; that is the business case, and it lines up with the DORA metrics (deployment frequency, lead time for changes, change failure rate, time to restore) that leadership already understands. A 35-minute gate with 25 developers is also real money: roughly [25 × 3 runs a day × 25 minutes of waiting] is many engineer-hours a day spent context-switching.

I set an explicit budget (PR gate under 10 minutes, merge stage under 20) and treat breaches like performance regressions. I'm also explicit about what moves out of the gate: anything moved to post-merge needs main to be releasable, fast reverts and good alerting, otherwise you've just hidden the cost.

Option When it fits Cost When not to
Shared containers + Respawn Any suite using SQL Server or Redis Fixture setup work Tests that need different schemas
Parallel collections Isolated tests Upfront isolation work Suites with shared static state you can't remove yet
Sharding across agents Suites > ~10 min after other fixes More agent minutes Small suites: overhead dominates
Affected-only on PRs Large monorepos Selection tooling, misses indirect changes Small solutions; never on main
Moving tests to nightly Load, mutation, long E2E Later feedback Anything protecting correctness of common paths
Metric Source Why it matters
p50 / p90 PR gate duration Pipeline analytics (Azure DevOps Analytics, GitHub Actions usage data) Feedback speed, batch size
Flake rate Test results with retry data; Azure DevOps flaky-test detection Trust in red builds
Agent minutes per PR Billing / usage reports Cost of the strategy
Lead time and change failure rate Deployment records Business outcome

I review these monthly so the improvement is visible and regressions get caught early.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions quarantining flaky tests Why: Checks how they diagnose and fix flaky tests rather than just retrying
    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 says containers should start once Why: Checks xUnit fixture scopes for sharing expensive resources
    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.

  3. When: Candidate discusses what blocks a merge or release Why: Checks overall test strategy design for a service
    How to answer

    I'd start from the risks, not a pyramid: wrong money (pricing, payment), lost or duplicated orders, broken contracts with event consumers and the payment provider, and availability at peak. Then match each risk to the cheapest test that catches it. Unit tests for domain rules, integration tests for every endpoint and message handler using WebApplicationFactory, SQL Server in Testcontainers and a Service Bus emulator or fake, contract tests for published events and the payment API, a thin layer of smoke and E2E tests after each deployment, and load tests before launch. The merge gate is fast (under ~10 minutes); the release gate is smoke plus critical E2E on a staging slot. I judge it by escaped defects, change failure rate and feedback time. The trade-off is up-front effort in fixtures and contracts for much cheaper changes later.

🛠 Real-world problems: how you handle them

35-minute test stage leads to batched PRs and riskier releases
Situation
A .NET 10 modular monolith on Azure (Australia East) with [12] test projects and [about 3,200] tests, [25] developers. CI on [Azure Pipelines / GitHub Actions]. Integration tests used Testcontainers with a SQL Server container per test class.
Signals
PR gate p50 [35 minutes], p90 [50 minutes]; average PR size growing; developers merging [several features] at once; [two] incidents traced to large batched changes; flaky failures on [about 8%] of runs.
Investigation
Exported TRX results for [two weeks] of runs and ranked tests by duration; found [70] container start-ups per run, [15] tests using `Task.Delay` totalling [4 minutes], and every project rebuilding in its own job. Pipeline timeline showed test projects running serially on one agent. Flaky tests clustered in classes sharing one database while running in parallel.
Resolution
Immediate: build once with `--no-build` test runs and NuGet caching (saved [about 6 minutes]). Then an assembly-level SQL Server fixture with a database per collection and Respawn resets, `FakeTimeProvider` replacing sleeps, parallel collections, and [4] timing-balanced shards. Load tests and Stryker.NET moved to nightly; flaky tests quarantined with owners.
Prevention
CI duration budget with an alert when the PR gate p90 exceeds [10 minutes]; dashboard for flake rate and slowest tests; review checklist banning `Thread.Sleep`/`Task.Delay` in tests; ADR describing the PR, merge and nightly tiers.

How to tell it (STAR)

**S:** At [company] our PR test stage had grown to [35 minutes], so developers were batching changes and we'd had [two] incidents from big merges. **T:** I took on getting the PR gate under 10 minutes without dropping the integration tests. **A:** I ranked tests by duration from our TRX reports, then built once and reused the output, moved to a single SQL Server container with a database per collection and Respawn, replaced sleeps with FakeTimeProvider, enabled parallel collections and split the suite into [four] balanced shards. Slow load and mutation runs went nightly, and flaky tests got quarantined with owners. **R:** The PR gate dropped to [8 minutes], flaky runs fell from [8%] to [under 1%], and PRs per developer roughly [doubled] as people stopped batching.

More in Testing Practices

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me