Skip to content

Add atomic Redis lock acquisition to DistributedLockService#951

Merged
RUKAYAT-CODER merged 1 commit into
rinafcode:mainfrom
aliyudotdev:fix/888-atomic-redis-lock
Jun 29, 2026
Merged

Add atomic Redis lock acquisition to DistributedLockService#951
RUKAYAT-CODER merged 1 commit into
rinafcode:mainfrom
aliyudotdev:fix/888-atomic-redis-lock

Conversation

@aliyudotdev

Copy link
Copy Markdown

Summary

  • acquireLock already issued a single SET key value NX PX ttl command, but returned a plain boolean and wrote a hardcoded value ('locked'), so once the TTL expired any caller could release a lock it never held.
  • acquireLock now generates a unique token per call and returns it (or null if the lock is already held).
  • releaseLock(key, token) only deletes the key if the stored value still matches the token, via a single atomic Lua GET+DEL script — matching the pattern already used in session.service.ts.
  • Added withLock(key, ttl, fn): acquires, runs fn, and always releases in a finally block, even if fn throws.
  • Added unit tests: single-command SET NX PX verified via spy, exactly one winner under 100 concurrent acquireLock calls, token-mismatch release is a no-op, and withLock releases on both success and throw.

Test plan

  • npm test -- distributed-lock.service
  • Verified set mock is called exactly once per acquireLock with ('key', token, 'PX', ttl, 'NX')
  • Verified exactly 1 of 100 concurrent acquireLock calls on the same key returns a non-null token

Closes #888

acquireLock already used a single SET key value NX PX command, but it
returned a boolean and a hardcoded value, so any caller could release a
lock it never held once the TTL expired. acquireLock now returns a
unique token (or null if already held), releaseLock only deletes the
key if the token still matches (atomic GET+DEL via Lua), and a new
withLock(key, ttl, fn) helper acquires, runs fn, and always releases —
even if fn throws.

Closes rinafcode#888
@drips-wave

drips-wave Bot commented Jun 29, 2026

Copy link
Copy Markdown

@aliyudotdev Great news! 🎉 Based on an automated assessment of this PR, the linked Wave issue(s) no longer count against your application limits.

You can now already apply to more issues while waiting for a review of this PR. Keep up the great work! 🚀

Learn more about application limits

@RUKAYAT-CODER

Copy link
Copy Markdown
Contributor

Thank you for contributing to the project.

@RUKAYAT-CODER RUKAYAT-CODER merged commit e79bce4 into rinafcode:main Jun 29, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add atomic Redis lock acquisition to prevent race conditions in DistributedLockService

2 participants