API reference

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

function

Creates an independent instance with custom configuration.

createCache(options?: CacheOptions): MemoryCacheEngine
options
Cache configuration (maxItems, defaultTtl, l2Storage, serializer).

Returns Configured .

tsts
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

function

Parses 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.

tsts
duration("500ms"); // 500duration("5m");    // 300_000duration("1h");    // 3_600_000duration("1d");    // 86_400_000duration(undefined, 1000); // 1000

parsePriority

function

Normalizes 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

class

Thrown when cache operations (retrieval, eviction, serialization) fail.

class CacheError extends Error

DoublyLinkedList

class

High-performance Doubly Linked List with strict O(1) insertions, removals, and promotions.

10 members

  • headproperty
    head: ListNode<T> | null

    Head (front) node of the list.

  • tailproperty
    tail: ListNode<T> | null

    Tail (back) node of the list.

  • sizeproperty
    size:

    Current number of elements in the list.

  • append
    append(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 .

  • prepend
    prepend(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 .

  • moveToHead
    moveToHead(node: ListNode<T>): void

    Promotes an existing node directly to the front (head) in O(1) pointer operations.

    node
    The existing node in the list to promote.
  • shift
    shift(): T | null

    Removes 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.

  • pop
    pop(): T | null

    Removes 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.

  • unlink
    unlink(node: ListNode<T>): void

    Decouples an arbitrary node from anywhere in the list in O(1) time.

    node
    The node to decouple.
  • clear
    clear(): void

    Clears all nodes from the list and resets size to 0.

MemoryCacheEngine

class

High-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.

23 members

  • mapproperty
    map:
  • listproperty
    list:
  • tagIndexproperty
    tagIndex:
  • inFlightproperty
    inFlight:
  • hitsproperty
    hits:
  • missesproperty
    misses:
  • writesproperty
    writes:
  • evictionsproperty
    evictions:
  • maxItemsproperty
    maxItems: number
  • defaultTtlMsproperty
    defaultTtlMs: number
  • l2property
    l2?: L2CacheStore
  • serializerproperty
    serializer: CacheSerializer
  • get
    get<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}
  • set
    set<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",});
  • remember
    remember<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"] });
  • triggerBackgroundRefresh
    triggerBackgroundRefresh(key: string, ttl: Duration, factory: () => any, tags?: string[]): void
  • delete
    delete(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.

  • deleteInternal
    deleteInternal(key: string): boolean
  • invalidateTags
    invalidateTags(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"]);
  • tags
    tags(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();
  • evictOldest
    evictOldest(): void
  • clear
    clear(): Promise<void>

    Clears all keys, tags, and inflight tasks from L1 memory and wipes L2 persistent storage.

  • getMetrics
    getMetrics(): CacheStats

    Returns current cache performance metrics (hits, misses, hitRatio, size, evictions).

MemoryQueueO1

class

True O(1) in-memory job queue with discrete priority buckets:

class MemoryQueueO1 implements JobStore

21 members

  • queuesproperty
    queues:
  • activeNodesproperty
    activeNodes:
  • allJobsproperty
    allJobs:
  • uniqueKeysproperty
    uniqueKeys:
  • delayedHeapproperty
    delayedHeap:
  • init
    init(): Promise<void>

    Initializes the in-memory queue store (no-op for memory implementation).

  • getQueueBucket
    getQueueBucket(queue: string, priority: number): DoublyLinkedList<JobRecord>
  • enqueue
    enqueue(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 .

  • promoteDelayed
    promoteDelayed(): void

    Promotes delayed jobs using Lazy Deletion:

  • claimNext
    claimNext(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.

  • heartbeat
    heartbeat(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.

  • updateProgress
    updateProgress(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.
  • complete
    complete(id: string, result?: unknown): Promise<void>

    Marks a job completed and records its return result.

    id
    Job ID.
    result
    Returned output value.
  • fail
    fail(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.
  • reclaimStaleJobs
    reclaimStaleJobs(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.

  • getJob
    getJob(id: string): Promise<JobRecord | null>

    Retrieves a job record by ID.

    id
    Job ID.

    Returns A copy of the or `null` if not found.

  • getMetrics
    getMetrics(queue?: string): Promise<QueueMetrics>

    Returns current job counts partitioned by state.

    queue
    Optional queue name filter.
  • listDead
    listDead(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.

  • replayDead
    replayDead(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.

  • purgeQueue
    purgeQueue(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.

  • close
    close(): Promise<void>

    Clears all jobs, queues, priority buckets, and indices from memory.

MinHeap

class

Binary Min-Heap priority queue used for scheduling delayed jobs by execution timestamp.

class MinHeap

8 members

  • treeproperty
    tree: T[]
  • sizegetter
    size: number

    Total number of elements currently stored in the heap.

  • peek
    peek(): T | null

    Inspects the lowest-scored (root) element without removing it.

    Returns The root item with the lowest score, or `null` if the heap is empty.

  • push
    push(item: T): void

    Inserts an item into the heap and restores min-heap order via bubble-up in O(log N).

    item
    Item to insert.
  • pop
    pop(): T | null

    Removes 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.

  • bubbleUp
    bubbleUp(index: number): void
  • sinkDown
    sinkDown(index: number): void
  • clear
    clear(): void

    Removes all items from the heap.

QueueError

class

Thrown when queue operations (enqueue, claim, lease heartbeat, etc.) fail.

class QueueError extends Error

SQLiteL2CacheStore

class

Persistent 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)

tsts
const 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

  • dbproperty
    db: Database
  • sweepTimerproperty
    sweepTimer?: ReturnType<typeof setInterval>
  • openWithRetry
    openWithRetry(attempts?: ): void

    Applies 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.

  • init
    init()
  • get
    get<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`.

  • set
    set<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).
  • delete
    delete(key: string): Promise<void>

    Removes a cached entry from SQLite by key.

    key
    Cache key to delete.
  • invalidateTags
    invalidateTags(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.

  • cleanupExpired
    cleanupExpired(): Promise<number>

    Manually sweeps and deletes all expired keys from SQLite.

    Returns Total number of expired entries purged.

  • clear
    clear(): Promise<void>

    Deletes all records from the L2 cache table.

  • close
    close(): Promise<void>

    Stops the background sweeper timer and closes the underlying SQLite database connection.

Types

CacheOptions

interface

Configuration options for initializing .

interface CacheOptions

4 members

  • maxItemsproperty
    maxItems?: number

    Maximum number of items in L1 memory before least-recently-used (LRU) eviction occurs.

  • defaultTtlproperty
    defaultTtl?: Duration

    Default time-to-live duration applied to entries when `.set()` is called without an explicit TTL.

  • l2Storageproperty
    l2Storage?: L2CacheStore

    Optional persistent L2 storage adapter (e.g. ).

  • serializerproperty
    serializer?: CacheSerializer

    Serializer used for L2 encoding/decoding.

CacheRegister

interface

Register interface reserved for declaration-merging / module augmentation

interface CacheRegister

CacheSerializer

interface

Serialization adapter interface for encoding and decoding values stored in L2 persistent cache.

interface CacheSerializer

2 members

  • encode
    encode(value: unknown): string

    Serializes a value into a string for storage.

    value
    Raw in-memory payload.
  • decode
    decode<T>(raw: string): T

    Deserializes a string from storage back into the typed payload.

    raw
    Serialized string.

CacheStats

interface

Performance metrics snapshot for .

interface CacheStats

6 members

  • hitsproperty
    hits: number

    Total successful cache lookups (fresh and SWR hits).

  • missesproperty
    misses: number

    Total cache misses (expired or missing keys).

  • writesproperty
    writes: number

    Total write operations performed.

  • evictionsproperty
    evictions: number

    Total items evicted from L1 memory due to `maxItems` capacity limits.

  • sizeproperty
    size: number

    Current count of active keys residing in L1 memory.

  • hitRatioproperty
    hitRatio: number

    Ratio of hits to total lookups (0.0 to 1.0).

JobRecord

interface

Complete record of a background job managed by a .

interface JobRecord<TData = unknown, TResult = unknown>

19 members

  • idproperty
    id: string

    Unique job identifier.

  • queueproperty
    queue: string

    Target queue name (e.g. `"email"`, `"image-processing"`).

  • nameproperty
    name: string

    Descriptive job action or task name.

  • dataproperty
    data: TData

    Input payload data passed into the job.

  • stateproperty
    state: JobState

    Current job lifecycle state.

  • attemptsproperty
    attempts: number

    Number of execution attempts completed so far.

  • maxAttemptsproperty
    maxAttempts: number

    Maximum attempts permitted before the job is moved to the dead-letter state.

  • priorityproperty
    priority: number

    Numerical priority (higher values run first: 3 = critical, 2 = high, 1 = normal, 0 = low).

  • runAtproperty
    runAt: number

    Scheduled execution timestamp in milliseconds since epoch (`Date.now()`).

  • timeoutproperty
    timeout?: number

    Maximum execution time allowed before the lease expires or the job times out (in milliseconds).

  • retryproperty
    retry: RetryPolicy

    Retry and backoff policy applied upon execution failure.

  • leaseproperty
    lease?: { workerId: string; acquiredAt: number; expiresAt: number; }

    Active worker lease metadata while in the `"running"` state.

  • progressproperty
    progress: number

    Execution completion percentage (0 - 100).

  • progressMessageproperty
    progressMessage?: string

    Human-readable status update or progress message.

  • resultproperty
    result?: TResult

    The output result produced upon successful job completion.

  • errorproperty
    error?: SerializedError

    Serialized error details if the job failed or died.

  • uniqueKeyproperty
    uniqueKey?: string

    Unique deduplication key preventing duplicate concurrent enqueuing within the same queue.

  • createdAtproperty
    createdAt: number

    Timestamp when the job was initially created.

  • updatedAtproperty
    updatedAt: number

    Timestamp when the job was last updated or changed state.

JobStore

interface

Storage and state-management interface for job queues.

interface JobStore

14 members

  • init
    init(): Promise<void>

    Initializes database schemas, tables, and indexes for queue persistence.

  • enqueue
    enqueue(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 .

  • claimNext
    claimNext(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.

  • heartbeat
    heartbeat(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.

  • updateProgress
    updateProgress(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.
  • complete
    complete(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.
  • fail
    fail(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.
  • reclaimStaleJobs
    reclaimStaleJobs(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.

  • getJob
    getJob(id: string): Promise<JobRecord | null>

    Fetches a job record by ID.

    id
    Job ID.

    Returns The , or `null` if not found.

  • getMetrics
    getMetrics(queue?: string): Promise<QueueMetrics>

    Returns current queue volume metrics.

    queue
    Optional queue name filter.
  • listDead
    listDead(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.

  • replayDead
    replayDead(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.

  • purgeQueue
    purgeQueue(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.

  • close
    close(): Promise<void>

    Shuts down the store and releases held resources.

L2CacheRecord

interface

Record retrieved from L2 persistent store.

interface L2CacheRecord<T = unknown>

2 members

  • valueproperty
    value: T

    Deserialized payload value.

  • expiresAtproperty
    expiresAt: number | null

    Absolute expiration epoch in milliseconds, or `null` if indefinite.

L2CacheStore

interface

Storage interface for persistent L2 secondary cache adapters (e.g. SQLite, Redis).

interface L2CacheStore

7 members

  • get
    get<T>(key: string): Promise<L2CacheRecord<T> | null>

    Retrieves a record by key.

    key
    Unique cache key.
  • set
    set<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.
  • delete
    delete(key: string): Promise<void>

    Deletes a key from storage.

    key
    Unique cache key.
  • invalidateTags
    invalidateTags(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.

  • cleanupExpired
    cleanupExpired(): Promise<number>

    Purges expired entries from storage.

    Returns Total number of expired entries removed.

  • clear
    clear(): Promise<void>

    Truncates all records from the L2 store.

  • close
    close(): Promise<void>

    Closes the underlying storage connection and terminates background timers.

ListNode

interface

Doubly linked node structure for .

interface ListNode<T>

3 members

  • valueproperty
    value: T

    Payload value.

  • prevproperty
    prev: ListNode<T> | null

    Pointer to predecessor node, or `null` if head.

  • nextproperty
    next: ListNode<T> | null

    Pointer to successor node, or `null` if tail.

QueueMetrics

interface

Real-time queue operational metrics by job state.

interface QueueMetrics

6 members

  • queuedproperty
    queued: number

    Count of jobs ready and waiting to be processed.

  • delayedproperty
    delayed: number

    Count of jobs scheduled for future execution.

  • runningproperty
    running: number

    Count of jobs currently claimed and being processed by workers.

  • completedproperty
    completed: number

    Count of successfully processed jobs.

  • deadproperty
    dead: number

    Count of jobs in the dead-letter queue (exhausted retries).

  • totalproperty
    total: number

    Total count of all jobs across all states.

RememberOptions

interface

Options for `.remember()` singleflight computation.

interface RememberOptions

1 member

  • forceproperty
    force?: boolean

    When `true`, bypasses any existing cached or stale value and forces immediate execution of the factory.

RetryPolicy

interface

Retry and backoff configuration for failed jobs.

interface RetryPolicy

5 members

  • typeproperty
    type: "exponential" | "fixed"

    Backoff strategy:

  • delayproperty
    delay: number

    Initial delay duration in milliseconds before the first retry attempt.

  • factorproperty
    factor: number

    Exponential multiplier factor (e.g. `2` for doubling delay each attempt).

  • jitterproperty
    jitter: boolean

    Whether to apply random jitter to prevent the "thundering herd" problem.

  • maxDelayproperty
    maxDelay: number

    Maximum upper bound in milliseconds for any retry delay.

SerializedError

interface

Serialized error details saved onto failed or dead jobs for inspection and debugging.

interface SerializedError

3 members

  • messageproperty
    message: string

    Error message string.

  • stackproperty
    stack?: string

    Error stack trace if available.

  • codeproperty
    code?: string

    Error code or category identifier.

SetOptions

interface

Configuration options for storing entries in cache via `.set()` or `.remember()`.

interface SetOptions

4 members

  • ttlproperty
    ttl?: Duration

    Time-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).

  • swrproperty
    swr?: Duration

    Stale-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()`.

  • tagsproperty
    tags?: string[]

    Relational categorization tags for bulk invalidation (e.g. `["users", "org:123"]`).

  • consistencyproperty
    consistency?: CacheConsistency

    Persistence consistency mode for writing to L2 cache.

CacheConsistency

type

L2 persistence consistency mode:

type CacheConsistency = "async" | "sync"

CacheValue

type

Resolves the registered cache value type for a key, or `any` if unregistered.

type CacheValue<K extends string> = K extends keyof RegisteredCache ? RegisteredCache[K] : any

Duration

type

Human-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"}` | number

JobState

type

Represents the current execution lifecycle state of a queued job:

type JobState = "queued" | "delayed" | "running" | "completed" | "dead"

Priority

type

Named discrete priority levels for background jobs.

type Priority = "critical" | "high" | "normal" | "low"

RegisteredCache

type

Registered type mapping for global cache keys.

Tip
Most of the types above are inferred. You rarely import AuthConfig or JobPayload — declaring your schema once is enough for the rest to follow. See Typed keys.