5

I'm considering using redis as a key value store for my api application. The api basically only needs one client connection to the redis. What I'm not sure is that should I keep the connection open forever? Or should I only open the connection when I need to set or get values from redis?

One could think that opening the connection is an expensive operation, so in that sense one should prefer forever connections. On the other hand, keeping the connection always open is not as secure as opening it only when you need it. And also, having long open connections open could result in timeouts. Does redis try to reconnect if the connection fails for some reason? How well does redis handle long open connections? Any help is appreciated!

Ville Miekk-oja
  • 18,749
  • 32
  • 70
  • 106
  • Take a look at `https://www.npmjs.com/package/redis-connection-pool`. In general it is best to use a persistent connection pool so you can quickly perform operation on the database. And what do you mean by "keeping connections always open is not as secure"? You send the login credentials just once when opening a persistent connection. If you use a new connection on every db action you will also be sending the credentials every single time... – Vasil Dininski Oct 07 '16 at 13:49
  • But I only need one connection, not a number of them? Also it doesn't seem to support promises, which I would like. You still think connection-pool would be good for me? You have a good point about security. Though what I meant is that if the connection is always open, then in theory, someone with access to your application could use that connection more easily than if it is opened only when needed. – Ville Miekk-oja Oct 07 '16 at 13:53
  • 1
    Not really sure how you would be able to hijack an already established connection. The connection pool is a way to ensure that you always have an available connection to the database so you can perform a lot more queries simultaneously. – Vasil Dininski Oct 07 '16 at 13:58

1 Answers1

1

Redis auto-connection depends on the redis-client that you are using. For example, if you use ioredis, it will automatically try reconnect when the connection to Redis is lost except when the connection is closed manually.

Source: https://github.com/luin/ioredis#auto-reconnect

Ville Miekk-oja
  • 18,749
  • 32
  • 70
  • 106