Distributed locks and leases in .NET: Redis SET NX and Redlock, SQL Server sp_getapplock, Azure Blob leases, why locks fail (GC pauses, expiry, clock jumps, failover), fencing tokens, and designs that avoid locks.
A distributed lock is really a lease: a time-limited claim that expires so a crashed holder doesn't block everyone forever. That expiry is what makes it dangerous: a holder that pauses (a long GC pause, a VM freeze, a slow network) can lose the lease, carry on, and overlap with the next holder without knowing. Redis SET NX PX is fast but replication is asynchronous, so a failover can hand the same lock to two clients; Redlock adds a majority of nodes but still relies on timing assumptions. SQL Server sp_getapplock and Azure Blob leases are simpler and tied to stores you already trust. For correctness, the protected resource must check a fencing token (a number that only goes up) so stale holders are rejected. Better still, design the lock away with partition ownership, queues, optimistic concurrency or idempotency.
"The first thing I say is that a distributed lock is a lease, not a lock. In-process,
lockis held until you release it and the runtime guarantees nobody else gets in. Across machines, the lock service can't tell a crashed holder from a slow one, so every lock has an expiry. That creates the classic failure: instance A takes a 30-second lease, hits a 40-second stop-the-world pause or a network stall, the lease expires, instance B takes it, and then A wakes up and keeps writing as if it still holds the lock. Both are now inside the critical section.The options I'd consider in .NET: Redis with
SET key token NX PX 30000and a Lua compare-and-delete to release. It's fast, but Redis replication is asynchronous, so if the primary fails before the key reaches the replica, the new primary has no lock and a second client gets it. Redlock acquires the lock on a majority of independent Redis nodes to survive that, but, as Martin Kleppmann pointed out, it still assumes bounded pauses and clock drift. SQL Serversp_getapplockis attractive when the job already uses SQL: the lock is owned by the session or transaction, so it can't expire while the connection is alive, and it disappears if the connection drops. Azure Blob leases of 15 to 60 seconds are a simple choice for leader election. TheDistributedLockNuGet package wraps all three. For [example, at company] we [used a blob lease to elect one instance for a scheduled export, which cut duplicate runs to zero].The key question is whether the lock is for efficiency or correctness. If two holders overlapping just wastes work, any of these is fine. If overlap corrupts data or moves money twice, a lock alone isn't enough: the resource must check a fencing token, or the operation must be idempotent. And often the best lock is no lock: give each partition one owner, or use a queue."
| Mechanism | How it works | Strengths | Weaknesses |
|---|---|---|---|
| Redis single node / primary-replica | SET k token NX PX ttl, Lua release |
Very fast, simple | Async replication: failover can grant the lock twice |
| Redlock | Majority of N independent Redis nodes | Survives one node failing | Timing assumptions; operationally heavier |
SQL Server sp_getapplock |
Lock owned by session or transaction | No TTL while connected; you already run SQL | Holds a connection; lost if the connection drops |
| Azure Blob lease | 15-60 s or infinite lease on a blob, renewed by holder | Managed, cheap, good for leader election | Renewal loop needed; still a lease |
| ZooKeeper / etcd | Consensus, ephemeral nodes, revision numbers | Strongest guarantees, built-in fencing values | Another system to run |
| Purpose | Consequence of overlap | Enough? |
|---|---|---|
| Efficiency (avoid recomputing a cache, avoid duplicate report runs) | Wasted work | A lease is fine |
| Correctness (charge once, allocate stock once) | Wrong data, money lost | Lease + fencing token, or idempotency |
A stock-allocation worker ran on four instances and used a Redis lock with a 10-second TTL. During a Redis failover in Australia East, two instances both held the lock for about 6 seconds and allocated the same 140 units twice. Moving allocation to a SQL UPDATE ... WHERE Version = @expected (optimistic concurrency acting as a fencing check) removed the overlap risk entirely, and the lock stayed only as an efficiency measure.
Checks whether the candidate understands that distributed locks are leases with real failure modes and knows how to keep correctness anyway.
Green flags
Red flags
A lock service sees a holder go quiet. It can't distinguish 'crashed' from 'paused' from 'network partitioned'. If it waits forever, one crash blocks the system; so it expires the lock after a TTL. Correctness now depends on the holder finishing within the TTL, which nobody can guarantee.
Client A Lock service Storage
| acquire (ttl 30s) -> ok |
| ... GC pause 40 s ... |
| lease expires |
Client B -- acquire -> ok |
Client B -------- write v=2 ----------> |
| wakes, still thinks it holds lock |
| -------- write v=1 --------------> | <- stale write wins
Causes: stop-the-world GC (Gen2 pauses on big heaps can reach seconds), container CPU throttling, VM live migration, page faults, a slow network packet carrying the write.
The lock service hands out a number that increases with every grant (33, then 34). Every write to the protected resource includes it, and the resource rejects any token lower than the highest it has seen:
A gets token 33 -> pauses
B gets token 34 -> writes with 34 (storage records max = 34)
A wakes -> writes with 33 -> REJECTED (33 < 34)
In SQL Server you can implement the check as a conditional update: UPDATE ... SET Token = @t WHERE Id = @id AND Token < @t. etcd and ZooKeeper give you a natural token (revision, zxid). A plain Redis lock doesn't, which is part of Kleppmann's critique of Redlock.
SET resource random-token NX PX 30000; release only if the value still equals your token (Lua script), so you never delete someone else's lock. Replication to replicas is asynchronous, so a failover can lose the key.sp_getapplock: @LockOwner = 'Session' holds until released or the connection closes; 'Transaction' until commit or rollback. No expiry while connected, but if the connection is killed (failover, network), the lock silently goes and your process may not notice until its next command fails.DistributedLock libraryDistributedLock (by madelson, MIT) provides SqlDistributedLock, RedisDistributedLock, AzureBlobLeaseDistributedLock and others behind IDistributedLock. Handles expose HandleLostToken, a CancellationToken that fires when the library detects the lock is gone, which you should pass into your work.
Thread.Sleep(8000) in the holder, start a second holder, and log both writing.sp_getapplock in session mode and kill the connection with KILL <spid> mid-work; observe when the holder finds out.Token column and a conditional UPDATE, and replay the stale-writer case.AzureBlobLeaseDistributedLock against Azurite with two console apps and watch HandleLostToken fire when you stop renewals.A lease from the DistributedLock library for efficiency, plus a fencing-style conditional update so a stale holder can never overwrite newer work.
using Medallion.Threading.SqlServer;
using Microsoft.Data.SqlClient;
namespace Allocation;
public sealed class StockAllocator(string connectionString, ILogger<StockAllocator> logger)
{
public async Task AllocateAsync(string sku, int quantity, CancellationToken ct)
{
var @lock = new SqlDistributedLock($"allocate:{sku}", connectionString);
// Efficiency: avoid two instances doing the same work at the same time
await using var handle = await @lock.TryAcquireAsync(TimeSpan.FromSeconds(5), ct);
if (handle is null)
{
logger.LogInformation("Another instance is allocating {Sku}", sku);
return;
}
// If the connection holding the app lock drops, stop working immediately
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, handle.HandleLostToken);
await using var conn = new SqlConnection(connectionString);
await conn.OpenAsync(linked.Token);
var version = await ReadVersionAsync(conn, sku, linked.Token);
// Correctness: the write only succeeds if nobody changed the row since we read it.
// A stale holder (paused past its lease) fails here instead of corrupting stock.
await using var cmd = new SqlCommand("""
UPDATE Stock
SET Available = Available - @qty, Version = Version + 1
WHERE Sku = @sku AND Version = @version AND Available >= @qty
""", conn);
cmd.Parameters.AddWithValue("@qty", quantity);
cmd.Parameters.AddWithValue("@sku", sku);
cmd.Parameters.AddWithValue("@version", version);
if (await cmd.ExecuteNonQueryAsync(linked.Token) == 0)
logger.LogWarning("Allocation for {Sku} rejected: stale version or not enough stock", sku);
}
private static async Task<long> ReadVersionAsync(SqlConnection conn, string sku, CancellationToken ct)
{
await using var cmd = new SqlCommand("SELECT Version FROM Stock WHERE Sku = @sku", conn);
cmd.Parameters.AddWithValue("@sku", sku);
return (long)(await cmd.ExecuteScalarAsync(ct))!;
}
}
lock. Why it is wrong: it is a lease that can expire while you still think you hold it. Instead: design for the holder losing the lock mid-work.DEL. Why it is wrong: if your lease already expired, you delete the next holder's lock. Instead: compare the stored token and delete atomically with a Lua script.HandleLostToken).sp_getapplock dies with its connection. Why it is wrong: a dropped connection releases the lock while your code keeps going. Instead: watch for loss and fence the writes.My first question about any distributed lock is 'what happens if two holders overlap for ten seconds?' If the answer is 'some wasted CPU', I pick the simplest lease available, usually a SQL app lock or a blob lease because the team already runs those stores. If the answer is 'we charge someone twice', the lock is only an optimisation and the real protection lives in the data: a fencing token, a version check or an idempotency key.
Acquiring well matters as much as holding. Never spin on a lock: acquire with a bounded wait (TryAcquireAsync(TimeSpan)), and if you don't get it, either skip the work (another instance is doing it) or retry with exponential backoff and jitter so ten instances don't hammer Redis or SQL in lockstep. Treat a transient error while acquiring (a Redis timeout, a SQL failover) as 'not acquired', never as 'acquired'. While working, renew the lease on a timer at about a third of the TTL and cancel the work the moment renewal fails.
On Redis WAIT. WAIT numreplicas timeout blocks until the write reached that many replicas, which narrows the failover window, but Redis still doesn't guarantee a promoted replica has every acknowledged write (the old primary can also keep accepting writes during a partition). It makes double-granting rarer, not impossible. On SQL Server, sp_getapplock has behaved the same way for many versions; the improvement in modern setups is around it: Azure SQL and availability groups fail over faster, which also means the session (and its lock) disappears more often, so loss detection matters.
I also push back on locks as a design smell. Most 'we need a distributed lock' requests are really 'we need exactly one worker per key' (use partitions or sessions) or 'we need to avoid lost updates' (use optimistic concurrency).
| Option | When it fits | Cost | When not to |
|---|---|---|---|
SQL sp_getapplock |
Jobs already using SQL Server | Holds a connection | Very high lock rates |
| Azure Blob lease | Leader election, scheduled jobs | Renewal loop | Fine-grained per-entity locks |
| Redis lock | High-rate efficiency locks | Failover can double-grant | Correctness without fencing |
| etcd / ZooKeeper | Strong coordination needs | Another cluster to run | Small teams without the ops capacity |
| No lock (partitioning, optimistic concurrency) | Most business cases | Design effort | Truly global singletons |
An operation is idempotent if doing it once or many times leaves the system in the same state. It's the core tool because distributed systems produce duplicates all the time: clients retry after timeouts, brokers deliver at least once, users double-click. You get it in two ways. Some operations are naturally idempotent: 'set status to Shipped', a PUT of the full resource, an upsert by a natural key. The rest need deduplication: the caller sends a unique idempotency key (or the broker supplies a message id), and the service records it under a unique constraint in the same transaction as the business change, so a repeat is detected and answered with the stored result. The trade-off is storage and a little complexity, against duplicate charges, orders and emails.
An ETag is an opaque version identifier for a representation of a resource, returned in the ETag header. Clients send it back in conditional requests. On a GET, If-None-Match lets the server answer 304 Not Modified with no body when nothing changed, saving bandwidth. On a PUT, PATCH or DELETE, If-Match makes the write conditional: if someone else changed the resource since the client read it, the server returns 412 Precondition Failed instead of silently overwriting their change (the lost update problem). A SQL Server rowversion column, mapped with EF Core's IsRowVersion, makes a natural strong ETag. The trade-off: clients must read before they write and handle 412 by refreshing and retrying.
A cache stampede happens when a hot key expires and hundreds of concurrent requests all miss and run the same expensive query at once. I confirm it by lining up cache miss spikes, identical dependency calls per key and expiry times in Application Insights and Query Store.
Fixes, in layers:
The trade-off is slightly staler data in exchange for a database that survives expiry.
How to tell it (STAR)
**S:** During a [promotion], our [stock allocator] oversold [several] products after a Redis failover. **T:** I led the investigation and the fix. **A:** I matched duplicate 'lock acquired' traces to the failover and showed the lock could be granted twice, then moved correctness into the database with a version-checked conditional update and kept the lock purely as an optimisation. **R:** We've had zero oversells since, through [n] further failovers, and allocation latency went up by less than [2 ms].
Last updated 23 Nov 2026.