Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork7
🛡️ A module for improving the reliability and fault-tolerance of your NestJS applications
License
SocketSomeone/nestjs-resilience
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
A module for improving the reliability and fault-tolerance of yourNestJS applications
NestJS Resilience is an open-source library that provides a set of reliable patterns for building resilient applications on top of NestJS.The library includes several key features, including retry, circuit breaker, and timeout patterns, which help to ensure that yourapplication can handle failures and recover quickly from them.
With NestJS Resilience, you can easily configure these patterns for your application, allowing you to improve the reliability andfault-tolerance of your services. Whether you're building a high-traffic web application or a distributed system, NestJS Resilience providesthe tools you need to build robust, failure-resistant services that can withstand even the most challenging environments.
Features
- Circuit Breaker - Automatically fail fast when a service is unavailable
- Retry - Automatically retry failed requests
- Timeout - Automatically fail fast when a service is taking too long to respond
- Bulkhead - Limit the number of concurrent requests to a service
- Fallback - Provide a fallback response when a service is unavailable
- Rate Limiting - Limit the number of requests to a service
- De duplicate - Prevent duplicate requests from being processed
$ npm install nestjs-resilience$ yarn add nestjs-resilience$ pnpm add nestjs-resilience
import{Module}from'@nestjs/common';import{ResilienceModule}from'nestjs-resilience';@Module({imports:[ResilienceModule.forRoot()]})exportclassAppModule{}
Usestore field to configure cache (e.x.store: new RedisStore({ host: 'localhost', port: 6379 })).We usememory fromcache-manager store by default.
You can use it in three ways:
You can create a command by extending theResilienceCommand class. You can also use theResilienceFactory to create a command with a setof policies.
import{Injectable}from'@nestjs/common';import{ResilienceCommand,ResilienceFactory}from'nestjs-resilience';import{UsersService}from'./user.service';import{User,NullUserObject}from'./user.entity';@Injectable()exportclassGetUserByIdCommandextendsResilienceCommand{constructor(privatereadonlyfactory:ResilienceFactory,privatereadonlyuserService:UsersService){super([// You can use the injected factory to create a strategyfactory.createTimeout(1000),// Or you can create a strategy directlyResilienceFactory.createFallback((id)=>newNullUserObject(id))// You can also use mannually created strategies// new TimeoutStrategy(1000),]);}asyncrun(id:number):User{returnthis.usersService.getUser(id);}}
This way supports DI, just what you need add@Injectable() decorator to your command and to providers of your module. Inject yourcommand in the constructor or useresilienceService.getCommand(GetUserByIdCommand).
FAQ:
- Can I use
@Inject()decorator? Yes, you can. But you need to add@Injectable()decorator to your command. - Can I use w/o DI? Yes, you can. Just create a command with
newoperator.
You can use@UseResilience() decorator to wrap yourservice methods.
import{Injectable}from'@nestjs/common';import{TimeoutStrategy}from"./timeout.strategy";import{NullUserObject,User}from'./user.entity';@Injectable()exportclassUsersService{ @UseResilience(newTimeoutStrategy(1000),ResilienceFactory.createFallback((id)=>newNullUserObject(id)))asyncgetUser(id:number):User{returnthis.httpService.get(`https://example.com/users/${id}`).toPromise();}}
Not the best way to use in controller methods.
@UseResiliencerewrite your method.
You also can wrap your controller methods withResilienceInterceptor and use all the features of the library.
import{Controller,Get,UseInterceptors}from'@nestjs/common';import{ResilienceInterceptor}from'nestjs-resilience';import{UsersService}from'./users.service';@Controller('users')exportclassUsersController{constructor(privatereadonlyusersService:UsersService){} @Get() @UseInterceptors(ResilienceInterceptor(newTimeoutStrategy(1000),ResilienceFactory.createFallback(()=>[])))asyncgetUsers():User[]{returnthis.usersService.getUsers();}}
We also supportObservable as a return type. You can use it with@UseResilienceObservable() decorator orResilienceCommandObservable.
import{Injectable}from'@nestjs/common';import{TimeoutStrategy}from"./timeout.strategy";import{NullUserObject,User}from'./user.entity';import{Observable,of}from'rxjs';@Injectable()exportclassUsersService{ @UseResilienceObservable(newTimeoutStrategy(1000),ResilienceFactory.createFallback((id)=>newNullUserObject(id)))getUser(id:number):Observable<User>{returnof(newUser(id,'John Doe'));}}
Strategies processing in order which you pass them to theResilienceCommand orResilienceInterceptor.
What it means? Let's take a look at the example:
Timeout before Retry:
- If the command is executed successfully, the result will be returned.
- If the command is executed with an error or timed out, the command will be retried.
- If the command is executed with an error or timed out and the number of retries is exceeded, the error will be thrown.
Retry after Timeout:
- If the command is executed successfully, the result will be returned.
- If the command is executed with an error, the command will be retried.
- If the command is executed with an error and the number of retries is exceeded, the error will be thrown.
- If the command is executed with an error and the number of retries is exceeded or timed out, the error will be thrown.
| Strategy | Description |
|---|---|
TimeoutStrategy | Automatically fail fast when a service is taking too long to respond |
RetryStrategy | Automatically retry failed requests |
CircuitBreakerStrategy | Automatically fail fast when a service is unavailable |
BulkheadStrategy | Limit the number of concurrent requests to a service |
FallbackStrategy | Provide a fallback response when a service is unavailable |
ThrottleStrategy | Limit the number of requests to a service |
HealthCheckStrategy | Check the health of a service |
CacheStrategy | Cache the result of a service call |
DeduplicateStrategy | Prevent duplicate requests from being processed |
- Author -Alexey Filippov
- Twitter -@SocketSomeone
About
🛡️ A module for improving the reliability and fault-tolerance of your NestJS applications
Topics
Resources
License
Code of conduct
Security policy
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Sponsor this project
Uh oh!
There was an error while loading.Please reload this page.
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Contributors4
Uh oh!
There was an error while loading.Please reload this page.