Concurrency bugs share a cruel property: the code looks correct, passes every test, runs fine in dev, then fails one time in ten thousand under real load — which at 3,200 req/sec means dozens of times an hour. They're non-deterministic, don't reproduce on demand, and the stack trace points at a symptom (a duplicate row, a disposed object) far from the cause (two threads interleaving where the author assumed one).

Here are 7 that actually shipped to production (a multi-tenant SaaS: 110k MAU, .NET 9 / ASP.NET Core, Azure SQL), with the before/after fix and real metrics.

Full original (canonical) on PrepStack: https://prepstack.co.in/blog/race-conditions-concurrency-bugs-aspnet-core-production

The one mental shift

Most concurrency bugs come from a hidden assumption of atomicity:

var n = counter.Value; // read counter.Value = n + 1; // write 

Your brain reads that as one indivisible action. The CPU, the runtime, and two web requests do not. Between the read and the write, another thread reads the same old value — and one increment is silently lost.

Atomicity is not the default — it's something you ask the runtime or the database for explicitly. Every read-decide-write on shared state is three places another thread can interrupt you. Either make it genuinely one step, or guard it.

How you actually find races

You can't step through a race — pausing changes the timing. The toolkit:

# 1. Grep the symptom strings in logs at scale: # "A second operation was started on this context" # "Collection was modified; enumeration operation may not execute" # "ObjectDisposedException ... DbContext" | duplicate-key violations # 2. Reproduce by FORCING overlap bombardier -c 200 -d 30s -m POST https://api/orders await Parallel.ForEachAsync(Enumerable.Range(0, 500), async (_, ct) => await handler.Handle(sameCommand, ct)); # 500 at once # 3. A race fails SOME runs — run it 20x for i in $(seq 1 20); do dotnet test --filter Concurrency || echo "FAIL run $i"; done 

A test that passes 19 times and fails once is not flaky — it's correctly reporting a race.

Bug 1 — Lost update (read-modify-write)

Spend counter drifted below actual ad spend; a campaign could overspend. Two overlapping charges both read the same starting value; the second write clobbered the first.

// BEFORE — read-modify-write in app memory; the +30 vanishes under overlap var campaign = await _db.Campaigns.FirstAsync(c => c.Id == id, ct); campaign.SpentToday += charge; // read, then add in memory await _db.SaveChangesAsync(ct); // last writer wins 
// AFTER (counter) — atomic; the DB does read+add+write as one operation await _db.Campaigns.Where(c => c.Id == id) .ExecuteUpdateAsync(s => s.SetProperty(c => c.SpentToday, c => c.SpentToday + charge), ct); 

For read-modify-write that must load the entity, add an optimistic concurrency token ([Timestamp] byte[] RowVersion) and a bounded retry loop, so a clobbering write throws DbUpdateConcurrencyException and you redo on fresh data. ~40 drift incidents/month → 0.

Bug 2 — Check-then-act (TOCTOU)

"Does this slug exist? No? Insert." Two concurrent publishes both check (neither exists yet), both insert, one 500s.

// AFTER — the UNIQUE index does the atomic check; we react to the conflict for (var attempt = 1; attempt <= 3; attempt++) { try { _db.Posts.Add(new Post { Slug = slug }); await _db.SaveChangesAsync(ct); return slug; } catch (DbUpdateException e) when (IsUniqueViolation(e)) { _db.ChangeTracker.Clear(); slug = $"{baseSlug}-{attempt}"; } } 

For conditional transitions, put the condition in the WHERE of an atomic ExecuteUpdate ("publish only if still draft"). ~15 slug-collision 500s/month → 0.

Bug 3 — Shared mutable state in a singleton

A singleton cached feature flags in a plain Dictionary and mutated it on a timer while requests read it. Dictionary is not thread-safe — concurrent read+write corrupts its buckets.

// AFTER — immutable snapshot, atomic reference swap; readers never see a partial map private volatile IReadOnlyDictionary<string, bool> _flags = new Dictionary<string, bool>(); public bool IsOn(string key) => _flags.TryGetValue(key, out var v) && v; public void Reload(IEnumerable<Flag> fresh) => _flags = fresh.ToDictionary(f => f.Key, f => f.Enabled); // build new, then swap 

For per-key updates use ConcurrentDictionary; for counters, Interlocked. ~3 instance restarts/week → 0.

Bug 4 — One DbContext across parallel awaits

