Skip to main content
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.

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.
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.
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.

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. 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.

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. 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 and never loads another business’s facts. 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.

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.
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.

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.

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.
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.
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:
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.
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 says, and stop it with Ctrl-C.
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. In the scoped layout, a process keeps every index it loads, so unload idle ones.
A process uses them like this:

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:
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.
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.

Indexing data

Documents, metadata and batch writes.

Metadata filtering

The filter syntax the shared index relies on.

Multi-index search

Search a business index and a location index together.

Memory sizing

One client per process, and how many indexes it can hold.