> ## Documentation Index
> Fetch the complete documentation index at: https://docs.moss.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Postgres Sync

> Keep Moss in step with a Postgres table through an outbox, or move the table into Moss.

This recipe is for an application that keeps agent memory, or any other searchable facts, in
Postgres (Supabase included) and wants to retrieve them with Moss. It covers two setups:

1. **Moss replaces Postgres** as the store for these facts.
2. **Postgres stays the source of truth**, and Moss is the retrieval layer.

Both use the same pieces: a document mapping, an index layout, a backfill, an outbox that
syncs every change, and a reconciliation check. Those come first, then the steps for each setup.
For the rules behind them, see [From a database](https://docs.moss.dev/docs/integrate/indexing-data.md#from-a-database).

## What you need

* Postgres 14 or later, or Supabase.
* A Moss project ID and key.
* `@moss-js/moss` or `moss` 1.25 or later. From 1.25 the SDK runs the writes to one index one at a
  time, and sends a write that meets a running build (`BUILD_IN_PROGRESS`) again for up to a
  minute. Older versions fail it at once.
* For JavaScript, Node.js with `pg`. The code runs as an ES module, where `await` works at the top
  level.
* For Python, `psycopg` 3. Run the async functions with `asyncio.run`, as the worker below does.
  On Windows, psycopg's async connections need a selector event loop: from Python 3.12, pass
  `loop_factory=asyncio.SelectorEventLoop` to `asyncio.run`, and before 3.12, call
  `asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())` first.

## The table

The examples use one table of facts. Each fact belongs to a business and, optionally, to one of
its locations. Rename the columns to fit your schema.

The tables live in their own schema, `memory_sync`. Supabase's Data API serves only the schemas it
is set to expose, `public` by default, and its API roles get no access to a new schema until you
grant it, so no API key can read the facts or the outbox. If the tables must stay in `public`, write
`public` for `memory_sync` throughout. In the transaction that creates each table, enable row level
security on it and revoke every grant of the `anon` and `authenticated` roles. Row level security
does not bind a table's owner, so the trigger below keeps working, but the backend roles granted
below need a policy on each table they use.

```sql theme={null}
CREATE SCHEMA memory_sync;

-- Letters, digits and _, in groups joined by single dashes, at most 64 characters.
CREATE FUNCTION memory_sync.is_scope_id(value text) RETURNS boolean
LANGUAGE sql IMMUTABLE AS $$
  SELECT value ~ '^[A-Za-z0-9_]+(-[A-Za-z0-9_]+)*$' AND length(value) <= 64
$$;

CREATE TABLE memory_sync.memory_facts (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  business_id text NOT NULL CHECK (memory_sync.is_scope_id(business_id)),
  location_id text CHECK (memory_sync.is_scope_id(location_id)),  -- null for a fact that applies to every location
  fact_type text NOT NULL CHECK (octet_length(fact_type) <= 100),
  content text NOT NULL CHECK (octet_length(content) <= 100000),
  updated_at timestamptz NOT NULL DEFAULT now(),
  deleted_at timestamptz  -- set by a soft delete
);

-- Reads the facts of one business or location in id order.
CREATE INDEX memory_facts_by_scope ON memory_sync.memory_facts (business_id, location_id, id)
  WHERE deleted_at IS NULL;

-- Roles that do not own the tables, never a Data API role. app_backend writes facts and checks
-- scopes, and moss_sync runs the sync worker. Give app_backend the sequence of a serial id too.
GRANT USAGE ON SCHEMA memory_sync TO app_backend, moss_sync;
GRANT SELECT, INSERT, UPDATE, DELETE ON memory_sync.memory_facts TO app_backend;
GRANT SELECT ON memory_sync.memory_facts TO moss_sync;
```

The scope rule checks the form of business and location ids, not who may read them. It keeps them
safe to use in index names and filters, as the next two sections explain. UUIDs pass, and so do
numbers that are not negative. The size rules keep every document far inside one Moss request, even
after JSON escaping. Bound any other column you map to metadata the same way.

On an existing table, first create the schema and `is_scope_id`, and give every fact a business, a
type and content: the outbox below refuses a change without a business, and each document needs the
other two. Then run the SQL below, which moves the table and adds the rules, and the index and the
grants above. Point the application's SQL at `memory_sync.memory_facts`. To keep the table in
`public`, skip the move. The casts let the rules work on `uuid` and integer columns too, and the
change fails while any row breaks one.

```sql theme={null}
ALTER TABLE memory_facts SET SCHEMA memory_sync;

ALTER TABLE memory_sync.memory_facts
  ALTER COLUMN business_id SET NOT NULL,
  ALTER COLUMN fact_type SET NOT NULL,
  ALTER COLUMN content SET NOT NULL,
  ADD CONSTRAINT memory_facts_scope CHECK (memory_sync.is_scope_id(business_id::text)
    AND (location_id IS NULL OR memory_sync.is_scope_id(location_id::text))),
  ADD CONSTRAINT memory_facts_size CHECK (octet_length(content) <= 100000 AND octet_length(fact_type) <= 100);
```

Each process opens one Moss client and shares it: the sync worker for its writes, and an
application process for every session it serves. Clients in a process share the embedding model,
but each holds its own copy of the indexes it loads. See [Memory sizing](https://docs.moss.dev/docs/integrate/memory-sizing.md).

```js JavaScript theme={null}
import pg from 'pg'
import { MossClient, isMossError } from '@moss-js/moss'

// Keepalives notice a connection that dropped without an error, and the timeout ends a stuck query.
const db = new pg.Client({
  connectionString: process.env.DATABASE_URL,
  keepAlive: true,
  keepAliveInitialDelayMillis: 30_000,
})
await db.connect()
await db.query("SET statement_timeout = '60s'")
const client = new MossClient(process.env.MOSS_PROJECT_ID, process.env.MOSS_PROJECT_KEY)

// Closing the client sends its last usage report.
const stop = (code) => client.close().finally(() => process.exit(code))
process.on('SIGTERM', () => stop(0))
process.on('SIGINT', () => stop(0))
// A pg client cannot reconnect, so a lost connection ends the process for its manager to restart.
db.on('error', (error) => console.error('Lost the Postgres connection:', error))
db.on('end', () => stop(1))
```

```python Python theme={null}
import asyncio
import contextlib
import json
import logging
import os
import re
import signal
import time
import psycopg
from psycopg.rows import dict_row
from moss import DocumentInfo, MossClient, MossError, QueryOptions

async def connect():
    # Keepalives notice a connection that dropped without an error, and the timeout ends a stuck query.
    db = await psycopg.AsyncConnection.connect(
        os.environ["DATABASE_URL"], row_factory=dict_row, autocommit=True,
        keepalives=1, keepalives_idle=30, keepalives_interval=10, keepalives_count=3,
    )
    await db.execute("SET statement_timeout = '60s'")
    client = MossClient(os.environ["MOSS_PROJECT_ID"], os.environ["MOSS_PROJECT_KEY"])
    return db, client
```

## Map each row to a document

Each row becomes one Moss document, keyed by the fact id, so every later edit and delete
addresses the same document.

| Postgres column | Moss document |
| - | - |
| `id` | `id`, as a string |
| `content` | `text`, the part that is embedded and searched |
| `business_id` | `metadata.business_id` |
| `location_id` | `metadata.location_id`, or `"*"` for a business-wide fact |
| `fact_type` | `metadata.fact_type` |

Metadata values are strings. A business-wide fact gets the location `"*"`, so one filter returns
both a location's own facts and its business's facts. The scope rule keeps `*` out of real
location ids, so no location's facts can pass as business-wide. Soft-deleted rows are not copied.

```js JavaScript theme={null}
const ALL_LOCATIONS = '*'

// The queries below add conditions to this one, so keep its WHERE clause last.
const FACTS_SQL = `
  SELECT id, business_id, location_id, fact_type, content
  FROM memory_sync.memory_facts
  WHERE deleted_at IS NULL`

function toDocument(row) {
  return {
    id: String(row.id),
    text: row.content,
    metadata: {
      business_id: String(row.business_id),
      location_id: row.location_id === null ? ALL_LOCATIONS : String(row.location_id),
      fact_type: row.fact_type,
    },
  }
}
```

```python Python theme={null}
ALL_LOCATIONS = "*"

# The queries below add conditions to this one, so keep its WHERE clause last.
FACTS_SQL = """
  SELECT id, business_id, location_id, fact_type, content
  FROM memory_sync.memory_facts
  WHERE deleted_at IS NULL"""

def to_document(row):
    return DocumentInfo(
        id=str(row["id"]),
        text=row["content"],
        metadata={
            "business_id": str(row["business_id"]),
            "location_id": ALL_LOCATIONS if row["location_id"] is None else str(row["location_id"]),
            "fact_type": row["fact_type"],
        },
    )
```

## Choose an index layout

**Shared index.** One index, called `memory` here, holds every fact, and each query is filtered
to the caller's business and location. See [Metadata filtering](https://docs.moss.dev/docs/integrate/metadata-filtering.md).

**Scoped indexes.** One index per business (`memory--<business_id>`) for its business-wide facts,
and one per location (`memory--<business_id>--<location_id>`). A session searches its two with
[multi-index search](https://docs.moss.dev/docs/integrate/multi-index-search.md) and never loads another business's facts.

| | Shared index | Scoped indexes |
| - | - | - |
| Indexes to manage | one | one per business and per location |
| Isolation between businesses | by filter | by index |
| What a process loads into memory | every fact | the indexes of the sessions it serves |
| What a write rebuilds, and replicas download | the whole index | one small index |

The shared index suits writes that are few or batched. When facts are written during most
sessions, scoped indexes keep each write and each download small. The code below handles both;
set `LAYOUT` to pick one.

Scoped index names join the ids with `--`. Under the scope rule an id never starts or ends with a
dash or holds two in a row, so two different scopes never share a name. `INDEX` follows the same
rule and has at most 124 characters. A scoped name adds at most 132 to it, so every name stays
within the 256-byte limit on index names, and the code stops at startup when `INDEX` breaks the
rule. No other index may start with `INDEX` and `--`, since the repair below checks every such index.

```js JavaScript theme={null}
const LAYOUT = 'shared' // or 'scoped'
const INDEX = 'memory' // the shared index, or the name prefix of the scoped ones

// The rule of is_scope_id, plus room for the two ids of a scoped name.
const SCOPE_ID = /^[A-Za-z0-9_]+(-[A-Za-z0-9_]+)*$/
const isScopeId = (id) => SCOPE_ID.test(id) && id.length <= 64
if (!SCOPE_ID.test(INDEX) || INDEX.length > 124) throw new Error(`INDEX breaks the naming rule: ${INDEX}`)

function indexFor(businessId, locationId) {
  if (LAYOUT === 'shared') return INDEX
  return locationId === ALL_LOCATIONS
    ? `${INDEX}--${businessId}`
    : `${INDEX}--${businessId}--${locationId}`
}

function indexOf(doc) {
  return indexFor(doc.metadata.business_id, doc.metadata.location_id)
}

// The shared index needs this filter on every query.
function scopeFilter(businessId, locationId) {
  return {
    $and: [
      { field: 'business_id', condition: { $eq: businessId } },
      { field: 'location_id', condition: { $in: [locationId, ALL_LOCATIONS] } },
    ],
  }
}
```

```python Python theme={null}
LAYOUT = "shared"  # or "scoped"
INDEX = "memory"  # the shared index, or the name prefix of the scoped ones

# The rule of is_scope_id, plus room for the two ids of a scoped name.
SCOPE_ID = re.compile(r"[A-Za-z0-9_]+(-[A-Za-z0-9_]+)*")
if not SCOPE_ID.fullmatch(INDEX) or len(INDEX) > 124:
    raise ValueError(f"INDEX breaks the naming rule: {INDEX}")

def is_scope_id(value):
    return len(value) <= 64 and SCOPE_ID.fullmatch(value) is not None

def index_for(business_id, location_id):
    if LAYOUT == "shared":
        return INDEX
    if location_id == ALL_LOCATIONS:
        return f"{INDEX}--{business_id}"
    return f"{INDEX}--{business_id}--{location_id}"

def index_of(doc):
    return index_for(doc.metadata["business_id"], doc.metadata["location_id"])

# The shared index needs this filter on every query.
def scope_filter(business_id, location_id):
    return {"$and": [
        {"field": "business_id", "condition": {"$eq": business_id}},
        {"field": "location_id", "condition": {"$in": [location_id, ALL_LOCATIONS]}},
    ]}
```

## Write to Moss

* `addDocs` / `add_docs` adds documents and replaces any stored document with the same id, so an
  edit is one call. A row that moved to another scoped index is a delete from the old one and an
  add to the new one.
* `deleteDocs` / `delete_docs` deletes by id. Deleting an id that is not stored succeeds, so a
  retry is always safe.
* Each write rebuilds the index and publishes a new version, which takes seconds and grows with
  the index. Loaded copies pick up the new version on their next load or
  [auto refresh](https://docs.moss.dev/docs/build/data-hydration-sync.md).

Three rules follow:

1. **One writer per index.** The SDK runs writes to one index one at a time inside a process. A
   write from another process or host that arrives during a build is sent again for up to a minute,
   then fails, so send writes through one worker, as the outbox below does. In Python, await each
   write before the next when their order matters.
2. **Batch.** Collect changes for a few seconds, then send one add and one delete per index, not
   one call per row.
3. **Stay within the request limits.** A request takes up to 100,000 documents and a 50 MB body.
   The backfill, the sync and the repair all write through the helpers below, which split every
   add and every delete into requests of at most 10,000 items and 20 MB of JSON. That leaves more
   than half of the 50 MB for the rest of the request body.

The helpers also create an index on its first write and skip deletes on an index that is gone. An
item larger than 20 MB on its own raises an error that names its id, instead of being sent. The
size rules on the table keep such a fact out of it.

```js JavaScript theme={null}
const MAX_ITEMS = 10_000
const MAX_BYTES = 20_000_000
const isNotFound = (error) => isMossError(error) && error.code === 'NOT_FOUND'

// Splits documents or ids into requests. Each item counts its JSON and a comma.
function* batches(items) {
  let batch = []
  let bytes = 0
  for (const item of items) {
    const size = Buffer.byteLength(JSON.stringify(item)) + 1
    if (size > MAX_BYTES) throw new Error(`${item.id ?? item} is too large for one request`)
    if (batch.length === MAX_ITEMS || bytes + size > MAX_BYTES) {
      yield batch
      batch = []
      bytes = 0
    }
    batch.push(item)
    bytes += size
  }
  if (batch.length > 0) yield batch
}

async function write(client, name, docs) {
  for (const batch of batches(docs)) {
    try {
      await client.addDocs(name, batch)
    } catch (error) {
      if (!isNotFound(error)) throw error
      await client.createIndex(name, batch)
    }
  }
}

async function remove(client, name, ids) {
  for (const batch of batches(ids)) {
    try {
      await client.deleteDocs(name, batch)
    } catch (error) {
      if (!isNotFound(error)) throw error
      return
    }
  }
}
```

```python Python theme={null}
MAX_ITEMS = 10_000
MAX_BYTES = 20_000_000

# The JSON of a document or an id, plus a comma.
def request_size(item):
    if isinstance(item, DocumentInfo):
        item = {"id": item.id, "text": item.text, "metadata": item.metadata}
    return len(json.dumps(item, ensure_ascii=False).encode()) + 1

def batches(items):
    batch, size = [], 0
    for item in items:
        item_size = request_size(item)
        if item_size > MAX_BYTES:
            raise ValueError(f"{getattr(item, 'id', item)} is too large for one request")
        if len(batch) == MAX_ITEMS or size + item_size > MAX_BYTES:
            yield batch
            batch, size = [], 0
        batch.append(item)
        size += item_size
    if batch:
        yield batch

async def write(client, name, docs):
    for batch in batches(docs):
        try:
            await client.add_docs(name, batch)
        except MossError as error:
            if error.code != "NOT_FOUND":
                raise
            await client.create_index(name, batch)

async def remove(client, name, ids):
    for batch in batches(ids):
        try:
            await client.delete_docs(name, batch)
        except MossError as error:
            if error.code != "NOT_FOUND":
                raise
            return
```

## Backfill

The backfill writes one index at a time and reads its facts `PAGE_SIZE` rows at a time, so the
table never has to fit in memory. At the 100,000-byte limit on `content`, the default of 500 rows
holds at most about 50 MB, and the sync below reads its outbox in rounds of the same size. Each page
is one write and one index build, so with short facts, raise `PAGE_SIZE` for fewer builds. The
backfill is safe to run again, since a write replaces documents with the same id. For a one-off
copy of a Supabase table into one new index, see [Data connectors](https://docs.moss.dev/docs/integrations/data-connectors.md).

```js JavaScript theme={null}
const PAGE_SIZE = 500 // rows read from Postgres at once

// An index, with the condition on FACTS_SQL that selects its facts.
function scopeOf(businessId, locationId) {
  if (locationId === null) {
    const where = ' AND business_id = $1 AND location_id IS NULL'
    return { name: indexFor(String(businessId), ALL_LOCATIONS), where, params: [businessId] }
  }
  const where = ' AND business_id = $1 AND location_id = $2'
  return { name: indexFor(String(businessId), String(locationId)), where, params: [businessId, locationId] }
}

async function listScopes(db) {
  if (LAYOUT === 'shared') return [{ name: INDEX, where: '', params: [] }]
  const { rows } = await db.query(`SELECT DISTINCT business_id, location_id FROM (${FACTS_SQL}) AS facts`)
  return rows.map((row) => scopeOf(row.business_id, row.location_id))
}

// Reads the facts of one scope in pages, in id order.
async function* readPages(db, scope) {
  let after = ''
  let params = scope.params
  for (;;) {
    const { rows } = await db.query(`${FACTS_SQL}${scope.where}${after} ORDER BY id LIMIT ${PAGE_SIZE}`, params)
    if (rows.length > 0) yield rows.map(toDocument)
    if (rows.length < PAGE_SIZE) return
    params = [...scope.params, rows.at(-1).id]
    after = ` AND id > $${params.length}`
  }
}

async function backfill(db, client) {
  for (const scope of await listScopes(db)) {
    for await (const docs of readPages(db, scope)) await write(client, scope.name, docs)
  }
}
```

```python Python theme={null}
PAGE_SIZE = 500  # rows read from Postgres at once

# An index, with the condition on FACTS_SQL that selects its facts.
def scope_of(business_id, location_id):
    if location_id is None:
        where, params = " AND business_id = %s AND location_id IS NULL", [business_id]
        return index_for(str(business_id), ALL_LOCATIONS), where, params
    where, params = " AND business_id = %s AND location_id = %s", [business_id, location_id]
    return index_for(str(business_id), str(location_id)), where, params

async def list_scopes(db):
    if LAYOUT == "shared":
        return [(INDEX, "", [])]
    cursor = await db.execute(f"SELECT DISTINCT business_id, location_id FROM ({FACTS_SQL}) AS facts")
    return [scope_of(row["business_id"], row["location_id"]) for row in await cursor.fetchall()]

# Reads the facts of one scope in pages, in id order.
async def read_pages(db, where, params):
    after, last = "", []
    while True:
        cursor = await db.execute(f"{FACTS_SQL}{where}{after} ORDER BY id LIMIT {PAGE_SIZE}", params + last)
        rows = await cursor.fetchall()
        if rows:
            yield [to_document(row) for row in rows]
        if len(rows) < PAGE_SIZE:
            return
        after, last = " AND id > %s", [rows[-1]["id"]]

async def backfill(db, client):
    for name, where, params in await list_scopes(db):
        async for docs in read_pages(db, where, params):
            await write(client, name, docs)
```

## Sync every change through an outbox

A trigger records every insert, update and delete of a fact in an outbox table, in the same
transaction as the change, so no write path can skip Moss. Row triggers do not fire on `TRUNCATE`,
so reconcile after one.

```sql theme={null}
CREATE TABLE IF NOT EXISTS memory_sync.memory_outbox (
  seq bigserial PRIMARY KEY,
  fact_id text NOT NULL,
  business_id text NOT NULL,
  location_id text,
  created_at timestamptz NOT NULL DEFAULT now()
);

-- A row names the fact and the scope it was in. An update that changes the id
-- or the scope gets one row for the old fact and one for the new.
CREATE OR REPLACE FUNCTION memory_sync.memory_outbox_enqueue() RETURNS trigger
LANGUAGE plpgsql SECURITY DEFINER SET search_path = memory_sync, pg_temp AS $$
BEGIN
  IF TG_OP IN ('UPDATE', 'DELETE') THEN
    INSERT INTO memory_sync.memory_outbox (fact_id, business_id, location_id)
    VALUES (OLD.id::text, OLD.business_id, OLD.location_id);
  END IF;
  IF TG_OP = 'INSERT' OR (TG_OP = 'UPDATE' AND (NEW.id, NEW.business_id, NEW.location_id)
      IS DISTINCT FROM (OLD.id, OLD.business_id, OLD.location_id)) THEN
    INSERT INTO memory_sync.memory_outbox (fact_id, business_id, location_id)
    VALUES (NEW.id::text, NEW.business_id, NEW.location_id);
  END IF;
  RETURN NULL;
END
$$;

CREATE OR REPLACE TRIGGER memory_facts_outbox
  AFTER INSERT OR UPDATE OR DELETE ON memory_sync.memory_facts
  FOR EACH ROW EXECUTE FUNCTION memory_sync.memory_outbox_enqueue();

-- The sync worker reads the outbox and deletes what it sent.
GRANT SELECT, DELETE ON memory_sync.memory_outbox TO moss_sync;
```

The function runs as its owner, the role that ran this SQL, so the roles that write facts need no
grants on the outbox.

A sync drains the outbox in batches. For each row it reads the fact's current state, so the order
of the changes does not matter: a fact that still exists is added or replaced, and any other is
deleted. Each index gets one add and one delete per batch, split only by the request limits. The
outbox rows go away only after every write of the batch succeeded, so a failed sync is simply
retried on the next round.

```js JavaScript theme={null}
async function syncOnce(db, client) {
  const { rows: events } = await db.query(
    `SELECT seq, fact_id, business_id, location_id FROM memory_sync.memory_outbox ORDER BY seq LIMIT ${PAGE_SIZE}`,
  )
  if (events.length === 0) return 0
  const ids = [...new Set(events.map((event) => event.fact_id))]
  // Cast to the type of your primary key, so Postgres uses its index.
  const { rows } = await db.query(`${FACTS_SQL} AND id = ANY($1::uuid[])`, [ids])
  const current = new Map(rows.map(toDocument).map((doc) => [doc.id, doc]))
  const plans = new Map()
  for (const event of events) {
    const name = indexFor(event.business_id, event.location_id ?? ALL_LOCATIONS)
    if (!plans.has(name)) plans.set(name, { add: new Map(), remove: new Set() })
    const doc = current.get(event.fact_id)
    if (doc && indexOf(doc) === name) plans.get(name).add.set(doc.id, doc)
    else plans.get(name).remove.add(event.fact_id)
  }
  for (const [name, plan] of plans) {
    if (plan.add.size > 0) await write(client, name, [...plan.add.values()])
    if (plan.remove.size > 0) await remove(client, name, [...plan.remove])
  }
  await db.query('DELETE FROM memory_sync.memory_outbox WHERE seq = ANY($1)', [events.map((event) => event.seq)])
  return events.length
}
```

```python Python theme={null}
async def sync_once(db, client):
    events = await (await db.execute(
        f"SELECT seq, fact_id, business_id, location_id FROM memory_sync.memory_outbox ORDER BY seq LIMIT {PAGE_SIZE}"
    )).fetchall()
    if not events:
        return 0
    ids = list({event["fact_id"] for event in events})
    # Cast to the type of your primary key, so Postgres uses its index.
    rows = await (await db.execute(FACTS_SQL + " AND id = ANY(%s::uuid[])", [ids])).fetchall()
    current = {doc.id: doc for doc in map(to_document, rows)}
    plans = {}
    for event in events:
        location_id = ALL_LOCATIONS if event["location_id"] is None else event["location_id"]
        name = index_for(event["business_id"], location_id)
        add, delete = plans.setdefault(name, ({}, set()))
        doc = current.get(event["fact_id"])
        if doc is not None and index_of(doc) == name:
            add[doc.id] = doc
        else:
            delete.add(event["fact_id"])
    for name, (add, delete) in plans.items():
        if add:
            await write(client, name, list(add.values()))
        if delete:
            await remove(client, name, list(delete))
    await db.execute(
        "DELETE FROM memory_sync.memory_outbox WHERE seq = ANY(%s)", [[event["seq"] for event in events]]
    )
    return len(events)
```

Every queued scope passes the scope rule, since the trigger copies it from a row that does. An
outbox that already held events when you added the rule can hold one that breaks it. In the scoped
layout such an event can name an index that Moss refuses, such as a name longer than 256 bytes, so
its write fails on every round and holds up the outbox. Move those events to a table of their own
in the same schema, so the sync goes on without them:

```sql theme={null}
BEGIN;
CREATE TABLE memory_sync.memory_outbox_parked AS
  SELECT * FROM memory_sync.memory_outbox
  WHERE NOT (memory_sync.is_scope_id(business_id)
    AND (location_id IS NULL OR memory_sync.is_scope_id(location_id)));
DELETE FROM memory_sync.memory_outbox WHERE seq IN (SELECT seq FROM memory_sync.memory_outbox_parked);
COMMIT;
```

Then restart the sync worker. Its repair at startup compares the indexes under `INDEX` with
Postgres and fixes whatever those events would have changed. Drop `memory_outbox_parked` once a
check reports no drift.

## Verify and reconcile

`reconcile` compares each index with Postgres by fact id. It counts the facts that are missing in
Moss or differ in text or in any metadata key, and the documents Moss holds that Postgres no longer
has. With `repair`, it writes the missing and changed facts and deletes the extra ones. It reads an
index, then its facts one page at a time, and yields after each page, so the worker below can sync
between pages. `reconcileAll` / `reconcile_all` runs it to the end and returns the total drift.

```js JavaScript theme={null}
// A fact id as Postgres writes a uuid. Match it to your primary key.
const FACT_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/

// Every document of an index, or none when it does not exist.
async function readIndex(client, name) {
  try {
    return await client.getDocs(name)
  } catch (error) {
    if (isNotFound(error)) return []
    throw error
  }
}

// Equal only with the same keys and values, so an extra key counts as drift.
function sameMetadata(stored, expected) {
  const keys = Object.keys(expected)
  return Object.keys(stored).length === keys.length && keys.every((key) => stored[key] === expected[key])
}

async function* reconcile(db, client, repair = false) {
  const scopes = await listScopes(db)
  // Indexes with no facts left in Postgres are checked too, against an empty list.
  const names = LAYOUT === 'shared'
    ? [INDEX]
    : (await client.listIndexes()).map((index) => index.name).filter((name) => name.startsWith(`${INDEX}--`))
  const known = new Set(scopes.map((scope) => scope.name))
  for (const name of names) if (!known.has(name)) scopes.push({ name, where: ' AND false', params: [] })
  for (const scope of scopes) {
    const stored = new Map((await readIndex(client, scope.name)).map((doc) => [doc.id, doc]))
    let changed = 0
    for await (const docs of readPages(db, scope)) {
      const stale = docs.filter((doc) => {
        const copy = stored.get(doc.id)
        stored.delete(doc.id)
        return !copy || copy.text !== doc.text || !sameMetadata(copy.metadata ?? {}, doc.metadata)
      })
      if (repair && stale.length > 0) await write(client, scope.name, stale)
      changed += stale.length
      yield stale.length
    }
    const extra = [...stored.keys()]
    if (repair && extra.length > 0) {
      // A fact back in this index since its page was read is not extra: the sync sends it.
      // Only ids and scopes are read, by primary key, and an id that is not a uuid is no fact.
      const keys = extra.filter((id) => FACT_ID.test(id))
      const { rows } = await db.query(
        `SELECT id::text AS id, business_id::text AS business, coalesce(location_id::text, $2) AS location
         FROM (${FACTS_SQL}) AS facts WHERE id = ANY($1::uuid[])`,
        [keys, ALL_LOCATIONS],
      )
      const back = new Set(rows.filter((row) => indexFor(row.business, row.location) === scope.name).map((row) => row.id))
      await remove(client, scope.name, extra.filter((id) => !back.has(id)))
    }
    console.log(`${scope.name}: ${changed} missing or changed, ${extra.length} extra`)
    yield extra.length
  }
}

async function reconcileAll(db, client, repair = false) {
  let drift = 0
  for await (const count of reconcile(db, client, repair)) drift += count
  return drift
}
```

```python Python theme={null}
# A fact id as Postgres writes a uuid. Match it to your primary key.
FACT_ID = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")

# Every document of an index, or none when it does not exist.
async def read_index(client, name):
    try:
        return await client.get_docs(name)
    except MossError as error:
        if error.code != "NOT_FOUND":
            raise
        return []

async def reconcile(db, client, repair=False):
    scopes = await list_scopes(db)
    # Indexes with no facts left in Postgres are checked too, against an empty list.
    if LAYOUT == "shared":
        names = [INDEX]
    else:
        names = [index.name for index in await client.list_indexes() if index.name.startswith(INDEX + "--")]
    known = {name for name, _, _ in scopes}
    scopes += [(name, " AND false", []) for name in names if name not in known]
    for name, where, params in scopes:
        stored = {doc.id: doc for doc in await read_index(client, name)}
        changed = 0
        async for docs in read_pages(db, where, params):
            stale = []
            for doc in docs:
                copy = stored.pop(doc.id, None)
                if copy is None or copy.text != doc.text or (copy.metadata or {}) != doc.metadata:
                    stale.append(doc)
            if repair and stale:
                await write(client, name, stale)
            changed += len(stale)
            yield len(stale)
        extra = list(stored)
        if repair and extra:
            # A fact back in this index since its page was read is not extra: the sync sends it.
            # Only ids and scopes are read, by primary key, and an id that is not a uuid is no fact.
            keys = [fact_id for fact_id in extra if FACT_ID.fullmatch(fact_id)]
            cursor = await db.execute(
                "SELECT id::text AS id, business_id::text AS business, coalesce(location_id::text, %s) AS location"
                f" FROM ({FACTS_SQL}) AS facts WHERE id = ANY(%s::uuid[])",
                [ALL_LOCATIONS, keys],
            )
            back = {row["id"] for row in await cursor.fetchall() if index_for(row["business"], row["location"]) == name}
            await remove(client, name, [fact_id for fact_id in extra if fact_id not in back])
        print(f"{name}: {changed} missing or changed, {len(extra)} extra")
        yield len(extra)

async def reconcile_all(db, client, repair=False):
    return sum([count async for count in reconcile(db, client, repair)])
```

`reconcile` also checks the indexes whose facts are all gone from Postgres, such as after a
`TRUNCATE`: the shared index, or every index under the scoped prefix. A repair empties them. An
empty index answers with no results, so deleting the index of a closed location is only cleanup.

It holds one index in memory at a time, as `getDocs` / `get_docs` returns it, with the text and
metadata of every document. In the shared layout that is every fact: reading an index of 21 MB of
JSON took about 100 MB in JavaScript and 85 MB in Python, so plan for five times the JSON size of
your facts. Each read counts the whole index as egress, billed and checked against your plan's
limit like a load, even when it asks for a few `docIds`, so paging it would only cost more. A
repair adds the size of every index to your egress each time it runs. When the limit refuses a
read with a 429, the repair fails, and the worker below retries it an hour later.

No drift means Moss held the same facts as the Postgres rows the check read. It does not prove that
they still match: the check reads each index first and its facts after, and a write that commits in
between can be missed until the next run, or show up as drift that the sync then fixes.

A check without `repair` only reads, so it can run anywhere. A repair writes, so let the sync worker
below run it, as the only writer. Then compare answers: run a few hundred recent real queries
against your current retrieval and against Moss, compare the top results, and review the
differences by hand, since some will be improvements.

## Run one sync worker

One worker drains the outbox every few seconds. It runs a repair when it starts, another ten
minutes after that one ends, then one a day. A repair runs one step at a time between sync rounds,
so the outbox keeps draining. Each step reads one page of facts, plus the whole index on its first
page, and fixes the drift it finds. A failed repair starts over an hour later. An advisory lock
lets only one worker run at a time, and a second worker waits for it. Connect the worker as
`moss_sync`, and to Postgres directly, so the server timeouts it sets watch its own connection.
A session pooler keeps the lock too, but then the pooler decides how soon a dead worker's lock is
freed. A transaction pooler, such as Supabase's on port 6543, does not keep a session's advisory
lock.

The lock lasts as long as the worker's Postgres session, and Moss does not check it. When the
session drops, the worker ends, and its process manager starts a new one, which waits for the lock.
Postgres frees it at once when the old process exits, and within about a minute when its host or
network fails: the keepalives find an idle connection dead, and `tcp_user_timeout` one that dies
with a reply still unacknowledged. `tcp_user_timeout` needs a Linux server; elsewhere Postgres logs
that and leaves it at 0, and such a connection lasts until TCP gives up resending, often many
minutes. The old worker can still have a write in flight, and in Python it can send the rest of its
batch before it notices the lost session. Such a write can land after the new worker's writes and
leave a stale document. To keep that rare and short:

* Run the worker as a single instance that is restarted only after the old process has exited.
  In Kubernetes, that is one replica with the `Recreate` strategy.
* The second repair starts ten minutes after the first one ends, after the old worker's last write
  has finished, and fixes a stale one. Set that delay above your slowest index build.

A strict single writer would need Moss to refuse writes from an old lock holder, which it does not
do. The repairs are the backstop: a stale document lasts until the next one.

The Python worker stops on the Unix signal `SIGTERM`. On Windows, remove its `add_signal_handler`
line, run it on a selector event loop as [What you need](#what-you-need) says, and stop it with
Ctrl-C.

```js JavaScript theme={null}
const MINUTE = 60 * 1000
const HOUR = 60 * MINUTE

// Server keepalives let Postgres free the lock of a worker whose idle connection died, and the
// user timeout one that died with a reply in flight.
await db.query('SET tcp_keepalives_idle = 30; SET tcp_keepalives_interval = 10; SET tcp_keepalives_count = 3')
await db.query('SET tcp_user_timeout = 60000')
// Waits while another worker, or a dead one Postgres has not noticed yet, holds the lock.
while (!(await db.query("SELECT pg_try_advisory_lock(hashtext('moss-sync')) AS held")).rows[0].held) {
  await new Promise((resolve) => setTimeout(resolve, 5000))
}
let repair = null // the repair in progress, one step per round
let repairAt = 0
let repairs = 0
for (;;) {
  if (!repair && Date.now() >= repairAt) repair = reconcile(db, client, true)
  let busy = repair !== null
  if (repair) {
    try {
      if ((await repair.next()).done) {
        repair = null
        repairAt = Date.now() + (repairs++ === 0 ? 10 * MINUTE : 24 * HOUR)
      }
    } catch (error) {
      console.error('Repair failed, retrying in an hour:', error)
      repair = null
      repairAt = Date.now() + HOUR
    }
  }
  try {
    if ((await syncOnce(db, client)) > 0) busy = true
  } catch (error) {
    console.error('Sync failed, retrying:', error)
  }
  if (!busy) await new Promise((resolve) => setTimeout(resolve, 5000))
}
```

```python Python theme={null}
MINUTE = 60
HOUR = 60 * MINUTE

async def run_worker():
    db, client = await connect()
    # SIGTERM stops the worker as Ctrl-C does. Closing the client sends its last usage report.
    asyncio.get_running_loop().add_signal_handler(signal.SIGTERM, asyncio.current_task().cancel)
    async with db, client:
        # Server keepalives let Postgres free the lock of a worker whose idle connection died, and the
        # user timeout one that died with a reply in flight.
        await db.execute("SET tcp_keepalives_idle = 30; SET tcp_keepalives_interval = 10; SET tcp_keepalives_count = 3")
        await db.execute("SET tcp_user_timeout = 60000")
        # Waits while another worker, or a dead one Postgres has not noticed yet, holds the lock.
        lock = "SELECT pg_try_advisory_lock(hashtext('moss-sync')) AS held"
        while not (await (await db.execute(lock)).fetchone())["held"]:
            await asyncio.sleep(5)
        repair, repair_at, repairs = None, time.monotonic(), 0
        while True:
            if repair is None and time.monotonic() >= repair_at:
                repair = reconcile(db, client, repair=True)
            busy = repair is not None
            if repair is not None:
                try:
                    if await anext(repair, None) is None:
                        repair = None
                        repair_at = time.monotonic() + (10 * MINUTE if repairs == 0 else 24 * HOUR)
                        repairs += 1
                except Exception:
                    # A lost connection releases the lock, so the worker must end.
                    if db.closed:
                        raise
                    logging.exception("Repair failed, retrying in an hour")
                    repair, repair_at = None, time.monotonic() + HOUR
            try:
                if await sync_once(db, client) > 0:
                    busy = True
            except Exception:
                if db.closed:
                    raise
                logging.exception("Sync failed, retrying")
            if not busy:
                await asyncio.sleep(5)

if __name__ == "__main__":
    with contextlib.suppress(KeyboardInterrupt, asyncio.CancelledError):
        asyncio.run(run_worker())
```

Alert when the oldest outbox row is older than a few minutes plus your longest repair step: the
worker is down, or Moss keeps refusing a write. In the shared layout, the longest step is the first
of each repair, which reads the whole index. A write that fails every time holds up the whole
outbox, since its rows are never deleted. The worker logs the error. Fix the row in Postgres, and
the next round sends its current state.

## Read with one client per process

An application process opens one client when it starts, shares it across every session, such as
a phone call or a chat, and closes it when it stops.

* **At startup**, `checkIndexes` / `check_indexes` makes sure `INDEX` names indexes in this
  project, so a wrong name or project fails at once instead of answering every session with
  nothing. Moss creates an index with its first documents, so a dataset with no facts yet fails
  this check. Switch reads to Moss after the backfill. When the cloud cannot be reached or answers
  with a temporary error, which the SDK reports with the code `NETWORK`, the check logs the error
  and lets the process start on its disk copies, and any other error stops it. Until a later check
  reaches the cloud, `search` asks for keyword results only (`alpha` 0), since the embedding model
  may not open, so repeat the check, for example once a minute.
* **At the start of a session**, take the business and location from the session's server-side
  authorization, never from the request, and pass that same scope to `openSession` /
  `open_session` and to `search`. Give each id in the text form Postgres returns, which the index
  names use: lowercase for a `uuid` column, but never change the case of a text id. `openSession`
  checks only the form of both ids, against the scope rule, then loads the session's indexes. When
  one is already loaded, the load checks the cloud and swaps in a newer version without interrupting
  queries. In the scoped layout, a scope with no facts has no index. On `NOT_FOUND`, it asks
  Postgres whether the scope has facts: if not, the index is left out, and if so, it raises, since
  the index is missing. That includes a scope whose first facts the sync has not sent yet, for
  those few seconds. Any other failure raises. In the shared layout, every failure raises.
* **During the session**, `search` queries the indexes it opened. Ask for enough results to cover
  both tiers, so business-wide facts do not crowd out a location's own.

`cachePath` / `cache_path` keeps each index on local disk, so a load after a restart downloads only
a changed version. If the Moss cloud is unreachable, a load can still serve the disk copy, but a
process that has not opened the embedding model yet can then answer only keyword queries; see
[Loading from the cache offline](https://docs.moss.dev/docs/integrate/storage-persistence.md#loading-from-the-cache-offline).
In the scoped layout, a process keeps every index it loads, so
[unload idle ones](https://docs.moss.dev/docs/integrate/memory-sizing.md#unload-idle-indexes).

```js JavaScript theme={null}
const CACHE_PATH = '/var/cache/moss'
let keywordOnly = false // set while the cloud is unreachable, since the embedding model may not open

async function checkIndexes(client) {
  let names
  try {
    names = (await client.listIndexes()).map((index) => index.name)
  } catch (error) {
    if (!isMossError(error) || error.code !== 'NETWORK') throw error
    console.error('Moss is unreachable, starting from the disk copies:', error)
    keywordOnly = true
    return
  }
  keywordOnly = false
  const found = LAYOUT === 'shared'
    ? names.includes(INDEX)
    : names.some((name) => name.startsWith(`${INDEX}--`))
  if (!found) throw new Error(`No index for ${INDEX} in this project. Check INDEX, or run the backfill.`)
}

// The ids come from the session's authorization. The scope rule checks only their form.
async function openSession(db, client, businessId, locationId) {
  if (!isScopeId(businessId) || !isScopeId(locationId)) throw new Error(`Not a scope: ${businessId}, ${locationId}`)
  if (LAYOUT === 'shared') {
    await client.loadIndex(INDEX, { cachePath: CACHE_PATH })
    return [INDEX]
  }
  const scopes = [scopeOf(businessId, null), scopeOf(businessId, locationId)]
  const names = scopes.map((scope) => scope.name)
  const { loaded, failed, failedCodes } = await client.loadIndexes(names, { cachePath: CACHE_PATH })
  for (const scope of scopes.filter((scope) => scope.name in failed)) {
    // An empty scope has no index. A scope with facts must have one.
    const empty = failedCodes?.[scope.name] === 'NOT_FOUND' &&
      (await db.query(`${FACTS_SQL}${scope.where} LIMIT 1`, scope.params)).rows.length === 0
    if (!empty) throw new Error(`Could not load ${scope.name}: ${failed[scope.name]}`)
  }
  return loaded
}

async function search(client, names, businessId, locationId, question) {
  if (names.length === 0) return []
  const alpha = keywordOnly ? 0 : undefined
  if (LAYOUT === 'shared') {
    const filter = scopeFilter(businessId, locationId)
    return (await client.query(INDEX, question, { topK: 8, filter, alpha })).docs
  }
  return (await client.queryMultiIndex(names, question, { topK: 8, alpha })).docs
}
```

```python Python theme={null}
CACHE_PATH = "/var/cache/moss"
keyword_only = False  # set while the cloud is unreachable, since the embedding model may not open

async def check_indexes(client):
    global keyword_only
    try:
        names = [index.name for index in await client.list_indexes()]
    except MossError as error:
        if error.code != "NETWORK":
            raise
        logging.error("Moss is unreachable, starting from the disk copies: %s", error)
        keyword_only = True
        return
    keyword_only = False
    if LAYOUT == "shared":
        found = INDEX in names
    else:
        found = any(name.startswith(INDEX + "--") for name in names)
    if not found:
        raise RuntimeError(f"No index for {INDEX} in this project. Check INDEX, or run the backfill.")

# The ids come from the session's authorization. The scope rule checks only their form.
async def open_session(db, client, business_id, location_id):
    if not (is_scope_id(business_id) and is_scope_id(location_id)):
        raise ValueError(f"Not a scope: {business_id}, {location_id}")
    if LAYOUT == "shared":
        await client.load_index(INDEX, cache_path=CACHE_PATH)
        return [INDEX]
    scopes = [scope_of(business_id, None), scope_of(business_id, location_id)]
    result = await client.load_indexes([name for name, _, _ in scopes], cache_path=CACHE_PATH)
    for name, where, params in scopes:
        if name not in result.failed:
            continue
        # An empty scope has no index. A scope with facts must have one.
        empty = result.failed_codes.get(name) == "NOT_FOUND" and not await (
            await db.execute(f"{FACTS_SQL}{where} LIMIT 1", params)).fetchone()
        if not empty:
            raise RuntimeError(f"Could not load {name}: {result.failed[name]}")
    return result.loaded

async def search(client, names, business_id, location_id, question):
    if not names:
        return []
    alpha = 0 if keyword_only else None
    if LAYOUT == "shared":
        options = QueryOptions(top_k=8, alpha=alpha, filter=scope_filter(business_id, location_id))
        return (await client.query(INDEX, question, options)).docs
    return (await client.query_multi_index(names, question, QueryOptions(top_k=8, alpha=alpha))).docs
```

A process uses them like this:

```js JavaScript theme={null}
await checkIndexes(client) // once, when the process starts

// For each session:
const names = await openSession(db, client, 'b1', 'l1')
const facts = await search(client, names, 'b1', 'l1', 'When does the shop open?')
```

```python Python theme={null}
async def serve():
    db, client = await connect()
    async with db, client:
        await check_indexes(client)  # once, when the process starts

        # For each session:
        names = await open_session(db, client, "b1", "l1")
        facts = await search(client, names, "b1", "l1", "When does the shop open?")
```

## Setup 1: Moss replaces Postgres

Postgres keeps every write until the cutover is final, so a rollback is a switch, not a data copy.

**1. Start the outbox**

Install the outbox table and trigger. From then on, every fact write lands in Postgres and queues a
change for Moss in the same transaction. This is the dual write: every committed write is queued
for Moss, and the worker applies it a few seconds later. Never call Moss in the request path.

**2. Backfill**

Run `backfill`. Changes made while it runs wait in the outbox.

**3. Sync**

When the backfill is done, start the sync worker. Do not run it at the same time as the backfill,
so each index keeps a single writer.

**4. Check**

Run `reconcileAll` / `reconcile_all` without `repair` until it reports no drift, which means Moss
matched the Postgres rows that run read. Compare sample queries.

**5. Shadow reads (optional)**

Keep answering from the current store, run the same query against Moss in the background, and log
both.

**6. Cut over reads**

Behind a flag per business, switch reads to Moss: a few businesses first, then all. Keep the outbox
and the worker running.

Reads from Moss trail Postgres writes. The lag is usually a sync interval plus one index build, a
few seconds, and one repair step more while a repair runs. It has no fixed bound: it grows while
builds are slow, the outbox has a backlog or a write is retried, and a process serves the version
it loaded until its next load. The age of the oldest outbox row shows most of it. This cutover
accepts that lag, so a fact written during a session can reach Moss reads a little later. If a
session must see a fact it just wrote, keep that fact in the session as well.

**7. Roll back if needed**

Flip the flag back. Postgres has every write, so nothing is lost. Keep this option open for a set
window, for example two weeks.

**8. Finish**

Deploy the new write path, where the application queues fact writes for a new worker that batches
them into adds and deletes per index. Keep it switched off, so it accepts no fact edit until the
old write path has stopped and its outbox has drained, and do not start the new worker. Wait until
no process runs the old write path. Then freeze the table:

```sql theme={null}
CREATE FUNCTION memory_sync.memory_facts_frozen() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
  RAISE EXCEPTION 'memory_facts is frozen: facts are written to Moss';
END
$$;

-- Waits for every write in progress to finish, then refuses later ones.
CREATE TRIGGER memory_facts_frozen
  BEFORE INSERT OR UPDATE OR DELETE OR TRUNCATE ON memory_sync.memory_facts
  FOR EACH STATEMENT EXECUTE FUNCTION memory_sync.memory_facts_frozen();
```

Creating the trigger waits until every transaction that writes the table has committed or rolled
back. A request on the old path that reaches the table after that fails, instead of writing a fact
that never reaches Moss. Wait until the outbox is empty. Restart the sync worker, so it runs a
repair, and run `reconcileAll` / `reconcile_all` without `repair` until it reports no drift. That
covers changes no outbox row recorded, such as a `TRUNCATE`. Then stop the sync worker, start the
new worker, and switch the new write path on. Fact edits fail from the freeze until then, and any
other order can let an older write overwrite a newer one. Take a last export of the Postgres table,
then retire it. From then on, `openSession` / `open_session` must check a missing scoped index
against the store that replaced it. For backups, export each index on a schedule with `getDocs` /
`get_docs`, which returns every document with its text and metadata.

## Setup 2: Postgres stays the source of truth

Moss holds a copy of the facts for retrieval. Postgres decides what is true, and Moss can be rebuilt
from it at any time.

**1. Write path**

The application writes facts to Postgres only. The trigger queues each change in the same
transaction, and the sync worker copies it to Moss, usually within seconds. No fact write calls
Moss, so a Moss outage never fails one, and the outbox keeps the changes until Moss is back. Reads
still need Moss, or the disk copy described in [Read with one client per process](#read-with-one-client-per-process).

**2. Retries**

When a Moss write fails, `syncOnce` / `sync_once` keeps the outbox rows and raises, the worker logs
it, and its next round retries them. Every write is idempotent, so a retry is always safe.

**3. Deletes**

Hard deletes and soft deletes (`deleted_at`) both queue a change, and the sync deletes the fact from
Moss. A fact that moves to another location is deleted from its old index and added to the new one.

**4. Reconciliation**

The worker runs the repair one step at a time between syncs, so it never races them or holds them
up. It fixes any drift, for example after a manual change in Moss, a write made while the trigger
was disabled, or a late write from a previous worker.

**5. Rebuild**

Stop the sync worker and run the backfill into a new name (for example `memory-v2`, or a new prefix
for scoped indexes). Point the worker at it and start it, wait until the outbox is empty, reconcile,
then point reads at the new index and delete the old ones. Until then, reads use the old index,
which misses every change made since the worker stopped. Plan the rebuild for a quiet period, or
answer from Postgres until reads move. For a new embedding model, pass its `modelId` / `model_id`
to `createIndex` / `create_index` in `write`.

## Related

> [card] [Indexing data](https://docs.moss.dev/docs/integrate/indexing-data.md)
>
> Documents, metadata and batch writes.

> [card] [Metadata filtering](https://docs.moss.dev/docs/integrate/metadata-filtering.md)
>
> The filter syntax the shared index relies on.

> [card] [Multi-index search](https://docs.moss.dev/docs/integrate/multi-index-search.md)
>
> Search a business index and a location index together.

> [card] [Memory sizing](https://docs.moss.dev/docs/integrate/memory-sizing.md)
>
> One client per process, and how many indexes it can hold.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.