@mdaemon/persistent-queue
v1.0.0
Published
A durable, single-process job queue for Node: ProcessQueue in memory, with a write-ahead log on disk and crash recovery
Maintainers
Readme
@mdaemon/persistent-queue
A durable, single-process job queue for Node. It keeps its jobs in memory in a @mdaemon/process-queue ProcessQueue, appends every change to a write-ahead log on disk, and rebuilds the queue from that log after a crash.
Install
npm install @mdaemon/persistent-queueItems are processed by a worker, taken with take(), or both. Node only: it uses node:fs. It supports Node 20 and later. @mdaemon/process-queue 3.2 or later is a runtime dependency, installed with it.
Usage
import PersistentQueue from '@mdaemon/persistent-queue';
interface Email { id: string; to: string; body: string }
const queue = await PersistentQueue.open<Email>({
directory: './data/emails',
worker: async email => { await send(email); },
concurrency: 4,
maxRetries: 5,
retryDelay: attempt => 1000 * 2 ** attempt,
processingTimeout: 60_000,
});
await queue.add({ id: 'welcome-42', to: '[email protected]', body: 'Hi' }); // resolves once it's on disk
await queue.close(); // waits for running workers, saves a checkpoint, releases the directoryWith CommonJS, require('@mdaemon/persistent-queue') gives the class as .default and as .PersistentQueue.
Guarantees
- Durable changes.
add,addMany,remove,clearandclearDeadLetterQueueresolve once their change is on disk (fsync). Writes are grouped, so many changes share one fsync. - At-least-once delivery. An item whose worker was interrupted by a crash runs again after the queue reopens. An item whose completion reached the disk never runs again. Workers should be idempotent.
- The worker runs only once its start is on disk, and gets a copy of the item.
- ProcessQueue's features survive restarts: id deduplication, priority order, concurrency, retries with backoff, the dead letter queue and TTLs, including retry counts, retry times and TTL clocks.
- Visibility timeout. An item whose worker runs longer than
processingTimeoutis queued again, as in SQS. The first run may still be going, which is another reason workers must be idempotent. A timed-out item is queued again even when the queue has filled tomaxSizemeanwhile, so it is never lost. - Fail-stop. If writing to disk fails, the queue stops rather than go on with state it can't save. No new worker starts, every pending and later call rejects with the error,
fatalis emitted, and the queue closes. After the failure,fatalis the only event emitted (but for atornWritealready due fromopen): nothing more is saved, so a worker the failure stopped isn't reported aserrororfailed, and runs again after a restart.
API
PersistentQueue.open<T>(options)
Opens the queue in options.directory, making the directory if needed, and recovers what it holds. It resolves to the queue, which starts processing unless paused is set. The options are ProcessQueue's, plus:
| Option | |
|---|---|
| directory | Required. The queue's directory. One process at a time may open it. A new queue needs a new or empty directory, which, on Linux and macOS, only its owner can write: see The queue directory. |
| worker(item) | Processes an item, synchronously or by returning a promise. A failure (a throw or a rejection) is retried as maxRetries and retryDelay say, then the item goes to the dead letter queue. Without a worker, items are only taken with take() and takeMany(). |
| paused | Open paused: neither the worker nor take() gets items until resume(). |
| trust | Exceptions to the checks of who could change the queue's directory or its path (EINSECURE), for containers and volumes they refuse: owners, user ids whose directories count as root's; groups, group ids whose write permission is accepted; everyone, accepting directories every user can write. See Containers and volumes. |
| concurrency, maxRetries, retryDelay, maxDeadLetterSize, ttl, processingTimeout, maxSize, overflowStrategy, comparator, emplace, onListenerError | As in ProcessQueue. |
open rejects:
- with
code: 'ELOCKED'(and the owner'spid) if another live process, or this one (in any of its threads), has the directory open, or (with nopid) if its lock file keeps being removed; - with
code: 'EINSECURE'(and thepathrefused: the directory, or an entry along its path), on Linux and macOS, if another user owns the directory, or other users can write to it, or another user could change its path (see The queue directory); - with
code: 'ENOTQUEUE'(and the directory'spath) if the directory holds other files but no queue; - with
code: 'ECORRUPT'(and the file'spath) if a file is damaged anywhere but at the very end, where a crash can leave a torn write, or if the checkpoint, a journal or a lock isn't a regular file (a link or a FIFO, say); - with an
Errornaming both versions if the directory was written in a newer format; - with ProcessQueue's own errors for invalid options;
- with an
Errornaming the directory, and the comparator's error as itscause, if the comparator throws while the queue is restored.
When open refuses a directory, for any of these reasons, it leaves what the directory holds unchanged. A disk failure later in open, as it writes its checkpoint or creates its journal, can leave the checkpoint rewritten (a 0.1.0 directory then in format 2), with nothing lost. A directory it made for the queue, and its parents, stay. A directory holding more than maxSize items, as after lowering it, opens with them all. New adds are then refused (with reject or drop-newest) until the queue is below maxSize; with drop-oldest, each one evicts the oldest queued item instead, so the queue keeps its size until items are taken.
Methods
| Method | |
|---|---|
| add(item) | Adds an item, or updates the queued item with its id. Resolves to true, or false if the id is in process or awaiting a retry, or the queue is full with drop-newest (or with drop-oldest, when only items awaiting a retry fill it). Rejects if the queue is full with reject. |
| addMany(items) | Adds items in order, checking them all first. Resolves to one result per item. |
| remove(id) | Removes a queued item, or one awaiting a retry. Resolves to whether one was removed. |
| clear() | Empties the queue, the items in process and the retries; the dead letter queue stays. A worker whose take is still being written doesn't start; running workers go on, and their results are ignored. |
| clearDeadLetterQueue() | Empties the dead letter queue. |
| has(id), size() | Whether an id is queued, and how many items are. Items in process or awaiting a retry don't count. |
| getQueue(), getInProcess(), getDeadLetterQueue() | Copies of the queued items (not those awaiting a retry, as in ProcessQueue), the items in process, and the dead letters. |
| take() | Takes the next item, as the worker would, and resolves to a lease once that is on disk; undefined if nothing is queued or the queue is paused. |
| takeMany(count) | Takes up to count items from the front of the queue, as one change. |
| pause(), resume() | Stop and start handing out new work, to the worker and to take(). Running workers and held leases go on. |
| onIdle() | Resolves when nothing is queued, in process or awaiting a retry. Rejects if the queue closes or fails first, since a stopped queue may never be idle, so handle the rejection. |
| compact() | Saves a checkpoint now and starts a new journal. This also happens on its own as the journal grows. |
| close() | Stops taking new work, waits for running workers, saves a checkpoint and releases the directory. Until the workers settle, the queue's methods still work, so a worker can add a follow-up item, except resume(), compact() and onIdle(), which throw or reject; take() finds nothing, as the queue is paused. |
| on, once, off | ProcessQueue's events (added, processing, done, removed, expired, timeout, error, failed, empty, drain, paused, resumed), plus fatal(error), compactionError(error) and tornWrite({ file, offset, bytes }). tornWrite is emitted once, just after open resolves, if the newest journal ended in a torn write, which open left out; by then the journal it names is deleted, its records in the new checkpoint. Attach its handler as soon as open resolves, before awaiting anything else: of opens awaited together (Promise.all), one that resolved first has emitted it already, so attach each in its own .then. As in ProcessQueue, on and once registrations are separate, and off removes both. |
Once close() has waited for running workers, methods throw (or reject) with Error('The queue is closed'). After a disk failure, they throw or reject with that failure.
Leases
take() and takeMany() give leases. A lease is { item, ack(), release() }:
itemis a copy of the item.ack()marks the item done.release()puts it back in the queue. It counts no failure (ProcessQueue forgets the item's attempts), and goes in pastmaxSizeif the queue filled meanwhile.
Both resolve to true once the change is on disk. They resolve to false, changing nothing, for a stale lease. A lease goes stale when it was already acked or released, when the queue was cleared, or after processingTimeout: the item is then queued again, as a worker's run would be, and may be taken by someone else.
Taken items count toward concurrency, as in ProcessQueue: while takers hold concurrency items, the worker starts none. close() doesn't wait for leases. An item still taken at a crash or a close is back in the queue when the queue next opens.
Items
- Items are stored as their JSON form.
addkeepsJSON.parse(JSON.stringify(item)), so what the queue holds is what it can recover. ADatebecomes a string, and properties that areundefineddisappear. This happens at once, not only after a restart.addrejects with aTypeErroran item JSON can't encode (aBigInt, a cycle), and one whose JSON form has no valid id (anInfinityid becomesnull). - Items have limits.
addandaddManyreject with aTypeErroran item nested more than 64 levels deep (the item itself is level 1, and each object or array inside it one more), and one whose JSON is over 64 MiB. Deeper items overflow the stack when the queue copies them, and would stop it for good. - Don't change the items that event listeners receive. They are the queue's own objects; the worker gets a copy.
- What's on disk: every item that passes through the queue, and, for each item that fails for good, the start of the message of the error that failed it. Only the owner can read the files (see below).
The queue directory
A new queue goes in a new or empty directory.
openmakes the directory if it doesn't exist, and syncs it into its parent, as it does each parent it makes. It can't sync a parent this user can't read (mode 0711 or 0733), so there, make the queue directory beforehand: a crash soon afteropenmade it could otherwise lose it. A directory that holds other files but no queue is refused withENOTQUEUE, changing nothing, since the queue would delete or overwrite files with its own names..DS_Store,Thumbs.dbanddesktop.ini, which file browsers leave, a volume'slost+found, and.gitkeep,.keepand.gitignore, which keep an empty directory in git, don't count. Locks (lock.<token>, orlockfrom 0.1.0) and acheckpoint.tmpwith nothing else count as the queue's own, left by a first open that crashed: the locks are removed once stale, and the temp file replaced. A queue's directory may hold other files once the queue is in it.Only its owner may write it, on Linux and macOS.
openrefuses withEINSECUREa directory another user owns, or one with group or other write permission. Another user who could write to it could plant links that make the queue overwrite their targets, or replace the queue's files. Fix it withchmod go-w <directory>, or use a directory under the user's own; containers and volumes may need the exceptions in Containers and volumes. Windows isn't checked: a new directory there inherits its parent's ACL, so keep queues out of directories every user can write, such asC:\ProgramData, unless their ACL says otherwise.- A directory given as a link is resolved once, at
open: that's the directory checked and used, even if the link changes later. The directories along its path are checked too, as the next point says. - A path another user could change is refused too, since they could point it at another of your directories. So every directory along it must be yours or root's (its owner can rename anything in it and put a link in its place), and in one every user can write, it must have the sticky bit, and the entry in it must be yours or root's (only an entry's owner can replace it there, as in
/tmp). A link another user owns is refused in a directory other users can write: Linux doesn't follow another user's link in/tmp, but macOS does. Directories your own group can write are fine (umask 002 makes home directories 0775), and so is macOS's/tmp, which is root's link to/private/tmp. The path is checked as given, with..taken away first, before the directory is made and again after, and then where it leads. The queue then uses that path too, without the..:/tmp/x/../qis/tmp/q, whereverxleads. So a link of your own that leads somewhere refused can have had directories made through it before the refusal. - ACLs aren't checked. On macOS, an ACL can let other users write to a directory whose mode says they can't, so don't give a queue's directory one.
- Some file systems have no real owners or modes: WSL's
/mnt/c, SMB and FAT mounts show every directory as 0777, and NFS with root squashing shows other owners.openrefuses queues on them.trustcan let them through, but then every user, or the squashed owner, can change the queue.
- A directory given as a link is resolved once, at
The files are the owner's only. Whatever the umask, the queue creates its files readable and writable by their owner only (0600), and the directories it makes usable by their owner only (0700). On Windows, they inherit the directory's ACL. (A Kubernetes
fsGroupmount changes both: see Containers and volumes.)The queue writes only the files it creates, and never through a link. Each is created new: a leftover
checkpoint.tmp, link or not, is removed first, and anything else in the way of a new journal or lock makesopenfail. It reads only regular files, a chunk at a time, and refuses a link, FIFO or directory in place of one withECORRUPT.ELOCKED, but the queue isn't open anywhere? The error names the pid in a lock file (lock.<token>, orlockfrom 0.1.0). A process that crashed leaves its lock, which the nextopenremoves once that pid is gone. But if an unrelated process now has that pid, as often happens on Windows, the lock looks held. (A restarted container usually gets the crashed process's pid for itself; the lock's start tells them apart.) The message saysis being opened in process <pid> toowhen no open had the directory, but another was still opening it after 6 tries: one that is stopped, or a worker thread terminated mid-open, stays in that state until its process exits. Stop the process with that pid, or, once you're sure nothing has the queue open, delete the lock files. The message sayscouldn't be locked, as its lock file kept being removed(with nopid) if the lock file each try wrote was gone by the time it checked: something, such as a cleanup job, is deleting lock files. Within one process, a queue stays open until it is closed, even if the worker thread that opened it has ended. A lock file that another program, such as a virus scanner, has open can't be deleted on Windows: the queue tries again for about 5 seconds. A lock it still couldn't delete doesn't stop the thread that left it from opening the queue again. Other threads and processes take it for live until the process exits: one left atclose()for an open that has the queue (is already open), and one left by an open that backed off for one still opening it (is being opened).
Containers and volumes
Containers and mounted volumes often have owners and modes these checks refuse. The trust option makes the exceptions they need, each letting more users change the queue, so give only those your setup needs. Every other check still applies.
| Setup | Refused because | Option |
|---|---|---|
| Kubernetes fsGroup | The volume's root is root's and the group's to write (mode 2775). With the default fsGroupChangePolicy: Always, each mount makes the directories in it, the queue's included, the group's to write too (2770), so the second start fails | trust: { groups: [<fsGroup>] }. With fsGroupChangePolicy: OnRootMismatch, a queue in a directory inside the volume needs none |
| Kubernetes emptyDir | Every user can write it (mode 0777), with no sticky bit | trust: { everyone: true }, if you trust every user in the container |
| A volume another user owns, in a container that runs as root (docker run -v $PWD/data:/data); root running from a user's tree (sudo, a root service with its queue under /home); a service user's queue in a deploy user's tree | Another user owns a directory along the path, and could put a link in place of the next | trust: { owners: [<their uid>] }, and their group in groups too if it can write their directories, as under umask 002 (0775) |
| OpenShift, which runs an image as an arbitrary user in group 0, with the image's directories 0775 and group 0's | The image's user and group 0 can write them | trust: { owners: [<image uid>], groups: [0] }, trusting every member of group 0 |
| Flatpak, rootless Podman, unprivileged LXC | A user namespace shows the owners it doesn't map, such as host root's /home, as 65534 | trust: { owners: [65534] } |
// In a pod whose securityContext has fsGroup: 2000
const emails = await PersistentQueue.open<Email>({
directory: '/var/lib/app/queue',
worker: send,
trust: { groups: [2000] },
});A queue directory root owns is accepted only when this user can write it through permission trust accepts, as in a Kubernetes volume. On Linux, a directory's group bits are also the most any POSIX ACL entry grants, so groups accepts write a named user's ACL entry gives too. With fsGroup, each mount also makes the queue's files the group's to read and write (0660). trust changes nothing on Windows, where none of these checks are made. A bad value (ids that aren't integers of 0 or more, say), or a name other than owners, groups and everyone, is a TypeError.
Recipes
Shutting down
process.once('SIGTERM', () => {
// close() waits for running workers before it saves the checkpoint
queue.close().then(() => process.exit(0), error => {
console.error('Closing the queue failed; its journal still holds everything', error);
process.exit(1);
});
});When the disk fails
queue.on('fatal', error => {
console.error('The disk failed, so the queue stopped', error);
// The queue closes itself. Exit once it has, and let a supervisor restart the process: the
// next open recovers everything that reached the disk.
void queue.close().finally(() => process.exit(1));
});Idempotent workers
An item can run more than once: after a crash, or when its first run overran processingTimeout. Make the work safe to repeat, for example by recording what's done:
const worker = async (email: Email) => {
// At-least-once: a crash after send() but before the queue records the completion sends it again
if (await alreadySent(email.id))
return;
await send(email);
await markSent(email.id);
};Retrying with backoff
const options = {
maxRetries: 10,
// 2 s, 4 s, 8 s ... capped at 5 minutes; retry counts and times survive a restart
retryDelay: (attempt: number) => Math.min(300_000, 1000 * 2 ** attempt),
};Retrying the dead letters
clearDeadLetterQueue() empties the whole dead letter queue, including any item that failed after getDeadLetterQueue() returned.
const dead = queue.getDeadLetterQueue();
// Queue them first: a crash before the clear leaves them queued and dead, never lost
const requeued = await queue.addMany(dead);
// false means that id is already in process or awaiting a retry
if (requeued.every(Boolean))
await queue.clearDeadLetterQueue();Backpressure
// With overflowStrategy: 'drop-newest', a full queue refuses new items rather than throw.
// add() is also false for an id already in process or awaiting a retry.
if (!(await queue.add(email)))
tooBusy(email);Priorities
interface Job { id: string; priority: number }
const jobs = await PersistentQueue.open<Job>({
directory: './data/jobs',
worker: async job => { await run(job); },
// Lower first; equal priorities keep their arrival order
comparator: (a, b) => a.priority - b.priority,
});Adding many items quickly
Each awaited add waits for its own fsync. Changes made together share one:
// One fsync for the whole batch, rather than one per awaited add
await queue.addMany(batch);
// Concurrent adds share one too
await Promise.all(batch.map(email => queue.add(email)));Finishing the work, then closing
await queue.onIdle(); // rejects if the queue closes or fails first
await queue.close();Taking items yourself
A queue opened without a worker hands out items only through take(). Hold each lease no longer than processingTimeout, or the item goes back to the queue for someone else:
const emails = await PersistentQueue.open<Email>({ directory: './data/emails', processingTimeout: 60_000 });
for (;;) {
const lease = await emails.take();
if (!lease) {
await sleep(1000);
continue;
}
try {
await send(lease.item);
await lease.ack();
} catch {
// Back in the queue to be taken again; release() counts no failure, so there is no backoff
await lease.release();
}
}Behavior to know about
- A rejected change may still be there. If
addrejects because the disk failed, the item may still have reached the disk, and may reappear when the queue reopens. As with any database, a failed write has an unknown outcome. close()waits for running workers. Until they settle, they can still use the queue, as can other callers. A worker that never settles keeps it waiting, and a worker that awaitsclose()deadlocks.close()rejects if it can't write its checkpoint; the directory still holds everything, and the lock is released.- A comparator that throws while a timed-out item is queued again is fatal: ProcessQueue offers no way to dead-letter the item, and losing it would break at-least-once. Nothing records its release, so it runs again after a restart.
- A crash ends without
close(). The nextopentakes over the dead process's lock, replays the journal, and runs interrupted items again. - A retry whose timer fired just before a crash, before its worker started, re-enters the queue on recovery rather than at its old place.
- With
emplaceand a comparator, an update keeps the item's place, as in ProcessQueue, but reopening sorts the queue by the comparator, so an updated item may move. - A retry too long to record, as only an item from 0.1.0 with an id of nearly 65 MiB can be, is recorded as queued again at once: after a crash it runs again without waiting for its retry time.
- With
drop-oldest, a retry that re-entered the queue on its own counts as the newest item when choosing what to drop. As in ProcessQueue, evicting the only queued item emits neitheremptynordrain, a comparator that throws for the new item evicts nothing, and an add from aremovedlistener finds the queue still full, so it evicts for itself (the new item, if nothing else is queued), unless it is for the id being added, which it updates; and aclear()there clears the new item too, and emitsemptyanddrainat once. Unlike ProcessQueue, which emitsaddedfor the new item once its listeners are done, nothing is emitted for a new item such a listener cleared, replaced or evicted: it was never queued. With a comparator, an add that evicts runs it over the queue twice: first to check it, since ProcessQueue places the new item before it evicts, so a comparator that throws, or changes the queue's order (adding, taking, removing or clearing), evicts nothing. - Disks. The queue relies on fsync.
- On macOS, fsync doesn't flush the drive's own cache.
- On Windows, a directory can't be fsynced, so directory changes rely on NTFS's journal.
- Network file systems aren't supported, because the lock assumes one machine. Neither is a directory shared by containers that don't share a pid namespace: each takes the other's pid for a dead one.
Limits and performance
Every item lives in memory, as in ProcessQueue. The disk holds a copy, not an overflow.
Each change appends one line to the journal. The changes made in one tick, or while an fsync runs, share one
writeand onefdatasync, up to 1 MiB of them (a longer line goes alone). Throughput is bounded by the disk's fsync rate, divided among the changes that share each fsync.Make changes together, not one at a time. A change resolves only once its fsync is done, so awaiting each before starting the next waits for an fsync per change, often a millisecond or more. Changes started together share fsyncs: use
addManyandtakeMany, or start several calls and then await them all.// Slow: an fsync per email for (const email of batch) await queue.add(email); // Fast: the emails share their fsyncs await queue.addMany(batch);Compaction rewrites the whole queue as a new checkpoint and starts a new journal, deleting the old one:
- when the journal passes 16 MiB or 100,000 records;
- on
compact(); - on every
open.
close()writes a final checkpoint too, and leaves only that. Taking the snapshot, which encodes the queue as it is, is synchronous, and takes time in proportion to the queue's size; writing it isn't synchronous. A failed automatic compaction is tried again after 1 second, then after waits that double, up to 1 minute.Opening reads the checkpoint and the journals since it, 1 MiB at a time, so it takes time in proportion to both, and a queue of any size that fits in memory can be reopened. Replaying 100,000 changes takes well under a second.
A comparator inserts in O(n), as in ProcessQueue.
One open per directory, on a local disk, in any process or thread.
- Each
openwrites a lock file of its own, then reads the others. It has the directory only if none of them is live, so two opens can never both have it, however they interleave, even when they take over a dead process's lock at the same instant. - Opens at the same instant may find each other's locks: all but one back off, for a random time of up to 10 ms, then 20, 40, 80 and 160. One that still finds others contending after 6 tries fails with
ELOCKED. One that finds an open that already has the directory fails at once. - A lock file left by a process that died is removed by the next open to have the directory, if it can be (if not, the open still goes ahead). Content that stays unreadable (a crash between creating the lock and writing it, or a power loss while opens were contending) is waited on for about 5 seconds first, once per open; the lock files are read together, so several take that long in all. A lock caught between being created and written is read again 50 ms later.
- Each
File format
FORMAT_VERSION (2) is the format's version, and a queue refuses a directory written in a newer one. The directory holds:
| File | Content |
|---|---|
| checkpoint | A header record, then one record per entry of the queue's snapshot (see below) |
| journal.<n>.log | The changes since checkpoint <n>, one record line each |
| lock.<token> | An open's lock, named by its random token: <pid> <token> <start>\n, then held\n once that open has the directory. <start> is when the process started; it tells the process's threads, which share its pid, from a later process given the same pid. There may be several while opens contend, or stale ones that crashed opens left. |
| lock | The lock 0.1.0 wrote, <pid> <token>\n. 1.0.0 doesn't write one; it treats a live one as an open that has the directory, and removes a stale one. 0.1.0 doesn't look for 1.0.0's locks, so don't run both on one directory. |
| checkpoint.tmp | A checkpoint being written; a leftover one is ignored and deleted |
Record lines. A record line is <CRC-32 of the JSON, 8 lowercase hex digits> <JSON>\n. The CRC is the IEEE one zlib uses, over the JSON's UTF-8 bytes. A journal line, or a line of a format 2 checkpoint, is at most 65 MiB: an item of up to 64 MiB, and the record around it. A longer one is damage, and the queue never writes one.
The checkpoint. Its first record is {"format":2,"generation":<n>,"counts":{"queue":<q>,"inProcess":<p>,"deadLetterQueue":<d>,"itemState":<s>}}. The records after it are the entries of the ProcessQueue snapshot's lists, bare and in that order: <q> queued items, <p> items in process, <d> dead letters and <s> itemState entries. The file ends after the last one.
Version 0.1.0 wrote format 1, a checkpoint of one record: {"format":1,"generation":<n>,"snapshot":<ProcessQueue snapshot>}. The journals are the same in both formats. 1.0.0 opens a format 1 directory, and its open rewrites the checkpoint in format 2. After that, 0.1.0 refuses the directory: with ECORRUPT, or, if the queue was empty, as written in a newer format.
0.1.0 had no limits on items. In its directories, 1.0.0 reads items nested up to 512 levels deep. open refuses with ECORRUPT, changing nothing, a deeper item, a journal line over 65 MiB, or a checkpoint item too long for one, as a put record in a journal. The one exception: a journal line over 65 MiB at the very end of the newest journal is taken for a torn write, and left out.
Journal records. Each record is a JSON object with an op:
| op | Fields | Meaning |
|---|---|---|
| put | item, at | Queued or updated at time at (ms since the epoch). For an id in process, its release too: a timed-out item queued again. |
| take | ids | Started processing. A large batch is split into records of about 1 MiB of ids each. |
| ack | id | Finished |
| ackAll | | Every in-process item released (not written by this version) |
| delete | id | Removed, evicted or expired |
| retry | id, attempt, retryAt | Failed attempt times; waits until retryAt |
| requeue | id, attempt | Failed attempt times; queued again at once |
| dead | item, error | Failed for good, with the first 1,024 characters of the error's message |
| release | id | Released without being queued again (not written by this version) |
| clear, clearDead | | clear() and clearDeadLetterQueue() |
Recovery.
openloads checkpoint<n>and replays journals<n>,<n+1>, … in order, following ProcessQueue's own rules for where each item goes.- A gap in the journal numbers, or journals with no checkpoint, is corruption. Journal
<n>itself may be missing when nothing follows it. - Only the newest journal's end can be a torn write: a crash can cut short, zero-fill or lose part of the last write, which is at most 1 MiB, or one longer line. A damaged last line, or a damaged line within 1 MiB of the end, is left out, with everything after it; after a crash, none of it was acknowledged. The cost: damage there from a failing disk, to records that were acknowledged, is taken for a torn write too, and they are lost. A damaged line anywhere else is corruption, and
openrefuses withECORRUPTrather than guess. - The recovered queue then becomes checkpoint
<m>, one above the highest number on disk, with a new journal<m>, and the older files are deleted.
Times in the files (at, retryAt, and the snapshot's enqueuedAt and retryAt) come from the machine's clock, so changing the clock moves TTLs and retries, as in ProcessQueue.
Development
Building and testing needs Node 22.12 or later, because Vite and Vitest do.
npm ci
npm run lint # ESLint with typescript-eslint's recommended rules: the source, tests, fixtures and smoke tests
npm run build # Vite bundles dist/persistentQueue.{mjs,cjs}; TypeScript 7's tsc writes the .d.ts files
npm test # tsc type-checks the source and tests, then Vitest runs src/**/*.test.ts with coverage thresholds
npm run test:smoke # node:test smoke checks of the built bundles (smoke/)TypeScript 7 is installed as @typescript/native and provides tsc. The typescript package is an alias of @typescript/typescript6, because typescript-eslint needs the TypeScript 6 API to parse the source.
Some tests read the built dist/, so run npm run build before npm test after changing the source. Among them, the fixtures in test-types/ type-check the published declarations the way consumers use them: through the package's exports map, as ES module and CommonJS code under nodenext resolution, and under bundler resolution.
The crash tests run in two ways:
src/crash.test.tscrashes generated workloads, on an in-memory file system, after any file operation, then checks the guarantees after recovery.smoke/kill.cjskills a real process running the built bundle while it adds, then checks that every add it reported survived. It runs in Vitest and in the smoke suite.
npm test fails when coverage of src/ drops below 95% of lines, functions and statements, or 90% of branches. The HTML report is written to coverage/.
CI runs the full suite on Node 22, 24 and 26 on Linux, and on Node 24 on Windows. The smoke suite in smoke/ uses only node:test and the runtime dependencies, so CI also runs it on Node 20, where the toolchain cannot run, against the bundles built on Node 24.
Changelog
See CHANGELOG.md.
License
Published under the LGPL-2.1 license.
Published by MDaemon Technologies, Ltd.
Simple Secure Email
https://www.mdaemon.com
