Skip to content

Latest commit

 

History

History
97 lines (71 loc) · 2.97 KB

File metadata and controls

97 lines (71 loc) · 2.97 KB
NestJS Redis Toolkit Logo

@nestjs-redis/lock

Distributed locking for NestJS using Redis and the Redlock algorithm

npm version npm downloads License: MIT TypeScript NestJS Redis


Features

  • Redlock-based distributed locks
  • Works with existing @nestjs-redis/client connections
  • Decorator @Redlock() and RedlockService
  • Type-safe, production-ready

Installation

npm install @nestjs-redis/lock @nestjs-redis/client redis

The recommended approach is to use RedisModule from @nestjs-redis/client so Redis connections are lifecycle-managed by Nest (connect/disconnect with your app). Alternatively, you can pass your own Redis client (e.g. created with createClient() from redis) and manage its lifecycle yourself.

Quick Start

// app.module.ts
import { Module } from '@nestjs/common';
import { RedisModule, RedisToken } from '@nestjs-redis/client';
import { RedlockModule } from '@nestjs-redis/lock';

@Module({
  imports: [
    RedisModule.forRoot({ options: { url: 'redis://localhost:6379' } }),
    RedlockModule.forRootAsync({
      inject: [RedisToken()],
      useFactory: (redis) => ({ clients: [redis] }),
    }),
  ],
})
export class AppModule {}

Decorator usage

import { Injectable } from '@nestjs/common';
import { Redlock } from '@nestjs-redis/lock';

@Injectable()
export class UserService {
  @Redlock('user:update', 5000)
  async updateUserBalance(userId: string, amount: number) {
    // critical work
  }
}

Service usage

@Injectable()
export class PaymentService {
  constructor(private readonly redlock: RedlockService) {}

  async processPayment(paymentId: string) {
    return this.redlock.withLock([`payment:${paymentId}`], 5000, async () => {
      // critical work
    });
  }
}

Links

Contributing

Please see the root contributing guidelines.

License

MIT © CSenshi