Part 1 · When a cache helps: an in-process LRU with a TTL
What a cache buys and what it costs
A menu page that shows the same 200 products to every visitor should not run the same database query for each of them. A cache keeps a copy of an answer somewhere faster, so the next request skips the slow work.
A cache pays off when reads are much more frequent than writes, when the same keys are asked for again and again, and when a slightly old answer is acceptable. The measure is the hit ratio: hits divided by all lookups. A hit returns the stored copy. A miss means the copy was not there, so the code does the slow work and usually stores the result. If a hit costs 1 ms, a miss costs 50 ms and the hit ratio is 90%, the average lookup costs 0.9 x 1 + 0.1 x 50 = 5.9 ms. That is arithmetic and not a measurement, but it shows why the ratio matters more than the speed of the cache itself.
Every cache also has a cost. The copy can go stale, meaning the original has changed and the copy has not. It uses memory. And somebody has to decide when a copy is thrown away, which is the hard part. Good candidates are expensive, repeated, shared answers that tolerate staleness for a few seconds or minutes: a menu, a product list, a rendered fragment. Poor candidates are answers that differ for every user, that are asked for once, or that must always be exact, such as a wallet balance.
An LRU with a time to live
Two rules keep an in-process cache honest. A time to live (TTL) gives each entry an expiry, so staleness has an upper bound. A size limit with LRU eviction throws away the least recently used entry when the cache is full, so memory cannot grow without end.
JavaScript's Map helps, because it remembers the order in which keys were inserted. The bounded cache in the memory chapter used the same trick. If every read deletes the key and inserts it again, the first key in the map is always the least recently used. The class below uses exactly that. It takes the clock as an option, which will make it testable without waiting.
js
exportclass TtlLru {
#map = new Map();
#max;
#ttlMs;
#now;
constructor({ max, ttlMs, now = Date.now }) {
this.#max = max;
this.#ttlMs = ttlMs;
this.#now = now;
}
get size() {
returnthis.#map.size;
}
get(key) {
const entry = this.#map.get(key);
if (!entry) returnundefined;
if (entry.expires <= this.#now()) {
this.#map.delete(key);
returnundefined;
}
this.#map.delete(key); // re-insert: now the newestthis.#map.set(key, entry);
return entry.value;
}
cache.mjs, the class and get
get returns undefined for a missing or expired entry, deleting the expired one on the way. For a live entry it re-inserts the key, which moves it to the end of the map. set does the same, then checks the size.
When the map is over its limit, this.#map.keys().next().value is the first key, which is the least recently used one, and it is removed. Note that get cannot tell a stored undefined from a miss. Store null when you need to cache "not found".
Testing it with a fake clock
Time makes caches awkward to test. The class receives a now function, so a test can supply its own clock and move it by hand. This file uses Node's built-in test runner and assert/strict. It checks that a miss returns undefined, that an entry expires exactly at its TTL, that the least recently used entry is the one evicted after a read refreshes another, and that the size never passes the limit.
js
import { test } from'node:test';
import assert from'node:assert/strict';
import { TtlLru } from'./cache.mjs';
function make(max = 2, ttlMs = 1000) {
const clock = { t: 0 };
const cache = new TtlLru({ max, ttlMs, now: () => clock.t });
return { cache, clock };
}
test('returns what was stored, and undefined for a miss', () => {
const { cache } = make();
cache.set('a', 1);
assert.equal(cache.get('a'), 1);
assert.equal(cache.get('b'), undefined);
});
test('an entry expires after its time to live', () => {
const { cache, clock } = make(2, 1000);
cache.set('a', 1);
clock.t = 999;
assert.equal(cache.get('a'), 1);
clock.t = 1000;
assert.equal(cache.get('a'), undefined);
assert.equal(cache.size, 0);
});
cache.test.mjs, setup and two tests
js
test('evicts the least recently used entry', () => {
const { cache } = make(2);
cache.set('a', 1);
cache.set('b', 2);
cache.get('a'); // a is now newer than b
cache.set('c', 3);
assert.equal(cache.get('b'), undefined);
assert.equal(cache.get('a'), 1);
assert.equal(cache.get('c'), 3);
});
test('never grows past its limit', () => {
const { cache } = make(3);
for (let i = 0; i < 100; i++) cache.set(i, i);
assert.equal(cache.size, 3);
});
cache.test.mjs, the other two
text
✔ returns what was stored, and undefined for a miss (0.6396ms)
✔ an entry expires after its time to live (0.1188ms)
✔ evicts the least recently used entry (0.0843ms)
✔ never grows past its limit (0.7612ms)
ℹ tests 4
ℹ suites 0
ℹ pass 4
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 69.6449
Node 24.18.0. The durations vary from run to run.
All four passed. The eviction test is the one that proves the LRU order: after reading a, the entry b is older, so adding c removes b. Without the re-insert in get, the cache would have evicted a, which is first-in-first-out and a different policy.
Hit ratio depends on cache size and on the workload
The next script simulates 100,000 reads over 1,000 distinct keys. Some keys are far more popular than others: key number k is chosen with a weight of 1 divided by k. A seeded generator makes the run repeatable. The workload is invented, not real traffic. The script runs four cache sizes and reports the hit ratio.
js
import { TtlLru } from'./cache.mjs';
function rng(seed) { // a small seeded generator, so the run repeatsreturn () => {
seed = (seed * 1664525 + 1013904223) % 4294967296;
return seed / 4294967296;
};
}
const KEYS = 1000;
const weights = Array.from({ length: KEYS }, (_, i) => 1 / (i + 1));
const total = weights.reduce((a, b) => a + b, 0);
function pick(random) {
let r = random() * total;
for (let i = 0; i < KEYS; i++) {
r -= weights[i];
if (r <= 0) return i;
}
return KEYS - 1;
}
l1-ratio.mjs, the workload
js
for (const max of [10, 50, 200, 1000]) {
const cache = new TtlLru({ max, ttlMs: 60_000 });
const random = rng(42);
let hits = 0;
for (let i = 0; i < 100_000; i++) {
const key = pick(random);
if (cache.get(key) !== undefined) hits++;
else cache.set(key, 'row');
}
console.log(`cache of ${String(max).padStart(4)} entries:`,
`${(hits / 1000).toFixed(1)}% of reads were hits`);
}
l1-ratio.mjs, the runs
text
cache of 10 entries: 20.8% of reads were hits
cache of 50 entries: 45.8% of reads were hits
cache of 200 entries: 69.6% of reads were hits
cache of 1000 entries: 99.0% of reads were hits
Repeatable: the generator is seeded.
A cache of 10 entries, which is 1% of the keys, still answered one read in five, because the popular keys stay in it. Growing it to 200 entries (a fifth of the keys) lifted the ratio to about 70%. With room for all 1,000 keys only the first read of each key missed, so the ratio was 99.0%, and the remaining 1% were those first reads, called cold misses. A bigger cache always hits more, but each extra entry costs memory, so the right size is a decision about memory and not a rule of thumb. The Redis documentation notes that a skewed access pattern, where a small subset of keys gets most reads, is a very common case. Measure the hit ratio of your real traffic before you decide, and keep measuring after.
A cache hit takes 2 ms, a miss takes 100 ms, and the hit ratio is 80%. What is the average lookup cost?
0.8 x 2 + 0.2 x 100 = 21.6 ms. The misses dominate, which is why improving the hit ratio matters more than making hits faster.
Why does get delete a key and insert it again when it finds a live entry?
A Map iterates in insertion order. Re-inserting moves the key to the end, so the first key is always the least recently used one, which set evicts when the cache is full.
Why give the cache class a now option instead of calling Date.now() inside it?
A test can pass a fake clock and move time forward by hand, so TTL behaviour is tested exactly and without waiting.
Part 2 · Cache-aside, invalidation and stale data
The cache-aside pattern
Most service caches use cache-aside, also called lazy loading. The application code talks to both the cache and the database, and the cache is never the source of truth. That keeps a cache failure from losing data.
On a read, the code asks the cache first. On a hit it returns the copy. On a miss it reads the database, stores the result in the cache, and returns it. On a write, the code updates the database, and then deletes the cache key. The next read misses and loads the new value. Deleting is simpler than writing the new value into the cache. When two writers update the same row, two cache writes can land in the wrong order and leave the old value behind, whereas a delete leaves nothing to be wrong.
Step
Read path
Write path
1
look in the cache
update the database
2
hit: return the copy
delete the cache key
3
miss: read the database
the next read refills the cache
4
store the row with a TTL, return it
the TTL still limits any stale copy
Cache-aside around a database query
This module wraps a PGlite query, which is PostgreSQL compiled to WebAssembly and running in the same process. It adds pg_sleep(0.05) to the SQL to stand in for a query that takes 50 ms. getProduct is the read path and updatePrice is the write path. The cache is the class from the previous lesson, and the module also counts queries.
js
import { PGlite } from'@electric-sql/pglite';
import { TtlLru } from'./cache.mjs';
exportconst db = new PGlite();
await db.exec(`
CREATETABLE products (id int PRIMARY KEY, name text, price int);
INSERT INTO products
SELECT n, 'item ' || n, 100 + n FROM generate_series(1, 200) n`);
exportconst counters = { queries: 0 };
// pg_sleep(0.05) stands in for a query that takes 50 msexportasyncfunction loadProduct(id, sleepSecs = 0.05) {
counters.queries++;
const r = await db.query(
`SELECT id, name, price, pg_sleep($2) FROM products
WHERE id = $1`, [id, sleepSecs]);
const { id: pid, name, price } = r.rows[0];
return { id: pid, name, price };
}
shop.mjs, the database and loader
js
exportconst cache = new TtlLru({ max: 500, ttlMs: 60_000 });
exportasyncfunction getProduct(id) {
const hit = cache.get(id);
if (hit) return hit;
const row = await loadProduct(id);
cache.set(id, row);
return row;
}
exportasyncfunction updatePrice(id, price) {
await db.query('UPDATE products SET price = $2 WHERE id = $1',
[id, price]);
cache.delete(id);
}
shop.mjs, the read and write paths
The script reads a product twice, updates its price, then reads it twice more, timing each read.
first read (miss) price 10751 ms (queries so far: 1)
second read (hit) price 1070 ms (queries so far: 1)
read after update price 15051 ms (queries so far: 2)
read again (hit) price 1500 ms (queries so far: 2)
On this machine; the 50 ms is the sleep added to the query.
The first read missed and paid the query cost. The second was a hit and cost almost nothing, and the query count stayed at 1. After the update the key was deleted, so the next read missed, loaded the new price of 150, and the read after that hit again. The cache never served 107 once the write had finished.
The race that deletion does not close
There is a gap in the write path above. A reader that missed may read the database, then pause, for example behind a slow network call or a garbage collection. If a writer updates the row and deletes the key during that pause, the reader then stores what it read earlier. The cache now holds the old value, and nothing will remove it until the TTL ends. The next script forces that order of events with a gate, so the race happens every time.
js
import { setTimeout as sleep } from'node:timers/promises';
import { db, cache, loadProduct, updatePrice } from'./shop.mjs';
let writerDone;
const gate = new Promise((resolve) => { writerDone = resolve; });
const reader = (async () => {
const row = await loadProduct(7); // a miss: reads the old priceawait gate; // the reader is delayed, say by a long pause
cache.set(7, row, 100); // and caches what it read, now out of date
})();
await sleep(10);
await updatePrice(7, 150); // write the database, then delete the key
writerDone();
await reader;
const fresh = await db.query('SELECT price FROM products WHERE id = 7');
console.log('database price:', fresh.rows[0].price);
console.log('cached price :', cache.get(7).price);
await sleep(120);
console.log('after the TTL :', cache.get(7));
l2-race.mjs
text
database price: 150
cached price : 107
after the TTL : undefined
The gate makes the interleaving repeatable.
The database holds 150 and the cache holds 107. In a real service the window is narrow, so this is rare, but with enough traffic it happens. The TTL is the safety net: the entry was stored with a 100 ms TTL here, and after it passed, the lookup missed and the next read would refill the cache correctly. That is why every cache entry should have a TTL, even when you also invalidate on write.
TTL jitter and common mistakes
If you fill a cache at start-up and give every entry the same TTL, they all expire together, and the database sees a burst of misses at once. A little random jitter on each TTL spreads the expiries out. This script prints six TTLs for a 60 second base with 10% jitter.
six 60 s TTLs with 10% jitter: 64527, 59292, 58468, 54416, 65077, 61042
Random: each run prints different values.
Most of the mistakes seen in practice come from a short list.
No TTL. The copy lives until it is evicted, so one missed invalidation becomes permanent.
Caching per-user data under a shared key. A key such as cart instead of cart:meera shows one customer's data to another.
Unbounded keys. A key built from free user input, such as a search string, grows the cache without limit unless the size is capped.
Caching a failure. Do not store an error as if it were an answer. Cache "not found" deliberately, with a short TTL, if at all.
Never measuring. Without a hit ratio you cannot tell a useful cache from an expensive habit.
A write updates the database and then deletes the cache key. A reader that missed earlier stores its old read after the delete. What limits the damage?
The TTL. The stale entry expires and the next read refills the cache from the database. Without a TTL it would stay stale until evicted.
Why delete the key on a write instead of writing the new value to the cache?
With two concurrent writers, cache writes can arrive in the wrong order and leave the older value. A delete leaves nothing behind, and the next read loads the current row.
What is the point of adding jitter to TTLs?
Entries created at the same time would otherwise expire at the same time and send a burst of misses to the database. Random jitter spreads the expiries out.
Part 3 · Cache stampedes and single flight
A hundred misses at once
A popular key expires, and within the same few milliseconds 100 requests arrive for it. Each one misses, because the cache is still empty when it looks, and each one runs the slow query.
This is a cache stampede, also called a thundering herd. The database receives 100 identical queries instead of one, and it is under the most load at exactly the moment the cache was meant to protect it. If the query is slow, more requests pile up while it runs, which makes it slower.
The fix is single flight: while one request is loading a key, every other request for that key waits for that same load instead of starting its own. In JavaScript this is natural, because a promise can be shared. Keep a Map from key to the promise of the load that is in progress. The first caller creates the promise and stores it. Later callers find it and return it.
Animated sceneOne query for a hundred requests0:18
Watch for 100 identical requests becoming a single database query
Read it as steps
The first miss starts the load, 99 requests wait on the same promise, and one query answers all of them.
The database saw one query, and the 100 callers all got the same row. The scene matches the script in the next page, which counts the queries.
The helper and the count
The whole mechanism is eight lines. singleFlight returns the existing promise if the key is in the map. Otherwise it starts the load and stores the promise. finally removes the entry when the load ends, whether it succeeded or failed, so the next miss starts a fresh load.
The test script uses the PGlite module from the last lesson, with a 10 ms query. It fires 100 reads at once for the same key, first with plain cache-aside and then with the helper. It then makes 100 callers share one load that fails.
plain cache-aside: 100 queries
with single flight: 1 query
failed together: 100
the next call retries: item 7
Node 24.18.0, PGlite 0.5.15.
Plain cache-aside ran 100 queries for 100 reads. With single flight, the count was 1. In the failing case, all 100 callers received the same rejection, and because finally had cleared the entry, the next call started a new load and succeeded. Be aware of both halves of that behaviour: a failure is shared, so the callers must be ready for it, and a failure is not cached, so recovery is automatic.
What single flight does not do
The map lives in one process. With four Node instances behind a load balancer, a stampede becomes four queries, one per instance, instead of 100. That is usually a good enough result. When it is not, the instances can compete for a short-lived lock in a shared store: the Redis SET key value NX EX seconds command sets a key only if it does not exist, with an expiry, and returns OK to exactly one caller. The Redis documentation describes this as a simple locking pattern, and says that for stronger guarantees the Redlock algorithm is preferred. The next lesson shows SET ... NX running.
Two other tools reduce stampedes. Refresh ahead reloads a hot key a little before it expires, so readers never see a miss. Serving stale data while refreshing returns the old copy to readers and updates it in the background. Both trade a little freshness for steady latency. They need more machinery than single flight, so start with single flight and add them only when the numbers ask for it.
Single flight also fits outside caches. Anything where many callers ask for the same slow result at the same time, such as loading a configuration file or exchanging a token that is about to expire, can share one promise.
What does singleFlight do with 100 concurrent calls for the same key?
The first call starts the load and stores its promise in a map. The other 99 find the promise and return it, so one load runs and all 100 callers get its result.
Why is the map entry removed in finally rather than only on success?
If a failed load stayed in the map, every later call would receive the same rejected promise forever. Removing it in finally lets the next call start a fresh load.
Four instances each use single flight on a key that just expired. How many queries can reach the database?
Up to four, one per instance, because each process has its own map. A shared lock such as SET key value NX EX can reduce that to one.
Part 4 · Shared caches with Redis
Why a shared cache
An in-process cache is fast and simple, but each Node instance has its own. With four instances, the same hot product is held four times and loaded four times. A price update deletes the key in one instance and leaves the other three serving the old value. A restart empties that instance's cache and sends a burst of misses to the database. A shared cache is one store that every instance uses, which removes all three problems at the cost of a network call on every lookup.
Redis is the common choice. It is a server that keeps data in memory and speaks a simple command protocol. Values are not only strings: Redis has hashes (a map of fields inside one key), lists, sets and sorted sets, and any key can have an expiry. This chapter runs against a real Redis server, version 6.2.14, started in WSL on a port reserved for this lesson with persistence turned off, and talks to it from Node with the ioredis client. The Redis documentation recommends node-redis as its primary Node client and documents ioredis as the older one. The commands are the same in both.
The connection lives in one small module.
js
import { Redis } from'ioredis';
// Redis 6.2.14 started in WSL on port 55601exportconst connect = () =>
new Redis({ host: '127.0.0.1', port: 55601 });
redis-client.mjs
The commands you will use
The script below tries one command from each family. SET with EX 60 stores a string that expires in 60 seconds. HSET stores a hash, like a cart with an item count per product. ZADD adds members to a sorted set, ordered by score, which suits leaderboards. The last two lines call SET ... NX twice, which sets the key only when it does not exist.
OK
{"id":7,"price":150}
ttl: 60
{ idli: '2', dosa: '1' }
[ 'asha', '130', 'meera', '120' ]
lock for a: OK | lock for b: null
Redis 6.2.14, ioredis 6.0.0.
The TTL is 60 seconds, as set. Redis returns every hash value as text, which is why idli is '2'. The sorted set came back highest score first with the scores as text. And SET ... NX returned OK to the first caller and null to the second, which is the whole basis of a lock.
Two settings decide what Redis does when it fills up. maxmemory is the limit, and the documentation says its default on 64-bit systems is 0, which means no limit. maxmemory-policy chooses what to evict when the limit is reached. For a cache, the documentation suggests allkeys-lru as a good default when a subset of keys is read far more often than the rest. On the server used here, CONFIG GET returned a maxmemory of 0 and a maxmemory-policy of noeviction. With that policy, the documentation says Redis returns an error for commands that add data once the limit is hit, which is wrong for a cache, so set the policy when you set a limit.
One cache for many instances
The next script opens two connections and treats them as two instances of a service. Instance A writes a key. Instance B reads it twice, and then asks for a key that does not exist. The script also reads Redis's own counters, keyspace_hits and keyspace_misses, before and after. The Redis documentation gives the hit ratio as keyspace_hits / (keyspace_hits + keyspace_misses) * 100.
B reads A's write: ["idli","dosa"]
new hits: 2
new misses: 1
B saw A's write at once, and the server counted two hits and one miss. This is the number to watch in production. If the ratio is lower than you expect and evicted_keys is high, the cache is too small or the policy is wrong; if expired_keys is high, the TTLs may be too short, as the documentation explains.
A rate limiter on shared counters
Redis counters also solve a problem that an in-process limiter cannot: a limit that holds across instances. In a fixed window limiter, each client has a counter for the current time window. The first request in a window creates the counter, each request increments it, and requests past the limit are refused until the window ends. INCR creates a missing key at 1 and returns the new value, and the Redis documentation describes this rate limiter pattern.
Two commands must both happen: INCR and EXPIRE. The first rate limiter pattern in the INCR documentation runs both inside MULTI and EXEC, which Redis applies together, and that is what the module does. Its second pattern, one counter that is created once, warns that an INCR without its EXPIRE leaks the key if the client fails between them, and fixes that with a Lua script. The key includes the window number, so each window gets a fresh counter.
The Retry-After value depends on where in the 30 second window the run began.
Three requests passed and two were refused with 429. The Retry-After value is the number of seconds left in the window, which is when a counter starts over. The shared state sits in Redis, so a second Node instance running this code would count the same requests. A fixed window allows a burst at the boundary: three requests at the end of one window and three at the start of the next. If that matters, use a sliding window or a token bucket. The login throttling advised in the auth chapter and the toy 429 route in the API design chapter are what this counter replaces.
Four instances each hold their own in-process cache. A price changes and one instance deletes the key. What do the other three do?
They keep serving the old value until their own TTL ends, because their caches are separate. A shared cache removes the problem: one delete is seen by all.
What does SET lock:job1 worker-b EX 10 NX return when the key already exists?
Null. The NX option sets the key only if it does not exist, so the second caller gets no OK, and only one caller holds the lock.
Why run INCR and EXPIRE inside MULTI?
So both are applied together. If a client did the INCR, then failed before EXPIRE, the counter would never expire.
Part 5 · Why background jobs, retries and backoff
Moving slow work out of the request
Placing an order should answer in milliseconds, but the receipt needs an email, and an email server can take seconds or fail. Work that is slow, flaky or not needed for the answer belongs in a background job.
The request handler records what must be done, in a queue, and answers at once, often with 202 Accepted. A separate worker takes jobs from the queue and runs them. The user waits only for the quick part. If the email server is down, the job waits and tries again, and the request that created it already succeeded. Typical jobs are receipts and notifications, image resizing, report generation, and calls to partners whose uptime you do not control.
The price is a new kind of failure. A job can run twice, or fail repeatedly, or never run because the process died. Queues usually promise at-least-once delivery: a job is delivered until the worker acknowledges it, so if a worker crashes after doing the work but before the acknowledgement, the job runs again. The BullMQ documentation says this too and recommends that processors be idempotent. Delivery is rarely exactly once, so the handler must tolerate repeats.
Retries with backoff and jitter
When a job fails, retrying at once usually fails again, and many jobs retrying together make an overloaded service worse. The Amazon Builders' Library article on timeouts, retries and backoff warns that retries which add load can make matters significantly worse. Exponential backoff waits longer after each failure, and jitter adds randomness so that many failed jobs do not all return at the same instant.
One common form is called full jitter. Compute a ceiling that doubles with each attempt, up to a cap, and wait a random time between zero and the ceiling. This formula is a common choice and does not come from that article. The implementation in the next page uses a 20 ms base and a 400 ms cap so that the demo is quick. Real values are in seconds.
A job also needs a limit. After a fixed number of attempts, the job moves to a dead-letter queue, a place for jobs that will not succeed by themselves. Someone looks at it, fixes the cause, and replays it. Without that limit, one poison job (a malformed address, say) retries forever and costs resources while the real problem stays hidden.
Concept
What it is for
At-least-once delivery
a job is retried until acknowledged, so it can run more than once
Idempotent handler
running the same job again has no extra effect
Exponential backoff
waits grow with each attempt, easing the load on a struggling service
Jitter
random spread so retries do not arrive together
Dead-letter queue
where jobs go after their last attempt, for a person to review
A small in-process queue
The queue below runs inside one Node process and has no storage, so a crash loses its jobs. That makes it a teaching tool and not a production queue, but it holds the same ideas. The next lesson uses a real one. This first part holds the backoff helpers and the constructor.
js
exportconst ceiling = (attempt, baseMs = 20, capMs = 400) =>
Math.min(capMs, baseMs * 2 ** attempt);
// full jitter: wait a random time between 0 and the ceilingexportconst backoff = (attempt, random = Math.random) =>
Math.floor(random() * ceiling(attempt));
exportclass JobQueue {
jobs = new Map();
#waiting = [];
#running = 0;
#timers = new Set();
constructor({ handler, maxAttempts = 4, concurrency = 2, onEvent }) {
Object.assign(this, { handler, maxAttempts, concurrency, onEvent });
}
add(id, data) {
const job = { id, data, attempts: 0, state: 'waiting' };
this.jobs.set(id, job);
this.#waiting.push(job);
this.#pump();
}
queue.mjs, backoff and add
The middle part takes jobs off the list up to the concurrency limit and runs the handler. A job that succeeds is completed. A failure goes to #fail.
#fail decides between retry and giving up. A job with attempts left becomes delayed and a timer puts it back after the jittered wait. A job on its last attempt becomes dead.
The script queues four receipts. ok works at once. flaky fails twice, then works. broken always fails. lost-ack does its work, then throws, which models a connection reset after the email was sent. The handler is idempotent: it keeps a set of receipts already sent, and skips the send if a job id is in it.
js
import { JobQueue, ceiling } from'./queue.mjs';
const sent = new Set(); // receipts already sentlet emails = 0;
asyncfunction handler(data, job) {
if (data.kind === 'flaky' && job.attempts < 3) {
thrownew Error('mail server busy');
}
if (data.kind === 'broken') thrownew Error('bad address');
if (!sent.has(job.id)) { // idempotent: skip if already done
sent.add(job.id);
emails++;
}
if (data.kind === 'lost-ack' && job.attempts === 1) {
thrownew Error('connection reset after sending');
}
}
The order of the first ten lines varies between runs, because of the jitter. This is one real run.
The first ten lines are the events. ok completed on its first attempt. flaky went through delayed twice before it completed on attempt 3. broken used all four attempts and ended dead. Then the table lists the final state of each job, and the delay ceilings the code used: 40, 80, 160, 320 and then the 400 ms cap.
The last line is the point of idempotency. The lost-ack job ran twice, because the first attempt threw after sending. But only 3 receipts were sent: for ok, for flaky on its successful third attempt, and once for lost-ack. The second run of lost-ack found its id in the set and skipped the send. A handler that sent unconditionally would have sent a fourth email. In a real service, the record of what has been done lives in the database, in the same transaction as the effect where possible, the way the idempotency key table did in the API design chapter.
Animated sceneThe life of a job that never succeeds0:16
Watch for the job returning to waiting after each failure, until attempts run out
Read it as steps
A failing job goes through waiting, active and delayed again and again, and is dead-lettered after its last attempt.
This is the broken job from the run: four attempts, then the dead-letter state. The scene gives the window of the first wait as 0 to 40 ms because the ceiling after the first failure was 40 ms.
A worker sends an email, then crashes before it can acknowledge the job. What happens next, and what must the handler be?
The queue delivers the job again, because it was never acknowledged. The handler must be idempotent, so the second run sends nothing new.
Why add jitter to a retry delay?
Without it, many jobs that failed together retry together and can overload the service again. Random delays spread the retries out.
What is a dead-letter queue for?
It holds jobs that failed their last attempt, so that a person can find the cause, fix it and replay them, instead of the job retrying forever.
Part 6 · Job queues in practice: BullMQ, scheduling and shutdown
BullMQ on Redis
The in-process queue loses everything when the process stops, and it cannot share work between machines. A real job queue stores its jobs outside the process. BullMQ is a Node library that keeps its queues in Redis. Its documentation says it needs Redis 6.2 or newer, which the server in this chapter satisfies, and that every state transition of a job is atomic.
Three objects matter. A Queue adds jobs. A Worker runs a function on each job; you can run several workers, in several processes, on the same queue. A job has a name, a data object and options, including attempts and backoff, which are the retry settings from the last lesson. The script queues three jobs on the Redis server from the shared-cache lesson: one that works, one that fails twice before it works, and one that always fails with two attempts allowed.
plain: completed (attempt 1): sent to meera@example.com
flaky: attempt 1 failed: mail server busy
broken: attempt 1 failed: bad address
flaky: attempt 2 failed: mail server busy
broken: attempt 2 failed: bad address
flaky: completed (attempt 3): sent to ravi@example.com
{ completed: 2, failed: 1, waiting: 0 }
BullMQ 6.7.2, Redis 6.2.14. The order of the middle lines can vary.
plain completed. flaky failed on attempts 1 and 2 and completed on attempt 3, using an exponential backoff setting with a delay option of 50 ms. broken failed on attempts 1 and 2 and stopped. The counts show 2 completed jobs and 1 in the failed set. The run shows that a job which used all its attempts stays in the failed set, where you can inspect it. Replaying it is a step this lesson does not run; the BullMQ documentation describes it.
Keep job data small: store ids and read the rest from the database when the job runs, so that the job never works from an outdated copy. The backoff option also takes a jitter fraction between 0 and 1 that randomises each delay; the BullMQ documentation describes it, and it was not run here.
Delayed and repeating jobs
Many jobs should run later, not now: a reminder in an hour, or a retry window. BullMQ supports a delay option on a job. Repeating work, such as a nightly report, uses a job scheduler, which creates a new job at a fixed interval or on a cron pattern. The next script adds one job now, one with a 500 ms delay, and a scheduler that repeats every 400 ms, and prints the time each job began to run.
13 ms now
16 ms repeat
509 ms repeat
509 ms delayed
909 ms repeat
1211 ms repeat
Times are from one run. The gaps between repeats varied: about 300 to 500 ms in this run and close to 400 ms in a second run.
The immediate job ran at once, and so did the first repeat job. The delayed job ran at about 500 ms, and the scheduler produced further repeat jobs about 300 to 500 ms apart, close to its 400 ms interval but not exact. Treat delays and repeats as approximate: they run no earlier than asked, and they depend on the worker being free and the clock of the machines. The script ends by removing the scheduler. A scheduler that nobody removes keeps producing jobs after you have forgotten it.
Shutting down without losing work
A deploy sends your process a stop signal. If a worker is halfway through generating an invoice and the process exits, that job is left unfinished. It can be run again later, which is why handlers must be idempotent, but it is better not to cut work off at all.
A BullMQ worker's close() method stops it from taking new jobs and waits for the job it is running to finish. The script queues two slow jobs, closes the worker while the first runs, and then asks how many jobs are still waiting. The shutdown function is what a SIGTERM handler would call. Signals on Windows do not reach handlers, so the script calls it directly after a delay, as the scaling chapter explains.
js
import { setTimeout as sleep } from'node:timers/promises';
import { Queue, Worker } from'bullmq';
const connection = { host: '127.0.0.1', port: 55601 };
const queue = new Queue('slow', { connection });
await queue.obliterate({ force: true });
const worker = new Worker('slow', async (job) => {
console.log(`${job.name}: started`);
await sleep(400); // pretend to render a PDF
console.log(`${job.name}: finished`);
}, { connection });
await queue.add('invoice-1', {});
await queue.add('invoice-2', {});
await sleep(100); // invoice-1 is now runningasyncfunction shutdown() { // what a SIGTERM handler would call
console.log('shutdown: closing the worker');
await worker.close(); // waits for the running job
console.log('shutdown: worker closed');
console.log('still waiting:', await queue.getJobCounts('waiting'));
await queue.close();
}
await shutdown();
l6-drain.mjs
text
invoice-1: started
shutdown: closing the worker
invoice-1: finished
shutdown: worker closed
still waiting: { waiting: 1 }
BullMQ 6.7.2.
The close request arrived while invoice-1 was running. The job finished first, then the worker closed. invoice-2 was never started and stayed waiting, so another worker, or this one after a restart, will pick it up. Add a deadline in real code: if close() has not returned within a set time, exit anyway, because a deployment platform usually kills the process after a grace period.
Before you run it for real
The BullMQ production checklist has four items that matter early. Set the Redis maxmemory-policy to noeviction: BullMQ cannot work properly if Redis evicts keys, which is the opposite of the allkeys-lru advice for a cache, so keep queues and caches on separate Redis servers. Turn on persistence, preferably AOF, because a queue held only in memory loses its jobs when Redis restarts. Remove finished jobs automatically, for example with the removeOnComplete and removeOnFail job options, so that Redis does not fill up. And shut workers down gracefully on SIGINT and SIGTERM, as the last page showed.
The Redis server in this chapter had noeviction by default and persistence switched off, which suits a lab and not production. The first two items were read from the BullMQ documentation and were not run.
Other brokers, and a summary
BullMQ on Redis is not the only choice. RabbitMQ is a message broker with exchanges and acknowledgements, Kafka is a distributed log that consumers read at their own position, and Amazon SQS is a managed queue. They differ in delivery guarantees, ordering and operations, and none was run in this chapter. When you pick one, ask four questions: can jobs be lost if the broker restarts, can a job be delivered twice, is ordering guaranteed, and who runs it.
Term
Meaning
Cache-aside
the application checks the cache first and fills it on a miss
Single flight
concurrent requests for one key share one load
Hit ratio
hits divided by hits plus misses
At-least-once
a job is redelivered until acknowledged, so it can run twice
Dead-letter queue
the holding place for jobs that used all their attempts
A worker is stopped while it runs a job. What does worker.close() do that exiting the process does not?
It stops taking new jobs and waits for the running job to finish before closing, so the job is not cut off halfway.
Why keep job data small and store only ids?
The job reads the current row when it runs, so it never works from a copy that went stale while it waited in the queue, and the queue stores less in Redis.
A job with attempts: 2 fails both times. Where does BullMQ leave it, according to the run?
In the failed set. The run showed one job in failed after both attempts, and you can inspect it there.