yatta/cache
L1 memory and L2 SQLite caching, singleflight, SWR.
30 exported symbols and 149 members, read from src/types/cache_queue.ts.
Construct
createCache
functionCreates an independent instance with custom configuration.
createCache(options?: CacheOptions): MemoryCacheEngine- options
- Cache configuration (maxItems, defaultTtl, l2Storage, serializer).
Returns Configured .
import { createCache, SQLiteL2CacheStore } from "./cache_queue"; const userCache = createCache({ maxItems: 10_000, defaultTtl: "30m", l2Storage: new SQLiteL2CacheStore("Database/users_cache.db"),}); await userCache.set("user:42", { name: "Bob" }, { swr: "5m" });duration
functionParses a human-readable duration string into milliseconds.
duration(value?: Duration, fallbackMs?: ): number- value
- Duration string (e.g. `"5m"`, `"1h"`) or numeric milliseconds.
- fallbackMs
- Fallback millisecond value if `value` is `null` or `undefined`. Defaults to 0.
Returns Parsed duration in milliseconds.
duration("500ms"); // 500duration("5m"); // 300_000duration("1h"); // 3_600_000duration("1d"); // 86_400_000duration(undefined, 1000); // 1000parsePriority
functionNormalizes a named priority string or number to an integer priority tier (0–3).
Mappings: - `"critical"` or `>= 3` -> `3` - `"high"` or `2` -> `2` - `"normal"` or `1` -> `1` (default fallback) - `"low"` or `<= 0` -> `0`
parsePriority(p?: Priority | number): number- p
- Named priority string or numerical tier.
Returns Normalized priority integer: 3, 2, 1, or 0.
CacheError
classThrown when cache operations (retrieval, eviction, serialization) fail.
class CacheError extends ErrorDoublyLinkedList
classHigh-performance Doubly Linked List with strict O(1) insertions, removals, and promotions.
class DoublyLinkedList10 members
headpropertyhead: ListNode<T> | nullHead (front) node of the list.
tailpropertytail: ListNode<T> | nullTail (back) node of the list.
sizepropertysize:Current number of elements in the list.
appendappend(value: T): ListNode<T>Appends an element to the back (tail) of the list in O(1) time complexity.
- value
- Item to add.
Returns Newly created .
prependprepend(value: T): ListNode<T>Prepends an element to the front (head) of the list in O(1) time complexity.
- value
- Item to add.
Returns Newly created .
moveToHeadmoveToHead(node: ListNode<T>): voidPromotes an existing node directly to the front (head) in O(1) pointer operations.
- node
- The existing node in the list to promote.
shiftshift(): T | nullRemoves and returns the value at the head (front) of the list in O(1).
Returns Value of the removed head node, or `null` if the list is empty.
poppop(): T | nullRemoves and returns the value at the tail (back) of the list in O(1).
Returns Value of the removed tail node, or `null` if the list is empty.
unlinkunlink(node: ListNode<T>): voidDecouples an arbitrary node from anywhere in the list in O(1) time.
- node
- The node to decouple.
clearclear(): voidClears all nodes from the list and resets size to 0.
MemoryCacheEngine
classHigh-Performance Multi-Tier Cache Engine.
Features: - O(1) in-memory L1 LRU caching backed by doubly linked list pointers. - Optional durable L2 persistence with TTL-preserving backfill. - Singleflight promise coalescing (prevents dog-piling / thundering herd on concurrent cache misses). - Stale-While-Revalidate (SWR) support for instant reads with asynchronous refresh. - Indexed relational tag invalidation.
class MemoryCacheEngine23 members
mappropertymap:listpropertylist:tagIndexpropertytagIndex:inFlightpropertyinFlight:hitspropertyhits:missespropertymisses:writespropertywrites:evictionspropertyevictions:maxItemspropertymaxItems: numberdefaultTtlMspropertydefaultTtlMs: numberl2propertyl2?: L2CacheStoreserializerpropertyserializer: CacheSerializergetget<T = unknown>(key: string): Promise<T | null>Retrieves a cached value from L1 memory, or backfills from L2 preserving remaining TTL.
- key
- Unique cache key.
Returns The cached value if present and unexpired; otherwise `null`.
tsts const user = await cache.get<User>("user:123");if (!user) { // Cache miss}setset<T = unknown>(key: string, value: T, options?: SetOptions): Promise<void>Stores a value in L1 memory and optional L2 storage with TTL, SWR grace periods, and relational tags.
- key
- Unique cache key.
- value
- Value to cache.
- options
- Cache parameters (ttl, swr, tags, consistency).
tsts await cache.set("user:42", userData, { ttl: "15m", swr: "1h", tags: ["users", "user:42"], consistency: "async",});rememberremember<T = unknown>(key: string, ttl: Duration, factory: () => Promise<T> | T, options?: Omit<RememberOptions, "ttl">): Promise<T>Singleflight memoization with Stale-While-Revalidate (SWR) support.
Execution Flow: 1. **L1 Fresh Hit**: If key exists and `now <= expiresAt`, returns immediately. 2. **SWR Grace Hit**: If expired but `now <= swrUntil`, returns the stale value immediately and triggers an asynchronous background execution of `factory` to refresh the entry. 3. **Singleflight Miss**: If not cached or expired beyond SWR: - Coalesces concurrent calls to the same key into a single shared execution promise (prevents thundering herd). - Awaits `factory()`, sets L1/L2 cache, and returns the freshly produced value.
- key
- Unique cache key.
- ttl
- Time-to-live duration string or milliseconds.
- factory
- Asynchronous or synchronous producer function invoked on cache miss or SWR refresh.
- options
- Additional options (`swr`, `tags`, `consistency`, `force`).
Returns The fresh or cached value.
tsts const profile = await cache.remember(`profile:${userId}`, "10m", async () => { return await fetchRemoteProfile(userId);}, { swr: "1h", tags: ["profiles"] });triggerBackgroundRefreshtriggerBackgroundRefresh(key: string, ttl: Duration, factory: () => any, tags?: string[]): voiddeletedelete(key: string): Promise<boolean>Deletes a specific key from L1 memory and L2 storage.
- key
- Key to remove.
Returns `true` if key was present in L1 memory.
deleteInternaldeleteInternal(key: string): booleaninvalidateTagsinvalidateTags(tags: string | string[]): Promise<number>Evicts all keys associated with one or more tags across L1 memory and L2 persistent storage.
- tags
- Tag string or array of tag strings to invalidate.
Returns Total number of keys evicted from **L1 memory** (L2 records are removed concurrently).
tsts await cache.invalidateTags(["users", "user:42"]);tagstags(tags: string | string[])Fluent helper targeting a specific tag or list of tags for group invalidation.
- tags
- Tag or array of tags.
Returns Object providing an `.invalidate()` method.
tsts await cache.tags("users").invalidate();evictOldestevictOldest(): voidclearclear(): Promise<void>Clears all keys, tags, and inflight tasks from L1 memory and wipes L2 persistent storage.
getMetricsgetMetrics(): CacheStatsReturns current cache performance metrics (hits, misses, hitRatio, size, evictions).
MemoryQueueO1
classTrue O(1) in-memory job queue with discrete priority buckets:
class MemoryQueueO1 implements JobStore21 members
queuespropertyqueues:activeNodespropertyactiveNodes:allJobspropertyallJobs:uniqueKeyspropertyuniqueKeys:delayedHeappropertydelayedHeap:initinit(): Promise<void>Initializes the in-memory queue store (no-op for memory implementation).
getQueueBucketgetQueueBucket(queue: string, priority: number): DoublyLinkedList<JobRecord>enqueueenqueue(job: Omit<JobRecord, "attempts" | "state" | "createdAt" | "updatedAt">): Promise<JobRecord>Enqueues a new job into the appropriate priority bucket or delayed min-heap.
- job
- Partial job definition without timestamps and initial state.
Returns Newly scheduled or existing matching .
promoteDelayedpromoteDelayed(): voidPromotes delayed jobs using Lazy Deletion:
claimNextclaimNext(queue: string, workerId: string, lockDurationMs: number): Promise<JobRecord | null>Strict O(1) Queue Claim:
- queue
- Target queue name.
- workerId
- Claiming worker ID.
- lockDurationMs
- Lock duration in milliseconds.
Returns Claimed or `null` if none available.
heartbeatheartbeat(id: string, workerId: string, lockDurationMs: number): Promise<boolean>Renews the active worker lease for a running job.
- id
- Job ID.
- workerId
- ID of worker holding current lease.
- lockDurationMs
- Lease extension in milliseconds.
Returns `true` if lease renewed, `false` otherwise.
updateProgressupdateProgress(id: string, progress: number, message?: string): Promise<void>Updates progress and status message for a running job.
- id
- Job ID.
- progress
- Progress percentage (0 - 100).
- message
- Optional status message.
completecomplete(id: string, result?: unknown): Promise<void>Marks a job completed and records its return result.
- id
- Job ID.
- result
- Returned output value.
failfail(id: string, error: SerializedError, nextRunAt?: number, dead?: ): Promise<void>Handles job failure, updating retry state or moving to the dead-letter queue.
- id
- Job ID.
- error
- Serialized error object.
- nextRunAt
- Timestamp to re-attempt execution.
- dead
- Whether retries have been exhausted.
reclaimStaleJobsreclaimStaleJobs(staleThresholdMs: number): Promise<number>Scans running jobs and resets abandoned ones (expired lease or exceeding threshold) back to queued.
- staleThresholdMs
- Stale lease threshold in milliseconds.
Returns Total number of recovered jobs.
getJobgetJob(id: string): Promise<JobRecord | null>Retrieves a job record by ID.
- id
- Job ID.
Returns A copy of the or `null` if not found.
getMetricsgetMetrics(queue?: string): Promise<QueueMetrics>Returns current job counts partitioned by state.
- queue
- Optional queue name filter.
listDeadlistDead(queue?: string, limit?: ): Promise<JobRecord[]>Lists jobs in the dead-letter queue.
- queue
- Optional queue filter.
- limit
- Maximum results to return (default: 50).
Returns Array of dead s.
replayDeadreplayDead(id: string): Promise<boolean>Resurrects a dead-letter job and requeues it for execution.
- id
- Job ID to replay.
Returns `true` if replayed, `false` if not dead or not found.
purgeQueuepurgeQueue(queue: string, state?: JobState): Promise<number>Purges all jobs for a queue, optionally filtered by state.
- queue
- Target queue name.
- state
- Optional lifecycle state to purge.
Returns Count of removed jobs.
closeclose(): Promise<void>Clears all jobs, queues, priority buckets, and indices from memory.
MinHeap
classBinary Min-Heap priority queue used for scheduling delayed jobs by execution timestamp.
class MinHeap8 members
treepropertytree: T[]sizegettersize: numberTotal number of elements currently stored in the heap.
peekpeek(): T | nullInspects the lowest-scored (root) element without removing it.
Returns The root item with the lowest score, or `null` if the heap is empty.
pushpush(item: T): voidInserts an item into the heap and restores min-heap order via bubble-up in O(log N).
- item
- Item to insert.
poppop(): T | nullRemoves and returns the lowest-scored (root) element from the heap in O(log N).
Returns The root item with the lowest score, or `null` if the heap is empty.
bubbleUpbubbleUp(index: number): voidsinkDownsinkDown(index: number): voidclearclear(): voidRemoves all items from the heap.
QueueError
classThrown when queue operations (enqueue, claim, lease heartbeat, etc.) fail.
class QueueError extends ErrorSQLiteL2CacheStore
classPersistent SQLite-backed secondary cache (L2) with support for time-to-live (TTL),
Configured with: - `PRAGMA journal_mode = WAL;` (Concurrent reads while writing) - `PRAGMA synchronous = NORMAL;` (High throughput with crash resilience) - `PRAGMA foreign_keys = ON;` (Cascading tag deletes)
class SQLiteL2CacheStore implements L2CacheStoreconst l2 = new SQLiteL2CacheStore("Database/cache.db");await l2.set("user:123", { name: "Alice" }, 60_000, ["users"]);const record = await l2.get("user:123");11 members
dbpropertydb: DatabasesweepTimerpropertysweepTimer?: ReturnType<typeof setInterval>openWithRetryopenWithRetry(attempts?: ): voidApplies pragmas and creates the schema, retrying briefly on SQLITE_BUSY.
Switching a database into WAL mode itself requires a lock, so it can fail with SQLITE_BUSY when several worker threads open the same file at once — before busy_timeout has any effect on the remaining DDL. Retrying the whole open sequence (not just init) is what makes mounting `cache` reliable.
initinit()getget<T>(key: string): Promise<L2CacheRecord<T> | null>Retrieves a cached value and its expiration metadata from SQLite.
- key
- Unique cache key.
Returns Deserialized if found and valid, otherwise `null`.
setset<T>(key: string, value: T, ttlMs?: number, tags?: string[]): Promise<void>Writes a value into SQLite with optional TTL and relational tags.
- key
- Unique cache key.
- value
- Value to serialize and store.
- ttlMs
- Time-to-live in milliseconds from now (optional).
- tags
- Array of tags for grouped invalidation (optional).
deletedelete(key: string): Promise<void>Removes a cached entry from SQLite by key.
- key
- Cache key to delete.
invalidateTagsinvalidateTags(tags: string[]): Promise<number>Evicts all cache keys linked to any of the specified tags.
- tags
- Array of tag identifiers to invalidate.
Returns Total number of cache keys deleted.
cleanupExpiredcleanupExpired(): Promise<number>Manually sweeps and deletes all expired keys from SQLite.
Returns Total number of expired entries purged.
clearclear(): Promise<void>Deletes all records from the L2 cache table.
closeclose(): Promise<void>Stops the background sweeper timer and closes the underlying SQLite database connection.
Types
CacheOptions
interfaceConfiguration options for initializing .
interface CacheOptions4 members
maxItemspropertymaxItems?: numberMaximum number of items in L1 memory before least-recently-used (LRU) eviction occurs.
defaultTtlpropertydefaultTtl?: DurationDefault time-to-live duration applied to entries when `.set()` is called without an explicit TTL.
l2Storagepropertyl2Storage?: L2CacheStoreOptional persistent L2 storage adapter (e.g. ).
serializerpropertyserializer?: CacheSerializerSerializer used for L2 encoding/decoding.
CacheRegister
interfaceRegister interface reserved for declaration-merging / module augmentation
interface CacheRegisterCacheSerializer
interfaceSerialization adapter interface for encoding and decoding values stored in L2 persistent cache.
interface CacheSerializer2 members
encodeencode(value: unknown): stringSerializes a value into a string for storage.
- value
- Raw in-memory payload.
decodedecode<T>(raw: string): TDeserializes a string from storage back into the typed payload.
- raw
- Serialized string.
CacheStats
interfacePerformance metrics snapshot for .
interface CacheStats6 members
hitspropertyhits: numberTotal successful cache lookups (fresh and SWR hits).
missespropertymisses: numberTotal cache misses (expired or missing keys).
writespropertywrites: numberTotal write operations performed.
evictionspropertyevictions: numberTotal items evicted from L1 memory due to `maxItems` capacity limits.
sizepropertysize: numberCurrent count of active keys residing in L1 memory.
hitRatiopropertyhitRatio: numberRatio of hits to total lookups (0.0 to 1.0).
JobRecord
interfaceComplete record of a background job managed by a .
interface JobRecord<TData = unknown, TResult = unknown>19 members
idpropertyid: stringUnique job identifier.
queuepropertyqueue: stringTarget queue name (e.g. `"email"`, `"image-processing"`).
namepropertyname: stringDescriptive job action or task name.
datapropertydata: TDataInput payload data passed into the job.
statepropertystate: JobStateCurrent job lifecycle state.
attemptspropertyattempts: numberNumber of execution attempts completed so far.
maxAttemptspropertymaxAttempts: numberMaximum attempts permitted before the job is moved to the dead-letter state.
prioritypropertypriority: numberNumerical priority (higher values run first: 3 = critical, 2 = high, 1 = normal, 0 = low).
runAtpropertyrunAt: numberScheduled execution timestamp in milliseconds since epoch (`Date.now()`).
timeoutpropertytimeout?: numberMaximum execution time allowed before the lease expires or the job times out (in milliseconds).
retrypropertyretry: RetryPolicyRetry and backoff policy applied upon execution failure.
leasepropertylease?: { workerId: string; acquiredAt: number; expiresAt: number; }Active worker lease metadata while in the `"running"` state.
progresspropertyprogress: numberExecution completion percentage (0 - 100).
progressMessagepropertyprogressMessage?: stringHuman-readable status update or progress message.
resultpropertyresult?: TResultThe output result produced upon successful job completion.
errorpropertyerror?: SerializedErrorSerialized error details if the job failed or died.
uniqueKeypropertyuniqueKey?: stringUnique deduplication key preventing duplicate concurrent enqueuing within the same queue.
createdAtpropertycreatedAt: numberTimestamp when the job was initially created.
updatedAtpropertyupdatedAt: numberTimestamp when the job was last updated or changed state.
JobStore
interfaceStorage and state-management interface for job queues.
interface JobStore14 members
initinit(): Promise<void>Initializes database schemas, tables, and indexes for queue persistence.
enqueueenqueue(job: Omit<JobRecord, "attempts" | "state" | "createdAt" | "updatedAt">): Promise<JobRecord>Enqueues a new job into the queue or delayed heap.
- job
- Job specifications without generated timestamps and initial state.
Returns The newly created or existing .
claimNextclaimNext(queue: string, workerId: string, lockDurationMs: number): Promise<JobRecord | null>Atomically claims the next highest-priority ready job in the specified queue.
- queue
- Target queue name.
- workerId
- Unique identifier of the requesting worker.
- lockDurationMs
- Lease duration in milliseconds before the job can be reclaimed if lost.
Returns Claimed with active lease, or `null` if no ready jobs exist.
heartbeatheartbeat(id: string, workerId: string, lockDurationMs: number): Promise<boolean>Renews the active lease for a currently running job to prevent premature reclamation.
- id
- Job ID.
- workerId
- Worker holding the lease.
- lockDurationMs
- Milliseconds to extend the lock by.
Returns `true` if heartbeat succeeded; `false` if job was lost or lease mismatch.
updateProgressupdateProgress(id: string, progress: number, message?: string): Promise<void>Updates execution progress and optional status message for a running job.
- id
- Job ID.
- progress
- Percentage complete (0 - 100).
- message
- Optional progress description.
completecomplete(id: string, result?: unknown): Promise<void>Marks a job as completed and stores its result.
- id
- Job ID.
- result
- Optional returned value from the job handler.
failfail(id: string, error: SerializedError, nextRunAt?: number, dead?: boolean): Promise<void>Marks a job as failed, scheduling a retry or moving it to dead-letter state.
- id
- Job ID.
- error
- Serialized error object.
- nextRunAt
- Optional scheduled timestamp for retry.
- dead
- Whether all retry attempts are exhausted.
reclaimStaleJobsreclaimStaleJobs(staleThresholdMs: number): Promise<number>Reclaims running jobs whose leases expired or became orphaned back to the queued state.
- staleThresholdMs
- Time elapsed in milliseconds before a running job is deemed abandoned.
Returns Total number of reclaimed jobs.
getJobgetJob(id: string): Promise<JobRecord | null>Fetches a job record by ID.
- id
- Job ID.
Returns The , or `null` if not found.
getMetricsgetMetrics(queue?: string): Promise<QueueMetrics>Returns current queue volume metrics.
- queue
- Optional queue name filter.
listDeadlistDead(queue?: string, limit?: number): Promise<JobRecord[]>Retrieves jobs currently residing in the dead-letter queue.
- queue
- Optional queue name filter.
- limit
- Maximum number of records to return. Defaults to 50.
Returns List of dead s.
replayDeadreplayDead(id: string): Promise<boolean>Requeues a dead job for execution, resetting attempts and clearing errors.
- id
- Job ID.
Returns `true` if replayed, `false` if not found or not in dead state.
purgeQueuepurgeQueue(queue: string, state?: JobState): Promise<number>Purges jobs from the queue.
- queue
- Queue name.
- state
- Optional state filter to only purge jobs in a specific state.
Returns Count of purged jobs.
closeclose(): Promise<void>Shuts down the store and releases held resources.
L2CacheRecord
interfaceRecord retrieved from L2 persistent store.
interface L2CacheRecord<T = unknown>2 members
valuepropertyvalue: TDeserialized payload value.
expiresAtpropertyexpiresAt: number | nullAbsolute expiration epoch in milliseconds, or `null` if indefinite.
L2CacheStore
interfaceStorage interface for persistent L2 secondary cache adapters (e.g. SQLite, Redis).
interface L2CacheStore7 members
getget<T>(key: string): Promise<L2CacheRecord<T> | null>Retrieves a record by key.
- key
- Unique cache key.
setset<T>(key: string, value: T, ttlMs?: number, tags?: string[]): Promise<void>Stores a record with TTL and relational tags.
- key
- Unique cache key.
- value
- Payload to store.
- ttlMs
- Time-to-live in milliseconds from now.
- tags
- Relational tags for group invalidation.
deletedelete(key: string): Promise<void>Deletes a key from storage.
- key
- Unique cache key.
invalidateTagsinvalidateTags(tags: string[]): Promise<number>Invalidates all keys matching any of the specified tags.
- tags
- Array of tags to purge.
Returns Total number of rows/keys deleted.
cleanupExpiredcleanupExpired(): Promise<number>Purges expired entries from storage.
Returns Total number of expired entries removed.
clearclear(): Promise<void>Truncates all records from the L2 store.
closeclose(): Promise<void>Closes the underlying storage connection and terminates background timers.
ListNode
interfaceDoubly linked node structure for .
interface ListNode<T>3 members
valuepropertyvalue: TPayload value.
prevpropertyprev: ListNode<T> | nullPointer to predecessor node, or `null` if head.
nextpropertynext: ListNode<T> | nullPointer to successor node, or `null` if tail.
QueueMetrics
interfaceReal-time queue operational metrics by job state.
interface QueueMetrics6 members
queuedpropertyqueued: numberCount of jobs ready and waiting to be processed.
delayedpropertydelayed: numberCount of jobs scheduled for future execution.
runningpropertyrunning: numberCount of jobs currently claimed and being processed by workers.
completedpropertycompleted: numberCount of successfully processed jobs.
deadpropertydead: numberCount of jobs in the dead-letter queue (exhausted retries).
totalpropertytotal: numberTotal count of all jobs across all states.
RememberOptions
interfaceOptions for `.remember()` singleflight computation.
interface RememberOptions1 member
forcepropertyforce?: booleanWhen `true`, bypasses any existing cached or stale value and forces immediate execution of the factory.
RetryPolicy
interfaceRetry and backoff configuration for failed jobs.
interface RetryPolicy5 members
typepropertytype: "exponential" | "fixed"Backoff strategy:
delaypropertydelay: numberInitial delay duration in milliseconds before the first retry attempt.
factorpropertyfactor: numberExponential multiplier factor (e.g. `2` for doubling delay each attempt).
jitterpropertyjitter: booleanWhether to apply random jitter to prevent the "thundering herd" problem.
maxDelaypropertymaxDelay: numberMaximum upper bound in milliseconds for any retry delay.
SerializedError
interfaceSerialized error details saved onto failed or dead jobs for inspection and debugging.
interface SerializedError3 members
messagepropertymessage: stringError message string.
stackpropertystack?: stringError stack trace if available.
codepropertycode?: stringError code or category identifier.
SetOptions
interfaceConfiguration options for storing entries in cache via `.set()` or `.remember()`.
interface SetOptions4 members
ttlpropertyttl?: DurationTime-to-live before entry expires (e.g. `"5m"`, `"1h"`, `300000`).
Behavior: - If omitted, falls back to the cache instance's configured `defaultTtl`. - If explicitly `0` (or if instance has no default TTL), persists indefinitely (subject to LRU eviction).
swrpropertyswr?: DurationStale-While-Revalidate window (e.g. `"15m"`).
During this grace period after TTL expiration: - Calls return the stale cached value immediately. - A background asynchronous refresh is triggered using the factory function in `.remember()`.
tagspropertytags?: string[]Relational categorization tags for bulk invalidation (e.g. `["users", "org:123"]`).
consistencypropertyconsistency?: CacheConsistencyPersistence consistency mode for writing to L2 cache.
CacheConsistency
typeL2 persistence consistency mode:
type CacheConsistency = "async" | "sync"CacheValue
typeResolves the registered cache value type for a key, or `any` if unregistered.
type CacheValue<K extends string> = K extends keyof RegisteredCache ? RegisteredCache[K] : anyDuration
typeHuman-readable duration string or raw milliseconds as a number.
Supported units: - `"ms"`: Milliseconds - `"s"`: Seconds - `"m"`: Minutes - `"h"`: Hours - `"d"`: Days - `"w"`: Weeks
type Duration = `${number}${"ms" | "s" | "m" | "h" | "d" | "w"}` | numberJobState
typeRepresents the current execution lifecycle state of a queued job:
type JobState = "queued" | "delayed" | "running" | "completed" | "dead"Priority
typeNamed discrete priority levels for background jobs.
type Priority = "critical" | "high" | "normal" | "low"RegisteredCache
typeRegistered type mapping for global cache keys.
type RegisteredCache = CacheRegisterAuthConfig or JobPayload — declaring your schema once is enough for the rest to follow. See Typed keys.