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 current copy of a shop’s orders in an analytical warehouse. A worker copies every existing order once, then applies committed changes incrementally. A signed webhook wakes the worker on commit, so nothing polls between writes. The same worker feeds ClickHouse, Snowflake, BigQuery, Postgres and DuckDB.
Snapshot backfill to incremental warehouse sync
Run one keyset scan to seed the warehouse table, then stream incremental GET /changes batches across a durable cursor into ClickHouse, Snowflake, BigQuery, Postgres or DuckDB.
- The change log
- Every committed change of a branch in commit order, paged over HTTPS with GET /changes. The log returns only rows the reader’s service key is permitted to read.
- A notify
- One declaration on a type that names an event. A webhook subscribed to that event receives a signed ping whenever a write to the type commits.
- 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.
- A change log
- A cluster keeps a change log once log storage is on (
napalm storage enable <cluster> log). Until then,GET /changesanswers409 change_log_not_configured. - A notify on the type
- The schema below declares
order_changedonOrder. A webhook follows an event by that name. - Somewhere to run code
- A route that answers HTTPS for the webhook, and a job queue that runs one job at a time for the worker.
- A branch on one shard
- The change log does not yet cover a branch spread over several shards. On such a branch, a change log read answers
409 branch_distributedand a rows webhook cannot be added.
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 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'); }}Give the sync a read-only key#
The sync reads as a service key. A service key is not a person, so global caller is empty and the buyer’s rule shows the key nothing. The rules that name global role let the key read. Add { "default::role": "service" } to serviceGlobals in the project’s endpoint settings through the console or the Control API.
# The change log reads past your deployed queries, so service keys must be let past themnapalm endpoint shop --passthrough keys # A key for the sync alone. It can only read. It’s shown once: store it as NAPALM_SYNC_KEY.napalm keys create shop --label warehouse-sync --read-only # What it can reach, before anything depends on itnapalm keys reach shop <key-id> napalm queries push shopNapalm refuses every write from a --read-only key before the statement runs. A copy of the sync key can read orders and products and cannot change a row.
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)Copy every row once#
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!// The sync’s own key, which can only read.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} /** Copies every order, then removes what the warehouse holds that the project no longer does. */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 time it was written. await warehouse.upsert('orders', orders) after = orders[orders.length - 1].id } await warehouse.removeUntouchedSince('orders', began) // Where to read the log from. A minute early: it repeats a little and misses nothing. return new Date(began.getTime() - 60_000).toISOString()}- Orders that change meanwhile
- 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.
- Rows that are gone
- 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.
Then follow the 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.
Causal change-log cursor and bookmarks
Each GET /changes page advances a Napalm-Bookmark pin along committed transaction blocks, carrying session causality so follow-up ordersByIds reads observe those commits on every replica.
// src/sync/orders.ts, continued/** Applies what changed since the cursor. Given a webhook’s position, it reads exactly up to it. */export async function followOrders(reach?: string) { let from = await cursors.get('orders') if (!from) { // Nothing copied yet: copy everything, then read the log from when the copy began. 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) { // A stretch the log can’t give, or a change too big to read by the row. 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 { // The log says which orders changed. The query reads them as the warehouse stores them. if (changed.size) await warehouse.upsert('orders', await call<Order>('ordersByIds', { ids: [...changed] })) if (deleted.size) await warehouse.remove('orders', [...deleted]) } // Saved only once the page is applied: a crash repeats a page and never skips one. 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 with links and computed fields. - A read that sees the change
- 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.
- One worker at a time
- Two workers sharing one cursor would apply pages out of order. Run the sync job with a concurrency of 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 ping wake-up
Each order_changed commit dispatches a lightweight HMAC-SHA256 signed ping carrying Napalm-Position with zero row values on the wire.
Bounded reach read
Passing delivery.position as reach on GET /changes drains every committed batch from your saved cursor through that exact commit.
# Webhooks from this branch may go to this host and no othernapalm webhooks hosts shop --add hooks.example.com # A ping whenever an order commits. Its signing secret is shown once: store it as NAPALM_WEBHOOK_SECRET.napalm webhooks add shop https://hooks.example.com/napalm --event order_changedA ping names the event that fired and the branch’s position (Napalm-Position) but carries no rows. Several writes close together share one ping.
// 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 { // 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 }) } // A test from the console or the CLI is some other kind, and moves nothing. if (delivery.kind === 'ping') { // A retried ping keeps its id, so one sent twice is queued once. await jobs.add('follow-orders', { reach: delivery.position }, { id: delivery.id }) } // Answer first. The job does the reading. return new Response(null, { status: 204 })}The job calls followOrders(reach). With a position given, a read waits up to 30 seconds for the log to reach that position, so the job never wakes to find nothing. Between writes, no connection is open and no timer runs.
- A ping that fails
- Napalm retries any answer but a 2xx after 10 seconds, then at doubling waits of up to 5 minutes. Retries stop after an hour.
- A lost ping
- The next ping covers the lost ping. Each read starts from the worker’s saved cursor, so one ping catches up on any number of writes.
- Pings out of order
- An older ping’s job finds the log already read past the ping’s position and ends after one call.
Write idempotently#
The log is read at least once, because a crash between writing a page and saving its bookmark repeats that page. Instead of values from the log, the worker writes the query’s current result keyed by id, so a repeat writes the same row again.
| Warehouse | Upsert a page | Remove |
|---|---|---|
| ClickHouse | A ReplacingMergeTree ordered by id, with the stamp as the version column. Insert the rows and read with FINAL. | RemoveInsert a row with is_deleted = 1, the engine’s second argument. |
| Postgres | 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 the same MERGE with a deleted flag. |
| DuckDB | INSERT OR REPLACE INTO orders, with id the primary key. | RemoveDELETE FROM orders WHERE id IN (…) |
Handle gaps in the log#
The log marks a gap in place, and reading continues after the gap. The worker resolves every case below with a fresh full copy.
has_every_row: false- One transaction changed too many rows to list. The page names the changed types in
types. - A gap,
expired - The worker was away longer than the log is kept.
napalm storage keep <cluster> log --dayssets the log’s retention. - A gap,
unrecorded - Changes that never reached the log.
- A gap,
lost - A failover removed commits the last primary had acknowledged.
- A gap,
moved - The branch moved to another shard or was recreated.
Keep every version instead#
A copy holds each order’s current state. For an append-only history table of every change, write the log’s own rows directly and skip the query. Every row entry in a change carries four fields.
fields- The object after an insert or update, and before a delete.
- Value format
- Booleans, integers and floats are JSON values. Other values are PostgreSQL’s text form, such as a datetime, a decimal or an enum value. A single link such as
buyeris the linked object’sid. previous- For an update of a type a notify watches, the fields the update changed, with the old values.
caller- The caller class (user session or service key) and protocol source, such as
httpormcp, without individual user identities.
Key the table by the change’s bookmark and the row’s place in the change, so a repeated page inserts nothing new. Notifications & webhooks lists every field.
Check the sync#
Count the key’s reach
napalm keys reach shop <key-id>counts orders and products and shows that the key cannot write.Run the worker once
The warehouse holds every order, and the cursor holds a bookmark. Run the worker again, and nothing is copied.
Place an order
napalm webhooks deliveries shopshows a ping answered 204. The order is in the warehouse a moment later.napalm changes shop --since 1hshows the same change with the kind of caller.Stop the worker, change some orders and restart the worker
The first ping after the restart brings the warehouse up to date from the saved bookmark.
Send a test
napalm webhooks test shop https:/is answered 204 and queues nothing./ hooks.example.com/ napalm
To have the rows sent to a route instead of read by a worker, add the webhook with a key. Search index & cache sync and Queues & streams are built that way.