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
