Multi level cache that always prefers stale data
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});
});
});
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 |
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.