Skip to the page

Guides · Integrations

Search index & cache sync

Keep a search index or a cache in step with your rows. Napalm sends each committed change to a route that saves or removes the matching documents.

In the schema
—

What you’ll build#

You will keep an external search index of a shop’s listed products synchronized with every committed write. Napalm pushes ordered change batches to your HTTPS route, which reloads the affected product IDs at the delivery’s causal bookmark and upserts or removes documents in Algolia, Meilisearch, Typesense or OpenSearch. The exact same route invalidates Redis or CDN cache keys.

Managed cursor over committed rows

A --key webhook delivers committed row IDs in order with causal Napalm-Position bookmarks and retries until your route returns 2xx.

Built-in search vs storefront replicas

Keep access-controlled search inside Napalm with ext::ai::hybrid_search, and mirror public catalog rows to external engines only for storefront facets or typo tolerance.

You run no polling worker and store no cursor table. Napalm tracks the webhook’s position in the change log and advances it only after your route acknowledges the batch.

Decide whether you need a copy#

Napalm includes built-in vector and full-text search that evaluates each caller’s access rules during index scans, with no external copy to keep synchronized. Add a separate search engine only when you need one of three storefront capabilities.

Typo tolerance and synonyms
A search box that forgives “runing shoes”.
Facets and counts
Filters down the side of a catalog, each with a count of the matching items.
A search box already built
A front end written against Algolia, Meilisearch or Typesense.

Use the copy for rows everyone may find, like a catalog. Keep rows that only some people may read on Napalm’s own search.

Before you start#

Enable cluster change-log storage, declare a notify trigger on Product and grant the service role visibility across both listed and unlisted products.

A change log
Rows are read from the cluster’s change log (napalm storage enable <cluster> log). Without a change log, adding the webhook answers 409 change_log_not_configured.
A notify on the type
The schema declares product_changed on Product for inserts, updates and deletes.
A branch on one shard
Row-carrying webhooks support single-shard branches. The change log does not yet cover branches spread across multiple shards.
The service role
{ "default::role": "service" } in the endpoint’s serviceGlobals, as Warehouse sync sets the role. The rule that names the role lets a service key read unlisted products too.
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 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');  }}

Have the rows sent to you#

A webhook added with --key gets rows instead of pings. Each delivery is a stretch of the change log limited to the rows that key may read.

Ordered commit batches

Napalm streams committed Product transactions from the branch’s change log in order under the key’s select rules, one delivery in flight at a time.

Signed rows delivery

Each batch arrives sealed with Napalm-Signature HMAC-SHA256 and carries Napalm-Position so napalm.reach() reads fresh state on any replica.

External search or cache sink

Your route upserts listed documents and deletes unlisted IDs in Algolia, Meilisearch, Typesense or Redis before acknowledging with 204.

Terminal
# The key the rows are read as. It can only read. Note its id.napalm endpoint shop --passthrough keysnapalm keys create shop --label search-sync --read-only # Rows, not pings: the webhook is added with a keynapalm webhooks hosts shop --add hooks.example.comnapalm webhooks add shop https://hooks.example.com/search --event product_changed --key <key-id> napalm queries push shop
Start point
The moment the webhook is added. Every later write to a product is sent.
In order
One delivery is in flight at a time, and the next waits for your answer. A delivery holds up to 100 transactions or 1 MiB, always whole transactions.
Until answered
A delivery that is not answered with a 2xx is sent again from the same place for as long as the log keeps those rows.
The key
A key that is revoked, expired or held to deployed queries is sent nothing. The webhook waits in place until the key works again.

Index the delivered ids#

Extract the changed product IDs from the delivery, advance the client session to delivery.position and reload current product rows through a deployed query. Saving every listed result and removing every remaining ID handles inserts, edits, unlistings and deletes with one rule.

