Skip to the page

Guides · Integrations

Email, Slack & push

Send an email, a channel message or a push when a row changes. Queue each message with the write or send from the change log.

In the schema
ext::napalm::Job

What you’ll build#

You will send external notifications only after the database write commits: a buyer receipt emailed through Resend when an order transitions to Paid, and a Slack alert for every refunded order. Postmark, Amazon SES, Discord, Microsoft Teams and mobile push services follow the same two commit-coupled patterns.

Commit-coupled fan-out across email, chat and push

Notifications dispatch only after the SQL transaction commits, using an ext::napalm::Job queued in the write statement for single-workflow receipts and push alerts, or a rows webhook tailing the change log for updates from any caller.

The two paths complement each other. Queueing a job inside markOrderPaid binds the receipt to that exact mutation, while a change-log webhook catches every transition to Refunded whether initiated by your app, a support tool or an MCP agent.

Pick how the message is sent#

Choose between an outbox job, a change-log webhook, a synchronous action or a cron schedule based on what triggers the notification.

WhenUseWhy
Your query makes the change, and the message must follow itA job queued in the same commitWhyThe change and the job commit together or not at all. A job is retried until done.
Every change to a type from any caller needs a messageA webhook that carries rowsWhyA notify fires for a write by any path: your app, an agent, a job or the console.
The person is waiting for the resultAn actionWhyThe caller gets your handler’s answer in the same request.
On a clock, like a digest each morningA scheduleWhyA deployed query run on a cron in a time zone you name.

Before you start#

