Skip to the page

Guides · App patterns

Actions & background jobs

Charge a card, send an email or run a multi-step workflow from a deployed query as the caller. Jobs replace a message broker.

In the schema
ext::napalm::Job

What you’ll build#

You will wire every part of a shop that reaches outside the database: a synchronous card refund, a receipt emailed after an order commits, a weekday morning digest and a payout that requires a second person’s approval. Each workflow pairs a deployed query with minimal handler code and runs as the requesting caller under the same schema access rules as the rest of your app.

Before you start#

You need a project with deployed queries and a place to serve a handler. Your first app sets up a project, and any server, edge function or hosted handler folder that answers HTTPS can serve your actions.

Pick an action, a job or a schedule#

Choose the primitive that matches when external work runs and whether a caller is waiting on the response.

Synchronous actions

Gatekeeper query checks caller access first, dispatches permitted rows with an ES256 assertion and returns typed JSON in the same request.

Commit-atomic jobs and schedules

Insert ext::napalm::Job inside the domain mutation or attach a cron schedule so work commits atomically and retries with backoff.

PatternMechanismWhen to use
Synchronous side effectDeployed query + action handlerWhen to useCaller waits for the external result (charging a card, issuing a refund, provisioning an external resource) and gets a typed response across HTTP, CLI, MCP and A2A.
Transactional outbox / delayed workinsert ext::napalm::JobWhen to useWork must happen reliably after a mutation commits (emails, PDF rendering, expiring invites in 7 days) with automatic exponential retries.
Recurring batch or rollupnapalm schedules addWhen to useWork runs on a cron schedule as a deployed query or action under a dedicated service key in an explicit IANA time zone.
Downstream event fan-outSchema notify + GET /changesWhen to useCommitted rows sync to a search engine, a warehouse or another service. See Warehouse sync.

Every example below builds on one Order schema.

dbschema/default.gel
using extension auth;using extension napalm;using future simple_scoping; module default {  global caller := global ext::auth::ClientTokenIdentity;  scalar type OrderStatus extending enum<Pending, Paid, Refunded>;   type Order {    required buyer: ext::auth::Identity;    required total_cents: int64;    required currency: str {      default := 'usd';    };    required status: OrderStatus {      default := OrderStatus.Pending;    };    stripe_charge_id: str;    receipt_sent_at: datetime;     notify order_changed after insert, update, delete;     access policy buyer_can_read      allow select      using (.buyer ?= global caller);    access policy buyer_can_place      allow insert      using (.buyer ?= global caller and .status in {OrderStatus.Pending, OrderStatus.Paid});    access policy buyer_can_refund_paid      allow update      using (.buyer ?= global caller);  }}

Call external services as the caller#

An action pairs a deployed query with an HTTPS handler URL. A caller can invoke POST /query/refundOrder, run shop refund-order in your project CLI or call the refundOrder MCP tool, and in every case Napalm executes the query first as that caller under your schema’s access policies.

  1. Write the gatekeeper query and optional answer schema

    If the query returns zero rows, Napalm immediately responds 403 nothing_found and never calls your handler because the order belongs to another user, does not exist or is not Paid.

    dbschema/queries/refundOrder.edgeql
    # Refund a paid order owned by the callerselect Order {  id,  total_cents,  currency,  stripe_charge_id,}filter .id = <uuid>$order  and .status = OrderStatus.Paid  and exists .stripe_charge_id
    refund-answer.json
    {  "type": "object",  "required": ["refundId", "status"],  "properties": {    "refundId": { "type": "string" },    "status": { "type": "string", "enum": ["refunded"] }  }}
  2. Register the action and regenerate your SDK

    Terminal
    napalm queries push shopnapalm actions add shop refundOrder https://api.example.com/actions/refundOrder \  --answer-schema refund-answer.json \  --timeout 20# Prints the action secret once; store as NAPALM_ACTION_SECRET.napalm generate shop --deployed --lang ts

    Supplying --answer-schema types db.POST('/query/refundOrder') and the MCP outputSchema with { refundId: string; status: "refunded" } instead of the gatekeeper query’s raw row shape.

  3. Mount handleCalls on your server or edge worker

    handleCalls from napalm-client verifies the Authorization: Bearer ES256 JWT against your project’s /.well-known/jwks.json (cached automatically), confirms the target handler URL and timestamp and verifies the request body’s SHA-256 digest before parsing JSON and dispatching by action name.

    app/actions/[action]/route.ts
    // app/actions/[action]/route.ts (or Deno.serve / Bun.serve / Cloudflare Worker)import Stripe from 'stripe'import { handleCalls } from 'napalm-client'import { sendReceiptEmail } from '@/lib/email' const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!) type RefundRow = {  id: string  total_cents: number  currency: string  stripe_charge_id: string} export const POST = handleCalls(  {    async refundOrder(call) {      // 1. ES256 JWKS signature, audience, expiry, and body SHA-256 are already verified.      // 2. call.rows is guaranteed non-empty and policy-filtered for call.caller.      const [order] = call.rows as RefundRow[]       // 3. Deduplicate external side effects: jobs pass call.job.id across retries;      //    synchronous calls can key on the order transition itself.      const refund = await stripe.refunds.create(        { charge: order.stripe_charge_id, amount: order.total_cents },        { idempotencyKey: call.job?.id ?? `refund:${order.id}` },      )       // 4. Trade call.assertion for a 60-second NapalmClient scoped to the exact caller.      const callerDb = await call.db()      const res = await callerDb.fetch('https://notes.napalmdata.com/query/markOrderRefunded', {        method: 'POST',        headers: { 'Content-Type': 'application/json' },        body: JSON.stringify({ variables: { order: order.id } }),      })      if (!res.ok) throw new Error(`Failed to record refund: ${res.status}`)       return { refundId: refund.id, status: 'refunded' as const }    },     async sendReceipt(call) {      const [order] = call.rows as { id: string; total_cents: number }[]      await sendReceiptEmail(order, { idempotencyKey: call.job?.id ?? `receipt:${order.id}` })      return { sent: true }    },  },  {    address: 'https://notes.napalmdata.com',    handlers: 'https://api.example.com/actions',    secret: process.env.NAPALM_ACTION_SECRET,    onError: (err, action) => console.error(`Action ${action} failed:`, err),  },)

