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.
| When | Use | Why |
|---|---|---|
| Your query makes the change, and the message must follow it | A job queued in the same commit | WhyThe 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 message | A webhook that carries rows | WhyA notify fires for a write by any path: your app, an agent, a job or the console. |
| The person is waiting for the result | An action | WhyThe caller gets your handler’s answer in the same request. |
| On a clock, like a digest each morning | A schedule | WhyA 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.
handleCallsfrom the client library checks that each call comes from your project. - The service role
{ "default::role": "service" }in the endpoint’sserviceGlobals. 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.
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().
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.
select Order { id, email, total_cents }filter .id = <uuid>$order and .status = OrderStatus.Paid and not exists .receipt_timenapalm 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.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 },)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_timeon 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 failedlists 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
sendReceiptfinds only an order with noreceipt_time. Once the receipt is marked sent, a later attempt finds nothing and the job is done.- The job’s id
call.job.idis the same on every attempt. Send the id as the provider’s idempotency key, and the provider drops a second send.- The first write
markOrderPaidmoves only aPendingorder, 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.
# 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.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
fieldsis the order after the update.previousholds the changed fields with the old values. Together,fieldsandpreviousshow that the order went fromPaidtoRefunded.- The caller
- Each transaction’s
callernames the kind of caller and the source. A refund made overmcpcame from an agent. - A delivery sent twice
- Posts twice, because Slack has no key to drop a repeat. Keep the last
positionthe 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-idfor Apple,collapse_keyfor 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#
| Message | Sent from | Duplicate guard |
|---|---|---|
| Email: Resend, Postmark, Amazon SES | A job’s handler | Duplicate guardThe provider’s idempotency key where available, and a …_time on the row the query checks. |
| A channel: Slack, Discord, Teams | A route that receives rows | Duplicate guardThe last position the route handled. |
| Push: APNs, Firebase, Expo | A job’s handler | Duplicate guardA collapse id made from the job’s id. |
| SMS | A job’s handler | Duplicate guardA …_time on the row the query checks. |
Check the messages#
Mark an order paid
napalm queue ls shop --query sendReceiptlists one job. The email arrives, and the order has areceipt_time.Mark the order paid again
The query answers no rows, and no second job is queued.
Make the handler fail once
The job is tried again ten seconds later, and
call.job.idis the same on the second try.Refund an order with a service key, outside your app
The channel gets the message, though your app made no call.
napalm webhooks ls shopshows the webhook’s health.
Actions & background jobs builds the same pieces into a shop’s refunds and payouts, and Jobs & schedules has every limit.