dbschema/queries/productsByIds.edgeql
select Product { id, name, description, price_cents, is_listed }filter .id in array_unpack(<array<uuid>>$ids)
src/app/hooks/search/route.ts
// src/app/hooks/search/route.tsimport { readDelivery, type Delivery } from 'napalm-client'import { jobs } from '@/lib/jobs'import { index } from '@/lib/search'import { call, napalm, type Product } from '@/sync/products' 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 })  }  const changes = delivery.transactions ?? []  // A stretch the log couldn't give, or a change too big to list: fill the index again, in the background.  if (delivery.kind === 'gap' || changes.some((change) => !change.has_every_row)) {    await jobs.add('reindex-products', {}, { id: delivery.id })  }  const ids = [...new Set(changes.flatMap((change) => change.rows.map((row) => row.id)))]  if (ids.length) {    // The read below then sees this delivery's changes, whichever machine answers.    if (delivery.position) napalm.reach(delivery.position)    const listed = (await call<Product>('productsByIds', { ids })).filter((product) => product.is_listed)    await index.save(listed)    // A product the query didn't give back as listed was deleted or unlisted.    await index.remove(ids.filter((id) => !listed.some((product) => product.id === id)))  }  // Only now. An answer that isn't 2xx has the same rows sent again.  return new Response(null, { status: 204 })}
A delivery sent twice
The repeat names the same ids, and the route reads those products’ current state. The index ends up the same.
An old value
The route never saves a value from the delivery, so a repeat cannot restore an old value.
A slow engine
The answer waits for the index. If the engine is down, the route fails and Napalm sends the same rows again later.

Fill and refill the index#

Add the webhook first, then fill the index once. Changes made during the fill arrive through the webhook, and the route reads those products again. No change falls between the fill and the webhook.

dbschema/queries/productsAfter.edgeql
select Product { id, name, description, price_cents, is_listed }filter .id > <uuid>$afterorder by .idlimit <int64>$limit
src/sync/products.ts
// src/sync/products.tsimport { NapalmClient } from 'napalm-client'import { index } from '@/lib/search' const address = process.env.NAPALM_URL!// The read-only key the webhook was added with.export const napalm = new NapalmClient(address, { token: process.env.NAPALM_SYNC_KEY }) export type Product = { id: string; name: string; description: string; price_cents: number; is_listed: boolean } export 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} /** Fills the index from every product, then removes what it still holds that isn't listed any more. */export async function reindexProducts() {  const began = new Date()  let after = '00000000-0000-0000-0000-000000000000'  for (;;) {    const products = await call<Product>('productsAfter', { after, limit: 1000 })    if (!products.length) break    // save stamps each document with the time it was written.    await index.save(products.filter((product) => product.is_listed))    after = products[products.length - 1].id  }  await index.removeUntouchedSince(began)}

The same function handles a gap. When the change log cannot give a stretch, the delivery carries kind: "gap". A transaction too big to list carries has_every_row: false. The route queues a fill for both. Each document is stamped on save, and documents the fill did not touch are removed at the end.

Keep private rows out of the index#

A search engine does not apply your access rules, so anyone with the engine’s search key can find every document in the index.

Index public rows only
The route saves listed products only. An unlisted product is read by the service key and then left out.
Owned rows
Search owned rows from your server with a key scoped to the owner. Meilisearch has tenant tokens, Algolia has secured API keys and Typesense has scoped search keys.
Read every row, then filter
The change log leaves out a row the key cannot read. A sync key that saw only listed products would never get the change that unlisted a product, and the index would keep that product. Let the key read every product and filter in the route.

Map the calls to your engine#

Map index.save, index.remove and timestamp-based stale pruning to your search engine’s bulk upsert and delete calls.

EngineSaveRemoveRemove stale documents
MeilisearchaddDocuments, which replaces by primary keyRemovedeleteDocuments(ids)Remove stale documentsdeleteDocuments({ filter }) on the stamp
Typesensedocuments().import(docs, { action: "upsert" })Removedocuments(id).delete()Remove stale documentsdocuments().delete({ filter_by }) on the stamp
AlgoliasaveObjects, by objectIDRemovedeleteObjectsRemove stale documentsdeleteBy({ filters }) on the stamp
Elasticsearch, OpenSearch_bulk with index actions, by _idRemove_bulk with delete actionsRemove stale documents_delete_by_query with a range on the stamp

Empty a cache the same way#

For a cache, delete each changed key and let the next read repopulate it. Writing values directly from a webhook could overwrite a newer value with an older delivery, whereas key invalidation stays safe across retries.

src/app/hooks/search/route.ts
// In the same route, for a cache in place of an indexfor (const id of ids) await redis.del(`product:${id}`)

Check the sync#

  1. Send a test

    napalm webhooks test shop https://hooks.example.com/search answers with the route’s outcome. A test names no rows, and the route saves nothing.

  2. Fill the index, then change a product’s name

    The new name is searchable a moment after the write commits. napalm webhooks ls shop shows the webhook’s health.

  3. Unlist a product, then delete another

    Both leave the index.

  4. Stop the route for a minute

    Change a few products while the route is down. When the route is back, the missed deliveries arrive in order and the index catches up.

For a warehouse, where a worker reads the log directly, see Warehouse sync. Notifications & webhooks has every field of a delivery.

Type a word or two to search every docs page.