Skip to the page

Migrating · Migration steps

Switching over

Rehearse your cutover on a branch, backfill rows in batches while the legacy database serves traffic and switch over with a brief write pause.

In the schema
—

What you’ll build#

This guide cuts a live production database over to Napalm with a brief write pause. Your existing database keeps serving traffic while an initial backfill copies records into Napalm and you verify row counts and access rules. At cutover, you pause writes on the old database for a few minutes, send the final delta and point your app at Napalm.

Two properties make the cutover safe to repeat. Every import statement upserts by old_id, so re-sending any batch is idempotent, and you rehearse the entire flow end to end on an isolated branch before touching main.

Idempotent copy and cutover switch

Idempotent batches backfill production rows online before cutover switches client traffic.

Before you start#

Before starting, finish your schema, access rules and branch role global configuration so a migration service key can write imported rows. Your platform guide walks through translating the schema, and Moving your users covers the Person type and serviceGlobals setup. The batch sender below (scripts/send.ts) runs on Node 22 with zero external dependencies, while each source export script installs only that platform’s client SDK.

Rehearse on a branch#

Create a rehearsal branch with its own HTTPS endpoint and a branch-scoped service key to test your import end to end.

Terminal
# Create an isolated branch with its own HTTPS endpoint and push your schemanapalm branches create notes rehearsalnapalm endpoint notes --branch rehearsal --enablenapalm schema push notes --branch rehearsal --yes # Compile the batch import statements against the branch without deployingnapalm queries push notes --queries dbschema/move --branch rehearsal # Create a branch-scoped service key for the import script (the secret prints once)napalm keys create notes --label move --branch rehearsal export NAPALM_URL=https://<project-address>/branches/rehearsalexport NAPALM_KEY=ndb_…

Branch rehearsals isolate every piece of migration state from main:

Branch service globals
Each branch maintains independent endpoint settings. Configure serviceGlobals on rehearsal with the same { "default::role": "service" } mapping that main will use.
Ad-hoc statement execution
Named deployed queries live on main. On a branch, the batch sender posts EdgeQL statement text to POST /query with your branch-scoped service key under the same schema and access policies.
Testing the app on a branch
To point a staging build of your app at rehearsal, run napalm generate without --deployed so generated SDK calls send statement text under the branch’s access rules.
Resetting a rehearsal
napalm branches remove notes rehearsal deletes the branch along with its imported rows and service key so you can start a fresh rehearsal in one command.

Import rows in batches#

Keep migration statements in dbschema/move separate from dbschema/queries so napalm queries push never deploys import statements to public callers. Each import file accepts a $rows JSON array and upserts objects by old_id.

dbschema/move/importNotes.edgeql
# One batch of notes. Their people come first: a note whose owner hasn't been moved stops the batch.for row in json_array_unpack(<json>$rows)union (  insert Note {    old_id := <str>row['id'],    owner := assert_exists((select Person filter .old_id = <str>row['owner_id'])),    shared_with := (select Person filter .old_id in array_unpack(<array<str>>row['shared_with'])),    title := <str>row['title'],    body := <str>row['body'],    # Now, for a source that kept no date.    created := <datetime>json_get(row, 'created_at') ?? datetime_current(),  }  unless conflict on .old_id  else (    update Note set {      shared_with := (select Person filter .old_id in array_unpack(<array<str>>row['shared_with'])),      title := <str>row['title'],      body := <str>row['body'],    }  ))

One shared batch sender (scripts/send.ts) accepts an async stream of rows from any platform export script, splits payloads into size-bounded batches and posts each batch to its target EdgeQL statement.

scripts/send.ts
// scripts/send.tsimport { readFileSync } from 'node:fs' const address = process.env.NAPALM_URL as string // the project's address, or a branch's under itconst key = process.env.NAPALM_KEY as string // a service key made for the move /** A request to the project is at most 1 MiB. A batch stops at half of that. */const BATCH_BYTES = 512 * 1024 /** Runs one of the move's statements with a batch of rows, and again while the project is busy or away. */async function send(statement: string, rows: object[]) {  for (let attempt = 0; ; attempt++) {    const answer = await fetch(`${address}/query`, {      method: 'POST',      headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json' },      body: JSON.stringify({ query: statement, variables: { rows } }),    })    if (answer.ok) return    const isWorthATry = answer.status === 429 || answer.status >= 500    if (!isWorthATry || attempt === 5) throw new Error(`${answer.status} ${await answer.text()}`)    await new Promise((resolve) => setTimeout(resolve, 500 * 2 ** attempt))  }} /** * Sends every row a reader gives to the statement in dbschema/move/<name>.edgeql, in batches under the limit. * The statements write by the old id, so a run that stops can start again from the top. */export async function move(name: string, rows: AsyncIterable<object>) {  const statement = readFileSync(`dbschema/move/${name}.edgeql`, 'utf8')  let batch: object[] = []  let bytes = 0  let count = 0  for await (const row of rows) {    const size = Buffer.byteLength(JSON.stringify(row))    if (batch.length > 0 && bytes + size > BATCH_BYTES) {      await send(statement, batch)      batch = []      bytes = 0    }    batch.push(row)    bytes += size    count++  }  if (batch.length > 0) await send(statement, batch)  console.log(`${name}: ${count} rows`)}
Request size bounds
Projects reject HTTP payloads larger than 1 MiB with 413 request_too_large. Sizing batches to half that limit leaves headroom for statement text and wide rows.
Parent records first
Because importNotes resolves .owner by old_id, import Person batches before Note batches. If a batch references a missing parent, assert_exists aborts the entire batch atomically.
Safe restarts
If an import run stops mid-stream, restart the script from the beginning. Already imported rows update in place with identical values.
Transient retries
The sender retries 429 and 5xx responses up to six attempts with exponential backoff and halts immediately on any 4xx schema or policy error.
Platform export scripts
Pair scripts/send.ts with the export script for your source database: Postgres, Supabase, Firebase, Convex or Gel.

