express-rate-limit / cluster-memory-store

express-rate-limit Store that shares state between all the workers in a node.js cluster
MIT License
4 stars 1 forks source link

Working with PM2 #5

Open jfoclpf opened 1 month ago

jfoclpf commented 1 month ago

Can you kindly exactly tell me how does this work with PM2?

I mean, is do we really put only 1 instance, as documented?

instances: 1,
exec_mode: 'fork',

Is the example still valid?

I guess I would need the NGINX to make load balance between different ports, right?

I mean, if we have only 1 instance, what's the purpose of using PM2 then? Dealing only with restarts and server reboots, I guess

Thanks a lot for the great project

nfriedly commented 1 month ago

Hi,

Yes, I believe the example is still valid.

I guess I would need the NGINX to make load balance between different ports, right? ...we have only 1 instance...

No, because of this bit:

https://github.com/express-rate-limit/cluster-memory-store/blob/b167b3e734e406e4a8986cbc4dfb6a24d1910d55/example/server.js#L19-L21

That uses the node.js built-in cluster module to spin up one worker instance per CPU core. These workers all share a single port with the primary process handling load balancing, so no Nginx needed.

...what's the purpose of using PM2 then? Dealing only with restarts and server reboots, I guess

Yeah, basically. Normally PM2 manages the workers directly, but in this case there's an extra layer between PM2 and the workers. That extra layer manages the workers and also synchronizes the hit counts. You are giving up some of the benefits of using PM2, but not all of them.

The alternative is to use an external store (memcache, redis, etc.) and then PM2 can manage the workers directly.

(There may be a third way to do this where you use the PM2 programmatic API but I haven't taken the time to figure that out yet. If you want to do that and put up a better example, let me know.)