📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do distributed locks work, and why are they so easy to get wrong? Compare Redis (including Redlock), SQL Server application locks and Azure Blob leases, explain fencing tokens, and tell me when you would avoid a distributed lock altogether.

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.

Senior Theory Advanced azure-blob-storage distributed-locks distributed-systems fencing-tokens redis sql-server

🎯 Key points

  • A distributed lock is really a lease: it expires, so the holder can lose it without knowing
  • Failure modes: GC or VM pause past expiry, network delay, Redis failover losing the key, clock jumps
  • Redis: SET key token NX PX ttl, release with a compare-and-delete Lua script; replication is asynchronous, and WAIT only narrows the failover window
  • Redlock uses a majority of independent nodes but still assumes bounded pauses and clock drift
  • SQL Server sp_getapplock (session or transaction owned) holds while the connection lives and vanishes if it drops; Azure Blob leases (15-60 s or infinite) suit leader election
  • Acquire with a bounded wait and retry with backoff and jitter; renew while working and stop when renewal fails
  • Fencing token: a monotonically increasing number checked by the resource, so a stale holder's writes are rejected
  • Locks for efficiency vs correctness; prefer lock-free designs: partition ownership, queues, optimistic concurrency, idempotency

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"The first thing I say is that a distributed lock is a lease, not a lock. In-process, lock is 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 30000 and 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 Server sp_getapplock is 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. The DistributedLock NuGet 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."


The options compared

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

Efficiency vs correctness locks

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

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate understands that distributed locks are leases with real failure modes and knows how to keep correctness anyway.

Green flags

  • Calls it a lease and describes the pause-past-expiry failure.
  • Compares Redis, SQL app locks and blob leases with their trade-offs.
  • Explains fencing tokens and the efficiency vs correctness distinction.
  • Suggests designs that avoid locks.

Red flags

  • 'Use Redlock and it's safe.'
  • Releases locks with plain DEL or no ownership check.
  • Protects payments with a lock and nothing else.

📚 Learn in depth

1. Why every distributed lock is a lease

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.

2. The pause problem

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.

3. Fencing tokens

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.

4. How each implementation behaves

  • Redis: acquire with 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.
  • Redlock: try to acquire on N (usually 5) independent masters with a short timeout each; succeed if a majority (3) grant it and the elapsed time is well under the TTL. Fails safe against single-node loss, but not against long pauses or clock jumps on the Redis servers.
  • SQL Server 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.
  • Azure Blob leases: acquire a lease (15-60 s or infinite) on a blob, get a lease id, renew before expiry. Only the lease id can write the blob, so the blob itself is fenced, but other resources aren't.

5. The DistributedLock library

DistributedLock (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.

6. Designing locks away

  • Partition ownership: Kafka partitions or Service Bus sessions guarantee one consumer per key.
  • Queues: put work items on a queue; competing consumers each take different items.
  • Optimistic concurrency: rowversion or ETag checks reject conflicting writes.
  • Idempotency: overlap is harmless if a repeat has no extra effect.

Try it yourself

  1. Start Redis in Docker, take a lock with a 5-second TTL, Thread.Sleep(8000) in the holder, start a second holder, and log both writing.
  2. Repeat with sp_getapplock in session mode and kill the connection with KILL <spid> mid-work; observe when the holder finds out.
  3. Implement a fencing check with a Token column and a conditional UPDATE, and replay the stale-writer case.
  4. Use AzureBlobLeaseDistributedLock against Azurite with two console apps and watch HandleLostToken fire when you stop renewals.

💻 Code

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))!;
    }
}

⚠ Common mistakes

  • Mistake: Treating a distributed lock like a C# 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.
  • Mistake: Releasing a Redis lock with a plain 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.
  • Mistake: Using a lock alone to protect money or stock. Why it is wrong: GC pauses, failovers and network delay allow overlap. Instead: add a fencing token or optimistic concurrency, or make the operation idempotent.
  • Mistake: Assuming Redis primary-replica gives a safe lock. Why it is wrong: replication is asynchronous; a failover can lose the key and grant it again. Instead: accept it for efficiency locks only, or use a consensus-backed store.
  • Mistake: Picking a TTL shorter than the worst-case job time. Why it is wrong: the lease expires during normal slow runs, not just failures. Instead: renew the lease while working and stop when renewal fails (HandleLostToken).
  • Mistake: Ignoring that 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.
  • Mistake: Reaching for a lock when a queue or partition owner would do. Why it is wrong: locks add latency, a dependency and subtle failure modes. Instead: use competing consumers, Service Bus sessions or Kafka partitions.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate says the operation should be idempotent. Why: Checks the alternative to locking: making overlap harmless.
    How to answer

    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.

  2. When: Candidate mentions version checks or rowversion. Why: Checks optimistic concurrency as a fencing mechanism.
    How to answer

    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.

  3. When: Candidate mentions using a lock to stop duplicate recomputation. Why: Checks a common use of locks: protecting against cache stampedes.
    How to answer

    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:

    • Coalesce concurrent misses so one call loads the value: HybridCache does this per process.
    • Go cluster-wide with a short distributed lock and serve the stale value to everyone else.
    • Refresh early (background or probabilistic) so hot keys never go cold, and jitter TTLs so keys don't expire together.

    The trade-off is slightly staler data in exchange for a database that survives expiry.

🛠 Real-world problems: how you handle them

Redis failover lets two workers allocate the same stock
Situation
A stock-allocation worker ran on [four] instances in Azure Container Apps, using a Redis lock with a [10-second] TTL per SKU, during a [promotion] with [n] orders a minute.
Signals
Negative available stock for [several] SKUs; warehouse reported orders it couldn't fill; Azure Cache for Redis showed a failover event at the same time; Application Insights traces showed two instances logging 'lock acquired' for the same SKU within 6 seconds.
Investigation
Lined up the Redis failover time with the duplicate acquisitions, confirmed asynchronous replication had lost the lock keys, and checked the allocation code: it wrote with an unconditional UPDATE, so nothing stopped the second holder.
Resolution
Immediate: paused the promotion and corrected stock by hand from the order log. Real fix: changed the allocation to a conditional UPDATE with a version check and Available >= qty, so overlap can't oversell; kept the lock only to reduce contention.
Prevention
A concurrency test that runs two allocators against the same SKU with an artificial pause; an alert on negative stock; an ADR stating locks are for efficiency only and correctness lives in the database.

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].

↩ Usually asked after

More in Distributed Systems Core Concepts

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me