Skip to the page

Guides · Integrations

Search index & cache sync

Keep external search indexes and caches synchronized with committed writes through signed webhook deliveries.

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 webhook cursor

Napalm tracks the log cursor and retries each batch until acknowledged.

Built-in vs external search

Built-in search enforces row policies, while external indexes mirror public storefront catalogs.

You don’t deploy a polling worker or maintain a separate cursor table in your database.

When to run an external index#

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

Typo tolerance and synonyms
Prefix matching, fuzzy spelling correction (such as “runing shoes”) and custom synonym lists.
Facet counts
Interactive sidebar filters showing live document counts per category, brand or price bracket.
Existing storefront UI
InstantSearch or prebuilt storefront widgets already wired to Algolia, Meilisearch or Typesense.

Mirror only public catalog records to an external index. Keep user-private or workspace-scoped records inside Napalm’s built-in search so row-level policies stay enforced.

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.

Change-log storage
Row-carrying webhooks read from the cluster’s change log (napalm storage enable <cluster> log). Without log storage, adding the webhook returns 409 change_log_not_configured.
Notify trigger
The schema declares product_changed on Product across inserts, updates and deletes.
Single-shard branch
Row-carrying webhooks run on single-shard branches. The change log does not yet cover multi-shard branches.
Service role
{ "default::role": "service" } in the endpoint’s serviceGlobals (configured as shown in Warehouse sync) lets a service key read both listed and unlisted products.
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 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');  }}

Subscribe to row deliveries#

Attaching --key to a webhook delivers committed row changes instead of empty pings. Each delivery streams a slice of the change log filtered by that service key’s select policies.

Ordered row batches

Napalm sends one policy-filtered batch at a time in commit order.

Signed causal deliveries

Each delivery carries an HMAC signature and a causal replica bookmark.

Search or cache sink

Your route updates the search index or evicts stale cache entries.

Enable service-key passthrough, create a dedicated read-only key and bind that key ID to your webhook endpoint.

Terminal
# Create a dedicated read-only service key and note its IDnapalm endpoint shop --passthrough keysnapalm keys create shop --label search-sync --read-only # Passing --key delivers changed row batches rather than empty pingsnapalm 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
Starting point
Delivery begins from the commit position when the webhook is created, covering every subsequent product write.
Single-flight order
One delivery stays in flight at a time until your route responds. Each payload packs up to 100 whole transactions or 1 MiB.
Automatic retries
Any non-2xx response retries from the same log position for as long as cluster log retention keeps those commits.
Key lifecycle
If the attached key expires, is revoked or is blocked by --passthrough none, deliveries pause in place until a valid key is restored.

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 {    // 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 })  }  const changes = delivery.transactions ?? []  // Queue a full rebuild on a log gap or an oversized transaction.  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) {    // Advance the client bookmark so replica reads include this delivery's commits.    if (delivery.position) napalm.reach(delivery.position)    const listed = (await call<Product>('productsByIds', { ids })).filter((product) => product.is_listed)    await index.save(listed)    // Delete any IDs that were removed or marked unlisted.    await index.remove(ids.filter((id) => !listed.some((product) => product.id === id)))  }  // Return 204 only after indexing succeeds so failed batches retry.  return new Response(null, { status: 204 })}
Duplicate deliveries
Retries carry the same product IDs, and reloading current state via productsByIds produces the exact same index state.
No stale overwrites
Because your route indexes live query results rather than historical payload fields, a delayed retry never overwrites newer edits.
Downstream outages
Await the search engine write before returning 204. If the search cluster is unreachable, returning 5xx lets Napalm retry the batch automatically.

Backfill and rebuild the index#

Register the webhook before running your initial reindexProducts() backfill. Any writes that commit while the backfill scans arrive via the webhook and re-read current state, leaving zero gap between snapshot and stream.

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!// Read-only service key attached to the search webhook.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} /** Scans every product in keyset pages, upserts listed items and prunes stale documents. */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 current sync timestamp.    await index.save(products.filter((product) => product.is_listed))    after = products[products.length - 1].id  }  await index.removeUntouchedSince(began)}

The same function heals gaps. When the change log emits kind: "gap" or a bulk write sets has_every_row: false, the webhook route queues reindex-products in the background. Stamping every upserted document and deleting older timestamps at the end prunes records deleted during the gap.

Keep private rows out of the index#

An external search engine does not evaluate your schema’s access policies, so anyone holding its public search key can query every document in the index.

Index public records only
Filter to product.is_listed in your route so unlisted drafts never reach the external index.
Tenant-scoped search
If you index tenant-owned records externally, issue short-lived scoped search tokens on your backend (Meilisearch tenant tokens, Algolia secured API keys or Typesense scoped keys).
Grant full read to the sync key
Because the change log omits rows hidden from the webhook’s service key, restricting the key’s policy to is_listed would hide the update that unlists a product, leaving stale listings in your search engine. Let the sync key read all Product rows and filter in the route.

Map operations to your search 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 (replaces by primary key)RemovedeleteDocuments(ids)Remove stale documentsdeleteDocuments({ filter }) on the timestamp
Typesensedocuments().import(docs, { action: "upsert" })Removedocuments(id).delete()Remove stale documentsdocuments().delete({ filter_by }) on the timestamp
AlgoliasaveObjects keyed by objectIDRemovedeleteObjectsRemove stale documentsdeleteBy({ filters }) on the timestamp
Elasticsearch, OpenSearch_bulk using index actions keyed by _idRemove_bulk using delete actionsRemove stale documents_delete_by_query filtering on the timestamp

Invalidate caches on commit#

For a cache, delete each changed key and let the next read repopulate the entry. 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
// Evict affected cache keys inside the same webhook routefor (const id of ids) await redis.del(`product:${id}`)

Check the sync#

  1. Send a synthetic test

    napalm webhooks test shop https://hooks.example.com/search reports the route’s response. Test deliveries carry zero rows, so the route indexes nothing.

  2. Backfill the index and update a product

    Run reindexProducts(), then edit a listed product’s name. The updated name becomes searchable moments after commit, and napalm webhooks ls shop reports the webhook as Delivering.

  3. Unlist one product and delete another

    Confirm that both documents disappear from search results.

  4. Verify catch-up after downtime

    Stop your webhook route for a minute while editing several products. Once the route restarts, Napalm delivers the queued batches in commit order and the index catches up.

For analytical warehouses where a worker pulls changes directly, see Warehouse sync. Notifications & webhooks documents every delivery header and payload field.

Type a word or two to search every docs page.