Guides · Shipping & operations
Live schema changes
Add required fields, rename properties, version deployed queries and build indexes on large tables without breaking live clients.
- API
- —
- In the schema
- —
What you’ll build#
You will evolve a live project’s schema without breaking active users. Because schema migrations and frontend deploys land seconds apart while open browser tabs continue calling the previous client build, breaking changes ship as expand-and-contract steps that keep prior queries working throughout rollout.
This guide walks through four rollouts: adding a required property, versioning a reshaped query, renaming a property and indexing a large table, along with committing migration decisions in git. Each step ships in its own pull request so the review comment previews the migration plan before anything reaches main.
Before you start#
Start from Your first app deployed with the CI workflow in Environments & going live, where each merge pushes dbschema/default.gel and every query in dbschema/queries to main together.
Napalm refuses any push that breaks a deployed query, so no single push can drop a property that live clients still read. The rollouts below lean directly on that compiler check.
napalm schema push sends your schema file verbatim without injecting hidden lines, so every schema must declare using extension napalm; explicitly or the push is refused.
Query compatibility check
Every push compiles your saved queries against the target schema before applying DDL.
Set up a backfill service key#
A backfill runs an EdgeQL update statement across existing rows via napalm query using a service key under your schema’s access policies. The CLI resolves the key from --key, then NAPALM_KEY, then the key saved by napalm keys create --save.
A service key has an empty global caller. Because the starter app’s policy admits only each note’s owner, an unscoped service key matches zero notes (see Update and delete).
Scoped backfill dry runs
Preview before-and-after row diffs inside a rolled-back transaction before updating live rows.
Grant update access to the backfill role in your schema and issue a one-day service key.
module default { # Bound to the backfill key via --global. Callers cannot override globals per request. global role: str; type Note { # … as before, and: access policy backfill_can_update allow select, update using (global role ?= 'backfill'); }}# Issue a one-day key scoped to the backfill role (napalm query reads NAPALM_KEY)export NAPALM_KEY=$(napalm keys create notes --label backfill --global default::role=backfill --days 1)- Backfill role
--globalbindsroleexclusively to the backfill key. Service keys covers per-key globals.- Dry run first
- Pass
--dry-runtonapalm queryto inspect modified notes without committing the update. - Batching large tables
- Each HTTP request has a 60-second statement timeout before returning
503 project_unavailable. Backfill large tables inlimitbatches as shown next. - Passthrough mode
- Ad-hoc
napalm queryupdates fail on--read-onlykeys or under--passthrough none. Set endpoint passthrough tokeysorallwhile running the backfill. - Cleanup
- The key expires automatically after 24 hours (or immediately via
napalm keys revoke). Drop the temporary backfill policy in your final cleanup push.
Add a required property#
Suppose every Note needs a required summary holding the first 120 characters of body. Roll the field out in three steps: add the property with an empty default, backfill existing rows in batches and drop the temporary default.
Add the property with an empty default
The default satisfies existing rows at migration time without rewriting the table under lock. In the same pull request, update
addNoteto populatesummaryon every new insert.dbschema/default.gel type Note { # … as before, and: required summary: str { # Populates existing rows on migration before the batch backfill runs. default := ''; };}dbschema/queries/addNote.edgeql # Preserves the existing input variables so open client tabs keep working.insert Note { owner := global caller, title := <str>$title, body := <str>$body, summary := (<str>$body)[:120],}Because
addNotekeeps its existing variables, open browser tabs continue callingaddNoteand still populatesummary. Accepting a new$summaryparameter from clients would change the query contract and require versioning the query.Backfill existing rows
Terminal# Preview before-and-after row diffs inside a rolled-back transactionnapalm query notes "update Note filter .summary = '' and .body != '' set { summary := .body[:120] }" --dry-run # Run the backfill across matching rowsnapalm query notes "update Note filter .summary = '' and .body != '' set { summary := .body[:120] }" # For large tables, update in 1,000-row batches until the result returns []napalm query notes "update (select Note filter .summary = '' and .body != '' limit 1000) set { summary := .body[:120] }"Each statement authenticates via
NAPALM_KEYand updates only notes whosesummaryis still empty, making repeated runs idempotent.Drop the temporary default
dbschema/default.gel type Note { # … as before, now without the temporary default: required summary: str;}Removing the default forces every future
insert Notestatement to supplysummaryexplicitly. Napalm rejects this push if any deployed query omitssummary.
Version a reshaped query#
Changing a deployed query’s input variables or output fields requires a new query name so open tabs running the prior build keep receiving the expected response shape. Here myNoteSummaries replaces myNotes by returning summary instead of body.
# List notes returning summary in place of bodyselect Note { id, title, summary }order by .titleDeploy the new query alongside the old query
Commit
myNoteSummaries.edgeqlbesidemyNotes.edgeqland merge.myNotesstays live for open tabs whilenapalm generate notes --deployed --lang tsgenerates typed bindings formyNoteSummaries.Deploy the updated client
Newly loaded tabs call
myNoteSummarieswhile older open tabs continue callingmyNotes.Wait for traffic on the old query to drain
Run
napalm insights notes --days 7to inspect per-query call counts over the past week, and proceed oncemyNotesrecords zero calls.Retire the old query
Delete
dbschema/and merge. Each push replaces the active catalog, retiringqueries/ myNotes.edgeql myNotes. Runningnapalm queries push notesinteractively prompts for confirmation before removing a deployed query.
Rename a property#
To rename summary to preview without locking large tables or breaking active queries, keep both properties online temporarily while dual-writing and migrating readers.
Add the new property and dual-write
dbschema/default.gel type Note { # … as before, and: required summary: str; required preview: str { default := ''; };}Update every write query (such as
addNote) to setpreview := (<str>$body)[:120]alongsidesummaryso newly inserted notes populate both columns.Backfill the new property
Terminalnapalm query notes "update Note filter .preview != .summary set { preview := .summary }"Filtering on
.preview != .summarytouches only uncopied rows, so re-running the backfill changes nothing.Point read queries at the new property
Alias
summary := .previewinsidemyNoteSummariesso existing client builds keep their response field name while reading from the new column.dbschema/queries/myNoteSummaries.edgeql # Project preview under the summary key so open tabs keep workingselect Note { id, title, summary := .preview }order by .titleKeep dual-writing both columns until the final step. Exposing the renamed key
previewto clients is a response-shape change and follows Version a reshaped query.Drop the old property
dbschema/default.gel type Note { # … as before, dropping summary, the backfill policy and the temporary default: required preview: str;}Remove
summary, the temporary backfill policy and the empty default onpreview, and removesummaryfromaddNotein the same pull request. Napalm blocks the push if any deployed query still referencessummary, and interactive pushes warn before dropping stored data.
Resolve migration prompts#
Certain schema transitions cannot be inferred from target SDL alone, such as distinguishing a column rename from a drop-and-add or casting existing strings to integers.
Committed migration decisions
Saved decision files commit migration answers in git for repeatable CI pushes.
In-transaction row rewrites
Migration expressions populate or cast existing rows inside the DDL transaction.
Local shard execution
Multi-shard projects run each migration expression locally on every shard in parallel.
Whenever planning cannot infer row transformations automatically, the planner requests one of four structured decision kinds.
| Decision kind | Triggered when | Example answer |
|---|---|---|
fill | An optional field becomes required, or a new required field has no default. | Example answer.body[:120] ?? '' |
convert | A property changes to a type without an implicit cast, such as str to int64. | Example answer<int64>.score |
single | A multi property or link changes to single cardinality. | Example answerarray_join(array_agg(.tags), ', ') |
rename | The planner detects a candidate field or type rename and asks rename vs replace. | Example answerchoice: rename |
Save decisions in dbschema/decisions.yaml (or pass --decisions to use an alternate path) so napalm schema push submits your answers automatically. Address fields as Type.field, module::Type.field or Type.link@property, and address candidate type renames by the prior type name paired with to.
# Saved answers for interactive migration prompts. Remove entries once merged to main.decisions: # Populate existing Note rows with the first 120 characters of body. - field: Note.summary kind: fill expression: ".body[:120] ?? ''" # When filling and converting in one step, fill returns the prior type (str). - field: Metric.score kind: fill expression: "'0'" - field: Metric.score kind: convert expression: "<int64>.score" # Collapse multi-property tags into a single comma-separated string. - field: Post.tags kind: single expression: "array_join(array_agg(.tags), ', ')" # Confirm a column rename (replace would drop existing titles). - field: Note.title to: headline kind: rename choice: renameInteractive prompts in a terminal#
In an interactive terminal, napalm schema push prompts for each required decision, replanning after every round in case later steps depend on your answer. Before applying the migration, the CLI offers to append new answers to dbschema/decisions.yaml while preserving existing comments.
Non-interactive pushes in CI#
In CI (or whenever --yes is passed), napalm schema push never blocks on stdin. Instead, the CLI prints the exact YAML snippet missing from dbschema/decisions.yaml and exits with status 1 before modifying the branch.
- Candidate renames
- Heuristic rename candidates pause the push until confirmed in
decisions.yaml. Choosingrenamepreserves stored data, whereasreplacedrops the old column and counts toward destructive drop warnings. Unambiguous renames need no entry. - Table rewrite locks
- Migration plans report how many existing rows each
fill,convertorsingleexpression rewrites. Concurrent writes to that type wait while the rewrite commits, so prefer batched backfills on large tables. - Expression rules
- Each expression is a single EdgeQL value expression up to 8 KiB referencing fields on the current object. Top-level commas and semicolons are allowed only inside brackets, and unclosed string interpolations, template tokens such as
\(fill_expr), mismatched types or empty results fail planning with a compiler error. - Combined fill and convert
- When one step both marks a field required and changes its type, the engine runs
fillbeforeconvert, so thefillexpression must return the old type (such as'0'before castingstrtoint64). - Multi-shard execution
- On sharded branches, each shard evaluates the expression over its local rows without cross-shard reads. Plan row counts reflect the base shard.
- Pruning applied entries
- Once a migration lands on
main, the push output lists any stale entries indecisions.yamlthat are no longer needed so you can delete those entries cleanly. - Unsupported transitions
- If a complex schema edit triggers a planner prompt outside these four decision kinds, split the change into smaller incremental pushes.
Index a large table#
PostgreSQL builds new indexes inside the migration transaction, so concurrent writes to that type wait until the index build finishes. On high-write tables with millions of rows, run index builds during a low-traffic window.
napalm insights identifies slow statements and recommends specific indexes, and napalm schema index builds a recommended index on main.
# Inspect slow statements and recommended indexes with estimated savingsnapalm insights notes # Preview the index migration DDL without applying changesnapalm schema index notes Note title --plan # Prompt for confirmation and build the index on mainnapalm schema index notes Note titleThe command previews the DDL and asks for confirmation before building the index. Commit the matching index on (.title); line in dbschema/default.gel afterward so your next napalm schema push retains the index. Automation scripts can trigger the same operation via POST / (see Recommended indexes).
Preview migrations on pull requests#
napalm schema push notes --review renders the full migration plan as Markdown for pull-request comments without applying changes. The output covers generated DDL statements, destructive drop counts, inferred root paths, affected notify webhooks, planner warnings, row counts rewritten by active decisions, any missing decisions.yaml entries and compile verdicts for every deployed query.
# Render the migration plan as Markdown for pull-request comments without applyingnapalm schema push notes --review > review.md # Print the full migration plan and inferred root paths in the terminalnapalm schema push notes --plan- CI exit codes
--reviewexits non-zero whenever a migration requires an unanswered decision or breaks a deployed query, failing the pull-request check automatically.- Destructive drops
- Valid drops pass
--reviewwhile surfacing an explicit drop count in the PR comment. Connected GitHub App repositories hold destructive merges for approval from a repository maintainer. - Terminal preview
--planprints the same dry-run migration plan and root table directly in your terminal.- Control API
- Calling
POST /withprojects/ {id}/ schema isApplied: falsereturns the same structured plan and Markdown review. See Schema migrations.
Branches provides the complete CI workflow for posting migration reviews on pull requests.
Check the schema changes#
Run four checks to confirm that open client tabs, backfilled rows and deployed queries survived every rollout step cleanly.
Insert a note from a pre-deploy browser tab
Keep a browser tab open from before adding
summary, merge the first step and create a note from that unrefreshed tab. Confirm the write succeeds.Verify zero unbackfilled rows remain
With your backfill key in
NAPALM_KEY, runnapalm query notes "select count(Note filter .summary = '' and .body != '')"before dropping the temporary default, and confirm the count is0.Confirm the retired query is removed
Verify
napalm insights notes --days 7shows zero calls tomyNotesbefore deleting its file, and confirmnapalm queries ls noteslistsmyNoteSummariesalone after merge.Confirm a clean no-op plan on main
Run
napalm schema push notes --reviewafter the final cleanup merge and confirm zero pending DDL changes, every query compiling and exit code0.