Dialog
Dialog

Reputation: 180

Using global variable as database cache?

Site is working with nodejs+socketio+mysql.
Is it normal to create a global object just before starting my app to store everything I have in the database? Something like user's password hashes for a very quick authentication process, compare the given token + userid.

var GS= {
    users: {
        user1: {
            token: "Djaskdjaklsdjklasjd"
        }
        ,
        user555: {
            token: "zxczxczxczxc"
        }
        ,
        user1239: {
            token: "ertertertertertret"
        }
    }
};

On connect, node check user with gived user_id.

if (GS.hasOwnPropery("user"+user_id)) {
  //compare gived token GS["user"+user_id].token
} else {
  //go to database to get unknown id and then store it in GS
  GS["user"+user_id] = { token: database_result };
}


And with everything else the same thing, using object property instead of querying the database. So if someone go to url /gameinfo/id/1, I just look in variable GS["game"+url_param] = GS["game"+1] = GS.game1 And of course, we don't talk about millions of rows in the database. 50-70k max.
Don't really want to use something like Redis or Tarantool.

Upvotes: 1

Views: 526

Answers (1)

kkkkkkk
kkkkkkk

Reputation: 7748

You can have a global object to store these info, but there are something to consider:

  • If you app are running by more than one machine (instance), this object won't be shared between these them.
  • This leads to some functional downsides, like:
    • you would need sticky session to make sure request from one particular client always directed to one particular instance
    • you can not check status of an user having data stored in another instance ...
    • Basically, anything that requires you to access user session data, will be hard, if not impossible, to do
  • In case your server goes down, all session data will be lost
  • Having a big, deep nested object is dangerously easy to mess up

If you are confident that you can handle these downsides, or you will not encounter them in your application, then go ahead. Otherwise, you should consider using a real cache library, framework.

Upvotes: 2

Related Questions