简体   繁体   中英

PM2 NodeJS cluster - Should I consider synchronizing when using 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.

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 :-)

Yes it may mess when multiple processes writing/appending the same file at the same time. So then best way is to only use one process to write file, or you have to synchronize them

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM