How would you investigate a production-only race condition in an asynchronous C# order workflow?
Paytm · Full Stack Developer · 3-4-years · technical
Published
Year not specified · .NET, C#, Software Engineering
Community answers
Posted by wasAsked editorial collection
Start by defining the violated invariant, such as “payment is captured once” or “an order can transition from Pending to Confirmed only once.” Add correlation IDs and structured logs around reads, writes, versions, retries, and external calls. Reproduce with concurrent requests in a test that uses the real persistence boundary; a single-threaded unit test rarely exposes the race.
The durable fix normally belongs in the database, not only in an in-process lock. Use an atomic conditional update, unique constraint, transaction, or optimistic concurrency token:
```csharp
public async Task<bool> ConfirmAsync(Order order, CancellationToken ct)
{
order.Status = OrderStatus.Confirmed;
try
{
await db.SaveChangesAsync(ct); // RowVersion is checked by EF Core
return true;
}
catch (DbUpdateConcurrencyException)
{
return false; // Reload and decide whether the operation is already complete
}
}
```
Also make external operations idempotent by sending a stable operation key. Trace thread-pool metrics, but do not assume every async defect is a threading defect. Finally, verify the fix under repeated parallel load and confirm the stored state, not merely HTTP success responses.
Prince Yadav · · 0 likes
Production-only race conditions usually depend on real concurrency, timing and data volume, so the investigation relies on evidence rather than reproduction in a debugger.
1. Gather evidence
- Collect logs and traces for the affected orders: structured logs with order ID, trace ID, thread or instance ID and precise timestamps. Distributed traces show overlapping operations.
- Look for patterns: duplicate events, retries, two instances processing the same order, double clicks, timeouts followed by retries.
- Check database history: audit columns, row versions, and the sequence of status changes.
2. Form hypotheses about shared state
- Two requests or message handlers updating the same order (read-modify-write without concurrency control).
- Shared mutable state in singletons or static fields (a Dictionary used without locks, a cached entity modified by several requests).
- Async methods that are not awaited (fire-and-forget) running at the same time as later code.
- A DbContext shared across concurrent tasks.
- At-least-once message delivery processing the same event twice.
3. Reproduce deliberately
- Write a stress test that runs the workflow in parallel (Parallel.ForEachAsync, many HTTP requests at once, or duplicate messages) against a real database.
- Inject delays at suspicious points to widen the race window.
- Production-like settings matter: several instances, real latency, real isolation level.
4. Fix the root cause
- Optimistic concurrency (rowversion) or conditional updates (WHERE Status = 'Pending') so only one transition succeeds.
- Idempotency keys for requests and an inbox table for messages.
- Distributed locks (database application locks or Redis) only when necessary, with timeouts.
- Make shared objects immutable or thread-safe (ConcurrentDictionary, SemaphoreSlim for async critical sections — never lock around await).
- Await every task; avoid async void.
5. Prevent recurrence
- Keep the stress test in the suite.
- Add metrics and alerts for invariant violations (orders in impossible states, duplicate payments).
- Add a reconciliation job to detect and repair inconsistencies.