A handler
A route that answers HTTPS and sends the receipt. handleCalls from the client library checks that each call comes from your project.
The service role
{ "default::role": "service" } in the endpoint’s serviceGlobals. The key that marks orders paid gets rights from the rules that name the service role.
A change log
For the channel: napalm storage enable <cluster> log. The receipt needs none.
dbschema/default.gel
using extension auth;using extension napalm;using future simple_scoping; module default {  global caller := global ext::auth::ClientTokenIdentity;  # 'service' for a service key, set in the endpoint's serviceGlobals. A session can't set it.  global role: str;   scalar type OrderStatus extending enum<Pending, Paid, Refunded>;   type Order {    required buyer: ext::auth::Identity;    # Where its receipt goes.    required email: str;    required total_cents: int64;    required status: OrderStatus {      default := OrderStatus.Pending;    };    receipt_time: datetime;     notify order_changed after insert, update;     access policy buyer_can_read_and_place      allow select, insert      using (.buyer ?= global caller);    access policy service_can_read_and_update      allow select, update      using (global role ?= 'service');  }}

Email a receipt when an order is paid#

The query that marks the order paid queues the receipt in the same statement. An order that does not move to Paid queues nothing, and an order that moves to Paid cannot lose the receipt.

Commit-bound job enqueue

markOrderPaid transitions the order and inserts the sendReceipt job inside one SQL statement so rolled-back writes queue nothing.

Signed delivery payload

Action deliveries arrive with a verified ES256 body digest and stable call.job.id, while rows webhooks sign payloads with Napalm-Signature.

External delivery target

Your handler dispatches to Resend, Slack or push providers with Idempotency-Key: call.job.id and records receipt_time via call.db().

dbschema/queries/markOrderPaid.edgeql
with  paid := (    update Order    filter .id = <uuid>$order and .status = OrderStatus.Pending    set { status := OrderStatus.Paid }  ),  # An order that was already paid isn't found above, so no second receipt is queued.  queued := (    for order in paid union (      insert ext::napalm::Job {        query := 'sendReceipt',        variables := <json>(order := <str>order.id),      }    )  ),select paid { id }

The job runs sendReceipt, a deployed query with a handler attached. If the query returns rows, Napalm forwards those rows to your handler.

dbschema/queries/sendReceipt.edgeql
select Order { id, email, total_cents }filter .id = <uuid>$order  and .status = OrderStatus.Paid  and not exists .receipt_time
Terminal
napalm queries push shop # sendReceipt's rows go to your handler. Its secret is shown once: store it as NAPALM_ACTION_SECRET.napalm actions add shop sendReceipt https://app.example.com/actions/sendReceipt
src/app/actions/[action]/route.ts
// src/app/actions/[action]/route.tsimport { handleCalls } from 'napalm-client' const address = process.env.NAPALM_URL! type Receipt = { id: string; email: string; total_cents: number } export const POST = handleCalls(  {    async sendReceipt(call) {      // The query found a paid order with no receipt yet, or this wasn't called.      const [order] = call.rows as Receipt[]      const sent = await fetch('https://api.resend.com/emails', {        method: 'POST',        headers: {          Authorization: `Bearer ${process.env.RESEND_API_KEY}`,          'Content-Type': 'application/json',          // The job's id is the same on every try, so Resend drops a second one.          'Idempotency-Key': call.job?.id ?? `receipt:${order.id}`,        },        body: JSON.stringify({          from: 'Shop <receipts@example.com>',          to: order.email,          subject: 'Your receipt',          text: `Thanks for your order. We charged ${(order.total_cents / 100).toFixed(2)}.`,        }),      })      // A failure fails this attempt, and the job is tried again.      if (!sent.ok) throw new Error(`Resend answered ${sent.status}`)      // Written as the job's caller, under the same rules.      const db = await call.db()      const marked = await db.fetch(`${address}/query/markReceiptSent`, {        method: 'POST',        headers: { 'Content-Type': 'application/json' },        body: JSON.stringify({ variables: { order: order.id } }),      })      if (!marked.ok) throw new Error(`markReceiptSent answered ${marked.status}`)      return { sent: true }    },  },  { address, handlers: 'https://app.example.com/actions', secret: process.env.NAPALM_ACTION_SECRET },)
dbschema/queries/markReceiptSent.edgeql
update Orderfilter .id = <uuid>$orderset { receipt_time := datetime_of_statement() }
The job’s caller
The caller that queued the job. Here that caller is the key that marked the order paid, and the handler’s call.db() writes as the same caller.
When the job runs
At once. Set run_time on the job to send later, such as a reminder in three days.
When the handler fails
Napalm retries the job after 10 seconds, then at doubling waits of up to an hour. Retries stop after a day. napalm queue ls shop --status failed lists the jobs that gave up.

Send each message once#

A job runs at least once. An attempt can send the email and then fail before recording the send, and the next attempt starts from the top. Three safeguards keep the buyer from getting two receipts.

The query
sendReceipt finds only an order with no receipt_time. Once the receipt is marked sent, a later attempt finds nothing and the job is done.
The job’s id
call.job.id is the same on every attempt. Send the id as the provider’s idempotency key, and the provider drops a second send.
The first write
markOrderPaid moves only a Pending order, so a second call finds no order and queues no job.

Providers without idempotency keys leave one narrow window: if the email sends and the handler crashes before markReceiptSent runs, the retry sends a second copy. Where duplicate messages are unacceptable, choose a provider that honors an Idempotency-Key header.

Tell a channel about every change#

A refund can come from your app, a support agent’s tool or an AI agent over MCP. A webhook that carries rows gets every refund because it reads committed changes from the log.

Terminal
# The key the rows are read as. It can only read. Note its id.napalm endpoint shop --passthrough keysnapalm keys create shop --label refund-alerts --read-only napalm webhooks hosts shop --add app.example.comnapalm webhooks add shop https://app.example.com/hooks/refunds --event order_changed --key <key-id>
src/app/hooks/refunds/route.ts
// src/app/hooks/refunds/route.tsimport { readDelivery, type Delivery } from 'napalm-client' export async function POST(request: Request) {  let delivery: Delivery  try {    // Checked against the raw body, before anything reads it.    delivery = await readDelivery(await request.arrayBuffer(), request.headers, process.env.NAPALM_WEBHOOK_SECRET!)  } catch {    return new Response(null, { status: 401 })  }  for (const change of delivery.transactions ?? []) {    for (const row of change.rows) {      // previous holds what an update changed, with what it was: this is the move from Paid to Refunded.      if (row.fields?.status !== 'Refunded' || row.previous?.status !== 'Paid') continue      const total = (Number(row.fields.total_cents) / 100).toFixed(2)      const told = await fetch(process.env.SLACK_WEBHOOK_URL!, {        method: 'POST',        headers: { 'Content-Type': 'application/json' },        body: JSON.stringify({ text: `Order ${row.id} was refunded: ${total}.` }),      })      // Not taken: Napalm sends these rows again.      if (!told.ok) return new Response(null, { status: 502 })    }  }  return new Response(null, { status: 204 })}
The change
fields is the order after the update. previous holds the changed fields with the old values. Together, fields and previous show that the order went from Paid to Refunded.
The caller
Each transaction’s caller names the kind of caller and the source. A refund made over mcp came from an agent.
A delivery sent twice
Posts twice, because Slack has no key to drop a repeat. Keep the last position the route handled and skip any delivery at or before that position, or accept a rare double.

Push to a phone#

A push works like the receipt, with a device token in place of an address. Keep each device’s token on a row the person owns, queue a job in the commit that causes the push, and send from the job’s handler.

A repeat
Give the push a collapse id made from the job’s id: apns-collapse-id for Apple, collapse_key for Firebase. A second copy replaces the first on the phone.
An invalid token
When the push service reports an expired device token, delete its row from the handler through call.db().
While the app is open
No push is needed. A live query already shows the change.

Compare the kinds of message#

MessageSent fromDuplicate guard
Email: Resend, Postmark, Amazon SESA job’s handlerDuplicate guardThe provider’s idempotency key where available, and a …_time on the row the query checks.
A channel: Slack, Discord, TeamsA route that receives rowsDuplicate guardThe last position the route handled.
Push: APNs, Firebase, ExpoA job’s handlerDuplicate guardA collapse id made from the job’s id.
SMSA job’s handlerDuplicate guardA …_time on the row the query checks.

Check the messages#

  1. Mark an order paid

    napalm queue ls shop --query sendReceipt lists one job. The email arrives, and the order has a receipt_time.

  2. Mark the order paid again

    The query answers no rows, and no second job is queued.

  3. Make the handler fail once

    The job is tried again ten seconds later, and call.job.id is the same on the second try.

  4. Refund an order with a service key, outside your app

    The channel gets the message, though your app made no call. napalm webhooks ls shop shows the webhook’s health.

Actions & background jobs builds the same pieces into a shop’s refunds and payouts, and Jobs & schedules has every limit.

Type a word or two to search every docs page.