5

My node.js API runs some expensive "group" queries against MongoDB using for example:

app.get('/group/:collection', function(req, res) {
    [...]
    db.collection("indicators").group(keys, conds, { value : 0 } [...]

What are some fairly easy-to-implement caching solutions here?

dani
  • 4,880
  • 8
  • 55
  • 95
  • 1
    What do you mean by 'solutions'? Are you looking for some ready-made library? In that case, this is **off-topic** because you're looking for a library recommendation. If you're looking for an *approach to implement caching yourself*, this is a rather **broad question** with the trivial answer "store your results in some kind of object and solve the usual caching challenges that are described elsewhere across the interwebs and too complex to discuss at length here." – mnemosyn Feb 08 '15 at 23:30
  • I would advice you to use LRU cache, there is already a good node module which is also easy to use, you might want to take a look here: https://github.com/isaacs/node-lru-cache – Ma'moon Al-Akash Feb 10 '15 at 10:08
  • The solution you want depends on your implementation. If your app currently runs, and will run for the foreseeable future, on a single machine (sometimes called a dyno), then in-memory caching is fine for you. In-memory caching is easy to set up. You can use node-cache, lru-cache, or any of several others available on npmjs.com. If, however, your app runs from multiple dynos then you need a distributed cache all dynos can share such as redis. If you want a combination of both cache types, you can look at tiered solutions such as cache-service on npmjs.com (disclaimer: I wrote cache-service). – jpodwys Jun 03 '15 at 18:45

1 Answers1

1

redis is very easy to implement

  1. Install redis

  2. Install the redis node module

    npm install redis --save
    
  3. Create a caching service. This is really the hardest part, but the general flow looks something like this:

    1. make request to cache service.
    2. cache service checks redis for cached object based on query.
    3. cache returns data from redis if it exists OR from mongo if it doesn't exist.
    4. if data didn't already exist in redis or had expired, cache service writes data to redis.

On top of doing amazingly well at caching, redis offers some amazing functionality for handling queues, pub/sub messaging, list management...

Brian Noah
  • 2,962
  • 18
  • 27