Module A-5·20 min read

Reentrant locking with Hash-stored reentry counters, lock hierarchies and consistent ordering to prevent circular waits, the watchdog pattern for automatic lock extension, and distinguishing mutex locks from counting semaphores.

JJS
Written by Jatin Jain Saraf · Senior Software Engineer

A-5 — Reentrant Locks, Hierarchies, and Deadlock Prevention

Who this module is for: You have basic Redis locking working but are hitting edge cases — a function that holds a lock tries to call another function that also acquires the same lock (deadlock), or you need to acquire multiple locks without racing with another process doing the same. This module covers reentrant locks, lock hierarchies, and the patterns that prevent deadlock at scale.


The Reentrant Lock Problem

A basic Redis lock (SET NX PX) is not reentrant. If a function holds lock:resource and calls a subroutine that also tries to acquire lock:resource, the subroutine is waiting for itself to release a lock it holds — it can never succeed while the outer call is still running.

text

Using A-1's acquireLock() (bounded retries, returns null on exhaustion) as written, the inner call doesn't hang forever — it retries a few times and returns null, so validateInventory has to handle a null lock result it was never designed for, typically by throwing. Either way, processOrder never reaches the code path that releases the outer lock: not because the single-threaded event loop is blocked (an await suspends only the current async function and lets the event loop keep running everything else), but because the outer function's own continuation never gets past the failed inner acquireLock() call. It's a logical deadlock in your application's control flow, not a stalled event loop.


Reentrant Lock Implementation

A reentrant lock tracks the holder's identity and a reentry count. The same holder can acquire the lock multiple times; it is released only when the reentry count reaches zero.

Use a Redis Hash to store both the holder token and the count:

lua
lua
typescript

Sign in to keep reading

The rest of this module is free — sign in with Google to unlock it and track your progress.

Sign in & Register

Discussion

0

Join the discussion

Loading comments...

© 2026 Jatin Jain Saraf (JJS). All rights reserved.