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

📚 Interview question

How do service lifetimes relate to thread safety? Explain what must be thread-safe in a singleton, why "A second operation was started on this context instance" happens even in scoped code, whether scoped services can be used from multiple threads in one request, and how per-request versus per-message scoping changes this.

Covers the concurrency contract each lifetime implies: thread-safe singletons, scoped services shared by parallel work within one request, DbContext concurrent use, and how message consumers and parallel processing need a scope per concurrent unit.

Senior Theory Advanced aspnet-core concurrency dbcontext dependency-injection service-lifetimes thread-safety

🎯 Key points

  • Singletons are shared by all requests concurrently: every field must be immutable, concurrent or locked
  • Scoped is per scope, not per thread: Task.WhenAll or Parallel.ForEachAsync inside one request share the same scoped instances
  • DbContext is not thread-safe (one connection, one change tracker); EF's concurrency detector throws InvalidOperationException ('A second operation...') when operations overlap, rather than corrupting state
  • Common triggers in scoped code: Task.WhenAll on one context, missing await, fire-and-forget (Task.Run) using the request's services after the response
  • Treat the exception as a bug to fix, not to retry: one scope or one IDbContextFactory<T> context per concurrent branch
  • Every concurrent context may hold a pooled connection: size parallelism against Max Pool Size (100 by default)
  • Message consumers: one scope per message; with concurrency > 1 each in-flight message needs its own scope
  • Fire-and-forget after the request: the request scope is disposed, so hand work to a Channel<T> or queue whose worker creates its own scope

⏱ 30-second answer

Lifetimes imply a concurrency contract. A singleton is used by every request at the same time, so its state must be immutable, concurrent (ConcurrentDictionary, Interlocked) or locked. A scoped service is per scope, not per thread: inside one request, Task.WhenAll or Parallel.ForEachAsync branches get the same scoped instances, so a DbContext shared by parallel branches throws "A second operation was started on this context instance". The same error comes from a missing await or fire-and-forget work using request services after the response (often ObjectDisposedException).

The rule: one scope per concurrent unit of work. For parallel database work use IDbContextFactory<T> (a context per branch); for message consumers with concurrency above 1, a scope per in-flight message. Trade-off: more scopes means more connections, so bound the parallelism.

🗣 Full answer (senior)

How I would answer this in an interview

"I think of each lifetime as a promise about concurrency. A singleton says 'many threads, at once, for ever', so anything mutable in it has to be thread-safe: immutable data, concurrent collections, Interlocked, or a lock around compound operations. Transient says 'nobody else has this instance', which is the safest. Scoped is the one people get wrong: it means one instance per scope, not per thread. In a request, the scope is shared by everything in that request, including parallel tasks you start yourself.

That's why you can get 'A second operation was started on this context instance' even when the DbContext is correctly scoped. The classic cause is Task.WhenAll over three repository calls in one handler: three branches, one context. A missing await does the same thing more subtly, and fire-and-forget is worse: the request finishes, the scope disposes the context, and the background task gets ObjectDisposedException. For example, at [company] we [had a dashboard endpoint that loaded four widgets in parallel] and [about 1% of requests] failed with that error; giving each branch its own context from IDbContextFactory<T> fixed it and [kept the latency gain of running in parallel].

In message consumers the scope is per message. If the consumer runs with a concurrency limit of 16, that's 16 scopes and 16 contexts in flight, which is correct, but it also means 16 connections, so I size the pool and the concurrency together. The one-line rule I give teams: one scope per concurrent unit of work, and singletons must be safe for every request at once."


Lifetime → concurrency contract

Lifetime Who uses it concurrently Requirement
Singleton All requests and workers Thread-safe state
Scoped Everything in one scope, including your own parallel tasks Don't share across parallel branches unless thread-safe
Transient Only its consumer Safe unless the consumer shares it

Causes of "second operation" in scoped code

Cause Fix
Task.WhenAll over calls on one context Context per branch (IDbContextFactory<T>) or sequential awaits
Missing await Await every call; enable CA2012/CS4014 warnings as errors
async void event handler using the context async Task, awaited
Fire-and-forget using request services New scope inside the background work; better, a queue
Captive context in a singleton Fix the lifetime

Per request vs per message

Host Scope Concurrency
ASP.NET Core request One per request Many requests in parallel, each isolated
Queue consumer (concurrency N) One per message N scopes in flight
Batch job with Parallel.ForEachAsync You decide One scope per branch, bounded MaxDegreeOfParallelism

