Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Caching responses in express

I have some real trouble caching responses in express… I have one endpoint that gets a lot of requests (around 5k rpm). This endpoint fetches data from mongodb and to speed things up I would like to cache the full json response for 1 second so that only the first request each second hits the database while the others are served from a cache.

When abstracting out the database part of the problem my solution looks like this. I check for a cached response in redis. If one is found I serve it. If not I generate it, send it and set the cache. The timeout is too simulate the database operation.

app.get('/cachedTimeout', function(req,res,next) {
  redis.get(req.originalUrl, function(err, value) {
    if (err) return next(err);
    if (value) {
      res.set('Content-Type', 'text/plain');
      res.send(value.toString());
    } else {
      setTimeout(function() {
        res.send('OK');
        redis.set(req.originalUrl, 'OK');
        redis.expire(req.originalUrl, 1);
      }, 100);
    }
  });
});

The problem is that this will not only make the first request every second hit the database. Instead all requests that comes in before we had time to set the cache (before 100ms) will hit the database. When adding real load to this it really blows up with response times around 60 seconds because a lot of requests are getting behind.

I know this could be solved with a reverse proxy like varnish but currently we are hosting on heroku which complicates such a setup.

What I would like to do is to do some sort of reverse-proxy cache inside of express. I would like it so that all the requests that comes in after the initial request (that generates the cache) would wait for the cache generation to finish before using that same response.

Is this possible?

like image 201
Calle Erlandsson Avatar asked Oct 22 '22 02:10

Calle Erlandsson


1 Answers

Use a proxy layer on top your node.js application. Vanish Cache would be a good choice to work with Nginx to serve your application.

like image 52
Rix Avatar answered Oct 23 '22 16:10

Rix