Skip to content
This repository has been archived by the owner on Mar 19, 2019. It is now read-only.

Multi level cache that always prefers stale data

License

Notifications You must be signed in to change notification settings

pr3tori4n/stale-multi-cache

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

48 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

stale-multi-cache

Multi level cache that always prefers stale data

Version Build Status Coverage License

Usage

This library is undergoing API changes at the moment. We will be making a 1.0.0 release in the next few days after more testing.

var Cache = require('stale-multi-cache');
var Redis = require('ioredis');
var redis = new Redis();

// Create the cache
var cache = new Cache([
  new Cache.LRUMemoryStore({max:500}),
  new Cache.RedisStore(redis)
]);

function getUser(user) {
  // really really slow function
  return {};
}

// Even with a stale TTL of 10, this cache will always send stale data,
// but do a background update of the data after the data expires.
// We're setting the expire TTL to 86400 at that point we'll HAVE to refresh.
function cachedGetUser(user) {
  return cache.wrap('user:'+user, function() {
    return getUser(user);
  }, 10, 86400);
}

// Now we can use the cachedGetUser
app.get('/user', function(req, res) {
  return cachedGetUser('kelsin').then(function(user) {
    return res.json({user:user});
  });
});

Stores

Store Description
NoopStore Store that never stores anything, for testing purposes
ErrorStore Store that never stores anything and errors on sets, for testing purposes
SimpleMemoryStore Object store, for testing purposes
LRUStore Memory store that uses lru-cache
RedisStore Redis store that uses any ioredis compatible client

Why?

I often need caches that are double buffered but where TTL is more of an update interval than a hard expire. I want to use LRU based stores and update at set times but always keep stale data. I never want most web caches to expire. I'd rather have old data on the site than no data on the site. This cache provides that.

About

Multi level cache that always prefers stale data

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript 100.0%