Production example

The dashboard endpoint went from [~1%] 'second operation' failures to zero, and kept a p95 of [180 ms] versus [520 ms] for the sequential version. Connection pool usage peaked at [4 per request], which we had sized for at [~100 concurrent requests per instance].

🔍 What the interviewer is checking

Checks that the candidate links lifetimes to concurrency correctly, especially that scoped is per scope rather than per thread.

Green flags

  • "Scoped is not thread-local" with the Task.WhenAll example
  • Explains the EF concurrency detector and the fire-and-forget disposal problem
  • One scope per concurrent unit; IDbContextFactory<T> for parallel branches
  • Sizes concurrency against the connection pool
  • Treats per-request data in singletons as a security issue

Red flags

  • Locks around a shared DbContext
  • Task.Run with request services after the response
  • Unsynchronised collections in singletons

📚 Learn in depth

1. Scoped is not thread-local

Request scope
  ├─ handler (scoped) ──┐
  ├─ repoA   (scoped) ──┼── all share AppDbContext #1
  └─ repoB   (scoped) ──┘

Task.WhenAll(repoA.LoadAsync(), repoB.LoadAsync())
  thread X: AppDbContext #1 query A  ─┐ overlap → InvalidOperationException
  thread Y: AppDbContext #1 query B  ─┘

Async continuations can run on any thread-pool thread; the scope follows the logical flow (HttpContext.RequestServices), not a thread.

2. EF Core's concurrency detector

DbContext uses a ConcurrencyDetector that marks an operation in progress. A second entry while one is active throws immediately. It is not a lock; it is a guard that converts silent corruption of the connection and change tracker into a clear exception. It only fires when operations actually overlap, so the error rate rises with load and latency.

3. Singleton thread safety patterns

State Pattern
Read-only after start-up Immutable types, FrozenDictionary
Counters Interlocked.Increment
Key-value cache ConcurrentDictionary (beware GetOrAdd factory running twice) or IMemoryCache
Compound updates lock or SemaphoreSlim (async) around the whole operation
Refreshable snapshot Swap a reference atomically (Volatile.Write / Interlocked.Exchange)

4. Fire-and-forget and scope disposal

request → _ = Task.Run(() => service.DoAsync())  // captures scoped service
response sent → scope disposed → DbContext disposed
background task → ObjectDisposedException

Correct: enqueue to a Channel<T> consumed by a BackgroundService that creates its own scope per item.

5. Sizing parallel scopes

Each concurrent scope with a DbContext may hold a pooled connection. SQL Server's ADO.NET pool defaults to Max Pool Size=100. Concurrency per instance × connections per unit must stay under it, or requests queue for connections (timeouts after 15 seconds by default).

Try it yourself

  1. Write a handler that runs two EF queries with Task.WhenAll on one context; load test it and count exceptions.
  2. Rewrite with IDbContextFactory<T> per branch and compare latency to sequential awaits.
  3. Remove an await and see the analyser warning (CS4014) and the runtime failure.
  4. Hammer a singleton holding a Dictionary<,> from 32 threads and watch it corrupt or throw; switch to ConcurrentDictionary.

💻 Code

Parallel reads in one request: wrong and right.

using Microsoft.EntityFrameworkCore;

namespace Dashboard;

public sealed record Widget(string Name, int Value);

public sealed class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options)
{
    public DbSet<Order> Orders => Set<Order>();
    public DbSet<Customer> Customers => Set<Customer>();
}
public sealed class Order { public int Id { get; set; } public bool Open { get; set; } }
public sealed class Customer { public int Id { get; set; } public bool Active { get; set; } }

// WRONG: two operations overlap on the request's single scoped context.
public sealed class DashboardServiceBroken(AppDbContext db)
{
    public async Task<Widget[]> LoadAsync(CancellationToken ct)
    {
        var orders = db.Orders.CountAsync(o => o.Open, ct);
        var customers = db.Customers.CountAsync(c => c.Active, ct); // second operation → throws
        await Task.WhenAll(orders, customers);
        return [new("Open orders", orders.Result), new("Active customers", customers.Result)];
    }
}