Write back as the caller#

Action handlers hold no super-privileged backend key. Calling await call.db() inside handleCalls (or calling callerClient(call, { address, secret }) directly when using readCall) exchanges the database’s signed assertion and your action secret at POST /sign-in/agents/token (RFC 8693 token exchange) for a 60-second NapalmClient bound to the originating caller.

dbschema/queries/markOrderRefunded.edgeql
# Record completed refund under the caller's own access policyupdate Orderfilter .id = <uuid>$orderset { status := OrderStatus.Refunded }
User and agent bounds
If a human user called the action, call.db() acts as that user’s Identity. If an OAuth 2.1 agent called it (call.caller.grant is set), call.db() inherits that exact AgentGrant and fails immediately once the user revokes the grant.
Read-only propagation
When call.caller.isReadOnly is true, the exchanged token is also capped at read-only.
Data-plane only
Exchanged 60-second tokens are accepted on /query and /uploads. /mcp never accepts exchanged tokens, so a handler cannot start recursive agent tool loops.

Queue work in the same commit#

Inserting an ext::napalm::Job inside the same EdgeQL with block as your domain write gives you a commit-atomic outbox. If the Order insert rolls back, zero jobs are queued. When the insert commits, both immediate and delayed jobs commit durably in the same PostgreSQL transaction.

All-or-nothing transactional outbox

One PostgreSQL commit binds the Order write and its queued ext::napalm::Job rows together. If any policy, constraint or queue cap fails, nothing commits.

dbschema/queries/placeOrder.edgeql
# Place an order and atomically enqueue receipt deliverywith  order := (    insert Order {      buyer := assert_exists(global caller),      total_cents := <int64>$total_cents,      status := OrderStatus.Paid,      stripe_charge_id := <str>$charge_id,    }  ),  receipt_job := (    insert ext::napalm::Job {      query := 'sendReceipt',      variables := <json>(order := <str>order.id),    }  ),  followup_job := (    insert ext::napalm::Job {      query := 'checkDelivery',      variables := <json>(order := <str>order.id),      run_time := datetime_of_statement() + <duration>'72 hours',    }  ),select {  order_id := order.id,  receipt_job_id := receipt_job.id,}

Each caller identity (a person, a key or the service) can have at most 10,000 jobs waiting, counted across all sources. Once a caller hits that limit, a statement that queues another fails with 429 job_limit_reached and commits nothing, including the order. Scheduled jobs do not count toward this limit.

Make retries safe#

If a job’s query or action handler throws, times out or returns a non-2xx status, Napalm records a failed ext::napalm::JobRun and retries after 10 seconds. The wait doubles on each attempt up to 1 hour until expire_time, which defaults to 24 hours after run_time and can extend up to 30 days.

