Redis cache for koa web service with policies


Redis Content Cache with polcies


Making the cache more efficient in a limited space requires certain eviction algorithm that delete entries after the memory is drained.

By default redis emploies a policy named volatile-lru, which only evicts keys that have been set with an expire.

You should note that a cache entry may be deleted from Redis regardless of control of this middleware if the redis is configured to use some different evition policy.

On the other side, EXPIRE command will not always ensure a key is deleted due to the probabilistic algorithm used by Redis. And this behavior cannot be alterd or configured.

For performance concern, we only use the simple key-value storage of Redis, instead of the various data structures like hash, set.

By defualt, all the keys of cache entries are prefixed by koa-cache.

Sample can be found at tests/app.js

ctx is a koa context.

Set or get a cache. If no arguments given, will read cache using ctx.cacheKey() to retrive default key.

Set or get a cache key in session.

If key is given, it will save this.req.url and key pair in session.

Otherwise, it retrieve cache key from session using this.req.url.

Delete a cache entry by key. If key is not given, will delete using key generated by ctx.cacheKey().

To get a cache instance

var cache = require("koa-cache")();

Cache all result for this url:

app.get("/data", cache.all(), function*() {
  this.body = "hello";

Session aware:

app.get("/data", cache.all(), function*() { // using user name as cache key this.cacheKey(this.session.username);

//deliver content of session-related this.body = this.session.username; });

  • Using matcherGenFunc to determin if we are reading from cache.
  • Useful if we are dealing with user context, e.g, reading cache for a specific user
app.get("/data", cache.match(function*() {
  if(this.session.user) {
    return true;
  return false;
}), function*() {
  this.body = "private!";
  // can be used with cacheKey