---
title: Jobs
description: The registry runs jobs and rebuilds saved scopes.
---

A job is one listener delivery, scheduled call, or cron run.

<Diagram caption="The runner extends its lease until the job finishes or the runner stops renewing it.">
  <Flow>
    <Node title="Job" subtitle="Waits in the queue" />
    <Arrow n={1} label="claim" />
    <Fan>
      <Node slot="from" title="Lease" subtitle="Runner renews its claim" tone="accent" />
      <Node title="Done" subtitle="Runner removes the job" />
      <Node title="Retry" subtitle="Backoff then claim again" />
      <Node title="Failed" subtitle="Adapter keeps the job">
        <Check>Runs `failed`, if the listener has one</Check>
      </Node>
    </Fan>
  </Flow>
</Diagram>

```ts twoslash
import { init } from "logic-sdk";
import { z } from "zod";

const { event, listener, mutation } = init<{ scope: { actor: string | null } }>();
const confirmed = event({ payload: z.object({ bookingId: z.string() }) });
const create = mutation({
  input: z.object({ title: z.string(), bookingId: z.string() }),
  async handler() {},
});
const tasks = { create };
// ---cut---
export const prepareStay = listener({
  event: () => confirmed,
  attempts: 3,
  async handler(ctx, { bookingId }) {
    await ctx.run(tasks.create, { title: "Prepare keys", bookingId });
  },
});
```

- **Commit.** Deliveries and scheduled calls commit with the mutation in the jobs table.
- **Claim (1).** A claim spends one attempt. The receipt controls renewal and settlement.
- **Done.** The runner removes the row before delivering follow-up jobs.
- **Retry.** The runner renews every third of the lease for up to 15 minutes. An expired lease makes the job available again. Default backoff is `exp(min(attempt, 10))` seconds.
- **Failed.** An expired final claim fails the job without running its handler again.
- **Idempotency.** Work can repeat after a crash. Use a unique constraint or idempotency key. For deliveries, pair `ctx.event.id` with the listener's identity.

Compare [adapter guarantees](/docs/reference/adapters).

## Listener options

{/* source: packages/logic-sdk/src/core/registry.ts (listener), packages/logic-sdk/src/core/jobs.ts */}

| Option | Rule |
|---|---|
| `attempts`, `delay`, `queue` | The job keeps its attempts and due time. See [defaults](/docs/reference/api#listener-and-cron). |
| `when` | Tests parsed payload at commit. False skips delivery. A throw rolls back. Check current state in the handler. |
| `key` | Runs jobs in enqueue order, one at a time per listener and key. Concurrent commits have no defined order. Waiting spends no attempt. Backoff holds the key. Terminal failure releases it. Use `ctx.run` for follow-up jobs with that key. |
| `unique` | Keeps the first waiting job per value. Group bursts with `delay`. Read current state. |
| `timeout` | Aborts `ctx.signal` and blocks new `ctx.run` calls. Pass the signal to external operations. A running mutation can still commit. |
| `retry` | Overrides the default of retrying only `conflict` among app errors. Unexpected exceptions retry while attempts remain. Stale payloads fail immediately. |
| `failed` | Runs after terminal failure outside a transaction, with current payload and scope. A crash or discard can skip it. Throws reach `onError` as `"<listener> (failed)"`. |

Use either `key` or `unique`. Both read parsed payload at commit. Empty values or throws roll back the mutation.

## Scope

`store` saves IDs from the scope with the job. `load` rebuilds the scope when the job runs, and reads today's role through `ctx.db`.

```ts twoslash
import { init, type DatabaseAdapter } from "logic-sdk";
import { databaseQueue } from "logic-sdk/drizzle/pg";

type Scope = { accountId: string; actor: { id: string; role: string } | null };
type Db = { roleOf(accountId: string, userId: string): Promise<string | null> };
const { createRegistry } = init<{ scope: Scope; db: Db }>();
declare const database: DatabaseAdapter<Db>;
// ---cut---
createRegistry({
  modules: {},
  database: { adapter: database },
  jobs: {
    adapter: databaseQueue(),
    scope: {
      store: (scope) => ({ accountId: scope.accountId, actorId: scope.actor?.id ?? null }),
      async load(ctx, saved) {
        const { accountId, actorId } = saved;
        if (!actorId) return { accountId, actor: null };
        const role = await ctx.db.roleOf(accountId, actorId);
        return role ? { accountId, actor: { id: actorId, role } } : null;
      },
    },
  },
});
```

- **Default.** Deliveries and scheduled calls inherit the mutation's scope. Each `ctx.run` checks policy.
- **Override.** A listener's `scope(payload)` picks a whole scope at commit. Take account IDs from the emitter's `ctx.scope`.
- **Store.** Save plain JSON with `jobs.scope.store`. Keep enough to rebuild system scopes. Omit `store` to save the whole scope.
- **Load.** Set `jobs.scope.load(ctx, saved)` when you set `store`, or when the jobs adapter keeps jobs to run later. Every adapter except `inProcess()` keeps them, and `createRegistry` refuses a registry without `load`. Rebuild membership and roles through `ctx.db`. Return `null` to discard. A throw or `undefined` fails the attempt.
- **Order.** Put `store` first for type inference. The loader runs before handlers and again for a listener's `failed`, even in tests. Crons use their declared scope.

## Scheduled calls

```ts
ctx.schedule(tasks.create, { title: "Collect keys", bookingId }, { at: checkOut, replace: true });
```

- **Target.** In a mutation, schedule a registered mutation or action. The registry checks input at commit and input and policy at run time.
- **Time.** Use a `Date` for `at` or seconds for `delay`. Past dates and zero delay run after commit. Future calls need an adapter that holds jobs.
- **Input.** Use plain JSON.
- **Options.** Set `attempts`, `queue`, or a whole `scope`. See [loop limits](/docs/concepts/events#durability-and-loops).
- **Replacement.** With `replace: true`, the newest waiting call with the same function and input wins. Use IDs in the input.
- **Cancellation.** Update the app row and check it before acting. Check and write in the same mutation when possible. Scheduling returns no handle.

## Queues

Declare extra names in `jobs.queues`. Workers and sweeps take the first listed queue with a due job. Without a list, they take the earliest available job. With default `runIn`, the request handles due-now jobs if local workers cannot take all of them.

## Operations

| Method on `registry.jobs` | Result |
|---|---|
| `sweep({ queues })` | Runs due jobs and counts outcomes. Returns zeros without a sweeper. |
| `run(job, { attempt })` | Consumer acknowledges `"done"`, `"failed"`, or `"discarded"` and retries on a throw. |
| `failed({ source, scope, limit, cursor })` | Lists failures newest first. Matches nested fields in stored scope. Default limit 100. Reuse the returned cursor. |
| `retry(id)` | Gives a failed job fresh attempts. |
| `forget(id)` | Removes a failed job. |
| `invoke(cron, { at })` | Hands off one cron and returns a new job ID. |

- **Reports.** `onError` gets source, job, attempt, and outcome when available.
- **Access.** Guard operator routes with a policy. For user retries, check the app row in a mutation and emit again.
- **Deploys.** Keep [definition IDs](/docs/reference/api#definers) stable. An unknown ID spends an attempt. Deploy a new listener before its emitter.

## See also

- [Crons](/docs/concepts/crons)
- [Adapters](/docs/reference/adapters)
- [Node workers](/docs/guides/node)
- [Testing](/docs/guides/testing)
