Skip to the page

Guides · Integrations

Email, Slack & push

Send emails, Slack messages or push notifications when rows change, either atomically inside the write transaction or 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.

Post-commit notification fan-out

Outbox jobs dispatch transactional receipts while change-log webhooks drive channel alerts.

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.

Choose a delivery pattern#

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

TriggerPatternWhy
A specific mutation must send one messageOutbox job in the same commitWhyThe row update and ext::napalm::Job insert commit or roll back together, and failed runs retry automatically.
Any write to a type from any caller needs an alertRow-carrying webhookWhyA notify trigger captures writes from your app, MCP agents, background jobs and the console alike.
The caller awaits the external responseSynchronous actionWhyPostgreSQL checks access first and returns your handler’s response in the same HTTP request.
Recurring digests on a fixed scheduleCron scheduleWhyRuns a deployed query on a cron expression in your chosen time zone.

Before you start#

Prepare an HTTPS handler route for receipt emails, configure your branch’s service role and enable cluster change-log storage for Slack alerts.

Action handler
An HTTPS route that sends the receipt email. handleCalls in napalm-client verifies each incoming ES256 call assertion.
Service role
{ "default::role": "service" } in the endpoint’s serviceGlobals so the service key calling markOrderPaid satisfies the schema’s role policies.
Change-log storage
Required for the Slack refund webhook (napalm storage enable <cluster> log). Outbox jobs do not require log storage.
dbschema/default.gel
using extension auth;using extension napalm;using future simple_scoping; module default {  global caller := global ext::auth::ClientTokenIdentity;  # Set to 'service' for service keys via endpoint serviceGlobals (user sessions cannot spoof it).  global role: str;   scalar type OrderStatus extending enum<Pending, Paid, Refunded>;   type Order {    required buyer: ext::auth::Identity;    # Recipient address for order receipts.    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#

An outbox notification pairs a transactional job enqueue with a signed external handler that records completion once the email provider accepts the message.

Transactional job enqueue

One database commit updates the order status and enqueues the receipt job.

Signed handler calls

Action deliveries carry an ES256 assertion and a stable retry job ID.

Idempotent provider send

Your handler passes the job ID to Resend and records delivery time.

markOrderPaid transitions a pending order to Paid and inserts the receipt job in one EdgeQL statement. If no pending order matches, zero jobs queue.

dbschema/queries/markOrderPaid.edgeql
with  paid := (    update Order    filter .id = <uuid>$order and .status = OrderStatus.Pending    set { status := OrderStatus.Paid }  ),  # Already-paid orders return empty above, preventing duplicate receipt jobs.  queued := (    for order in paid union (      insert ext::napalm::Job {        query := 'sendReceipt',        variables := <json>(order := <str>order.id),      }    )  ),select paid { id }

The job executes sendReceipt, a deployed gatekeeper query paired with an external handler. Whenever the query returns a matching row, Napalm forwards that row 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

Push the query catalog and attach your HTTPS handler URL to sendReceipt.

Terminal
napalm queries push shop # Attach an external handler to sendReceipt (store the printed secret as NAPALM_ACTION_SECRET)napalm actions add shop sendReceipt https://app.example.com/actions/sendReceipt

Inside the handler, send the email through Resend using call.job.id as the idempotency key, then record receipt_time on the order.

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) {      // Napalm invokes the handler only when sendReceipt matches an order awaiting a receipt.      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',          // call.job.id stays constant across retries so Resend deduplicates repeat attempts.          '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)}.`,        }),      })      // Throwing fails this attempt and schedules an automatic job retry.      if (!sent.ok) throw new Error(`Resend answered ${sent.status}`)      // Exchange the call assertion for a short-lived session scoped to the job's caller.      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() }
Caller identity
Jobs run under the credential that inserted the Job row (here, the service key that called markOrderPaid), and call.db() writes under that exact identity.
Delayed execution
Jobs run immediately by default. Set run_time on ext::napalm::Job to schedule future delivery, such as a three-day reminder.
Retry schedule
Failed attempts retry after 10 seconds with exponential backoff up to one hour for 24 hours. Inspect exhausted jobs with napalm queue ls shop --status failed.

Avoid duplicate notifications#

Background jobs execute at least once. If a handler sends the email and crashes before recording receipt_time, the next retry runs from the top. Three safeguards prevent duplicate buyer emails.

Gatekeeper filter
sendReceipt selects only orders missing receipt_time. Once markReceiptSent commits, any later retry matches zero rows and finishes cleanly.
Provider idempotency key
call.job.id stays identical across every retry. Passing that ID in Idempotency-Key lets providers like Resend and Postmark drop duplicate sends.
Transition guard
markOrderPaid updates only Pending orders, so calling the mutation twice updates zero rows and queues zero extra jobs.

Email providers without idempotency keys leave one narrow window: if the provider accepts the message and the handler crashes before markReceiptSent commits, the retry sends a second email. Use a provider that honors Idempotency-Key whenever duplicate emails are unacceptable.

Post channel alerts from the change log#

Refunds can originate from your storefront, an internal support tool or an AI agent over MCP. A row-carrying webhook catches every refund because it tails committed transactions in the change log regardless of caller.

Terminal
# Create a dedicated read-only service key and note its IDnapalm 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 {    // Verify the HMAC signature over the raw request bytes before parsing.    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) {      // Match updates that transitioned status specifically 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}.` }),      })      // Non-2xx responses retry the same change batch.      if (!told.ok) return new Response(null, { status: 502 })    }  }  return new Response(null, { status: 204 })}
Transition check
fields holds post-update values and previous holds prior values for modified fields, letting your route match transitions from Paid to Refunded.
Caller metadata
Each transaction’s caller object reports the credential class and protocol source, such as an agent refund over mcp.
Duplicate deliveries
Incoming Slack webhooks do not take an idempotency key. Persist the last processed delivery.position and skip deliveries at or before that bookmark if strict deduplication is required.

Send mobile push notifications#

Mobile push notifications follow the same outbox job pattern using a stored device token instead of an email address. Store each device token on a user-owned schema type, insert a job inside the triggering write and dispatch to APNs or Firebase Cloud Messaging from your handler.

Collapse identifiers
Derive apns-collapse-id (Apple) or collapse_key (Firebase) from call.job.id so a retried push replaces the first notification on the device.
Expired device tokens
When APNs or FCM reports an unregistered device token, delete that token row from your handler via call.db().
Foreground apps
Skip push notifications when the client is already active, because a live query streams the update directly.

Deduplication by channel#

Match your duplicate guard to each destination channel’s delivery contract.

ChannelDispatched fromDuplicate guard
Email (Resend, Postmark, SES)Outbox job handlerDuplicate guardProvider Idempotency-Key header plus a …_time column checked by the gatekeeper query.
Chat (Slack, Discord, Teams)Row-carrying webhook routeDuplicate guardLast processed delivery.position bookmark stored by the receiver.
Mobile push (APNs, FCM, Expo)Outbox job handlerDuplicate guardCollapse identifier derived from call.job.id.
SMSOutbox job handlerDuplicate guardA …_time column checked by the gatekeeper query.

Check the messages#

  1. Mark an order paid

    napalm queue ls shop --query sendReceipt lists one completed job, the buyer email arrives and the order row records receipt_time.

  2. Call markOrderPaid a second time

    Confirm the query returns zero rows and queues no duplicate job.

  3. Simulate a transient handler failure

    Throw once inside sendReceipt and verify the job retries 10 seconds later carrying the exact same call.job.id.

  4. Refund an order directly with a service key

    Confirm the Slack channel receives the refund alert even though your web app did not initiate the write, and check napalm webhooks ls shop for Delivering status.

Actions & background jobs applies the same patterns to refunds and seller payouts, and Jobs & schedules documents queue quotas and retry limits.

Type a word or two to search every docs page.