Help center / Your data

Keep a copy of your memories in your own Postgres

Updated November 22, 2026 · 5 min read

CrystalBrain stays where memories are checked and fixed. Your own database can hold a copy that follows every change: CrystalBrain sends a webhook, your server reads the memory with the REST API and writes it into a table. CrystalBrain never connects to your database.

The copy
CrystalBrainSends an event
memory.created, updated, archived
Your endpointChecks and reads
Signature, then GET /api/v1/memory
Your PostgresWrites the row
Insert or update by ID
One change, from CrystalBrain to your table.

Steps

  1. Create the table in your database.
  2. In Connections, tab API keys, create a key named for example “Postgres copy”. In the Webhooks tab, add your endpoint’s URL with the events memory.created, memory.updated, memory.archived and user.deleted. Copy the signing secret: it is shown only once.
  3. Run the receiver below on your server, with the key, the secret and your database address in its environment.
  4. Click Send test on the endpoint: the delivery should show Delivered. A test event writes nothing.
create table crystalbrain_memory (
  id          uuid primary key,  -- the memory's ID in CrystalBrain
  user_id     text not null,     -- the user's ID in CrystalBrain
  external_id text,              -- your customer's ID, as your app sent it
  brain       text,
  type        text not null,
  title       text not null,
  content     text not null,
  tags        text[] not null default '{}',
  status      text not null,     -- active or archived
  version     int  not null,
  synced_at   timestamptz not null default now()
);
import http from "node:http";
import crypto from "node:crypto";
import pg from "pg";

const db = new pg.Pool({ connectionString: process.env.DATABASE_URL });
const API = "https://crystalbrain.ai/api/v1";
const KEY = process.env.CRYSTALBRAIN_API_KEY;            // Connections › API keys
const SECRET = process.env.CRYSTALBRAIN_WEBHOOK_SECRET;  // whsec_…, shown once

// rawBody: the request body exactly as received (a string, before JSON.parse).
function isFromCrystalBrain(rawBody, signatureHeader, secret) {
  const parts = Object.fromEntries(signatureHeader.split(",").map((p) => p.split("=")));
  const expected = crypto.createHmac("sha256", secret).update(`${parts.t}.${rawBody}`).digest("hex");
  const fresh = Math.abs(Date.now() / 1000 - Number(parts.t)) < 300; // refuse replays older than 5 minutes
  return fresh && parts.v1?.length === expected.length && crypto.timingSafeEqual(Buffer.from(parts.v1), Buffer.from(expected));
}

// Reads the memory as it is now and writes it into the table.
async function copyMemory(item) {
  const res = await fetch(`${API}/memory?id=${item.id}`, { headers: { Authorization: `Bearer ${KEY}` } });
  if (res.status === 404) return db.query("delete from crystalbrain_memory where id = $1", [item.id]);
  if (res.status === 409) return; // user scheduled for deletion: user.deleted follows
  if (!res.ok) throw new Error(`CrystalBrain answered ${res.status}`);
  const m = await res.json();
  await db.query(
    `insert into crystalbrain_memory (id, user_id, external_id, brain, type, title, content, tags, status, version, synced_at)
     values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, now())
     on conflict (id) do update set brain = excluded.brain, type = excluded.type, title = excluded.title,
       content = excluded.content, tags = excluded.tags, status = excluded.status, version = excluded.version, synced_at = now()`,
    [m.id, m.user.id, item.user.external_id, m.brain, m.type, m.title, m.content, m.tags, m.status, m.version],
  );
}

http.createServer(async (req, res) => {
  const chunks = [];
  for await (const chunk of req) chunks.push(chunk);
  const raw = Buffer.concat(chunks).toString("utf8");
  if (!isFromCrystalBrain(raw, req.headers["crystalbrain-signature"] ?? "", SECRET)) return res.writeHead(401).end();
  const { event, data } = JSON.parse(raw);
  res.writeHead(200).end(); // answer within 5 seconds, then copy
  try {
    if (event.startsWith("memory.")) for (const item of data.memories) await copyMemory(item);
    if (event === "user.deleted") await db.query("delete from crystalbrain_memory where user_id = $1", [data.user.id]);
  } catch (err) {
    console.error(err); // the nightly catch-up fixes what was missed
  }
}).listen(3000);

Why the receiver reads each memory

An event carries the IDs, titles, brain and user of the memories, not their content. Reading the memory as it is now, rather than trusting the order of the events, keeps the copy right when a delivery is retried or arrives after a newer one: writing the same memory twice gives the same row. A retried delivery keeps its CrystalBrain-Delivery header, if you want to skip it instead.

What sends no event

Some changes do not send a memory event, so the copy misses them until it catches up: imported memories, merges and duplicates archived by the memory checks, a merge undone in the Review queue, and the automatic archive of stale memories. Once a night, list your users with GET /api/v1/users?status=all, then each user’s memories with GET /api/v1/memories?user=…&status=all, 100 per page at most, following next_offset, and write them the same way. Users scheduled for deletion are not listed.

Limits to plan for

  • Your endpoint must answer with a 2xx status within 5 seconds, so the receiver answers first and copies after. On a serverless host, work done after the answer can be cut: copy inside the request when it is short, or put the event in a queue.
  • Each memory read is one API call. A key makes 60 calls a minute on Free, 300 on Starter and 600 on Pro; beyond that the API answers 429 with a Retry-After header.
  • During the 7 days before a permanent deletion, reading the user’s memories answers 409 USER_DELETION_PENDING. The receiver leaves the rows until user.deleted arrives; delete them earlier if you prefer.
  • The copy goes one way. A row changed in your table does not change CrystalBrain: change the memory in the dashboard or with PATCH /api/v1/memory, and the copy follows.

The payload format and the signature are in the API reference. If deliveries fail, see My webhook does not receive events. For a one-off copy, the CSV export is simpler: see Export your data.

Free up to 25 tracked users, no card.

Start free