Someone parallelized dashboard queries with Task.WhenAll on the same DbContext — which is explicitly not thread-safe. Result: InvalidOperationException: A second operation was started on this context, ~1,400/day.

// AFTER (true parallelism) — one short-lived context per concurrent query async Task<List<Kpi>> LoadKpis(Guid t, CancellationToken ct) { await using var db = await _factory.CreateDbContextAsync(ct); // IDbContextFactory return await db.Kpis.Where(k => k.TenantId == t).ToListAsync(ct); } 

Or just run them sequentially — at sub-10 ms each it was simpler and plenty fast. ~1,400/day → 0.

Bug 5 — Missing idempotency on writes

Double-clicked "Create order" and client retries created duplicate orders, each a manual refund. The client sends an idempotency key; the server records it with a unique index, so a duplicate means "already done" and returns the original.

app.MapPost("/api/orders", async ([FromHeader(Name="Idempotency-Key")] Guid key, CreateOrder cmd, AppDbContext db, CancellationToken ct) => { try { await using var tx = await db.Database.BeginTransactionAsync(ct); var order = new Order(cmd); db.Orders.Add(order); db.IdempotencyKeys.Add(new IdempotencyKey(key, cmd.TenantId, order.Id)); await db.SaveChangesAsync(ct); await tx.CommitAsync(ct); // unique index rejects the retry return Results.Created($"/api/orders/{order.Id}", order); } catch (DbUpdateException e) when (IsUniqueViolation(e)) { var existing = await db.IdempotencyKeys.FirstAsync(k => k.Key == key, ct); return Results.Created($"/api/orders/{existing.OrderId}", null); // return the first result } }); 

~22 duplicate orders/month → 0.

Bug 6 — The same scheduled job on every instance

A BackgroundService timer runs in every instance (6 of them); two grab the same unsent-report rows and email them twice. Fix: elect a single leader via a distributed lock (an Azure Blob lease), or let all instances atomically claim distinct rows (SELECT ... FOR UPDATE SKIP LOCKED). We used a blob-lease leader for the email job and row-claiming for high-volume ingest. Duplicate month-end emails → 0.

Bug 7 — Fire-and-forget after the scope is gone

_ = SendNotificationAsync() returned the response faster — but the task captured the request-scoped DbContext. When the request completed, the DI scope disposed and the still-running task blew up: ObjectDisposedException, ~260/day. Fire-and-forget that captures scoped services is a use-after-free in disguise.

// AFTER — enqueue a value; a BackgroundService processes it in its OWN scope await _notifications.Writer.WriteAsync(cmd.PostId, ct); // just a Guid, no scoped capture public class NotificationWorker(ChannelReader<Guid> reader, IServiceScopeFactory scopes) : BackgroundService { protected override async Task ExecuteAsync(CancellationToken ct) { await foreach (var postId in reader.ReadAllAsync(ct)) { using var scope = scopes.CreateScope(); // fresh scope per item var db = scope.ServiceProvider.GetRequiredService<AppDbContext>(); var subs = await db.Subscribers.ToListAsync(ct); // its own live context } } } 

~260/day → 0 — plus the channel gives natural backpressure.

The shape underneath all seven

Every bug is an assumed-atomic step that wasn't. The fix is always one of:

  • collapse step1+step2 into ONE atomic operation (ExecuteUpdate, Interlocked)
  • let the DB enforce the invariant (unique index + catch)
  • guard the section (lock, concurrency token)
  • don't share the resource (scope/context per task)
  • coordinate across instances (distributed lock / atomic claim)

Aggregate metrics (8 weeks before vs after)

Metric Before After
"Second operation on context" / day ~1,400 0
Duplicate orders / mo ~22 0
Lost-update drift / mo ~40 0
Singleton-corruption restarts / wk ~3 0
Fire-and-forget ObjectDisposed / day ~260 0
Slug-collision 500s / mo ~15 0
"Can't reproduce" pages / mo ~6 <1
API p95 120 ms 120 ms

Every number went to zero, and none of it cost latency. Concurrency correctness is almost never a performance trade-off — it's usually cheaper than the broken version.

The closing mental model

Assume nothing is atomic unless you made it so. For every multi-step operation on shared state, picture a second thread running the same lines interleaved — if that corrupts anything, you have a race today, not "if you get unlucky." Push invariants down to the database (a unique index, a rowversion, an atomic ExecuteUpdate enforce correctness no matter how threads interleave). And test concurrency by forcing it.

Originally published on PrepStack.