Skip to the page

Migrating · Migration steps

Switching over

Rehearse the move on a branch, copy the rows in batches while the old system serves, then switch with one short pause.

In the schema
—

What you’ll build#

This guide moves a live database to Napalm with one short write pause. Your existing system keeps serving while an initial pass copies rows into your project and you verify row counts and access rules. You then pause writes on the old database for a few minutes, send the final delta and point the app at Napalm.

Two things make the move safe to repeat. Every statement of the move writes by the old system’s id, so sending a row twice changes nothing. You also run the whole move on a branch first, where nothing real is at stake.

Idempotent copy and cutover switch

Idempotent batches copy rows by legacy id while the old database serves, then a brief write pause flushes final changes and flips live traffic cleanly to Napalm.

Before you start#

You need the schema and rules written, and the role setting that lets a service key write. The page for your source walks through the schema and rules. Moving your users has the schema, rules and role setting for people. The sender below runs on Node 22 and needs no packages. Each source’s reader needs that source’s own packages.

Rehearse on a branch#

Terminal
# A branch with main's schema and sign-in settings, and an address of its own.napalm branches create notes rehearsalnapalm endpoint notes --branch rehearsal --enablenapalm schema push notes --branch rehearsal --yes # The move's statements, compiled against the branch. Nothing is deployed.napalm queries push notes --queries dbschema/move --branch rehearsal # A key for the move, good on the branch only. It's shown once.napalm keys create notes --label move --branch rehearsal export NAPALM_URL=https://<project-address>/branches/rehearsalexport NAPALM_KEY=ndb_…
The branch’s settings
A branch has separate endpoint settings. In the console or through the Control API, give the branch’s serviceGlobals the same { "default::role": "service" } that main will have.
Statements as text
A branch serves no deployed queries by name, because deployed queries live on main. The move sends each statement as text with the move’s key, so each statement runs on a branch exactly as on main.
The app on a branch
To try the app on a branch, generate the app’s client without --deployed. Each call then carries the statement text, and the branch runs the statement under the same rules.
Start over
napalm branches remove notes rehearsal removes the branch along with the rows and the key. A second rehearsal costs one command.

Move the rows#

The move’s statements live apart from the app’s queries in dbschema/move, so napalm queries push never deploys those statements. Each statement takes a batch of rows as JSON and writes the rows 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 sender takes rows from any reader, cuts the rows into batches and sends each batch to the matching 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`)}
Under the limit
A project refuses a request over 1 MiB with 413 request_too_large. A batch of half that size leaves room for the statement and for a row that is larger than most.
Parents first
A note names the owner by the owner’s old id, so people go before notes. A row with a missing parent stops the batch, and no row of the batch is kept.
Restarting a run
A run that stops halfway starts again from the first row. Rows already moved are written over with the same values.
A busy project
The sender retries a 429 or a 5xx with a longer wait each time. A request gets six tries in all. Any other refusal stops the run with the project’s own message.
The reader
Each source has a separate reader: Postgres, Supabase, Firebase, Convex and Gel.

Move the files#

A file is a record with bytes. The rows go first, and each row names the object’s key in the old store. Napalm then copies the bytes itself from any S3-compatible store.

Terminal
# Count what's waiting and try a few objects of each type. Nothing is written.napalm 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 # The same command without --plan copies them after you confirm. Jobs on Napalm run the copy under each type's own checks.napalm files store ls notes
The source’s key
The secret is read from NAPALM_SOURCE_SECRET_ACCESS_KEY or stdin, never from an argument. The secret is deleted when the import ends.
The type’s checks
Napalm measures each object and reads the format from the first bytes, as for an upload. napalm files errors lists each object a type’s rule refuses and the reason.
A store without an S3 API
Keep each file’s address on the record. Then run napalm files import, which fetches by URL. Files & uploads covers both kinds of import.

Check the copy against the old system#

Start with counts. The counts statement below returns the project’s row counts to compare against the old 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)" # What a new key would reach, and what one person does.napalm keys reach notes --new --branch rehearsalnapalm people reach notes ada@example.com --branch rehearsal

Then check access. A matching count confirms that every row arrived, though you should still verify per-user visibility. napalm people reach counts the rows a person’s session would read, change and delete in each type without signing anyone in. Pick someone whose rows you know and compare. napalm explain-access notes <object-id> --as ada@example.com names the rule that let one row through, or the reason no rule did.

Switch#

Load the bulk of your rows while the old database still serves traffic, then pause writes briefly for one final catch-up pass before pointing the app at your Napalm endpoint.

Short-pause catch-up and endpoint cutover

Backfill main online via idempotent old_id upserts, pause old writes for one final delta and deletion pass, and point traffic at your project HTTPS endpoint.

Revoke the migration key after cutover

Retire the move’s ndb_… service key with napalm keys revoke and drop temporary the_move_can_write rules once cutover completes.

  1. Set up main days ahead

    Push the schema and the app’s queries to main, turn on the sign-in methods and make a key for the move on main. Nobody is using main yet.

  2. Run the move against main while the old system serves

    The initial backfill takes the longest. Run the script again the night before cutover. Because a repeat run reads every row while writing only changed rows, its runtime measures how long your final cutover window will take.

  3. Stop writes on the old side

    Put the old app in maintenance or make the old database read-only. People notice this pause for as long as one pass takes.

  4. Send the last pass and the deletions

    Run the move from the top once more. A row the old system deleted since the first pass is still in the project. Send the deleted ids to a statement that removes those rows.

    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. Compare, then point the app at Napalm

    With no writes on either side, the counts match. Release the app built against the project. At sign-in, each user claims a person.

Keep the old database current#

For the first days you may want the old database kept current, so switching back loses nothing. Every moved row still carries the old id, and the old id makes the write-back possible.

Tail committed changes back by old_id

Stream ordered commits from GET /changes or a signed rows webhook to mirror post-cutover writes back to the legacy database during your soak window.

Send changes back
A webhook with a key delivers each committed row to your route. The route writes the row to the old database by the row’s old id. Search index & cache sync builds that route for another kind of copy.
Read the change log
GET /changes returns every committed change in order from a bookmark. A worker can read the changes on any schedule you choose. Warehouse sync builds that worker.
Rows made after the switch
A row created after the switch has no old id. The write-back route assigns and stores an old id, or the old side keys those rows by the project’s own id.

Take the move out of the schema#

The move leaves three things behind: the move’s key, the move’s rules and the old ids. Remove all three in that order.

  1. Revoke the key

    Run napalm keys revoke on the day the last pass is done. After that, no caller can write under the rules made for the move’s key.

  2. Remove the move’s rules

    Delete each the_move_can_write from the schema and push. If the app has a separate service that needs to write, give that service a rule named for the service’s job.

  3. Drop the unused old ids

    Drop old_id once you have stopped writing back. Keep old_sign_ins and the claim while people are still arriving. The claimed count shows how many people have arrived.

Check the move#

  1. Run the move twice on the branch

    The second run prints the same row counts and the project’s counts do not move.

  2. Stop the script halfway and run the script again

    The restarted run finishes with the same counts as a run that never stopped.

  3. Send a note whose owner is missing

    The statement refuses the batch, the script stops with the project’s message and no note of that batch is kept.

  4. Call an import statement with a person’s session

    The project refuses the call. Only the key’s role may write a row that is not the caller’s own.

Type a word or two to search every docs page.