Cache data locally to avoid contacting database

Hello,

I have my backend in NodeJS. This backend contact my remote database to fetch the data.

To avoid delay, I would like to cache the data on my backend to avoid contacting the database everytime. What is the best way, in koyeb to cache the JSON data “locally”.

Thanks in advance,
Jeremie

Hello,

It really depends what you are trying to cache, but you could simply:

  1. check if the cache file already exists. If yes, return the content
  2. otherwise query the database and store the result in the cache file

However, please ask yourself if you really want a cache. With this simple solution, what happens if you have two concurrent requests? Or, if you write the cache in 2., a write operation fails in the middle of the file? Or if the database is updated from another process, for example during a deployment on Koyeb when two instances are running your application at the same time? Or if multiple instances are running your application?

To solve these issues, you’ll have to implement more complex strategies (for example write the cache in a temporary file and move it to the destination), and maybe using the database is what you really want.

Hello,

Thank you for your advise. Below what I have done for my case, as it may be useful for someone else.

I use the plugin node-cache to manage the cached data. For the request I want to cache, I will cache it for 1 hour. If the database is modified in database, then I delete this cache.
The data cached is generated if not found.

The amount of requests to my database decreased and I think is a good solution for now. If you have any advise on improving this, I am open to know about it.

1 Like