# Defining and Enqueuing Jobs

> Define an outbox job with defineOutboxJob, list it, enqueue it inside the write's transaction, and write handlers that are safe to run twice.

*Canonical: https://makerkit.dev/docs/void-cloudflare/outbox/jobs*

---

## 1. Define the Job

A job is a kind, a payload schema, a timeout and a handler that returns an outcome:

```ts
// apps/web/jobs/welcome-email.job.ts
import { defineOutboxJob, ok, retry } from '@kit/outbox/server';
import { z } from 'zod';

import { sendWelcomeEmail } from '#/lib/welcome-email.server.ts';

export const welcomeEmail = defineOutboxJob({
  kind: 'app.welcome-email',
  payload: z.object({ userId: z.string() }),
  timeoutMs: 30_000,
  async handle({ userId }, ctx) {
    const result = await sendWelcomeEmail({ userId, signal: ctx.signal });

    if (result.rateLimited) {
      return retry({ code: 'rate_limited', after: 60_000 });
    }

    return ok();
  },
});
```

- **`kind`** names the job in the table and the logs. Prefix your kinds (`app.…`); `kit.…` is reserved for jobs the kit adds.
- **`payload`** is any Standard Schema validator (zod, valibot, arktype). It is checked when you enqueue and again when the job runs.
- **`timeoutMs`** bounds one attempt: past it the attempt counts as timed out (`ctx.signal` aborts, and a later result is discarded), and the lease that stops two workers running the job is derived from it. Keep it close to the real worst case, and under about 2 minutes: the sweep runs a job itself only if `timeoutMs` plus 35 seconds fits its 3-minute budget. Longer jobs (up to 10 minutes) run only through the queue: the sweep re-sends their nudge, so they need the queue binding.
- **`handle`** returns an outcome; a throw counts as `retry({ code: 'unexpected' })`. See [Failures](./failures).

## 2. List It

Add the job to `outboxJobs` in `apps/web/config/outbox.config.server.ts`:

```ts
import { welcomeEmail } from '#/jobs/welcome-email.job.ts';

import { kitOutboxJobs } from './kit-outbox-jobs.server';

export const outboxJobs = [...kitOutboxJobs, welcomeEmail] as const;
```

Only listed kinds are ever claimed, and only listed jobs type-check in `enqueue`. **Keep a job listed until its pending jobs have run**: an unlisted kind's jobs wait forever (cancel them first if you remove a job on purpose).

## 3. Enqueue It With Its Write

```ts
import { db } from 'void/db';

import { getOutbox } from '#/lib/outbox.server.ts';

await getOutbox().transaction(db, async (tx, enqueue) => {
  const [row] = await tx.insert(user).values(input).returning();

  await enqueue(welcomeEmail, {
    payload: { userId: row.id },
    dedupeKey: `welcome:${row.id}`,
  });
});
```

- **Pass the top-level `db`, never a `tx`.** The outbox opens the transaction and nudges the queue after it commits; inside an outer transaction, the nudge would go out before the real commit.
- **Write through `tx`** in the callback, so your rows and the job commit together.
- **`dedupeKey`** comes from business identity (`welcome:${userId}`, `invoice-paid:${invoiceId}`), never a random value: a retried request then finds its job instead of creating a second one, and `enqueue` returns `{ status: 'exists' }`. Keys are permanent, so to do something again on purpose put the reason in the key (`reminder:${userId}:${week}`).
- **A refused enqueue throws `OutboxEnqueueError`**: a payload that fails its schema (or is over 256 KiB), or a `dedupeKey` taken by another kind. The transaction rolls back, so your write never commits without its job. `error.result` says why.

Optional fields: `delayMs` (run no earlier than that), `tenantKey` (an organization id: scopes dedupe keys and operator actions to it), `correlationId` (a request id, to find related jobs), `metadata` (passed to the handler as `ctx.metadata`).

**Metadata must be ids-only, just like payloads.** `/admin/jobs/[id]` shows raw metadata to operators with `outbox:get`. Keep names, email addresses, tokens, secrets and request bodies out of it. The admin renders capped text, but does not redact the stored values.

### Inside a Transaction You Don't Own

Better Auth hooks and other libraries open their own transaction. Enqueue in it with `getOutbox().enqueue(tx, job, request)` (`tx` must run Drizzle SQL against the same database), and nudge after it commits (in Better Auth, an `after` hook), or let the sweep run it (up to 5 minutes later):

```ts
const job = await getOutbox().enqueue(tx, welcomeEmail, { payload: { userId }, dedupeKey: `welcome:${userId}` });

// after the library's transaction has committed:
await getOutbox().nudge([job]);
```

## Payloads

- **Ids, not data.** Payloads are stored in `outbox.job` and kept for weeks: put `userId`, read the user in the handler. Never personal data, tokens or secrets.
- **Small.** Over 256 KiB is refused; put large data in R2 and enqueue its key.
- **Change them additively.** Jobs already in the table carry the old shape and are validated again when they run: add optional fields, don't rename or remove required ones.

## Handlers Run at Least Once

A worker can crash after the work but before the job is marked done, so the same job can run twice. Make each handler safe to repeat:

- **Check before you act**: read the row, skip if it's already done (`welcomedAt` is set).
- **Pass `ctx.idempotencyKey`** to providers that dedupe on a key.
- **Pass `ctx.signal`** to every network and database call, so a timed-out attempt stops instead of running alongside its retry.
- **Never call another service inside a database transaction**: do the call, then commit the bookkeeping.
- **Read with `void/db`** in handlers, like the rest of the app.

`ctx` also holds `jobId`, `kind`, `attempt`, `tenantKey`, `correlationId` and `metadata`.

## Chaining Jobs

A job that enqueues another (the next step) reaches the outbox through `ctx.deps.getOutbox()`, which every `defineOutboxJob` job gets:

```ts
import { db } from 'void/db';
import { z } from 'zod';

import { defineOutboxJob, ok } from '@kit/outbox/server';

import { sendReceipt } from '#/jobs/send-receipt.job.ts';

export const chargeOrder = defineOutboxJob({
  kind: 'app.charge-order',
  payload: z.object({ orderId: z.string() }),
  timeoutMs: 30_000,
  async handle({ orderId }, ctx) {
    // … charge, then hand the receipt to its own job
    await ctx.deps.getOutbox().transaction(db, (_tx, enqueue) =>
      enqueue(sendReceipt, { payload: { orderId }, dedupeKey: `receipt:${orderId}` }),
    );

    return ok();
  },
});
```

**Splitting long work:** stop while `ctx.remainingMs()` still covers one more step (or check `ctx.deadline`), then enqueue the rest as the next step. Don't wait for `ctx.signal`: it aborts only once the attempt has already timed out, and a result after that is discarded (the attempt counts as a timeout and runs again).

**Never import `getOutbox` from `lib/outbox.server.ts` in a job file.** The job list feeds the outbox, so that import is a cycle, and whichever file loads first sees the other undefined. `ctx.deps.getOutbox()` is typed for any job; enqueueing one missing from `outboxJobs` throws.

## Where Job Files Go

Anywhere; the convention is `apps/web/jobs/<name>.job.ts` (type-checked and test-included like the rest of the app). That folder isn't one Void scans for bindings, so a binding only a job uses isn't provisioned. Email is already declared (`inference: { bindings: { email: true } }` in `void.config.ts`); for another (`void/storage`, `void/kv`), declare it the same way or use it from a scanned folder too.
