LazyLayersv9.0.0
Concepts

Keeping keys fresh

Reload a key the moment it expires in Redis or changes at the source, and size each key's TTL to how often its value really changes.

A TTL is a guess. Too long and readers get old values; too short and the origin takes load it does not need, and the first reader after expiry waits for it. 9.0 adds two ways to do better: reload a key when something says it changed, and learn each key's TTL from how often it changes.

Reload on a signal

keepFresh(key, loader) registers a key. Whenever a refresh source names it, or you call cache.refresh(key), the cache reloads it in the background and stores the result. Readers keep getting the current value until the new one is stored.

import { createCache, redisExpirySource } from 'lazy-layers-cache'

const cache = createCache({
  l2: redisStore,
  refresh: { sources: redisExpirySource(redis, { store: redisStore }) },
})

const stop = cache.keepFresh('rates:usd', () => fetchRates('usd'))
// later: stop() to let the key expire normally again

A reload is the key's in-flight load, so it follows the same rules as any other:

  • One at a time per key. Fifty signals at once still mean one call to the loader.
  • It takes an origin slot, so originLoad limits and tenant fairness apply.
  • With a shared layer that hands out leases, one server in the fleet loads and the rest wait for its result.
  • A loader that fails leaves the current value in place.

refresh.maxKeys (10,000 by default) bounds how many keys can be registered; registering one more throws a RangeError. Registering a key again replaces its loader. Namespaces have keepFresh and refresh too, under their prefix.

From your own events

cache.refresh(key) returns true when it started a reload, and false when the key is not kept fresh or the cache is closed. Call it from anything that knows a value changed:

app.post('/webhooks/catalog', async (req) => {
  for (const sku of req.body.changed) cache.refresh(`product:${sku}`)
})

A source wraps the same idea for something you subscribe to:

import { defineRefreshSource } from 'lazy-layers-cache'

const changes = defineRefreshSource({
  name: 'orders-cdc',
  subscribe(onKey) {
    const stream = db.watch([{ $match: { operationType: 'update' } }])
    stream.on('change', (change) => onKey(`order:${change.documentKey._id}`))
    return () => stream.close()
  },
})

A source that throws or rejects while starting, returns no stop function, or hangs or throws while stopping is logged and left out. The cache works without it, and close() waits at most one second for each.

When a key expires in Redis

redisExpirySource(redis, { store }) subscribes to Redis keyspace notifications for the store's keys only (the prefix filter runs on the Redis server) and names each key that expired.

OptionDefaultWhat it does
storerequiredThe RedisStore whose keys are watched. Locks, waiter lists and other stores' keys are ignored.
db0Redis database number.
events['expired']Add 'evicted' to also reload keys Redis removed under maxmemory. A DEL never triggers a reload.
configurefalseAdd the needed notify-keyspace-events flags with CONFIG SET.

Redis sends nothing unless notify-keyspace-events includes K and x (and e for evictions). The source checks the setting when it starts and logs the exact CONFIG SET to run when a flag is missing. Managed services often disable CONFIG; set the parameter in the provider's console instead.

Some limits come from Redis itself:

  • Redis reports an expiry when it removes the key. For a key nobody reads, that can be a little after its TTL.
  • A notification sent while the subscriber is reconnecting is lost. The key is then loaded on its next read.
  • On a Redis Cluster each node notifies only for its own keys. Create one source per primary.

With versioning enabled, an expiry of an earlier generation of a key is ignored: it is not the value readers see.

Every server receives the same notification, a few milliseconds apart. The first one to take the key's lease reloads it. A server whose notification arrives after that reload finished finds the key back in Redis, and since an expired key is gone from Redis, whatever is there now is that reload: it uses it instead of loading again. The source marks itself with reportsRemovals: true for this. Leave that unset on your own sources unless every key they name has just left the shared layer: after a change-stream signal, Redis still holds the old value, so every server that hears it reloads.

Adaptive TTL

adaptiveTtl sets each key's TTL from how often its value changes, as seen by this cache's writes and loads.

const cache = createCache({
  l2: redisStore,
  ttlMs: 60_000,
  adaptiveTtl: {
    minMs: 5_000,
    maxMs: 3_600_000,
    factor: 0.5,
    fingerprint: (doc) => doc.version,
  },
})

Each write is compared with the previous one for the same key. When the value changed, the time since the last change feeds a moving average of the key's change interval, and the TTL becomes factor times that interval. When the value has stayed the same for longer than usual, the TTL grows with it. The result is always within [minMs, maxMs]. A key that has never changed starts at the cache's TTL and grows as it stays the same.

OptionDefaultWhat it does
minMs1000Shortest TTL.
maxMs3600000Longest TTL.
factor0.5Share of the change interval used as TTL, above 0 and at most 1. Lower means fewer stale reads and more loads.
maxKeys10000Keys whose history is kept; the least recently written leave first.
fingerprinthash of the stored bytesIdentifies a value's content, such as a version or updatedAt. Use it when values carry fields that change without the content changing, such as a load timestamp.

A call that passes its own TTL keeps it. ttlJitter applies on top of the adaptive TTL. A per-level memory TTL set on the cache caps the memory copy. A fingerprint that throws leaves that write with the configured TTL. Each process learns from its own writes, so servers can settle on slightly different TTLs for the same key.

The two combine: adaptive TTL decides when a key expires, and keepFresh reloads it as soon as it does, instead of on the next read. A read in between joins the reload when it reaches the same server.

Questions

Does every server reload the key when it expires in Redis?

Every server receives the notification, but the reload takes the key's lease. One server calls the origin; the others wait for its result and read it from Redis.

What if a notification is lost?

Redis keyspace notifications are fire-and-forget. A lost one means the key is loaded on its next read, as it would be without refresh. Nothing stale is served because of it.

Does adaptive TTL apply to every write?

To every write that does not set its own TTL. A ttlMs passed to set or getOrSet is kept as given.

On this page