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.
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:
csharpprivate 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.
Getting Started with the DistributedLock Library
DistributedLock is the most widely used distributed locking library in .NET. It gives you one API that works on top of Redis, PostgreSQL, SQL Server, MySQL, Azure Blob Storage, ZooKeeper, and a few more.
You install one package per backend:
bashdotnet add package DistributedLock.Redis dotnet add package DistributedLock.Postgres
The main abstraction is IDistributedLockProvider.
It's a factory that creates locks by name, which makes it a natural fit for dependency injection.
Here is how to register the Redis provider:
csharpvar redisConnectionString = configuration.GetConnectionString("Redis")!; services.AddSingleton<IConnectionMultiplexer>(_ => ConnectionMultiplexer.Connect(redisConnectionString)); services.AddSingleton<IDistributedLockProvider>(sp => { var connection = sp.GetRequiredService<IConnectionMultiplexer>(); return new RedisDistributedSynchronizationProvider(connection.GetDatabase()); });
Both the ConnectionMultiplexer and the provider are singletons.
StackExchange.Redis is designed to share one multiplexer across the whole app, and the provider holds no per-request state.
The provider gives you two extension methods you'll use all the time:
csharp// Waits until the lock is free, or throws TimeoutException after the timeout await using var handle = await lockProvider.AcquireLockAsync( "shipments:10000001", TimeSpan.FromSeconds(5), cancellationToken); // Tries for up to the timeout, and returns null if the lock is still taken await using var handle = await lockProvider.TryAcquireLockAsync( "shipments:10000001", TimeSpan.Zero, cancellationToken);
Both return a handle.
The lock is held until you dispose the handle. Forget await using, and the lock stays taken until the Redis key expires.
Use AcquireLockAsync when waiting is the right behavior, and always pass a timeout.
Without one, the call waits forever.
Use TryAcquireLockAsync with TimeSpan.Zero when the right behavior is "someone else is already doing this, so I'll skip it".
Let's put the lock into the dispatch handler.
Locking a Single Shipment
Here is the same handler with the semaphore replaced by a distributed lock:
csharppublic async Task<ErrorOr<DispatchShipmentResponse>> HandleAsync( string number, CancellationToken cancellationToken) { await using var handle = await lockProvider.TryAcquireLockAsync( $"shipments:{number}", TimeSpan.Zero, cancellationToken); if (handle is null) { return Error.Conflict(description: $"Shipment '{number}' is already being dispatched"); } 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); }
Three details make this correct.
The lock name includes the shipment number.
Requests for shipments 10000001 and 10000002 acquire different locks and run in parallel.
Only requests for the same shipment compete.
A busy lock returns 409 Conflict.
A duplicate click or a retried request doesn't need to wait 2 seconds to learn the answer.
If you'd rather queue the request, use AcquireLockAsync with a timeout instead.
The status is checked inside the lock. This is the part people skip. The lock only guarantees that nobody else is dispatching right now. It doesn't guarantee that nobody dispatched a second ago. Reading the shipment after you get the lock and checking its status makes it safe to call the operation twice.
Per-request locks are one use case. The other common one is making sure some code runs on only one instance at a time.
Running Code on Only One Instance
Every instance of your app runs the same hosted services. Scale to three pods, and your "every 10 seconds" background job now runs three times every 10 seconds.
In our domain, a job picks up newly created shipments and sends them to the warehouse. If two instances do this simultaneously, the warehouse receives the same order twice.
csharppublic sealed class ShipmentProcessingJob( IServiceScopeFactory scopeFactory, IDistributedLockProvider lockProvider, InstanceInfo instance, ILogger<ShipmentProcessingJob> logger) : BackgroundService { protected override async Task ExecuteAsync(CancellationToken stoppingToken) { using var timer = new PeriodicTimer(TimeSpan.FromSeconds(10)); while (await timer.WaitForNextTickAsync(stoppingToken)) { await ProcessShipmentsAsync(stoppingToken); } } private async Task ProcessShipmentsAsync(CancellationToken stoppingToken) { await using var handle = await lockProvider.TryAcquireLockAsync( "jobs:shipment-processing", TimeSpan.Zero, stoppingToken); if (handle is null) { logger.LogInformation("[{Instance}] Skipped: another instance is running the job", instance.Name); return; } await using var scope = scopeFactory.CreateAsyncScope(); var dbContext = scope.ServiceProvider.GetRequiredService<EfCoreDbContext>(); var warehouseApi = scope.ServiceProvider.GetRequiredService<WarehouseApiClient>(); var shipments = await dbContext.Shipments .Where(s => s.Status == ShipmentStatus.Created) .OrderBy(s => s.CreatedAt) .Take(20) .ToListAsync(stoppingToken); foreach (var shipment in shipments) { await warehouseApi.SendForPackingAsync(shipment, stoppingToken); shipment.Status = ShipmentStatus.Processing; await dbContext.SaveChangesAsync(stoppingToken); } } }
Every instance wakes up on its timer and tries to take the same named lock with a zero timeout. The winner processes the batch, and the others log "Skipped" and go back to sleep.
Here is what the logs from both instances look like when six new shipments arrive:
12:11:21 [instance-1] Acquired the job lock, processing 6 new shipments 12:11:22 [instance-2] Skipped: another instance is running the job 12:11:22 [instance-1] Sending shipment 17373685 to the warehouse 12:11:23 [instance-1] Sending shipment 87214383 to the warehouse
A lock guarantees one holder at a time, and that's all it guarantees.
If instance 1 finishes in 300 ms and instance 2 wakes up a second later, instance 2 gets the lock too. That's fine here, because each shipment changes status after it's processed, so the second run finds nothing to do.
If you need a real schedule, like "run at 02:00 once", use a scheduler with persistence such as Quartz or TickerQ.
The same idea works at startup. When two pods start at the same moment, both try to seed the database:
csharpawait using (var scope = app.Services.CreateAsyncScope()) { var lockProvider = scope.ServiceProvider.GetRequiredService<IDistributedLockProvider>(); await using (await lockProvider.AcquireLockAsync("startup:database-setup", TimeSpan.FromMinutes(1))) { var dbContext = scope.ServiceProvider.GetRequiredService<EfCoreDbContext>(); await dbContext.Database.MigrateAsync(); var seedService = scope.ServiceProvider.GetRequiredService<SeedService>(); await seedService.SeedDataAsync(); } }
Here, AcquireLockAsync is the right choice, because the second instance should wait its turn.
When it gets the lock, the first instance has already finished, so its seed check finds the data and does nothing.
EF Core 9 and later already protect MigrateAsync itself from running twice at once.
Your own seeding code has no such protection, and that's what the lock adds.
So far everything runs on Redis. If you don't run Redis, you don't need to add it just for locks.
Switching to PostgreSQL Advisory Locks
PostgreSQL has a built-in feature for exactly this: advisory locks. An advisory lock is a lock on an arbitrary number, and your app decides what that number means.
DistributedLock maps your lock names to advisory lock keys for you. Switching from Redis is a one-line change in the DI registration:
csharpvar connectionString = configuration.GetConnectionString("Postgres")!; services.AddSingleton<IDistributedLockProvider>(_ => new PostgresDistributedSynchronizationProvider(connectionString));
The handler, the background job, and the startup code don't change at all.
They only depend on IDistributedLockProvider.
Postgres holds the lock differently. A Postgres session advisory lock belongs to a database connection and is released when that connection closes. So while you hold the lock, the library keeps a connection open.
That's also what makes it safe. If your process crashes, Postgres closes the connection and frees the lock immediately. There's no expiry to wait for.
By default, the library multiplexes: a single open connection can hold several locks at once, which keeps costs low.
Note: if you connect through PgBouncer in transaction pooling mode, session advisory locks don't work, because your "session" moves between server connections. Configure the provider with
options => options.UseTransaction(true)to use transaction-scoped locks instead, or connect to Postgres directly for locking.
Which backend should you pick? If you already run Redis, use Redis: it's fast and puts no load on your main database. If you only have Postgres, advisory locks do the job with no new infrastructure.
Handling Timeouts and Lock Loss
A distributed lock can be lost while you hold it.
With Redis, the lock is a key with an expiry, 30 seconds by default. The library extends it in the background every 10 seconds while you hold it. If your process freezes for longer than the expiry period, or Redis restarts, the key disappears, and another instance can take the lock.
With Postgres, the lock disappears if the connection drops.
The handle tells you when this happens through HandleLostToken.
Link it to your own cancellation token so the work stops as soon as the lock is gone:
csharpawait using var handle = await lockProvider.TryAcquireLockAsync( "jobs:shipment-processing", TimeSpan.Zero, stoppingToken); if (handle is null) { return; } using var cts = CancellationTokenSource.CreateLinkedTokenSource( stoppingToken, handle.HandleLostToken); try { await ProcessBatchAsync(cts.Token); } catch (OperationCanceledException) when (handle.HandleLostToken.IsCancellationRequested) { logger.LogWarning("[{Instance}] Lost the job lock, stopping the batch", instance.Name); }
I tested this by killing the Postgres connection that held the job lock in the middle of a 20-shipment batch. The job logged "Lost the job lock, stopping the batch" after 4 shipments, and the next run picked up the other 16.
Two things I learned from that test:
- Watching for loss isn't free. With Postgres, reading
HandleLostTokenmakes the library run a monitoring query on the lock's connection. Save it for long-running work, like a batch job. - Disposing a lost handle can throw. Releasing a Postgres lock whose connection is already gone throws
InvalidOperationException. Your job loop should catch exceptions so one lost lock doesn't stop the background service.
A distributed lock makes duplicate work rare. Your database has to keep the data correct.
Here is how a lock fails in practice. Instance 1 takes the lock, then hits a 40-second-long external call.
The Redis key expires, and instance 2 takes the lock and dispatches the shipment.
Instance 1 wakes up, still believes it holds the lock, and writes its own result.
The classic fix is a fencing token: a number that grows every time the lock is taken, which the database checks on every write. DistributedLock doesn't hand out fencing tokens, but your database can play the same role. Make the final write conditional on the state you expect:
csharpvar updated = await dbContext.Shipments .Where(s => s.Number == number && s.Status == ShipmentStatus.Processing) .ExecuteUpdateAsync(s => s .SetProperty(x => x.Status, ShipmentStatus.Dispatched) .SetProperty(x => x.DispatchedAt, DateTime.UtcNow), cancellationToken); if (updated == 0) { // Someone else dispatched it while we thought we held the lock }
Now a stale holder's write changes zero rows instead of overwriting good data. A concurrency token, as described in the optimistic concurrency article, does the same job when you use the change tracker.
Important note: a single Redis node with a replica can lose a lock during failover, because replication is asynchronous.
If that risk matters to you, pass several independent Redis databases to RedisDistributedSynchronizationProvider, and the library uses the RedLock algorithm across them.
Even then, keep the conditional write.
Before you add a lock, check whether you need one.
When You Don't Need a Distributed Lock
A distributed lock adds a network call and one more system that can fail.
These simpler tools often solve the same problem:
- One atomic statement. If the new value follows from the old one, like decrementing stock or moving a status forward,
ExecuteUpdateAsyncwith a guard inWheredoes it in one round trip. See Correct Way To Use ExecuteUpdate and ExecuteDelete Methods in EF Core. - A unique constraint. "Only one shipment per order" is a unique index on
OrderId. - Optimistic concurrency. If conflicts are rare and you can retry, a concurrency token is simpler and has no extra infrastructure.
FOR UPDATE SKIP LOCKED. If many workers pull jobs from a table, row locks let each worker take a different batch without any coordination.- Message partitioning. If messages for one shipment always go to the same consumer, for example with a Kafka partition key, there's nothing to lock.
Reach for a distributed lock when the protected work is slow, has side effects outside your database (like the carrier call), or spans more than one data store.
Summary
Let's recap the key takeaways:
-
In-process locks stop at the process boundary.
lockandSemaphoreSlimare correct on one instance and silently wrong on two. -
A distributed lock lives in a shared system. Every instance asks Redis or Postgres for the same named lock, and only one gets it.
-
Use DistributedLock instead of writing your own.
IDistributedLockProvidergives you one API for Redis, Postgres, and other backends, with expiry, extension, and loss detection already handled. -
Name locks per resource.
shipments:{number}serializes work on one shipment without blocking the others. -
Pick the acquire method by intent.
TryAcquireLockAsyncwithTimeSpan.Zeromeans "skip if busy".AcquireLockAsyncwith a timeout means "wait my turn". -
Re-check state inside the lock. The lock stops parallel work. The status check stops repeated work.
-
Keep correctness in the database. Watch
HandleLostTokenfor long work, and make the final write conditional so a stale holder can't corrupt data.
Most systems I've worked on needed only a handful of distributed locks. Each one protected a slow side effect and the database handled everything else.
There is no single correct way to handle concurrency; pick the simplest tool that fits each operation.
Hope you find this newsletter useful. See you next time.

