Introducing a new way to review your PRs.

Read the announcement

karakeep-app / karakeep

A self-hostable bookmark-everything app (links, notes and images) with AI-based automatic tagging and full text search

View on GitHub

21 documents · Updated Nov 23, 2026

docs / queue-execution-backends

Queue execution backends

The queue system moves slow or retryable application work out of the request path. It gives producers one contract for scheduling typed jobs while allowing the runtime to use either a local SQLite-backed Liteque worker or a Restate service-based worker. These jobs support content capture, enrichment, search indexing, and related background work described in search, inference, and plugins.

System role

Queues connect user-facing actions to work that can run later. A producer places a typed payload on a named queue, and a runner takes the job when capacity is available. This keeps request handling separate from work that may need network access, retries, or a long run time.

The queue layer is one part of the wider background system. Background processing gives the broader job model. Content ingestion and enrichment jobs and automation and operations jobs describe important consumers. Search and vector retrieval explains the search work that some queues feed.

flowchart LR
    A[Application action] --> B[Typed queue payload]
    B --> C[Named queue]
    C --> D[Scheduler]
    D --> E[Runner]
    E --> F[Application work]
    E --> G[Complete or error callback]
    G --> H[Downstream state]

The application does not select queue storage at each call site. The plugin system supplies the active queue client, so producers and workers use the same queue contract across both backends.

References: packages/…/queueing.ts• L74-104 packages/…/queues.ts• L19-78 packages/…/plugins.ts• L9-31

Queue contract

The common contract in packages/…/queueing.ts defines a queue as a named place for typed payloads and a runner as the component that executes them. It separates scheduling data from application logic, so the same job code can run with either backend.

Contract areaPurpose
Queue identityA stable name identifies the queue. Creating the same queue again must use the same retry and failed-job settings.
Enqueue optionsAn optional idempotency key prevents duplicate work. Priority controls order. A delay defers work. A group ID supports fair scheduling between groups.
Queue settingsThe queue sets the default retry count and whether failed jobs remain available for inspection.
Job dataA runner receives the job ID, typed payload, priority, run number, retries left, and an abort signal for the time limit.
Runner callbacksrun performs the work. onComplete handles a result. onError receives a failed attempt and its remaining retry count.
Client lifecycleThe client prepares storage or services, starts execution, creates queues and runners, and can shut down when the backend supports it.

Queue payloads are validated at their boundaries when a schema is supplied. The server defines these payload schemas beside the named queues, which keeps the producer contract close to the work classification.

References: packages/…/queueing.ts• L10-24 packages/…/queueing.ts• L44-104 packages/…/queues.ts• L80-337

Job lifecycle

Both backends follow the same high-level lifecycle. The backend assigns a job ID, waits for any delay and available capacity, invokes the runner, and then reports success or failure through the callback contract.

sequenceDiagram
    participant P as Producer
    participant Q as Queue
    participant R as Runner
    participant C as Callback

    P->>Q: enqueue(payload, options)
    Q-->>P: job ID
    Q->>R: deliver job when eligible
    R->>R: validate and run work
    alt success
        R->>C: onComplete(job, result)
    else retryable error
        R->>Q: release and retry
    else final error
        R->>C: onError(job, error)
    end

QueueRetryAfterError marks a temporary wait such as rate limiting. The backends delay that job without consuming its normal retry allowance. Other errors consume the configured retry budget. A timeout supplies an abort signal to the work and allows the backend to make the slot available again.

References: packages/…/queueing.ts• L10-18 packages/…/queueing.ts• L44-72 packages/…/index.ts• L97-142 packages/…/dispatcher.ts• L81-211

Application work queues

The server groups background work by the kind of state it changes. Each group has a typed payload and its own retry policy, which keeps failures in one kind of work from directly changing another kind of work.

Work groupQueue relationship
Link captureMain and low-priority crawler queues fetch links. The separate low-priority queue protects normal crawling from import load.
AI workThe inference queue handles summaries and tags. The embedding queue separates embedding creation, vector indexing, and vector deletion.
Search stateSearch indexing jobs index or delete a bookmark in the search store. A reindex request uses a bookmark-derived idempotency key.
Maintenance and integrationsAsset cleanup, video work, feeds, webhooks, rules, and backups run as independent queue workloads.

The embedding flow shows why a queue contract matters across stages. An embed job can produce one vector and pass it to both the tagging path and the index path. Index retries then stay separate from tagging, so a slow search index does not repeat the tag operation.

References: packages/…/queues.ts• L80-191 packages/…/queues.ts• L231-245 packages/…/queues.ts• L247-337

Liteque backend

Liteque is the local execution backend. It stores queue state in the application data directory through SQLite, so a worker can schedule and execute jobs without a separate queue service. Preparation applies the database migration, while start and shutdown do not need a service process.

The Liteque provider adapts the shared contract to Liteque's queue and runner APIs. It polls for work, applies the configured concurrency and timeout, returns string job IDs, and exposes queue statistics. It also maps QueueRetryAfterError to Liteque's delayed-retry result, which preserves the common retry meaning.

Liteque runs the runner in the application process. This suits a simple deployment with local durable queue state. The runner also supports draining work until the queue is empty, which is useful for controlled worker processes.

References: packages/…/index.ts• L27-63 packages/…/index.ts• L65-95 packages/…/index.ts• L97-148 packages/…/index.ts• L1-10

Restate backend

Restate is the service-based execution backend. Enqueue sends an invocation to a Restate service for the named queue, and Restate keeps the invocation durable while the work waits or retries. The provider is registered only when Restate is configured through RESTATE_LISTEN_PORT.

Each queue has two Restate roles. The dispatcher owns scheduling and retry decisions. The private runner owns payload validation and application callbacks. This split lets scheduling remain durable and lets runner capacity be shared across invocations.