Import stored files#

Each file in Napalm pairs a database record with object bytes. Import the file records first with each object’s legacy key in old_key, then run napalm files store import so Napalm copies the bytes directly from any S3-compatible bucket.

Terminal
# Preview pending file records and sample source objects without writing bytesnapalm files store import notes --endpoint https://s3.us-east-1.amazonaws.com --access-key-id AKIA… \  --map type=default::Attachment,key=old_key,bucket=old-attachments --plan # After re-running import without --plan, check progress and verified countsnapalm files store ls notes
Source bucket credentials
Supply the bucket secret via NAPALM_SOURCE_SECRET_ACCESS_KEY or standard input rather than command-line flags. Napalm discards the source credential once the import job finishes.
Format and size validation
As bytes arrive, Napalm records exact byte sizes and sniffs MIME formats from file headers just like direct uploads. napalm files errors lists any objects rejected by type constraints.
Non-S3 file stores
When migrating from storage without an S3 API, store each file’s signed download URL on the record and run napalm files import to fetch over HTTPS. Files & uploads covers both commands.

Verify counts and caller reach#

Start by comparing total row counts and unclaimed user counts between Napalm and your source database.

dbschema/move/counts.edgeql
# What the move has brought so far, to hold against the old system's own counts.select {  people := count(Person),  claimed := count(Person filter exists .identity),  notes := count(Note),  shares := sum((for note in Note union count(note.shared_with))),}
Terminal
curl "$NAPALM_URL/query" \  -H "Authorization: Bearer $NAPALM_KEY" -H "Content-Type: application/json" \  -d "$(jq -Rs '{ query: . }' dbschema/move/counts.edgeql)" # Audit reachable row counts for a service key and an individual usernapalm keys reach notes --new --branch rehearsalnapalm people reach notes ada@example.com --branch rehearsal

Matching totals confirm that every row arrived, and reach audits verify that access rules behave as intended. napalm people reach reports how many rows a given user could select, update and delete across every type without needing their credentials. To inspect a single record, napalm explain-access notes <object-id> --as ada@example.com names the exact policy that granted or denied access.

Cut over to main#

Backfill the bulk of your data while the legacy database continues serving traffic, then pause writes briefly for one final delta pass before switching your application to Napalm.

Online backfill and cutover

Repeat passes sync recent writes so your final maintenance window stays short.

Retire migration credentials

One CLI command revokes the migration key before you drop temporary write policies.

Run the cutover sequence in order from initial staging on main to credential cleanup:

  1. Prepare main ahead of cutover

    Push your schema and deployed queries to main, configure sign-in providers, set serviceGlobals and create a migration service key on main while production traffic stays on the old system.

  2. Backfill main while the old system serves traffic

    Run the full import against main, then run a second pass the night before cutover. Because a repeat pass scans source rows while writing only changes, its duration predicts your cutover maintenance window.

  3. Pause writes on the old system

    Enable maintenance mode or switch the legacy database to read-only. User-visible write downtime lasts only as long as the final delta pass.

  4. Run the final delta and deletion pass

    Re-run your import script to capture final inserts and updates, then pass any hard-deleted legacy IDs to a deletion statement so removed records disappear from main as well.

    dbschema/move/removeNotes.edgeql
    # The notes the old system deleted since the last pass, by their old ids.delete Note filter .old_id in array_unpack(<array<str>>$old_ids)
  5. Verify counts and switch traffic

    Confirm that counts.edgeql matches the frozen source database, then deploy your application pointed at Napalm. Returning users link their accounts automatically through claimPerson.

Mirror writes during your soak window#

During the first days after cutover, you can mirror new commits back to your legacy database so rolling back loses zero writes.

Mirror post-cutover commits

The change log streams new commits to your reverse-sync worker in order.

Preserving old_id on imported types gives your reverse-sync worker a stable key across two delivery options:

Commit webhooks
Configure a signed row webhook to push every committed change to an HTTP endpoint that updates the legacy database by old_id. Search index & cache sync builds that webhook consumer pattern.
Polling the change log
GET /changes streams committed changes in commit order from a durable cursor so a background worker can replay writes on your own schedule. Warehouse sync walks through cursor checkpointing.
Post-cutover inserts
Rows created natively on Napalm have an empty old_id. Your reverse-sync worker can either generate and store a legacy ID or key new legacy rows directly by Napalm’s UUID.

Remove temporary migration rules#

Once your soak window ends, clean up the migration credentials, temporary write policies and legacy ID fields in order.

  1. Revoke the migration service key

    Run napalm keys revoke as soon as the final delta pass finishes so no credential can write through the_move_can_write.

  2. Delete temporary migration policies

    Remove every the_move_can_write policy from dbschema/default.gel and push. Any ongoing backend worker should use a dedicated policy scoped to its specific types and operations.

  3. Drop unused legacy ID fields

    Drop old_id properties once reverse sync stops. Keep old_sign_ins and claimPerson in place while legacy users continue signing in for the first time, and track progress with the claimed count.

Check the cutover#

  1. Run the import twice on rehearsal

    Both runs print identical row counts and branch totals remain unchanged after the second pass.

  2. Interrupt a run mid-flight and restart

    Restarting from the beginning converges on the exact same row counts without duplicates.

  3. Send a child row with a missing parent

    The statement aborts with an assert_exists failure, the sender halts immediately and zero rows from that batch commit.

  4. Invoke an import statement with a user session

    Napalm rejects the write because user sessions never carry role = 'service'.

Type a word or two to search every docs page.