// RIGHT: one short-lived context per concurrent branch.
public sealed class DashboardService(IDbContextFactory<AppDbContext> contexts)
{
    public async Task<Widget[]> LoadAsync(CancellationToken ct)
    {
        var orders = CountAsync(db => db.Orders.CountAsync(o => o.Open, ct), ct);
        var customers = CountAsync(db => db.Customers.CountAsync(c => c.Active, ct), ct);
        var results = await Task.WhenAll(orders, customers);
        return [new("Open orders", results[0]), new("Active customers", results[1])];
    }

    private async Task<int> CountAsync(Func<AppDbContext, Task<int>> query, CancellationToken ct)
    {
        await using var db = await contexts.CreateDbContextAsync(ct);
        return await query(db);
    }
}

Thread-safe singleton state and fire-and-forget done properly:

using System.Collections.Concurrent;
using System.Threading.Channels;

namespace Dashboard;

public sealed class HitCounter
{
    private readonly ConcurrentDictionary<string, long> _hits = new();
    public void Hit(string path) => _hits.AddOrUpdate(path, 1, static (_, n) => n + 1);
    public long Get(string path) => _hits.GetValueOrDefault(path);
}

public sealed record AuditEvent(string UserId, string Action);

// Request code writes to the channel and returns; never Task.Run with scoped services.
public sealed class AuditQueue
{
    private readonly Channel<AuditEvent> _channel = Channel.CreateBounded<AuditEvent>(10_000);
    public ValueTask EnqueueAsync(AuditEvent e, CancellationToken ct) => _channel.Writer.WriteAsync(e, ct);
    public IAsyncEnumerable<AuditEvent> ReadAllAsync(CancellationToken ct) => _channel.Reader.ReadAllAsync(ct);
}

public interface IAuditWriter { Task WriteAsync(AuditEvent e, CancellationToken ct); }

public sealed class AuditWorker(AuditQueue queue, IServiceScopeFactory scopes) : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        await foreach (var e in queue.ReadAllAsync(stoppingToken))
        {
            await using var scope = scopes.CreateAsyncScope(); // own scope, not the dead request's
            await scope.ServiceProvider.GetRequiredService<IAuditWriter>().WriteAsync(e, stoppingToken);
        }
    }
}

⚠ Common mistakes

  • Mistake: Believing scoped services are safe because "each request has its own". Why it is wrong: Parallel tasks inside one request share them. Instead: One scope or context per concurrent branch.
  • Mistake: Using Task.WhenAll over several queries on one DbContext for speed. Why it is wrong: EF throws on overlapping operations. Instead: IDbContextFactory<T> per branch, or one combined query.
  • Mistake: Task.Run or _ = DoAsync() with request services after returning a response. Why it is wrong: The scope disposes them; you get ObjectDisposedException or worse, half-finished writes. Instead: A Channel<T> plus a worker with its own scopes, or a durable queue.
  • Mistake: Storing per-request data (current user, tenant) in a singleton field. Why it is wrong: Concurrent requests overwrite each other: a data-leak bug and a possible notifiable data breach under the Privacy Act. Instead: Scoped services or pass it explicitly.
  • Mistake: Using Dictionary<,> or List<> in a singleton without synchronisation. Why it is wrong: Concurrent writes corrupt internal state, causing infinite loops or lost entries. Instead: Concurrent collections, immutable snapshots or locks.
  • Mistake: Adding a lock around a shared DbContext. Why it is wrong: It serialises the work and still mixes change trackers. Instead: Separate contexts.
  • Mistake: Raising consumer concurrency without checking the connection pool. Why it is wrong: Each in-flight scope may hold a connection; past Max Pool Size requests queue and time out. Instead: Size concurrency and pool together.

🏛 Senior insight: trade-offs

When I review concurrency in DI-based code I map every concurrent flow to a scope. Requests already have one. Messages need one each. Parallel branches I create need one each. Anything that outlives the request needs its own. Singletons are reviewed like shared memory, because that's what they are. The particularly dangerous bug is per-request identity in a singleton: it's not just wrong data, it can show one customer's information to another, which in Australia is a potential eligible data breach under the Notifiable Data Breaches scheme.

Approach When it fits Cost When not to
Sequential awaits on one context Few, fast queries Latency adds up Many independent slow queries
IDbContextFactory<T> per branch Independent parallel reads One connection per branch Writes that must commit together
One combined query / projection Related data Query complexity Unrelated data sets
Scope per message Consumers Connection per in-flight message Shared transaction across messages
Channel<T> + worker for background work Post-response work In-memory: lost on crash Work that must survive restarts (use a durable queue / outbox)

