Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 1883

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 62k
Author
Asked: November 26, 20242024-11-26T12:17:07+00:00 2024-11-26T12:17:07+00:00

NestJS Dependency Injection in Worker Threads

  • 62k

There may be cases when you need to do CPU-intensive tasks on the backend like big JSON parsing, video encoding, compression, etc. If you have at least 2 cores in your processor's configuration you can run javascript in parallel for these tasks and not block the main thread of the NestJS app that handles client requests.

An excellent way of doing this is by using node.js worker threads.

You shouldn't use worker threads for I/O operations as node.js already gracefully handles this for you.

If you're eager to dive into the complete example right away, you can check out the GitHub repo for the full example. 

In order to illustrate this, we will use a very simple service that calculates the fibonacci sum, which is a CPU-intensive task, a great candidate for node.js worker threads!

import { Injectable } from '@nestjs/common';  @Injectable() export class FibonacciService {   fibonacci(n) {     if (n <= 1) {       return 1;     }     return this.fibonacci(n - 1) + this.fibonacci(n - 2);   } } 
Enter fullscreen mode Exit fullscreen mode

Now, let's dive into the code snippet that launches the worker thread:

import { Injectable, Logger } from '@nestjs/common'; import { Worker, isMainThread } from 'worker_threads'; import workerThreadFilePath from './worker-threads/config';  @Injectable() export class AppService {   private readonly logger = new Logger(AppService.name);    checkMainThread() {     this.logger.debug(       'Are we on the main thread here?',       isMainThread ? 'Yes.' : 'No.',     );   }    // do not run this from the worker thread or you will spawn an infinite number of threads in cascade   runWorker(fibonacci: number): string {     this.checkMainThread();      const thisService = this;     const worker = new Worker(workerThreadFilePath, {       workerData: fibonacci,     });     worker.on('message', (fibonacciSum) => {       thisService.logger.verbose('Calculated sum', fibonacciSum);     });     worker.on('error', (e) => console.log('on error', e));     worker.on('exit', (code) => console.log('on exit', code));      return 'Processing the fibonacci sum... Check NestJS app console for the result.';   } } 
Enter fullscreen mode Exit fullscreen mode

As we can see from the snippet above, we defined a new worker, gave it a path to a file to be executed by the worker, and gave it as param the workerData. Worker data is data sent from the main thread to the other thread.

We are using the constant workerThreadFilePath from associated config file on the same level in the directory tree so we can safely use the path for the worker thread regardless of where the app is deployed.

// it will import the compiled js file from dist directory const workerThreadFilePath = __dirname + '/findFibonacciSum.js';  export default workerThreadFilePath; 
Enter fullscreen mode Exit fullscreen mode

Take a note that we are using the js extension here because the transpiled output of typescript, as we know, it's javascript.

Let's explore the file which will be executed in the worker thread:

import { NestFactory } from '@nestjs/core'; import { workerData, parentPort } from 'worker_threads'; import { AppModule } from '../app.module'; import { FibonacciService } from '../fibonacci/fibonacci.service'; import { AppService } from '../app.service';  async function run() {   const app = await NestFactory.createApplicationContext(AppModule);   const appService = app.get(AppService);   const fibonacciService = app.get(FibonacciService);    const fibonacciNumber: number = workerData; // this is data received from main thread     // here we apply business logic inside the worker thread   appService.checkMainThread();   const fibonacciSum = fibonacciService.fibonacci(fibonacciNumber);   parentPort.postMessage(fibonacciSum); }  run(); 
Enter fullscreen mode Exit fullscreen mode

In order to have access to dependency injection in our NestJs app in the thread, we leverage Nest standalone application which is a wrapper around the Nest IoC container, which holds all instantiated classes.

Now, we can execute any method from any service.

Caveats: 

  • Be cautious when using dependency injection from NestJS in a worker thread, as it comes with a cost. The startup process of the NestJS app must be awaited before accessing the dependency injection. Therefore, utilize this method only if absolutely necessary, or if the startup bottleneck is negligible in terms of overall performance.
  • If your app setup is starting processes that you don't want to run on the separate thread you will need to configure your app module into a dynamic module to accept a parameter to not initiate the setup. Example:
const app = await NestFactory.createApplicationContext(   AppModule.register({ attachRabbitMqConsumers: false }), ); 
Enter fullscreen mode Exit fullscreen mode

Click here for the github repo.

If you'd like me to cover more interesting topics about the node.js ecosystem, feel free to leave your suggestions in the comments section. Don't forget to subscribe to my newsletter on rabbitbyte.club for updates!

javascriptnestjsnodewebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    How to ensure that all the routes on my Symfony ...

    • 0 Answers
  • Author

    Insights into Forms in Flask

    • 0 Answers
  • Author

    Kick Start Your Next Project With Holo Theme

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.