When a job invokes an action handler, call.job carries { id: string, attempt: number }. call.job.id stays identical across every retry of that job, so pass it as your payment processor’s or email provider’s idempotency key. A network drop after Stripe succeeds then never double-charges or sends duplicate emails.

Show a job’s progress#

The queuing caller can read each ext::napalm::Job row and cancel the job via delete. Deploy a status query and subscribe with a generated React hook so users see live progress without polling.

dbschema/queries/jobStatus.edgeql
# Watch a queued job and its attempt historyselect ext::napalm::Job {  id,  query,  status,  run_time,  finish_time,  runs: {    status,    start_time,    finish_time,    error,  } order by .start_time desc,}filter .id = <uuid>$job
ReceiptBadge.tsx
import { useJobStatus } from '@/napalm/hooks' export function ReceiptBadge({ jobId }: { jobId: string }) {  // One subscription, open while the badge is mounted. A finished job's row stops changing, so it costs nothing more.  const { rows } = useJobStatus({ job: jobId })  const job = rows?.[0]   if (!job || job.status === 'pending' || job.status === 'running') {    return <span>Sending receipt…</span>  }  return job.status === 'completed'    ? <span>Receipt delivered</span>    : <span>Delivery failed: {job.runs[0]?.error ?? 'retrying exhausted'}</span>}

Finished steps on a long job are queryable rows too. Select steps: { name, finish_time } on the job so the badge updates as each step finishes.

Operators can also inspect, retry or cancel branch jobs from the console or terminal with napalm queue ls shop, napalm queue retry shop <job-id> and napalm queue cancel shop <job-id>. See Jobs & schedules for full parameter details.

Schedule work and gate steps on approval#

Operational workflows such as weekday digest emails, trial expirations, dead-man’s switches and dual-control payout approvals require no external workflow cluster or Redis queue. Run a deployed query or action on a schedule with napalm schedules add, and enforce multi-step state machines with update read and update write policies.

Terminal
# 1. Deploy the query the schedule runsnapalm queries push shop # 2. Run it on weekday mornings, in a named time zone, as a service key of its ownnapalm keys create shop --label nightly-digest-runnernapalm schedules add shop sendDailyDigest '0 8 * * 1-5' \  --time-zone America/New_York \  --key <the keys id, from napalm keys ls>

Dual-control state transitions in SQL#

In the PayoutRequest schema below, an author can create a Draft and submit it (Draft → Submitted), cannot self-approve (.author != .approver) and relies on the designated approver to transition Submitted → Approved while atomically queueing the wire transfer job.

dbschema/default.gel
using extension auth;using extension napalm;using future simple_scoping; module default {  global caller := global ext::auth::ClientTokenIdentity;   scalar type PayoutStage extending enum<Draft, Submitted, Approved, Sent>;   type PayoutRequest {    required author: ext::auth::Identity;    required approver: ext::auth::Identity;    required amount_cents: int64 {      constraint min_value(1);    };    required stage: PayoutStage {      default := PayoutStage.Draft;    };     access policy participants_can_read      allow select      using (.author ?= global caller or .approver ?= global caller);    access policy author_creates_draft      allow insert      using (.author ?= global caller and .stage = PayoutStage.Draft and .author != .approver);    access policy author_submits_draft      allow update read      using (.author ?= global caller and .stage = PayoutStage.Draft);    access policy author_transitions_to_submitted      allow update write      using (.author ?= global caller and .stage = PayoutStage.Submitted);    access policy approver_targets_submitted      allow update read      using (.approver ?= global caller and .stage = PayoutStage.Submitted);    access policy approver_transitions_to_approved      allow update write      using (.approver ?= global caller and .stage = PayoutStage.Approved);  }}
dbschema/queries/approvePayout.edgeql
# Approve a submitted payout and enqueue wire execution in one transactionwith  approved := (    update PayoutRequest    filter .id = <uuid>$payout    set { stage := PayoutStage.Approved }  ),  queued := (    for p in approved union (      insert ext::napalm::Job {        query := 'executeWireTransfer',        variables := <json>(payout := <str>p.id),      }    )  ),select approved { id, stage }

Check the action and jobs#

  1. Call the action as someone who does not own the order

    POST /query/refundOrder returns 403 nothing_found, and your handler’s log shows no call. The query rejected the call before your code ran.

  2. Place an order and check the queue

    napalm queue ls shop lists the receipt job and the job scheduled three days out. Make the handler fail once, and the job runs again with the same call.job.id.

  3. Approve your own payout

    The schema rule refuses the approval without any app code checking the approver. Approve the payout as the named approver, and the transfer’s job is queued in the same commit.

Type a word or two to search every docs page.