flowchart LR
    A[Queue enqueue] --> B[Restate dispatcher]
    B --> C[Queue semaphore]
    C -->|lease granted| D[Private runner]
    D --> E[run]
    E --> F{Result}
    F -->|success| G[onCompleted]
    F -->|temporary wait| B
    F -->|error and retry| H[onError and retry]
    G --> I[Release lease]
    H --> I

The semaphore limits active jobs and chooses eligible work by priority. Lower numeric priority values run first. Jobs with the same priority can use group IDs so one busy group does not take all available turns. An idempotency key is checked before a queued item is accepted. Leases expire after a timeout window, which prevents a stalled invocation from holding capacity forever.

The dispatcher counts ordinary failures against the queue retry setting and applies a delay before the next attempt. A rate-limit result releases the lease and waits without increasing the attempt number. The runner sends errors across the service boundary as simple name, message, and stack data, then rebuilds the error for onError.

The Restate queue client reports pending and running work through its shared statistics shape. Restate retrying and failed invocation states are not represented in that shape, so operators must use Restate service statistics for those states.

References: packages/…/index.ts• L8-31 packages/…/index.ts• L23-95 packages/…/index.ts• L97-127 packages/…/index.ts• L129-219 packages/…/dispatcher.ts• L15-214 packages/…/runner.ts• L29-168 packages/…/semaphore.ts• L149-253 packages/…/types.ts• L6-58

Backend selection and lifecycle

The server loads queue providers before it first needs a queue client. Queue objects are also created lazily, so importing the queue definitions does not require the selected backend to be ready. The first queue operation creates one cached client and one cached instance for each queue name.

Provider order controls selection. The server loads Liteque first and Restate second. The plugin manager uses the last registered provider, so a configured Restate provider replaces Liteque. Without Restate configuration, Liteque remains the active provider.

The application prepares and starts the selected client as part of worker startup. Liteque preparation covers local database setup. Restate startup exposes dispatcher and runner services according to its deployment settings. Restate can expose both roles in one process or enable them in separate deployments.

References: packages/…/plugins.ts• L16-40 packages/…/queues.ts• L19-78 packages/…/plugins.ts• L61-89 packages/…/index.ts• L65-78 packages/…/index.ts• L8-31 packages/…/index.ts• L140-182 packages/…/env.ts• L10-24

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep the Queue, QueueClient, and Runner contracts aligned with both provider adapters. A change that only works in one backend can pass local execution and fail in a Restate deployment.
  • Keep queue names and payload schemas aligned with every producer and runner. A name change creates a different scheduling target.
  • Keep retry and timeout meaning aligned between the queue settings, dispatcher loop, runner timeout, and semaphore lease duration.
  • Preserve idempotency-key scope when changing payloads or enqueue flows. Equivalent work should share a key, while different work must not be deduplicated.
  • When changing provider load order or Restate registration conditions, check which backend becomes active in each deployment mode.
  • When changing Restate service payloads or error results, update both sides of the dispatcher-to-runner boundary.

References: packages/…/queueing.ts• L20-104 packages/…/queues.ts• L89-116 packages/…/plugins.ts• L24-35 packages/…/dispatcher.ts• L24-37 packages/…/types.ts• L15-77

Important failure modes

TriggerConsequenceGuard
Restate is configured but its ingress or service deployment is unavailableEnqueue or execution cannot reach the selected queue backendVerify the Restate runtime and exposed dispatcher and runner services before switching provider selection.
The same queue name is created with different retry or failed-job settingsThe queue client rejects the second definitionTreat queue names and queue settings as one shared contract.
A producer reuses an idempotency key for different workThe later job can be skipped as a duplicateBuild keys from all fields that change the requested work.
A job raises a normal error repeatedlyThe dispatcher or Liteque runner uses the retry budget and then reports failureSet retry counts for the work's failure pattern and use QueueRetryAfterError only for temporary waits.
A Restate operator reads the shared stats shape as a full backend reportpending_retry and failed appear as zero even when Restate has backing-off or suspended invocationsUse Restate service stats for its richer invocation states.
Code calls Restate cancelAllNonRunning or runUntilEmptyThe operation raises a not-implemented errorUse Restate administration and deployment controls for those operations.

References: packages/…/index.ts• L8-31 packages/…/index.ts• L80-95 packages/…/index.ts• L72-118 packages/…/index.ts• L184-219 packages/…/admin.ts• L3-80

Key files

FileWhy to read it
packages/…/queueing.tsDefines the backend-neutral queue, job, runner, retry, and lifecycle contracts.
packages/…/queues.tsShows the named application queues and their payload contracts.
packages/…/plugins.tsShows provider loading order and how queue providers are registered.
packages/…/index.tsShows the local SQLite queue adapter and in-process runner behavior.
packages/…/index.tsShows conditional Restate provider registration and client caching.
packages/…/index.tsShows Restate queue creation, enqueueing, service exposure, and shared statistics.
packages/…/dispatcher.tsShows Restate scheduling, capacity leases, retries, and callback order.
packages/…/runner.tsShows payload validation, timeout handling, and application callback execution.
packages/…/semaphore.tsShows priority, group fairness, idempotency, and lease-based capacity control.
packages/…/queue.test.tsDemonstrates the shared behavior expected from enqueue, retries, priorities, groups, rate limits, concurrency, and timeouts.

References: packages/…/queueing.ts• L1-112 packages/…/queues.ts• L1-337 packages/…/index.ts• L1-160 packages/…/index.ts• L1-31 packages/…/index.ts• L1-219 packages/…/dispatcher.ts• L1-215 packages/…/runner.ts• L1-169 packages/…/semaphore.ts• L149-582 packages/…/queue.test.ts• L227-711