Skip to content

feat(api): implement Redis distributed lock manager - #3

Merged
Prajjwaltripathi20 merged 1 commit into
vedant21-ctr:mainfrom
Prajjwaltripathi20:main
Sep 13, 2026
Merged

Prajjwaltripathi20 merged 1 commit into
vedant21-ctr:mainfrom
Prajjwaltripathi20:main

Conversation

@Prajjwaltripathi20

Copy link
Copy Markdown
Contributor

Summary

This PR adds a reusable Redis distributed lock manager for apps/api to provide safe concurrency control across processes.

Implementation

  • Added LockService with atomic Redis SET NX PX lock acquisition.
  • Uses crypto.randomUUID() to generate unique lock ownership tokens.
  • Returns null when the lock is already held.
  • Propagates Redis errors instead of treating them as successful lock acquisitions.
  • Validates lock keys and TTL values.
  • Added atomic Lua-based compare-and-delete logic for safe lock release.
  • Prevents stale tokens from deleting locks owned by another process.
  • Reuses the existing Redis client through CacheService.getRedisClient() without creating a new connection.
  • Added the required pino logger configuration.

Testing

Added Vitest coverage for:

  • Successful lock acquisition
  • NX / PX parameters
  • Lock contention
  • Independent lock keys
  • Token-matched release
  • Stale/mismatched token rejection
  • Redis acquisition and release errors
  • Invalid keys
  • Invalid TTL values
  • Unavailable Redis client

Verification

  • Vitest: 10/10 tests passing
  • API TypeScript typecheck: 0 errors
  • Monorepo TypeScript build: 0 errors
  • Working tree: clean

Requirements Satisfied

  • Atomic SET NX PX acquisition without preliminary GET
  • Positive finite TTL validation
  • crypto.randomUUID() ownership tokens
  • Lock contention returns null
  • Redis errors propagate correctly
  • Atomic Lua compare-and-delete release
  • Stale tokens cannot release another lock
  • Existing Redis client reused
  • No unnecessary Redis connections
  • Comprehensive tests added

@Prajjwaltripathi20
Prajjwaltripathi20 merged commit 55c005f into vedant21-ctr:main Sep 13, 2026
1 check failed
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.

1 participant