Step 08 — Run several publishers safely
What you'll do: claim each outbox batch with FOR UPDATE SKIP LOCKED inside a transaction, so several API instances can publish at the same time without sending the same row twice.
The problem: competing publishers
In production the API runs as several instances behind a load balancer, and each one runs its own OutboxPublisher. With the query from step 07, two instances that tick at the same moment read the same oldest rows and both publish them. Nothing is lost, and the inbox from step 06 would skip the copies, but every message would be sent twice: double the broker traffic, and double the work for every consumer.
You could run only one publisher (a separate process, or leader election), but then publishing stops when that one instance does. Row locks let every instance publish and share the work.
Steps
In OutboxPublisher.cs, open a transaction and replace the LINQ query with SQL that locks the rows it returns:
csharpawait using var transaction = await db.Database.BeginTransactionAsync(ct); var batch = await db.OutboxMessages .FromSql($""" SELECT * FROM outbox_messages WHERE processed_at IS NULL AND attempts < {settings.MaxAttempts} AND (next_attempt_at IS NULL OR next_attempt_at <= {now}) ORDER BY occurred_at LIMIT {settings.BatchSize} FOR UPDATE SKIP LOCKED """) .ToListAsync(ct);Commit at the end, after saving the processed rows:
csharpawait db.SaveChangesAsync(CancellationToken.None); await transaction.CommitAsync(CancellationToken.None);If the batch is empty, the method returns early and
await usingrolls the empty transaction back. If anything throws, the same happens and the locks are released.Add a second launch profile to launchSettings.json, so you can start another instance on port 5081:
json"http-2": { "commandName": "Project", "dotnetRunMessages": true, "launchBrowser": false, "applicationUrl": "http://localhost:5081", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } }
Check it works
Build, then start the worker and two API instances, each in its own terminal:
dotnet build OutboxInbox.slnx -warnaserror
dotnet run --project src/Shipping.Worker
dotnet run --project src/Orders.Api --launch-profile http
dotnet run --project src/Orders.Api --launch-profile http-2Send 300 orders at once, 150 to each instance, 20 at a time (curl expands {5080,5081} and [1-150] into 300 URLs; the API ignores the n query parameter):
curl -s --parallel --parallel-max 20 -X POST "http://localhost:{5080,5081}/orders?n=[1-150]" \
-H 'content-type: application/json' \
-d '{"customerEmail":"alex@contoso.com","items":[{"sku":"BOOK-1","quantity":1}]}' | grep -o '"id"' | wc -l 300After about ten seconds, both instances have published, and between them they sent each row once. In this run, the instance on 5080 logged 141 Published outbox message lines and the one on 5081 logged 159: together exactly 300. Your split will differ. The worker logged 300 Created shipment lines and no Skipped duplicate message line.
Check the counts in the databases:
docker compose exec postgres psql -U postgres -d orders -tAc \
"select count(*) filter (where processed_at is null) from outbox_messages"
docker compose exec postgres psql -U postgres -d shipping -tAc "select count(*) from shipments"The first number is 0 (nothing left to publish). The shipment count grew by exactly 300.
This is a timing test: it shows the instances sharing the work, but it cannot prove that a race never happens. The guarantee comes from the database locks, explained below.
Why it works
FOR UPDATE locks the selected rows until the transaction ends. Any other transaction that tries to lock the same rows has to wait.
SKIP LOCKED changes "wait" into "skip". The second instance does not queue up behind the first; it takes the next unlocked rows. So two publishers that tick together get two different batches, and each row is published by one instance only. When the first commits, its rows have processed_at set and no longer match the query.
Why raw SQL. LINQ has no way to express FOR UPDATE SKIP LOCKED. FromSql with an interpolated string sends the values (MaxAttempts, now, BatchSize) as SQL parameters, not pasted text, so it is safe from SQL injection. The results are normal tracked entities, so the rest of the method (RecordFailure, ProcessedAt, SaveChangesAsync) is unchanged. The column names are the snake_case names from step 02.
The cost: locks held while publishing. The transaction stays open while the batch is sent to RabbitMQ. With a batch of 20 and confirms that take a millisecond or two, that is short. With a slow broker, keep BatchSize small so locks are not held for long. (An alternative design marks rows as "claimed by instance X until time T" in one short transaction and publishes outside it, at the cost of more columns and a timeout to reclaim abandoned rows.)
Ordering across instances. Two instances publish different batches in parallel, so messages can reach the broker slightly out of occurred_at order. Step 07 already made consumers independent of order. If you need strict order per order id, route all of an aggregate's messages to one publisher, or give consumers a version number to check.
Duplicates can still happen, for the reasons in step 06 (a crash between confirm and commit). SKIP LOCKED removes the systematic duplicates caused by competing publishers; the inbox still handles the rare ones.