jiajianrong jiajianrong - 1 year ago 66
Node.js Question

should I consider synchronizing after using node pm2

My express server does a very simple work - saving the request url into a file (via fs.appendFile).

I suppose it works fine when not using pm2, because it has only one process, so no other process/thread saving the same file at the same time.

But when using pm2, I don't know if it will occur two processes write the same file at the same time? Thanks.

Answer Source

When you use pm2 on cluster mode, request routing will happen using Round Robin algorithm. That means the cluster master accepts all the incoming connections and routes them to the child processes (one request to one child process).

So, one request will be routed to one child process and the same request won't be processed by another process.

For your above case, When you receive two different requests from two different clients then they will be processed by two different processes.

As long as you have a logic to create a unique file name even though the requests handled at the same time, you won't get any issues.

You will get issues only if you try to write the files by two different processes with the same file name.

If you write different files from different clients with different file names then it won't be an issue.

Note: As a request from one client will be processed by one process, two or more processes won't process the same request and won't write the same file twice.

The issue will occur, If you write different files from different clients with the same file name.

Hope you understand :-)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download