Clean Markdown mirror for AI agents:
/guides/contended-stock-reservation.md · /llms.txt
Lab

Preventing Overselling with FOR UPDATE Locks and Outbox Atomicity

Race five concurrent buyers for one scarce SKU in PostgreSQL 18 using deterministic FOR UPDATE row locks, xmin tokens, and atomic outbox commits.

Orbit prevents overselling under concurrent order bursts by combining deterministic SELECT *, xmin FROM inventory.stock_items ... ORDER BY product_id FOR UPDATE row locks in PostgreSQL 18 with atomic EF Core Transactional Outbox writes. Five simultaneous orders for the last unit always produce one Confirmed winner and four StockRejected compensations.

Run the five-buyer contention test

Start Docker so Testcontainers can boot an isolated postgres:18-alpine instance, then execute the race test in Orbit.IntegrationTests:

dotnet test tests/Orbit.IntegrationTests/Orbit.IntegrationTests.csproj \
  --filter FullyQualifiedName~ConcurrentOrdersForLastUnit_GuaranteesExactlyOneConfirmedWinner

The test publishes a SKU with initialStockQuantity = 1 and fires five parallel POST /api/orders HTTP requests. All five HTTP calls return 201 Created in PendingStock state, wake the Outbox relay, and converge deterministically:

  • 1 order transitions to Confirmed (and triggers a Pending shipment in shipments.shipments).
  • 4 orders receive OrderStockRejectedIntegrationEvent and transition to StockRejected with a clear rejection reason.
  • inventory.stock_items finishes with QuantityOnHand = 1, QuantityReserved = 1, and AvailableQuantity = 0.

Inspect the lock and outbox boundary

Inside InventoryModule, StockRepository.GetByProductIdsForUpdateAsync sorts the requested GUIDs before locking rows:

Guid[] orderedIds = productIds.OrderBy(id => id).ToArray();

List<StockItem> locked = await dbContext.StockItems
    .FromSql(
        $"SELECT *, xmin FROM inventory.stock_items WHERE product_id = ANY({orderedIds}) ORDER BY product_id FOR UPDATE")
    .ToListAsync(cancellationToken);

Sorting orderedIds eliminates multi-line lock-inversion deadlocks. Including xmin satisfies EF Core’s concurrency token mapping on StockItem. When unitOfWork.SaveChangesAsync commits, InsertOutboxMessagesInterceptor writes the resulting OrderStockReserved or OrderStockRejected event (along with the caller’s W3C trace_parent) in the exact same PostgreSQL transaction.

Summary

  • Accept high-throughput order writes locally in Orders, then serialize stock allocation inside Inventory with ORDER BY product_id FOR UPDATE.
  • Always select *, xmin when using .FromSql(...) on Npgsql entities configured with UseXminAsConcurrencyToken().
  • Commit state mutations and outbox_messages rows in one database transaction so downstream modules always learn the outcome.

Verified C# source & test evidence

Frequently asked questions

Why is an optimistic read-then-write check not enough for contested inventory?

Under concurrent bursts, optimistic concurrency throws DbUpdateConcurrencyException for every contender except one, forcing noisy retry loops. Acquiring SELECT FOR UPDATE in sorted product_id order serializes contenders cleanly inside PostgreSQL.

Why sort product IDs before executing SELECT FOR UPDATE?

If Order A locks Product 1 then Product 2 while Order B locks Product 2 then Product 1, PostgreSQL deadlocks. Sorting product IDs ascending guarantees a consistent lock acquisition order.

Why include xmin in the raw SELECT FOR UPDATE projection?

EF Core's Npgsql provider maps PostgreSQL's hidden xmin system column as a concurrency token. Selecting *, xmin ensures EF Core populates the tracked concurrency token when materializing entities from raw SQL.

Keep exploring