liveBook · Manning

Distributed lock

As explained in Building Distributed Applications that Work

A distributed lock grants exclusive access to a shared resource across processes or application instances.

A distributed lock gives one process or application instance exclusive access to a shared resource at a time. Unlike an in-process lock, it can coordinate applications on separate machines. Redis can hold named locks in the same shared system used for distributed caching. section 7.3

Consider order placement when two customers buy the same product. If both requests adjust its stock concurrently, the result may be inconsistent. Locking the product while its stock is updated prevents another request from modifying it at the same time. section 7.4.4

In the order endpoint, acquire the lock through the shared Redis connection:

  • Inject IConnectionMultiplexer and call GetDatabase() to obtain the Redis database abstraction. section 7.4.4
  • Call LockTakeAsync() with a key containing the product ID, a lock value, and an expiry time. The product-specific key identifies what is locked; expiry prevents an abandoned lock from lasting indefinitely. section 7.4.4
  • Check the Boolean result. Acquisition fails when the same key is already locked; the simplified endpoint returns HTTP 423 rather than proceeding with the order. section 7.4.4
bool lockAcquired =
    await db.LockTakeAsync(
        lockKey,
        Environment.MachineName,
        TimeSpan.FromSeconds(10));

The LockTakeAsync call shows the three acquisition arguments together: lock key, machine-name value, and ten-second expiry. section 7.4.4

Locks also need operational attention. Redis Commander, reachable through the Aspire dashboard, lets an operator inspect stored locks and remove a stale one. It can also temporarily apply a lock when needed. section 7.5

How Building Distributed Applications that Work covers it

How deep it goes
Works through Redis lock acquisition, key choice, expiry, and contention handling; leaves broader Redis configuration beyond the fundamentals.
Examples
Uses an order endpoint with product-ID lock keys, a LockTakeAsync call, and Redis Commander’s lock view.
What it assumes
Introduces distributed locking through its concurrency problem before using an injected Redis connection in an API endpoint.
What you can do after
Apply it via Redis LockTakeAsync in an order endpoint, then inspect or remove stored locks with Redis Commander.
How it connects
Connects distributed caching, Redis, race conditions, stock updates, and HTTP 423 responses.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Building Distributed Applications that Work. The section links point to the parts of the book it draws on.