Search code examples
node.jspostgresqlredisriak

How to share an object in multiple instances of nodejs?


I have a functionality where user post data containing few userid and some data related to those userid and I am saving it into postgresql database. I want to save this returned userid in some object.

I just want to check if userid is present in this object and then only call database. This check happen very frequently so I can not hit db every time just to check is there any data present for that userid.

Problem is, I have multiple nodejs instances running on different server so how can I have a common object.

I know I can use redis/riak for storing key-value on server, but don't want to increase complexity/learning just for a single case.(I have never used redis/riak before.)

Any suggestion ?


Solution

  • If your data is in different node.js processes on different servers, then the ONLY option is to use networking to communicate across servers with some common server to get the value. There are lots of different ways to do that.

    1. Put the value in a database and always read the value from the common database
    2. Designate one of your node.js instances as the master and have all the other node.js instances ask the value is on the master anytime they need it
    3. Synchronize the value to each node.js process using networking so each node.js instance always has a current value in its own process
    4. Use a shared file system (kind of like a poor man's database)

    Since you already have a database, you probably want to just store it in the database you already have and query it from there rather than introduce another data store with redis just for this one use. If possible, you can have each process cache the value over some interval of time to improve performance for frequent requests.