I verify with a load test at expected concurrency and track EF concurrency exceptions, connection pool wait time (Microsoft.Data.SqlClient event counters) and p95 latency.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions the 'second operation' error Why: Checks DbContext concurrency rules and correct parallel patterns
    How to answer

    A DbContext wraps one connection and one change tracker and allows one operation at a time; EF's concurrency detector throws when a second async operation starts before the first completes, usually from a shared context or a missing await. To run work in parallel, give each branch its own context (IDbContextFactory<T>.CreateDbContextAsync()), or combine the queries into one round trip. Never share a context across Task.WhenAll branches.

  2. When: Candidate suggests ConcurrentDictionary for singleton state Why: Checks the GetOrAdd/AddOrUpdate caveats and compound operations
    How to answer

    System.Collections.Concurrent types are safe for many threads at once. ConcurrentDictionary uses lock-free reads and fine-grained (striped) locks for writes. Each single method is atomic, but check-then-act across two calls is not, so use GetOrAdd, AddOrUpdate, TryUpdate or TryRemove. Caveat: the value factory in GetOrAdd/AddOrUpdate can run more than once under contention (only one result is stored), so wrap expensive or side-effecting work in Lazy<T>. Count, IsEmpty and ToArray take every lock, so avoid them in hot paths. ConcurrentQueue/ConcurrentStack are lock-free FIFO/LIFO. ConcurrentBag is unordered, optimised for the same thread adding and taking. BlockingCollection adds bounding and blocking Take but blocks threads; for async producer/consumer use Channel<T>.

  3. When: Candidate mentions background processing after the request Why: Checks correct scoping in a BackgroundService
    How to answer

    AddHostedService<T>() registers the worker as a singleton, so a scoped DbContext in its constructor would be a captive dependency: one context for the life of the process (Development throws at start-up). Instead, inject IServiceScopeFactory and create a scope per unit of work:

    await using var scope = scopes.CreateAsyncScope();
    var svc = scope.ServiceProvider.GetRequiredService<IOrderService>();
    

    Each message or tick gets a fresh context that is disposed at the end. Pass stoppingToken everywhere, use PeriodicTimer for polling, and catch exceptions per item: since .NET 6 an unhandled exception in ExecuteAsync stops the host by default. If only a context is needed, IDbContextFactory<T> is simpler. Trade-off: smaller scopes mean fresher state and less memory, but more allocations per item.

🛠 Real-world problems: how you handle them

Parallel dashboard queries on one scoped DbContext failed under load
Situation
[Internal operations dashboard API, ~100 concurrent requests per instance at 9am, Azure App Service Australia East]. A developer parallelised four widget queries with Task.WhenAll to cut latency.
Signals
Application Insights showed InvalidOperationException 'A second operation was started on this context instance' on [~1%] of dashboard requests, rising to [~4%] at the morning peak; failures were intermittent and never reproduced locally with a single user.
Investigation
Grouped exceptions by operation: all from DashboardService.LoadAsync. Read the code and saw four CountAsync calls started before a Task.WhenAll on the injected scoped AppDbContext. Reproduced locally with a k6 script at 50 virtual users; failures appeared within seconds. Checked SqlClient event counters to estimate connection usage if each branch had its own context.
Resolution
Rewrote LoadAsync to create one context per branch with IDbContextFactory<AppDbContext> (registered with AddDbContextFactory, which also keeps the scoped context for other code). Raised nothing else; connection usage peaked at [~4 per request], within the default pool of 100.
Prevention
Added a k6 load test of the dashboard to the release pipeline; an analyser rule flags Task.WhenAll in classes that inject a DbContext for review; documented 'one scope or context per concurrent branch' in the team's backend guidelines; alert on any EF concurrency exception.

How to tell it (STAR)

**S:** At [company], our operations dashboard started failing for [about 1 in 25] users at the morning peak right after a performance change. **T:** I needed to keep the latency improvement but remove the failures. **A:** The exceptions were all EF's 'second operation' error from one service. The change had started four queries in parallel with Task.WhenAll on the request's scoped DbContext; scoped means one per request, not per thread, so the branches collided under load. I reproduced it with k6, then gave each branch its own short-lived context from IDbContextFactory and checked connection usage stayed well under the pool limit. **R:** Failures went to zero, p95 stayed at [180 ms] instead of the [520 ms] sequential version, and the load test now runs on every release.

More in Service Lifetimes

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me