Skip to main content

@hile/redis-lock

Protect short critical sections with Redis lease locks, wait policies, renewal, and fencing tokens.

Choose This Package When

Use When

Use these packages for distributed lease locks, duplicate execution protection, shared quotas, and durable Redis Streams job processing.

Do Not Use When

  • Do not claim exactly-once behavior.
  • Do not use locks as a replacement for database constraints.
  • Do not use queue jobId as the only idempotency boundary for side effects.
  • Do not use rate limits as authorization or authentication.

Install

Imports

Copy-Paste Example

Idempotent queue worker:

More Examples

Distributed lock with fencing:
Rate limit HTTP middleware:
Queue add with delayed retry policy:

Runtime And Lifecycle Notes

  • RedisLock.withLock() asserts ownership before returning a successful callback result.
  • tryLock() returns undefined if the key is already locked.
  • RedisIdempotency.run() stores IN_FLIGHT and DONE states in Redis and uses Redis locks for ownership.
  • Idempotency requires a stable fingerprint.
  • stableHash() is for plain DTOs and rejects unsupported shapes.
  • Rate limit algorithms: fixed-window, sliding-window, token-bucket.
  • dryRun rate limit checks do not mutate Redis.
  • Queue workers use Redis Streams consumer groups, delayed sorted sets, pending claim recovery, retry backoff, and DLQ streams.
  • Queue payload schema can expose parse() or safeParse().

Anti-Patterns

  • Random UUID per retry as idempotency key.
  • Returning Date, BigInt, or class instances from idempotent functions without a resultCodec.
  • Using stream() or RPC retries without idempotency around irreversible handlers.
  • Ignoring DLQ after max attempts.

Verification Checklist

  • Lock TTL is longer than normal critical-section time.
  • Fencing is enabled when stale owners can write to external resources.
  • Idempotency keys use business identifiers.
  • Queue handlers are idempotent or wrapped in idempotency.
  • Rate limit Retry-After is exposed in seconds for HTTP.
  • DLQ is monitored.

Redis Cache With Singleflight

Complete Example

Queue Worker With Idempotency

Complete Example

Enqueue:

Package-Local AI Guide

This package also ships AI.md in npm so agents can read accurate examples after installation.