Guides · Integrations
Warehouse sync
Keep a warehouse table in step with your project. Copy existing rows once, then wake a sync worker on each webhook to apply committed changes in order.
- API
GET /changes- In the schema
- —
What you’ll build#
You will keep a live mirror of a shop’s orders in ClickHouse, Snowflake, BigQuery, PostgreSQL or DuckDB. A signed webhook wakes a single-concurrency worker whenever orders commit, so nothing polls between writes.
Backfill and incremental sync
One worker backfills existing rows, then streams committed change batches in order.
Three primitives drive the pipeline without external connector daemons or database superuser credentials.
- The change log
- GET /changes pages every committed write on the branch in commit order and returns only rows the reader’s service key is permitted to read.
- Notify events
- A
notifydeclaration on a schema type emits a named event whenever a transaction inserts, updates or deletes a matching row. - Two queries
- One query scans orders in keyset pages for initial backfills, and the other reloads the specific IDs named by a change batch in the exact shape the warehouse stores.
Before you start#
Enable cluster change-log storage, declare a notify trigger on the synced type and prepare a single-concurrency worker queue.
- Change-log storage
- Enable cluster log storage with
napalm storage enable <cluster> log. Without log storage,GET /changesreturns409 change_log_not_configured. - Notify trigger
- The schema below declares
order_changedonOrderso webhooks can subscribe to that event name. - Worker queue
- Run an HTTPS route to receive webhook pings and a job queue with concurrency one to process change pages sequentially.
- Single-shard branch
- The change log runs on single-shard branches. Multi-shard branches return
409 branch_distributedonGET /changesand reject row-carrying webhooks.
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 Product { required name: str; required description: str; required price_cents: int64; required is_listed: bool { default := true; }; notify product_changed after insert, update, delete; access policy anyone_reads_listed allow select using (.is_listed); access policy service_has_full_access allow all using (global role ?= 'service'); } type Order { required buyer: ext::auth::Identity; required product: Product; required total_cents: int64; required status: OrderStatus { default := OrderStatus.Pending; }; required place_time: datetime { readonly := true; default := datetime_of_statement(); }; notify order_changed after insert, update, delete; 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'); }}Create a read-only sync key#
The sync worker authenticates with a service key. Because a service key does not represent an end user, global caller is empty and user-level access policies match zero rows. Grant read access through a policy on global role instead, and add { "default::role": "service" } to serviceGlobals in the project’s endpoint settings through the console or the Control API.
# Allow service keys to call GET /changes alongside deployed queriesnapalm endpoint shop --passthrough keys # Create a dedicated read-only key and store the printed secret as NAPALM_SYNC_KEYnapalm keys create shop --label warehouse-sync --read-only # Audit how many rows the key can read or write before deploying the workernapalm keys reach shop <key-id> napalm queries push shopNapalm rejects every mutation from a --read-only key before execution, so the sync credential can read orders and products without risking accidental writes.
select Order { id, buyer_id := .buyer.id, product_id := .product.id, total_cents, status, place_time,}filter .id > <uuid>$afterorder by .idlimit <int64>$limitselect Order { id, buyer_id := .buyer.id, product_id := .product.id, total_cents, status, place_time,}filter .id in array_unpack(<array<uuid>>$ids)Backfill existing rows#
On its first run the worker holds no log bookmark yet, so it backfills the table in keyset pages. ordersAfter reads a thousand orders at a time in UUID order, writing each page before fetching the next.
// src/sync/orders.tsimport { NapalmClient, isGap } from 'napalm-client'import { cursors, warehouse } from '@/lib/warehouse' const address = process.env.NAPALM_URL!// Read-only service key scoped to warehouse sync.const napalm = new NapalmClient(address, { token: process.env.NAPALM_SYNC_KEY }) type Order = { id: string buyer_id: string product_id: string total_cents: number status: string place_time: string} const call = async <Row>(query: string, variables: Record<string, unknown>) => { const answer = await napalm.fetch(`${address}/query/${query}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ variables }), }) if (!answer.ok) throw new Error(`${query} answered ${answer.status}`) return ((await answer.json()) as { data: Row[] }).data} /** Backfills every order in keyset pages, then prunes deleted rows from the warehouse. */export async function copyOrders() { const began = new Date() let after = '00000000-0000-0000-0000-000000000000' for (;;) { const orders = await call<Order>('ordersAfter', { after, limit: 1000 }) if (!orders.length) break // upsert stamps each row with the current sync timestamp. await warehouse.upsert('orders', orders) after = orders[orders.length - 1].id } await warehouse.removeUntouchedSince('orders', began) // Start the log cursor one minute early so concurrent writes replay safely. return new Date(began.getTime() - 60_000).toISOString()}- Concurrent writes
- Orders continue mutating while the backfill runs. Starting the log cursor one minute before the backfill began replays that overlap idempotently without missing a commit.
- Deleted records
- A later full resync stamps every touched row with a fresh write time and deletes rows carrying an older stamp, pruning records deleted while the worker was offline.
Stream incremental changes#
napalm.changes pages GET /changes in commit order, oldest first. Each page returns an opaque next bookmark. Persist that bookmark in or beside your warehouse only after applying the page.
// src/sync/orders.ts, continued/** Streams committed Order changes from the saved cursor up to an optional webhook position. */export async function followOrders(reach?: string) { let from = await cursors.get('orders') if (!from) { // Run an initial backfill when no cursor exists yet. from = { since: await copyOrders() } await cursors.set('orders', from) } for await (const page of napalm.changes({ types: ['Order'], ...from, reach, limit: 500 })) { const changed = new Set<string>() const deleted = new Set<string>() let isWhole = true for (const item of page.items) { // Trigger a full resync if the log reports a gap or an oversized transaction. if (isGap(item) || !item.has_every_row) { isWhole = false continue } for (const row of item.rows) { if (row.op === 'delete') { deleted.add(row.id) changed.delete(row.id) } else { changed.add(row.id) } } } if (!isWhole) { await copyOrders() } else { // Reload changed IDs through a deployed query for a uniform warehouse schema. if (changed.size) await warehouse.upsert('orders', await call<Order>('ordersByIds', { ids: [...changed] })) if (deleted.size) await warehouse.remove('orders', [...deleted]) } // Save the bookmark only after applying the page so crashes replay rather than skip. if (page.next) await cursors.set('orders', { after: page.next }) }}- IDs from the log
- The worker collects each change’s
opandidfrom the log and reloads live rows throughordersByIds, giving the warehouse one uniform projection including links and computed fields. - Causal replica reads
- Each page advances the client’s session bookmark to the page’s position, so the next query observes at least those changes on any replica.
- Single concurrency
- Two workers sharing one cursor would apply pages out of order. Run the sync job queue at concurrency one.
Wake the worker on commit#
Attach a ping webhook to order_changed so commits wake the worker immediately instead of polling on a timer.
Signed commit pings
Each commit dispatches a signed ping carrying the latest log position.
Bounded log reads
Your worker drains every committed change up to that target bookmark.
Allow your receiver domain on the branch and subscribe to order_changed. Rapid consecutive writes coalesce into a single ping, and no row values cross the wire.
# Restrict outbound webhooks on this branch to hooks.example.comnapalm webhooks hosts shop --add hooks.example.com # Subscribe to order_changed pings (store the printed signing secret as NAPALM_WEBHOOK_SECRET)napalm webhooks add shop https://hooks.example.com/napalm --event order_changedIn the webhook route, verify the raw-byte HMAC and enqueue a deduplicated job carrying the ping’s Napalm-Position bookmark.
// src/app/hooks/napalm/route.tsimport { readDelivery, type Delivery } from 'napalm-client'import { jobs } from '@/lib/jobs' export async function POST(request: Request) { let delivery: Delivery try { // Verify the HMAC signature against 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 }) } // Ignore synthetic test deliveries from the console or CLI. if (delivery.kind === 'ping') { // Deduplicate retried pings by delivery ID. await jobs.add('follow-orders', { reach: delivery.position }, { id: delivery.id }) } // Acknowledge immediately and let the background worker read the log. return new Response(null, { status: 204 })}The queued job runs followOrders(reach). When reach is provided, GET /changes waits up to 30 seconds for the log to reach that position, so the worker never wakes prematurely. Between writes, no connection stays open and no timer runs.
- Failed deliveries
- If your route returns a non-2xx status, Napalm retries after 10 seconds with exponential backoff up to 5 minutes for one hour.
- Missed pings
- Every sync run starts from the worker’s saved cursor, so the next ping catches up across any missed deliveries.
- Out-of-order pings
- If a delayed ping runs after a newer job has already advanced the cursor past that position, the read finishes immediately with zero items.
Write idempotently#
Change-log reads run at least once. If the worker crashes between writing a page and saving its bookmark, the next run replays that page. Reloading current row state via ordersByIds and upserting by id makes replayed pages idempotent.
| Warehouse | Upsert a page | Remove |
|---|---|---|
| ClickHouse | Use ReplacingMergeTree ordered by id using the sync timestamp as the version column, and query with FINAL. | RemoveInsert a tombstone row where is_deleted = 1 (the engine’s second parameter). |
| PostgreSQL | insert … on conflict (id) do update set … | Removedelete from orders where id = any($1) |
| Snowflake, BigQuery | Load the page into a staging table, then MERGE the staging table into orders on id. | RemoveDELETE … WHERE id IN (…), or include a deleted flag in the MERGE. |
| DuckDB | INSERT OR REPLACE INTO orders keyed on primary key id. | RemoveDELETE FROM orders WHERE id IN (…) |
Handle gaps in the log#
When the log cannot return row-level detail for a range of commits, GET /changes emits an explicit gap item in stream order and continues afterward. Your worker handles every case below by running a fresh copyOrders() backfill.
has_every_row: false- A single transaction modified too many rows to inline. Affected schema types appear in
types. - Gap:
expired - The worker stayed offline past the cluster’s log retention window. Adjust retention with
napalm storage keep <cluster> log --days. - Gap:
unrecorded - Commits completed while change-log capture was unavailable.
- Gap:
lost - An unplanned failover discarded commits that the prior primary had acknowledged.
- Gap:
moved - The branch moved across shards or was recreated.
Store an append-only history#
Upserting by id keeps only the latest state of each order. To build an append-only audit or history table instead, write the row entries directly from GET /changes without calling ordersByIds. Every row entry includes four fields.
fields- Post-commit field values on
insertorupdate, and pre-delete values ondelete. - Value format
- Booleans, integers and floats serialize as JSON primitives. Other scalars use PostgreSQL text format (such as timestamps, decimals and enums), and single links carry the target record’s
id. previous- Prior values for fields modified by an
updateon a type with anotifytrigger. caller- Caller class (
sessionorkey) and protocol source (http,mcp,joborschedule), without individual user identities.
Key the history table by the transaction’s bookmark and the row’s index within the batch so replayed pages insert zero duplicates. Notifications & webhooks documents the full response schema.
Check the sync#
Verify the key’s reach
napalm keys reach shop <key-id>reports the readable order and product counts and confirms zero write access.Run the initial backfill
Run the worker once to populate the warehouse and save an initial bookmark. Run the worker a second time and confirm that zero rows copy.
Place an order
Insert an order and check
napalm webhooks deliveries shopfor a204ping response. The new order appears in the warehouse moments later, andnapalm changes shop --since 1hlogs the commit alongside its caller class.Test catch-up after downtime
Stop the worker, mutate several orders and start the worker again. The next webhook ping drains every missed commit from the saved bookmark.
Send a synthetic test ping
napalm webhooks test shop https:/returns/ hooks.example.com/ napalm 204and queues zero sync jobs.
If you prefer Napalm to push changed rows directly to your HTTPS endpoint instead of running a pull worker, attach a service key to the webhook. Search index & cache sync and Queues & streams use that push model.