how to run multiple instances without duplicate job in nodejs

Viewed 34

I have a problem when I scale the project (nestjs) to multiple instance. In my project, I have a crawler service that run each 10 minutes. When 2 instance running, crawler will run on both instances, so data will duplicate. Does anyone know how to handle it?

Looks like it can be processed using a queue, but I don't have a solution yet

1 Answers

Jobs aren't the right construct in this case.

Instead, use a job Queue: https://docs.nestjs.com/techniques/queues

You won't even need to set up a separate worker server to handle the jobs. Instead, add Redis (or similar) to your setup, configure a queue to use it, then set up 1) a producer module to add jobs to the queue whenever they need to be run, 2) a consumer module which will pull jobs off the queue and process them. Add logic into the producer module to ensure that duplicate jobs aren't being created, if that logic is running on both your machines.

Conversely it may be easier just to separate job production/processing into a separate server.

Related