A customer gets two "Your shipment is on its way" emails.
The carrier sends two trucks to the same warehouse for the same parcel.
You open the code and the dispatch handler looks perfectly safe.
It even wraps the whole operation in a SemaphoreSlim, so only one request can dispatch a shipment at a time.
Then you notice the deployment changed last week.
The API now runs on two instances behind a load balancer.
A SemaphoreSlim only protects one process.
The second instance has its own semaphore, and it has no idea the first one exists.
This bug shows up the moment you scale out, and it doesn't show up in any test that runs on a single machine.
The fix is a lock that lives outside your process: a distributed lock.
Today, I want to show you how to implement distributed locks in .NET with the DistributedLock library, first with Redis and then with PostgreSQL.
I built a working project with two API instances and you can run it yourself.
In this post, we will explore:
- Why lock and SemaphoreSlim Stop Working When You Scale Out
- What Is a Distributed Lock
- Getting Started with the DistributedLock Library
- Locking a Single Shipment
- Running Code on Only One Instance
- Switching to PostgreSQL Advisory Locks
- Handling Timeouts and Lock Loss
- When You Don't Need a Distributed Lock
Let's dive in.
👉 Read original article on my newsletter: https://antondevtips.com/blog/distributed-locking-in-dotnet
Why lock and SemaphoreSlim Stop Working When You Scale Out
Here is the dispatch handler for our logistics domain.
It loads a shipment, asks the carrier to schedule a pickup, and marks the shipment as dispatched:
private static readonly SemaphoreSlim Semaphore = new(1, 1); public async Task<ErrorOr<DispatchShipmentResponse>> HandleAsync( string number, CancellationToken cancellationToken) { await Semaphore.WaitAsync(cancellationToken); try { var shipment = await dbContext.Shipments .FirstOrDefaultAsync(s => s.Number == number, cancellationToken); if (shipment is null) { return Error.NotFound(description: "$\"Shipment '{number}' not found\");" } if (shipment.Status is not ShipmentStatus.Processing) { return Error.Conflict(description: "$\"Shipment '{number}' can't be dispatched\");" } await carrierApi.SchedulePickupAsync(shipment, cancellationToken); shipment.Status = ShipmentStatus.Dispatched; shipment.DispatchedAt = DateTime.UtcNow; shipment.DispatchedBy = instance.Name; await dbContext.SaveChangesAsync(cancellationToken); return new DispatchShipmentResponse( shipment.Number, shipment.Status, shipment.DispatchedAt.Value, shipment.DispatchedBy); } finally { Semaphore.Release(); } } In one instance, this code is correct.
The second request waits for the semaphore, reads the shipment after the first one saved it, sees the Dispatched status, and returns a conflict.
The carrier call is the expensive part.
It takes a couple of seconds, and it can't be undone: once the carrier schedules a truck, the truck is coming.
Now run two instances:
Each instance holds its own semaphore, so each one thinks it is alone.
Both read Processing, both call the carrier, and both save.
Alternatives:
- You may read the database more times instead of a lock (it won't work).
- You may use a database transaction instead of a semaphore.
A database transaction won't save you here either, for the same reason I described in Optimistic vs Pessimistic Concurrency in .NET: under Read Committed, both transactions read a valid row.
And even a row lock wouldn't help much here, because you'd hold a database transaction open across a slow HTTP call to the carrier.
Yes, you can prevent this with the Serializable transaction isolation level, but do you know how much performance cost you will pay for it?
You need a lock that every instance can see, and that won't hurt performance of the rest of the application.
What Is a Distributed Lock
A distributed lock is a lock stored in a shared system, such as Redis or a database, instead of in your process memory.
Every instance asks the same shared system for the lock by name.
Only one of them gets it.
The others either wait or give up.
The lock name is just a string.
shipments:10000002 protects one shipment, and jobs:shipment-processing protects one background job.
Two requests for different shipments use different names, so they don't block each other.
A good distributed lock gives you three things:
- Mutual exclusion: only one holder of a given name at a time, across all instances.
- Automatic release: if the holder crashes, the lock frees itself. A Redis key expires, and a Postgres lock disappears when its connection closes. Without this, one crashed pod would block that shipment forever.
- Acquire timeouts: a caller can say "wait up to 5 seconds" or "don't wait at all" instead of blocking indefinitely.
You can build this yourself with SET key value NX PX 30000 in Redis or pg_try_advisory_lock in Postgres.
But I don't recommend it.
The hard parts are extending the lock while you hold it, releasing only your own lock, and noticing when you lose it.
There is already a library that solves all three problems.
👉 Read original article on my newsletter: https://antondevtips.com/blog/distributed-locking-in-dotnet



