# Napalm docs, in full > Every page of https://napalmdata.com/developers/primer, in reading order. The short version is https://napalmdata.com/llms.txt, and the HTTP API is > https://napalmdata.com/openapi.yaml. --- Source: https://napalmdata.com/developers/primer First principles Chapter 1 of 11 # Napalm’s origin Napalm compiles one schema into your entire backend on PostgreSQL 18. Data types, access policies, background jobs, search and live queries stay in sync without glue code. [Diagram: An engraving of a Napalm cluster. An engine bay runs along the top, and each shard bay below holds a primary over its replicas, linked across shard bays by a horizontal transfer pipe. One bus cables the bays. Every request passes a policy lock into the engine bay and a second lock into a shard, then leaves the engine as a write to a primary or a read to a replica while shards rebalance smoothly across primaries. The first lock turns unauthorized requests back. The drawing starts at one engine over one shard and grows through replicated and sharded clusters to eight engines over eight shards. Embers rise around the lit frame.] Building an application usually means stitching together separate services for sign-in, database queries, file storage, background jobs, search and live updates. Each service keeps its own permission checks, so one missed filter exposes private records and one failed queue call leaves state out of sync. **Try it** Napalm replaces those separate services with one schema file and saved EdgeQL queries. Run one command to scaffold a working starter app and configure a project. Terminal ``` napalm new notes-app notes ``` The starter app includes sign-in, live note lists, file uploads and search. ## Four jobs in one system Every backend has to identify the caller, enforce permissions, record changes and trigger downstream work. Conventional stacks assign each job to a separate tool, while Napalm handles all four from one schema. | | A typical stack | Napalm | |---|---|---| | Who is calling? | External auth service | Sign-in built into every project | | What is allowed? | Checks repeated in route code | Access policies declared on each type | | What changed? | Separate queue or polling worker | Ordered change log of every commit | | What updates next? | Custom workers and socket servers | Live queries, webhooks and jobs at commit | Web tabs, mobile apps, background workers, warehouse syncs, training pipelines and AI agents all read and write the same records. Keeping authorization inside HTTP route handlers leaves non-HTTP callers unprotected or forces your team to copy checks across every service. ## Compiling a backend from one schema Napalm moves those rules into one schema file and compiles your backend the way a language compiler builds a program. You declare types, links, indexes and access policies in `dbschema/default.gel` alongside saved `.edgeql` queries, and Napalm checks the whole set before anything deploys. | A language compiler | Napalm | |---|---| | Reads source files | Reads your schema and saved EdgeQL queries | | Rejects type errors before runtime | Validates every query against the schema on push | | Emits machine code | Compiles each query and its policies into one SQL statement | | Runs on target hardware | Executes across engines, replicas, shards and object storage | PostgreSQL 18 stores and executes everything underneath. Every EdgeQL expression carries a static type and cardinality without SQL NULLs, so queries compose cleanly and return predictable shapes. [Diagram: Requests pass the Policy Lock into the Query Engine, commit writes on the Primary with synchronous confirmation from the Replica, and route bookmarked reads to a caught-up Replica.] **From schema to cluster** Engines verify the caller, compile policies into SQL and run statements across your shards. ## How this primer works Each chapter ahead introduces a core part of Napalm first and then applies that capability to the starter notes schema. Along the way, one schema grows from private records and file uploads to collaborative live queries, actions, jobs and warehouse sync, multi-tenant workspaces and credit ledgers, hybrid search and model pipelines and sharded clusters. Two example users, Ada and Ben, test how permissions hold across sharing, team workspaces and AI agents. When Ada connects an assistant to read and organize her notes, a database password would expose Ben’s records and an unscoped API key would bypass user boundaries. [Diagram: Person Medallion: Single 3D extruded double-rimmed circular medallion with crescent hatch and geometric head-and-shoulders bust.] **Users** Sign-in binds `global caller` on every request. [Diagram: Service Key: Single 3D extruded steel key with octagonal bow, fluted shaft and stepped bit wards (2 teeth = write, 1 = read-only).] **Services** Scoped keys authenticate workers, schedules and sync jobs. [Diagram: AI Agent Core: Single watertight 8-sided 3D basalt core with optical iris spark wrapped by two intersecting 3D gimbal rings.] **AI agents** Consent and expiring grants limit tools to permitted rows. Every chapter returns to the same architectural test: people, backend services, data pipelines and AI agents all share one database under access policies you write once. Six architectural rules hold that guarantee together across every feature and machine. Learn more **Your first app** Run the five setup commands that create and deploy the starter notes app. **Napalm and Gel** Additions to Gel’s schema language and EdgeQL. **How Napalm works** How a request moves through engines, replicas and shards. --- Source: https://napalmdata.com/developers/primer/pillars First principles Chapter 2 of 11 # The six pillars Six architectural rules hold across every feature in Napalm. Together, those rules keep access, transactions and shard placement consistent as your app grows. Compiling your backend from a single schema works because Napalm enforces six rules across the compiler and runtime, from your first local migration to multi-shard failover. **Try it** Remove `body` from `Note` in your starter schema and run `napalm schema push`. Napalm checks every deployed query first and refuses the migration before anything changes. Your terminal ``` $ napalm schema push notes × dbschema/queries/myNotes.edgeql InvalidReferenceError: object type 'default::Note' has no link or property 'body' × dbschema/queries/addNote.edgeql InvalidReferenceError: object type 'default::Note' has no link or property 'body' Nothing was applied because the new schema would break these queries. Fix the queries or the schema. ``` Napalm lists every saved query that references body and leaves the database untouched. ## One typed graph Application tables, binary files (`ext::files::File`), vector and full-text indexes (`ext::ai::index`, `fts::index`), background jobs (`ext::napalm::Job`) and permission grants all live as typed objects and links in `dbschema/default.gel`. dbschema/default.gel ``` type Note { required owner: ext::auth::Identity; required title: str; required body: str; deferred index ext::ai::index(embedding_model := 'openai/text-embedding-3-small') on (.title ++ '\n\n' ++ .body); index fts::index on (( fts::with_options(.title, language := fts::Language.eng, weight_category := fts::Weight.A), fts::with_options(.body, language := fts::Language.eng, weight_category := fts::Weight.B) )); } type Attachment extending ext::files::File { required owner: ext::auth::Identity; access policy owner_has_full_access allow all using (.owner ?= global caller); } ``` Records, search indexes and file attachments live side by side in one schema. Full-text indexes and queued jobs commit inside the write transaction, while deferred vector embeddings refresh in the background. Every search, download and job enforces the same schema access policies without external sync workers. ## Caller-bound Every stored object type starts closed over the API. Napalm verifies each bearer credential, binds `global caller` or configured service globals inside PostgreSQL, and evaluates `access policy` expressions in the same EdgeQL language as your queries. dbschema/default.gel ``` global caller := global ext::auth::ClientTokenIdentity; type Note { access policy owner_has_full_access allow all using (.owner ?= global caller); } ``` Access policies walk links from the verified caller identity. One policy governs HTTP queries, live streams, signed file downloads, vector search, actions, jobs and MCP tools. Time-limited rules check `datetime_of_statement()` on the statement clock, and org tokens (`napalm_…`) manage clusters without reading row values. [Diagram: Access Policy Lock: Single monumental 3D extruded steel padlock with twin top-bevel shackle sockets (seated flame shackle shut vs lifted gold shackle open).] **Closed by default** Types without a matching policy return zero rows and refuse writes. [Diagram: User Session Capsule: Single 3D extruded stadium capsule pairing a gold caller jewel on the left with a bounded lifetime arc on the right.] **Verified identity** Napalm binds the caller identity inside PostgreSQL before any query runs. ## Compiled Every EdgeQL expression carries a static type and cardinality. When you push changes, the compiler checks your schema, access policies and saved `.edgeql` query files together before applying DDL. Terminal ``` napalm generate notes --lang ts ``` Generate typed SDKs, CLI commands and MCP tools from checked query files. Saved queries compose dynamic UI filters and cursors with typed `optional` parameters, while `POST /query` runs parameterized ad-hoc statements and `/ask` compiles plain-English questions read-only. In every path, the compiler lowers the query and its touched policies into a single SQL statement without N+1 round trips. ## Commit-atomic Row changes, ledger updates and queued `ext::napalm::Job` records commit or roll back together in one PostgreSQL transaction. Live query patches, `notify` webhooks and file upload windows fire only after commit, so rolled-back writes and dry-run previews emit nothing. dbschema/queries/addNoteWithReminder.edgeql ``` with note := (insert Note { owner := global caller, title := $title, body := $body }), job := (insert ext::napalm::Job { query := 'sendReminder', variables := (note := note.id) }), select note { id } ``` Inserting a note and queueing its reminder commit together in one statement. Committed responses return `Napalm-Bookmark`, and webhook pings carry `Napalm-Position`. Replicas and downstream workers wait for that commit position before reading, so callers never observe stale rows after their own writes. ## Distributed from links Conventional sharding forces you to copy a shard key across every table, foreign key and query. In Napalm, the compiler walks `required single` links upward to infer placement roots for any domain hierarchy (`Account`, `Project`, `Organization` or `Site`). `ext::napalm::root` annotations mark explicit roots, replicate lookup tables across shards or exclude secondary links from ownership. User identities (`ext::auth::Identity`) and `multi` links never claim shard ownership, so multi-org memberships and guest collaborators span roots freely. [Diagram: Busy Root Hex territories split cleanly along cell boundaries without cutting across an owner’s linked records, rebalancing across two Shard Bays behind one unchanged Endpoint.] **Sharding from links** Required links group related records on one shard without shard-key columns. Every table keeps a standard `uuid` primary key. Shards split and rebalance behind one project URL, bookmarks route reads to caught-up replicas and vector indexes scale past 100 million embeddings without query changes. ## Checked and fault-tested Static checks block breaking migrations and unplaceable root links before deploy, while runtime diagnostics verify permissions and durability under load. Terminal ``` napalm schema push notes --review napalm explain-access notes --as ben@example.com ``` Check migrations statically in CI or trace live access rules without exposing field values. In production, `napalm explain-access`, `napalm people reach`, `napalm insights` and dry-run `/ask` inspect permissions, reachable row counts, per-policy latency and index recommendations safely. Every release also runs automated fault campaigns on the public chaos lab, where incomplete evidence is marked Inconclusive rather than Passed. [Diagram: Value-Blind Access Trace: Shard bay tracing an admitted link hop to a locked policy hop above a hatched shuttered Stored Record whose field values stay masked.] **Policy diagnostics** Inspect live permissions and reachable row counts without reading field values. [Diagram: Chaos Lab Verification: Shard bay struck by an engineered fault bolt streaming verified commit blocks to a bookmarked Admit seal with zero lost writes.] **Release fault tests** Every release faces crashes, network splits and full disks before rollout. Before writing our first access policy, let’s look at how orgs, clusters, branches and credentials fit together. Learn more **How Napalm works** Request lifecycle, single-statement guarantees and causal replicas. **Schema** Types, links, migrations and the query check on every push. **Access & sign-in** Caller globals, closed types, graph-walk policies and reach proofs. **Scale & recovery** Root sharding, causal bookmarks and automated fault campaigns. --- Source: https://napalmdata.com/developers/primer/model First principles Chapter 3 of 11 # Parts of a project An org holds your clusters, projects and database branches. Each project serves one HTTPS endpoint for users, backend services and AI agents while keeping control credentials separate from row data. Before deploying a schema, you need a clean boundary between managing infrastructure and reading application rows. Developers and CI pipelines should be able to create branches and scale clusters without holding a password that reads private records. **Try it** Sign in from your terminal to save an org token that controls clusters and projects without access to row data. Your terminal ``` $ napalm login → Opening your browser to sign in… If the browser doesn’t open, visit: https://console.napalmdata.com/authorize-cli?port=53817&state=…&challenge=…&name=napalm+CLI+on+studio ✓ Signed in to Northwind Can make changes until 2026-11-16 01:12 PST ``` Browser sign-in saves an org token that manages infrastructure and never reads customer rows. ## Orgs, projects and branches Four resources organize your infrastructure and isolate development from production. | Resource | Role | |---|---| | Org | Holds your projects, clusters, org tokens, teammates and billing | | Project | Serves your backend API, MCP server and auth at `notes.napalmdata.com` | | Cluster | Runs dedicated engines, PostgreSQL primaries and replicas from `solo` up to sharded `scale` | | Branch | Provides an isolated database beside `main` with separate rows, service keys and sessions | Production traffic hits `main`, while feature work and pull requests target separate branches. Every cluster runs on dedicated compute, storage volumes, TLS keys and object buckets rather than sharing database processes with other customers. [Diagram: Dedicated Cluster: Locked top engine bay cabled through one orthogonal bus into dedicated primary-replica shard bays linked by an inter-shard transfer pipe.] **Dedicated cluster** Dedicated compute, disks, TLS keys and storage buckets per cluster. [Diagram: Isolated Branch Database: Branch Fork Rail splitting off main’s Primary into an isolated dashed Shard Bay holding its own branch Primary.] **Isolated branches** Separate rows, service keys and sessions alongside `main`. ## Callers and credentials Pillar at work: Caller-bound Four kinds of callers interact with a project. Each brings a distinct credential, and Napalm binds project credentials into typed EdgeQL globals before any query executes. | Caller | Credential | Bound globals | |---|---|---| | End user | Session token from built-in sign-in | The signed-in identity in `global caller` | | Backend service | Branch-scoped service key (`ndb_…`) | Empty `global caller`, plus configured service globals | | AI agent | OAuth session or scoped grant token | The approving user or agent identity in `global caller` | | Developer or CI | Org token (`napalm_…`) on the Control API | None (manages infrastructure only and cannot query row data) | Every stored type starts closed to application callers. In our running example, Ada and Ben authenticate with user sessions, background workers use branch-scoped service keys, and your CLI or CI pipeline uses an org token (`napalm_…`) that inspects schemas, row counts and access traces without reading field values. ## Schema and query files Pillar at work: One typed graph Your schema and queries live as plain files in git beside your application code. The starter notes project begins with one schema file and four EdgeQL query files. Your repository ``` dbschema/ default.gel # types, links and access policies queries/ addFile.edgeql addNote.edgeql myFiles.edgeql myNotes.edgeql ``` One schema file and four EdgeQL files define types, access policies and endpoints. Running `napalm schema push` against `main` checks all four query files against the schema, applies any migration in one transaction and deploys each query by name at `POST /query/{name}`. Pushing with `--branch` runs the same validation and migrates only that branch. When Ada saves a note on `main`, Napalm verifies her session, compiles `addNote` together with the insert policy into one SQL statement, and streams the committed note to her open tabs. With credentials separated and queries deployed, every stored type still starts closed until a policy opens access. Learn more **Organization & billing** Teammates, roles, billing and org activity. **Scale & recovery** Cluster shapes from single-machine `solo` to sharded `scale`. **Branches** Branch addresses, isolated keys, sessions and copied data. **Sessions & keys** How user sessions, service keys and org tokens differ. **SDKs** Deployed queries and the clients generated from your query files. --- Source: https://napalmdata.com/developers/primer/first-rule Feature by feature Chapter 4 of 11 # Rules, queries and files Access policies live on your schema types rather than inside route handlers. Saved EdgeQL files turn your schema into named endpoints, direct file uploads and typed client SDKs. Every object type in a freshly pushed schema starts closed over the API. Until an access policy grants permission, queries return zero rows and writes fail, even when a caller sends an unfiltered query. **Try it** Sign up as Ada in the starter app and save a note. Then sign in as Ben in a second browser window and query every `Note`. Ben’s query ``` select Note { title } ``` An unfiltered query under Ben’s session returns none of Ada’s notes. ## Policies on the type Pillar at work: Caller-bound An `access policy` lives inside an object type and declares which operations (`select`, `insert`, `update`, `delete` or `all`) are allowed when its `using` expression evaluates to `true`. Written in EdgeQL, policies can read properties, traverse links and check `global caller`. dbschema/default.gel ``` global caller := global ext::auth::ClientTokenIdentity; type Note { required owner: ext::auth::Identity; required title: str; required body: str; access policy owner_has_full_access allow all using (.owner ?= global caller); } type Attachment extending ext::files::File { required owner: ext::auth::Identity; access policy owner_has_full_access allow all using (.owner ?= global caller); } ``` The same three-line ownership policy protects both Note rows and Attachment files. Types without a matching policy stay closed, returning zero records on reads and refusing writes. Napalm verifies the bearer token before binding `global caller`, so no request can spoof another user’s identity. [Diagram: A Client Viewport calls a Deployed Query Stencil through the Query Engine. Linked Stored Records with an allow policy return in one snapshot, while any type without a policy stays sealed.] **Policies in every query** Matching policies compile into the SQL statement while closed types return nothing. ## Statement-level enforcement Pillar at work: Checked and fault-tested Napalm compiles matching policies straight into the single SQL statement PostgreSQL runs. Reads skip unpermitted rows, and `insert` or `update` statements validate the resulting row before committing, so Ben cannot insert a note naming Ada as `.owner`. Service keys and agents pass through the same check. A backend service key belongs to no user, so `global caller` is empty and workers see zero rows unless you add a policy checking service globals. An OAuth session approved by Ada binds `global caller` to Ada and restricts the client to her permitted rows. When debugging permissions, run `napalm people reach` to count reachable rows per type or `napalm explain-access` to inspect every policy clause on a specific object ID without exposing field values. Your terminal ``` $ napalm explain-access notes 0192c3f4-6b1a-7d8e-9f00-1a2b3c4d5e6f --as ben@example.com Object default::Note 0192c3f4-6b1a-7d8e-9f00-1a2b3c4d5e6f Access × read × change × delete × owner_has_full_access allows all × .owner ?= global caller global caller was set ``` Inspect why a specific Note ID was hidden from Ben without adding debug routes or reading private text. ## Saved queries and typed clients Pillar at work: Compiled In production, you store application reads and writes as `.edgeql` files in `dbschema/queries/`. Because ownership is already enforced on `Note`, `myNotes.edgeql` needs no manual `owner` filter. dbschema/queries/myNotes.edgeql ``` select Note { id, title, body } order by .title ``` The query omits a manual owner filter because the policy on Note scopes every read. Saved queries traverse nested links, backlinks and aggregates in one SQL statement with no N+1 round trips. Pushing deploys each file as `POST /query/{name}`. Callers pass typed JSON variables, including `optional` filter and cursor parameters, while query text remains on the server so user input cannot alter query structure. Terminal ``` curl https://notes.napalmdata.com/query/addNote \ -H "Authorization: Bearer $SESSION" \ -H "Content-Type: application/json" \ -d '{ "variables": { "title": "Printers", "body": "Call the vendor on Monday" } }' ``` Call `addNote` over HTTPS with a bearer session and typed JSON variables. Running `napalm generate` reads those same deployed queries and generates typed client SDKs in eight languages alongside project CLI commands and MCP tools. Terminal ``` napalm schema push notes npm run generate ``` Validate and deploy schema and queries, then generate typed client bindings. ## Files as typed records Pillar at work: One typed graph Subtyping `ext::files::File` keeps file metadata and access policies in PostgreSQL while raw bytes live in dedicated object storage. Inserting an `Attachment` checks the insert policy and returns a one-time upload plan while the record starts in `Pending`. dbschema/queries/addFile.edgeql ``` select (insert Attachment { owner := global caller, file_name := $name, file_size := $size, }) { id, file_upload } ``` Inserting a File subtype checks insert policies and returns a direct object-storage upload plan. Uploads go directly from the browser or phone to your cluster’s bucket without streaming through query engines. Once the transfer completes, Napalm inspects the leading file bytes against any `file_format` constraint before setting `file_status` to `Ready`. [Diagram: After receiving a one-time upload plan from the Query Engine, the Client Viewport streams file bytes straight into the Object Bucket. Completion checks the stored magic bytes before marking the File record Ready.] **Direct storage uploads** Uploads stream straight to object storage and pass a header check before becoming Ready. Selecting `file_download_url` signs a short-lived link inside the policy-filtered query, so unauthorized callers never receive a URL. Uploaded objects are immutable, keeping point-in-time restores and data-cloned branches consistent with historical rows. dbschema/queries/myFiles.edgeql ``` select Attachment { id, file_name, file_size, file_status, file_download_url } order by .file_name ``` Short-lived download URLs are signed only for Attachment rows the caller’s select policy allows. ## Checks in CI and production Every schema push validates all files in `dbschema/queries/` before running DDL. In pull-request CI, `napalm schema push --review` outputs the migration plan and exits non-zero if a change would break any deployed query. Terminal ``` napalm schema push notes --review > review.md ``` Generate a pull-request migration report and fail CI on broken queries. Once your client apps use generated functions exclusively, disable ad-hoc EdgeQL execution for user sessions while keeping full query access for backend service keys. Under live traffic, `napalm insights notes` reports per-query latency, replica read share, policy cost and index recommendations. Terminal ``` napalm endpoint notes --passthrough keys ``` Limit browser and mobile sessions to deployed queries. Once queries and access policies are deployed, keeping screens synchronized across tabs and devices requires zero extra backend code. Learn more **Access & sign-in** Callers, closed types, rule syntax, service globals and reach checks. **Queries & mutations** Nested shapes, filters, typed variables and writes. **Files & object storage** File types, direct-to-storage uploads, format verification and signed download URLs. **Schema** Migrations and query validation on every push. **SDKs** Generated clients and locking down custom queries. **How Napalm works** One SQL statement and one consistent read per request. --- Source: https://napalmdata.com/developers/primer/live Feature by feature Chapter 5 of 11 # Realtime apps Any deployed read query can stay open as a live subscription on web and mobile. Updates, shared records and presence rooms enforce the same access policies as an ordinary read. In Chapter 4, `myNotes.edgeql` fetched a static snapshot over HTTP. Keeping two browser tabs or a mobile app synchronized with that query requires no WebSocket server or separate pub-sub bus. **Try it** Open the starter app as Ada in two browser tabs, save a note in one tab and watch it stream into the second tab immediately. ## Live queries Pillar at work: Commit-atomic Any deployed read query from Rules, queries and files can stay open as a live subscription over `POST /subscribe`. Two lines subscribe a React component to `myNotes`. src/Notes.tsx ``` const myNotes = deployed>('myNotes') const { rows, error, isLoading } = useLiveQuery(myNotes, {}) ``` Generated hooks subscribe to deployed queries and apply incremental row diffs. External socket servers can race ahead of database transactions or update one component on a page before another. Napalm emits diffs strictly after commit, and every subscription on a connection advances at the same commit boundary so lists, counts and detail panes stay consistent. [Diagram: Multiplexed SSE Conduit: Single coaxial three-line channel: bright gold inner core flanked by two fine parallel steel guard rails.] **One shared connection** All live queries and presence rooms on a page share one stream. [Diagram: Realtime Live Stream: Query Engine driving a Multiplexed SSE Conduit and concentric commit wavefronts into subscriber Stored Records with instant policy revocation.] **Post-commit updates** Row patches stream only after commit, so rolled-back writes never appear. ## Sharing and revocation Pillar at work: Caller-bound Live subscriptions evaluate the same `access policy` expressions as ordinary reads on every commit. To support collaborative editing on `Note`, add a `multi editors` link and a policy granting `select` and `update` to listed editors. dbschema/default.gel ``` function identity_by_id(target: uuid) -> optional ext::auth::Identity using (select ext::auth::Identity filter .id = target); type Note { required owner: ext::auth::Identity; multi editors: ext::auth::Identity; required title: str; required body: str; access policy owner_has_full_access allow all using (.owner ?= global caller); access policy editors_can_read_and_change allow select, update using ((global caller in .editors) ?? false); } ``` A multi-link and a second access policy open shared notes to collaborators. Sharing or unsharing a note is an ordinary `update` query. dbschema/queries/shareNote.edgeql ``` update Note filter .id = $note and .owner ?= global caller set { editors += identity_by_id($person) } ``` Only the note’s owner satisfies the policy required to add or remove editors. When Ada adds Ben to `.editors`, the note streams onto Ben’s open list immediately. When Ada removes him, the note disappears from Ben’s screen on that exact commit without client refresh logic. ## Presence rooms Ephemeral state such as cursor coordinates, text selections and active viewer avatars does not belong in database tables. Any readable record ID can host an in-memory presence room that writes nothing to disk. src/Viewers.tsx ``` const { people, peers, isJoined, update } = usePresence(note, { state: { name, isTyping: false } }) ``` Join a record’s presence room over the existing live connection. Joining a room checks the caller’s read policy on that record. If Ada removes Ben from a shared note, Napalm evicts his connection from the presence room on the same commit. [Diagram: Presence Room: Dashed in-memory room halo around a shared File Monolith uniting Person Medallions, an AI Agent and live typing pulses.] **In-memory presence** Cursors and viewer lists stay off disk under the record’s read policy. ## Web and mobile clients Pillar at work: Compiled The same deployed `.edgeql` files drive web and native mobile apps. Web apps and React Native share `useSession` and `useLiveQuery` from `napalm-client/react`, while Flutter apps consume typed Dart `Stream`s generated by `napalm generate`. When a phone wakes from background sleep, the SDK resumes from its last commit bookmark automatically. Live streams keep connected clients current, while external APIs, scheduled tasks and data warehouses need reliable background execution. Learn more **Live queries & presence** Subscriptions, how saved writes reach the screen, access rules and presence rooms. **Realtime & collaboration** Shared notes, ordering and active viewers. **React Native** Running the realtime notes app on iOS and Android. **Flutter** Typed Dart streams for Flutter apps. --- Source: https://napalmdata.com/developers/primer/beyond Feature by feature Chapter 6 of 11 # Actions, jobs and webhooks External code, background jobs and webhooks run under the same caller rules and commit boundaries as your queries. Gatekeeper queries guard handlers and jobs commit alongside writes, while the change log feeds warehouses without polling. Queries and live subscriptions keep state inside PostgreSQL, while production apps also send emails, run delayed tasks and sync analytics warehouses. Moving work outside a database query should not bypass caller policies or fire on rolled-back data. **In practice** An action runs a gatekeeper query under the caller’s identity before invoking external code. If Ben calls `emailNote` with the ID of Ada’s private note, PostgreSQL returns zero rows and Napalm responds with `403 nothing_found` without waking the handler. When Ada calls `emailNote` on her note, the handler receives the permitted row and sends the email. ## Actions and hosted handlers Pillar at work: Caller-bound An action pairs a saved `.edgeql` query with handler code written in TypeScript, Python, Go, Rust or Dart. PostgreSQL executes the query first under the caller’s access policies, and Napalm invokes the handler only when at least one permitted row matches. [Diagram: Heat Comet & Verdict Seal: Single tapered 7-segment heat comet arriving at a machined circular escutcheon (gold Admit tick vs flame Refuse cross).] **Gatekeeper query** PostgreSQL checks the paired query first and blocks unauthorized calls. [Diagram: Hosted Handler: Single 3D struck rounded-square die with 4 corner studs and 24-tick bezel: dashed asleep, solid steel with caller core awake.] **On-demand handlers** Handlers wake per call and hold no standing database password. Because the gatekeeper query runs under `global caller`, unauthorized requests fail inside PostgreSQL before waking external code. dbschema/queries/emailNote.edgeql ``` select Note { title, body } filter .id = $note ``` The gatekeeper query loads the note under the caller’s select policy before any handler wakes. When a handler needs to write results back, exchanging its call token yields a 60-second session scoped to the original caller. Place a matching file in `handlers/` to run on Napalm’s serverless runtime, or point the action at your own HTTPS endpoint. Terminal ``` # handlers/emailNote.ts pairs with dbschema/queries/emailNote.edgeql napalm handlers deploy notes ``` Deploy hosted handlers in TypeScript, Python, Go, Rust or Dart. ## Jobs and cron schedules Pillar at work: Commit-atomic Enqueueing work on a separate broker from an HTTP handler can lose jobs on a crash or run jobs after a database rollback. In Napalm, background jobs are rows in `ext::napalm::Job` that commit in the same statement as your writes. dbschema/queries/addNoteWithReminder.edgeql ``` with note := (insert Note { owner := global caller, title := $title, body := $body }), reminder := (insert ext::napalm::Job { query := 'sendReminder', variables := (note := note.id), run_time := datetime_of_statement() + '24 hours', }), select note { id } ``` Inserting a Note and queueing its 24-hour reminder commit or roll back together. Rolled-back transactions leave no job behind. When `run_time` arrives, the job executes under the caller’s identity and carries a stable job ID across retries so handlers can deduplicate outbound calls. [Diagram: Job Queue & Cron Schedule: Queue Shard Bay holding three queued job Stored Records wired into a circular 3D Cron & Backoff Clock.] **Transactional jobs** Job rows commit alongside your writes and run asynchronously as the original caller. Recurring tasks without a user session, such as daily digests or rollups, run on cron schedules under a dedicated service key. Terminal ``` napalm schedules add notes sendDigest '0 8 * * *' --key ``` Schedule sendDigest daily at 08:00 UTC under a scoped service key. ## Commit notifications and webhooks External receivers watching changes to a type need no polling loop. Add a `notify` declaration on the schema type to emit an event whenever a transaction commits an insert, update or delete. dbschema/default.gel ``` type Note { required owner: ext::auth::Identity; multi editors: ext::auth::Identity; required title: str; required body: str; # …search indexes and access policies notify note_changed after insert, update, delete; } ``` Declare a post-commit notification event directly on the schema type. Subscribed HTTPS endpoints receive an HMAC-signed ping containing the commit’s `Napalm-Position` bookmark as soon as the write commits. Rolled-back transactions and dry runs send nothing. ## Reading the change log Pillar at work: Compiled Every committed write appends to the branch’s ordered change log. From a terminal, `napalm changes` summarizes recent commits with an org token without exposing row values. Your terminal ``` $ napalm changes notes --since 1h 2026-11-16 09:14 PST session 8f2c1e64 Note (1 added) 2026-11-16 09:18 PST session 8f2c1e64 Note (1 updated) 2026-11-16 09:22 PST key 0b6f1f5e Note (2 updated) ``` Each entry records commit time, caller kind, short credential ID and affected row counts. When a webhook ping wakes your sync worker, passing `Napalm-Position` as `reach` alongside the worker’s stored cursor guarantees the response includes the commit that triggered the ping, even when served by a read replica. Every row returned by `GET /changes` is filtered through the caller key’s `select` policies. Terminal ``` curl "https://notes.napalmdata.com/changes?since=2026-11-08T00:00:00Z&types=Note&limit=100" \ -H "Authorization: Bearer $NAPALM_KEY" ``` Fetch the next policy-filtered page of changes from a saved cursor. ## Warehouse sync Issue a dedicated read-only service key so your analytics or lakehouse worker can pull permitted changes without write privileges. Terminal ``` napalm keys create notes --label warehouse --read-only ``` Create a read-only service key for downstream warehouse sync. After an initial table copy, the worker pages forward from its saved cursor as webhook pings arrive. Applying a page is idempotent by primary key, and if a worker stays offline longer than your branch’s log retention, a gap marker instructs it to run a fresh copy. Each JSON change item also records how the write arrived (`http`, `mcp`, `job` or `schedule`). So far every record has belonged to an individual user. Multi-tenant apps add shared workspaces, role hierarchies, usage ledgers and shard roots. Learn more **Actions** The query guard on each call and exchanging a caller session. **Hosted handlers** Supported languages, secrets and deployment. **Jobs & schedules** The job queue, caller access, retries and schedules. **Notifications & webhooks** Notify declarations, signed webhook pings and the change log. **Warehouse sync** Initial copies, safe replays and handling gaps in the log. **Actions & background jobs** Building actions, webhooks and jobs step by step. --- Source: https://napalmdata.com/developers/primer/organizations Feature by feature Chapter 7 of 11 # Organizations and billing Required schema links model workspaces, roles and ownership hierarchies without repeating tenant IDs on every table. Single-statement transactions keep invites and credit ledgers exact while the compiler infers shard roots automatically. Up to this point, each `Note` belonged to a single user identity. Multi-user software groups records into workspaces or organizations, assigns member roles and tracks usage balances without leaking rows across tenants or double-spending credits under concurrent traffic. **In practice** Required object links enforce tenant boundaries without per-query filters. When Ada creates an organization and invites Ben, Ben sees only the pending invite until he accepts, and `myOrganizations` then returns the organization alongside his role. dbschema/queries/myOrganizations.edgeql ``` select Organization { id, name, slug, my_role := assert_single((select .members filter .identity ?= global caller)).role, } order by .name ``` Membership links determine both visibility and role with no manual tenant filter in the query. ## Hierarchies and role links Pillar at work: One typed graph Instead of repeating a `tenant_id` column across every table, child types link to their natural parent in the graph, and access policies walk that chain. Wrapping our notes schema in workspaces links `Note` to `Workspace` and `Workspace` to `Organization`. dbschema/default.gel ``` type Organization { required name: str; required slug: str { constraint exclusive; }; multi members := .$org), email := str_lower($email), role := $role, } ), email := ( insert ext::napalm::Job { query := 'sendInviteEmail', variables := (invite := invite.id), } ), select invite { id, email, role, expires } ``` If the invite insert rolls back, no invitation email is queued. Policies let the invited user inspect and accept the invite at the offered role, or enterprise customers can configure OIDC domain sign-in so verified employees join automatically on first login. ## Atomic credit ledgers Pillar at work: Commit-atomic Reading a wallet balance in application code before deducting usage creates a race condition under parallel requests. Composing an `insert` and an `update` inside one EdgeQL statement records the immutable `LedgerEntry` and decrements `CreditWallet.balance_credits` atomically. dbschema/queries/spendCredits.edgeql ``` with amount := $amount, wallet := assert_single((select CreditWallet filter .org.id = $org)), entry := ( insert LedgerEntry { wallet := wallet, delta_credits := -amount, reason := $reason, idempotency_key := $key, } ), debited := ( update wallet set { balance_credits := .balance_credits - amount } ), select { entry_id := entry.id, remaining_credits := debited.balance_credits, } ``` The ledger row and wallet debit commit together in a single statement. A schema constraint prevents `balance_credits` from dropping below zero, and an `exclusive` constraint on `idempotency_key` rejects duplicate charges when clients retry after a network timeout. [Diagram: Tenant Seats & Credit Ledger: Organization Root Hex wired to Stored Records inside Transaction Calipers clamped above a flame zero-floor invariant line and Verdict Seal.] **Atomic credit ledger** Each debit writes a ledger row and updates the balance in one statement. ## Placement roots from links Pillar at work: Distributed from links Those same `required single` links also tell Napalm how to shard data across primaries when a database grows (Placement roots and sharding). The compiler walks required stored links upward to find your schema’s ownership roots. Any top-level project type with no outbound required link that owns child types becomes a placement root, whether that type is `Account` in a consumer app, `Project` in a developer tool, `Site` in fleet software or `Organization` in B2B software. Every child type reaching that root unambiguously is rooted on the same shard. [Diagram: Root Territory Split: 13-cell isometric cluster of extruded hexagonal tenant roots on a stepped basalt slab, splitting cleanly along a flame seam.] **Inferred placement roots** Required single links group each root record and its descendants on one shard. When your domain needs explicit control, `ext::napalm::root` annotations mark top-level `'root'` types, replicate shared `'reference'` lookup tables (such as `BillingPlan`) to every shard in one commit, or pick the `'owner'` link when a record points to more than one parent. Links to `ext::auth::Identity`, `multi` links and links marked `'none'` never claim ownership, so users belong to multiple organizations and guest collaborators span roots freely. Running `napalm roots` on our workspace notes schema shows that general rule on concrete types: because `Membership`, `Workspace`, `Note` and `CreditWallet` all chain up to `Organization` through required links, all five types are ready for sharding with standard `uuid` keys and unchanged queries. Your terminal ``` $ napalm roots notes → Roots: 1 root, 4 rooted. → Placeable: Organization. Type Kind Root By Placeable ──────────── ────── ──────────── ────────────── ───────── Organization root yes Membership rooted Organization .org yes Workspace rooted Organization .org yes Note rooted Organization .workspace.org yes CreditWallet rooted Organization .org yes ``` napalm roots inspects required link chains and reports each type’s root classification. Those same structured records and access policies can power semantic search, training datasets and live model features without a separate ML data stack. Learn more **Schema** Root inference rules, reference tables and `ext::napalm::root` annotations. **Multi-tenant B2B SaaS** Organizations, roles, invites and enterprise OIDC sign-in. **Billing & payments** Subscriptions, checkout and atomic credit ledgers. --- Source: https://napalmdata.com/developers/primer/search Feature by feature Chapter 8 of 11 # Search and models Vector and full-text indexes live on your schema types and check access policies during scoring. Training exports, live model features and regression evals read straight from your tables. Once workspaces hold thousands of records, users expect semantic search and ML-powered features that respect the same permissions and deletes as ordinary queries. Filtering top search hits in application code after a vector scan can return empty pages whenever restricted records occupy the top ranks. **Try it** Vector and full-text indexes live on the schema type and evaluate access policies during the index scan. Query `POST /search` with Ada’s session token to rank permitted notes by semantic meaning and keywords. Terminal ``` curl https://notes.napalmdata.com/search \ -H "Authorization: Bearer $SESSION" \ -H "Content-Type: application/json" \ -d { "type": "Note", "query": "launch timeline and milestones", "limit": 5 } ``` A caller in another organization running the identical search receives none of Ada’s notes. ## Vector and keyword indexes Pillar at work: One typed graph Declaring indexes directly on an object type eliminates external embedding pipelines. On `Note`, two declarations add semantic vector search and weighted full-text search. dbschema/default.gel ``` deferred index ext::ai::index(embedding_model := 'openai/text-embedding-3-small') on (.title ++ '\n\n' ++ .body); index fts::index on (( fts::with_options(.title, language := fts::Language.eng, weight_category := fts::Weight.A), fts::with_options(.body, language := fts::Language.eng, weight_category := fts::Weight.B) )); ``` Declare semantic vector search and weighted full-text search directly on Note. Full-text indexes update inside the write transaction, while Napalm refreshes vector embeddings in the background using built-in embedding models or your own provider key. Indexes scale from small tables to tens of millions of vectors with no schema changes. [Diagram: Vector Index Plane: Single tilted basalt coordinate slab with a 36-tick graduated target reticle, sweeping radar hand and neighbor points.] **Background embeddings** Napalm refreshes vectors automatically from a few rows to tens of millions. [Diagram: Hybrid RRF Search: Tilted Vector Index Plane and lexical Query Stencil converging into a Query Engine emitting top-k Stored Records.] **Filtered hybrid search** Vector and keyword scoring enforce access policies during the index scan. Because access policies run during candidate scoring, requesting ten matches returns ten permitted records even when closer vectors belong to other tenants. Deleting a record removes it from search in the same commit. ## Consent-gated training data Pillar at work: Caller-bound Schema policies also enforce data-governance rules on training pipelines. To train a tag-suggestion model strictly on consenting customers, add `allows_training` to `Organization` from Organizations and billing and check that flag in a `select` policy for export service keys. dbschema/default.gel ``` type Organization { required name: str; required slug: str { constraint exclusive; }; required allows_training: bool { default := false; }; # …members and access policies } type Note { required workspace: Workspace { on target delete delete source; }; required owner: ext::auth::Identity; required title: str; required body: str; # …editors, indexes, notify and member policies access policy service_reads_consenting allow select using (global role ?= 'service' and .workspace.org.allows_training); } ``` Export keys carrying global role = 'service' see notes only when allows_training is true. Your training job exports permitted rows to Parquet shards in object storage. When an organization sets `allows_training` to `false`, subsequent dataset exports exclude every note in that organization immediately with no changes to your export script. [Diagram: Consented Training Dataset: Consented Stored Records streaming through an open gold Policy Lock into an Object Bucket while opted-out records stop at a shut flame Lock.] **Consent-gated exports** Service keys export Parquet shards only from records permitted by schema policies. ## Online features and evals Pillar at work: Compiled At inference time, you do not need a separate Redis feature cache. One deployed query joins live record attributes, historical counts and the active model version stored in `Slot` in a single round trip under the caller’s session. dbschema/queries/noteFeatures.edgeql ``` with note := (select Note filter .id = $note) select note { id, title, body, workspace_name := .workspace.name, author_note_count := count(( select .workspace. datetime_of_statement() )); } ``` Grant a background summarization agent read access to chosen notes until an exact timestamp. Granting `select` alone prevents writes, and checking `.expires > datetime_of_statement()` inside the policy enforces the deadline on PostgreSQL’s statement clock with no background cleanup job. [Diagram: Scoped Agent Grant: Flame grant perimeter encircling only two chosen File Monoliths beside excluded records, crowned by a countdown Cron Clock.] **Expiring row grants** Open chosen rows to an agent identity until an exact statement timestamp. [Diagram: Agent Audit & Kill Switch: AI Agent emitting provenance-tagged Commit Blocks into a Policy Lock and Refuse seal that severs live agent access in one cut.] **Immediate revocation** Deleting a grant cuts off queries and live streams on the same commit. ## Revoking access Cutting off an agent before its grant expires takes a single `delete`. dbschema/queries/revokeGrant.edgeql ``` delete AgentGrant filter .agent.id = $agent ``` Deleting the AgentGrant row drops those notes from any open live stream on the same commit. Subsequent tool calls from the background agent return zero rows, and users can disconnect OAuth MCP sessions at any time by revoking consent. That closes the architectural test from Chapter 1: users on web and mobile, backend workers, warehouse syncs, training jobs, in-app copilots and autonomous agents all share one database under access policies written once. Every caller now shares one schema on a single database. Next, we scale that schema across branches, read replicas and shards while testing real hardware faults. Learn more **Agent access & grants** Agent sign-in, narrow grants, prompt-injection defense and revoking access. **MCP server** The built-in MCP server, consent and query tools. **A2A agent** Agent cards, task messages and skills on every project. **In-app AI copilots** Questions and dry-run proposals as the signed-in user. **Watching and stopping an agent** Change-log sources, reach checks and stopping an agent. --- Source: https://napalmdata.com/developers/primer/scale Ship and scale Chapter 10 of 11 # Scale and the chaos lab Branches, read replicas and root-placed shards scale your project behind one hostname. Isolated branches test migrations before deploy, and public fault campaigns verify failover and durability on every release. Running everything on one primary database works early on, then hits three production walls: testing risky migrations safely, scaling throughput and storage past a single machine, and surviving hardware failures without losing acknowledged writes. **Try it** Create an isolated database branch and test a schema migration without touching `main`. Your terminal ``` $ napalm branches create notes pr-12 ✓ Created pr-12 in notes from main with no rows. $ napalm schema push notes --branch pr-12 --yes ALTER TYPE default::Note { CREATE PROPERTY archived: std::bool; }; ✓ Migrated pr-12 in notes: 1 change ``` The migration applies to pr-12 alone while production traffic continues on main. ## Branches Pillar at work: Compiled Each branch is an independent database beside `main` with separate rows, service keys and session keys. Developers iterate on personal branches, pull-request CI creates ephemeral branches such as `pr-12` to validate migrations and saved queries, and teams can run release rehearsals on branches cloned from `main`’s live data. [Diagram: Isolated Branch Database: Branch Fork Rail splitting off main’s Primary into an isolated dashed Shard Bay holding its own branch Primary.] **Isolated branches** Each branch keeps separate rows, service keys and sessions beside production. [Diagram: Checked Schema Push: v1 → v2 Schema Tablets bridged through a Query Engine that verifies Deployed Query Stencils at an Admit seal before apply.] **Checked migrations** Every branch push validates your saved queries before applying DDL. Because every push validates your query folder against the target branch schema first, incompatible changes fail in development or CI before reaching `main`. ## Horizontal shards Pillar at work: Distributed from links When write throughput or storage outgrows a single primary, `napalm placement enable` activates horizontal sharding across multiple PostgreSQL primary-replica shards without changing your schema, `uuid` primary keys or client queries. Using the placement roots inferred from `required single` links or declared with `ext::napalm::root`, Napalm places each root record and all of its rooted descendants on one shard while replicating `'reference'` lookup tables to every shard in one commit. Whether your schema’s root type is `Account`, `Project`, `Site` or `Organization`, single-root reads and writes execute locally on the owning shard with zero cross-shard fan-out. Terminal ``` napalm placement enable notes napalm placement split notes --shard shard-0a1b2c3d4e napalm placement keep notes --region iad napalm placement restore-root notes --to 2026-11-10T17:20:00Z ``` Enable root placement, split a busy shard, pin a root to a region or rewind one root to an earlier timestamp. Splitting a shard or moving a high-traffic root happens behind the same project hostname. Reads stay live throughout the move while writes to the moving root pause briefly at cutover, and `napalm placement restore-root` rewinds a single root subtree without rolling back the rest of the cluster. The branch-wide change log runs on single-shard branches. [Diagram: Replicated Shard Group: Shard bay crowned by a policy lock holding an ember primary streaming synchronous commits down to a gold replica.] **Root-placed shards** Each root record and its descendants stay on one shard and move online. ## Engines and replicas Pillar at work: Commit-atomic Stateless engines compile EdgeQL and route requests in front of your shards, while each replicated shard runs a primary and cross-zone read replicas. On clusters with a replica, writes confirm on both the primary and an in-region replica before returning. If no replica responds for 5 seconds, the primary commits alone until a replica returns. Terminal ``` napalm clusters scale --engines 4 --replicas 2 ``` Scale stateless engines and cross-zone read replicas online. Generated SDKs forward the `Napalm-Bookmark` header automatically so read queries route only to replicas caught up to the caller’s own commits. If a primary stops answering for 30 seconds, a replica promotes automatically behind the same project address. [Diagram: Query Engine: Single chamfered 8-sided 3D steel cabinet with 4 shaded side bevels, flame corner lamp, 12-tick vernier compiler dial and top/foot ports.] **Stateless engines** Scale query compilation and live connections without moving stored data. [Diagram: Causal Replica Routing: Ember primary streaming commits along a gold sync dash to a read replica gated by an anchored Napalm-Bookmark pin.] **Causal read replicas** Bookmarks keep reads fresh while cross-zone replicas stand ready for failover. ## Fault campaigns and promises Every Napalm release runs an automated fault campaign before rollout, and nightly campaigns test the live release again. Results publish to the chaos lab. [Diagram: Chaos Lab Verification: Shard bay struck by an engineered fault bolt streaming verified commit blocks to a bookmarked Admit seal with zero lost writes.] **Public fault campaigns** Release and nightly runs test real faults and publish every verdict. Scenarios are grouped by the system guarantee under test. | Group | Promise verified | |---|---| | Writes | Acknowledged writes survive server crashes, freezes and full disks. | | Replicas | A replica takes over when a primary fails. Two primaries never write at once. | | Change log and webhooks | Acknowledged writes reach the change log and signed webhooks in commit order. | | Presence | Room members keep their places when a server crashes. | | Shards | A cross-shard write commits on both shards or on neither shard. | | Access | Revoked credentials read zero rows even on a lagging replica. Tenants never see another tenant’s rows. | | Load | Expensive read queries never starve concurrent writes. | ## Inside a run and public verdicts Pillar at work: Checked and fault-tested Each scenario provisions fresh clusters running the release under test while clients drive continuous reads and writes and record every acknowledged commit. Mid-run, the harness injects a bounded fault such as a database server crash, a frozen server, a severed cross-zone network link or a full disk, then verifies every acknowledged write and access policy afterward. Published run · Broken canopy ``` Scenario Broken canopy · 2026.11.6 Fault A replica drops off the network for 10 seconds while clients write. Verdict Passed Promises ✓ The primary keeps taking writes. ✓ The cut-off replica refuses a write. ✓ The replica catches up once the network returns. Evidence Acknowledged writes 1,420 writes Writes lost or changed 0 writes Stale reads 0 reads 95th percentile write time 0.04 s ``` Published runs pair each scenario’s required outcomes with the post-fault measurements. Every run ends in one of three verdicts. Passed confirms that the fault took effect and every durability, latency and access invariant held. Failed means at least one invariant broke. Inconclusive means incomplete evidence prevented verification and never counts as a pass. Failed and inconclusive runs remain on the public record beside passes. Access scenarios combine network partitions and server crashes with credential revocation to verify that even a partitioned replica refuses reads from a revoked grant. Across branches, replicas, shards and injected faults, one compiled schema holds every guarantee together. Learn more **Branches** Personal branches, pull request branches and copied data. **Release rehearsals** Rehearsing a full release on a data-cloned branch. **Schema** Root inference rules, reference tables and ownership annotations. **Scale & recovery** Engines, replicas, shards, failover and restores. **Distribution** Splitting shards and moving, pinning or restoring roots. **Scale & recovery** Fault invariants, failover bounds and public evidence. --- Source: https://napalmdata.com/developers/primer/consequences Ship and scale Chapter 11 of 11 # One schema in practice Compiling data, identity and side effects together removes whole classes of bugs. Start locally in one command and explore the guides and reference for your stack. Across the preceding chapters, browsers, mobile apps, hosted handlers, cron schedules, warehouse workers and AI agents all operated on one schema. Every write from every caller landed on a single commit timeline. **Try it** One CLI command inspects recent commits across HTTP sessions, MCP tool calls and scheduled jobs from the change log. Your terminal ``` $ napalm changes notes --since 1d --json {"items":[{"commitTime":"2026-11-16T17:14:02Z","caller":{"kind":"session","id":"8f2c1e64","via":"http"},"types":[{"name":"default::Note","inserted":1}]}, {"commitTime":"2026-11-16T17:18:40Z","caller":{"kind":"session","id":"8f2c1e64","via":"mcp"},"types":[{"name":"default::Note","updated":1}]}, {"commitTime":"2026-11-16T17:22:15Z","caller":{"kind":"key","id":"0b6f1f5e","via":"schedule"},"types":[{"name":"default::Note","updated":2}]}]} ``` Browser edits (http), MCP tool calls (mcp) and scheduled jobs (schedule) share one ordered commit log without exposing field values. ## Six pillars and six guarantees The same six architectural guarantees held from the first private record through multi-shard failover. | Pillar | Guarantee | Chapter | |---|---|---| | One typed graph | Rows, files, search indexes, jobs and grants live in one schema under shared access policies and snapshots | Search and models | | Caller-bound | Access policies walk the graph from verified identity across queries, file URLs, actions and expiring grants | Rules, queries and files | | Compiled | Static checks block breaking pushes, compile policies into one SQL statement per request and generate SDKs and MCP tools | Agents and copilots | | Commit-atomic | Live subscriptions, webhooks, background jobs, ledger debits and causal replicas advance on one commit timeline | Actions, jobs and webhooks | | Distributed from links | Required ownership links group and move root subtrees across shards behind one unchanging address | Organizations and billing | | Checked and fault-tested | Push validation, reach diagnostics, dry-run previews and public fault campaigns verify every guarantee | Scale and the chaos lab | ## Cross-layer guarantees Compiling data, identity and commit order together gives you cross-feature guarantees without custom glue. Deleting an `AgentGrant` in Agents and copilots drops restricted rows from an agent’s open live stream on that commit, and queueing a job in Actions, jobs and webhooks commits or rolls back inside the same write transaction. [Diagram: Scoped Agent Grant: Flame grant perimeter encircling only two chosen File Monoliths beside excluded records, crowned by a countdown Cron Clock.] **Live revocation** Deleting a grant drops restricted rows from open streams on that commit. [Diagram: Job Queue & Cron Schedule: Queue Shard Bay holding three queued job Stored Records wired into a circular 3D Cron & Backoff Clock.] **Transactional jobs** Queued jobs commit or roll back inside the same statement as your writes. [Diagram: Point-in-Time Root Rewind: Central root hex rewinding from a faulted commit block to a verified gold commit while neighboring roots stay untouched.] **Single-root restore** Rewind one root record and its descendants while other roots stay live. Setting `allows_training` to `false` in Search and models excludes those records from the next Parquet export with no pipeline changes. When a bad import hits a single root in Scale and the chaos lab, `napalm placement restore-root` rewinds that root and its linked descendants while the rest of the cluster continues uninterrupted. ## Guides by use case Scaffold a project locally in one command, then follow Your first app for the five setup steps or jump to the quickstart to install the CLI and sign in. Terminal ``` napalm new notes-app notes ``` Create a fresh copy of the starter project. From there, pick the step-by-step guide for the architecture you are building. | Architecture | Guides | |---|---| | Realtime web and mobile apps | React, Vite & single-page apps, Next.js & React, React Native, Flutter and Realtime & collaboration | | Agents, MCP and copilots | Coding agents, In-app AI copilots, Tools for agents, Multi-agent pipelines and Watching and stopping an agent | | Documents, search, models and evals | Files, media & document search, Datasets & ML training, Model serving, Evals and Model registry | | Multi-tenant SaaS, sharding and ledgers | Multi-tenant B2B SaaS, Billing & payments and Actions & background jobs | | Change data and warehouse sync | Warehouse sync, Search index & cache sync and Queues & streams | | Moving from another platform | Moving to Napalm, Coming from Postgres, Coming from Supabase, Coming from Firebase, Coming from Convex and Coming from Gel | ## Learn and reference Beyond the application guides, Learn covers each subsystem in depth, Testing covers branch harnesses and policy verification, and Reference documents every schema extension, HTTP endpoint, generated SDK method, CLI flag and limit. | Surface | Covers | |---|---| | Schema & extensions | Schema declarations, access policies, files, vector indexes, jobs, agent grants and placement roots | | Testing & verification | Branch test harnesses, caller-matrix policy suites, dry-run previews and pull-request CI checks | | Project API | Project HTTP routes for queries, live streams, files, search and `/ask` | | Control API | Control HTTP routes for projects, schemas, branches, clusters, placement and orgs | | SDKs | Typed client SDKs generated by `napalm generate` across eight languages | | CLI reference | Every command, flag and exit code in `napalm` | Coding agents can also consume the docs directly. openapi.yaml specifies every HTTP route, llms-full.txt bundles the full documentation as plain text, and Known limits lists current boundaries and architectural trade-offs. Run `napalm new` and build from one schema. Start in Learn **How Napalm works** How a request runs and the guarantees behind every read and write. **Schema** Types, links, access rules, migrations and roots. **Access & sign-in** Sign-in, caller globals, closed types and reach checks. **Security & data lifecycle** Dedicated cluster isolation, regional root pins and retention sweeps. **Testing & verification** Automated policy suites, dry-run mutations and CI branch checks. **Troubleshooting & auditing** Fixing empty results, refused writes, slow rules and error codes. --- Source: https://napalmdata.com/developers # Napalm documentation Napalm compiles a single schema into your entire application backend, AI model pipeline and agent runtime on PostgreSQL 18. - API: `POST /query` - CLI: `napalm login`, `napalm schema push`, `napalm query` - In the schema: — - Guides: Live schema changes,Testing & verification,Your first app,Environments & going live,Rollbacks and restores ## Quickstart Install the CLI, sign in to your organization, push a schema and run your first query. Every approved organization starts with a project and a dedicated PostgreSQL cluster. **Install the CLI** macOS ``` curl -fsSL https://downloads.napalmdata.com/cli/install.sh | sh ``` Linux ``` curl -fsSL https://downloads.napalmdata.com/cli/install.sh | sh ``` Windows ``` irm https://downloads.napalmdata.com/cli/install.ps1 | iex ``` **Sign in to your organization** `napalm login` opens a browser prompt to authorize your machine and save a scoped org token locally. Your terminal ``` $ napalm login → Opening your browser to sign in… If the browser doesn’t open, visit: https://console.napalmdata.com/authorize-cli?port=53817&state=…&challenge=…&name=napalm+CLI+on+studio ✓ Signed in to Northwind Can make changes until 2026-11-16 01:12 PST ``` **Push your schema** Define your object types, links and access policies in `dbschema/default.gel`. dbschema/default.gel ``` using extension auth; using extension napalm; using future simple_scoping; module default { global caller := global ext::auth::ClientTokenIdentity; type Person { # Optional so callers who cannot see another person's Identity still read Person. identity: ext::auth::Identity { constraint exclusive; }; required name: str; access policy self_has_full_access allow all using (.identity ?= global caller); access policy signed_in_can_read allow select using (exists global caller); } type Note { required title: str; body: str; pinned: bool; required author: Person; multi shared_with: Person; access policy author_has_full_access allow all using (.author.identity ?= global caller); access policy shared_can_read allow select using ((global caller in .shared_with.identity) ?? false); } } ``` Run `napalm schema push` to plan the migration on the server and preview every change before applying it. Your terminal ``` $ napalm schema push notes CREATE FUTURE simple_scoping; CREATE GLOBAL default::caller := (GLOBAL ext::auth::ClientTokenIdentity); CREATE TYPE default::Person { CREATE LINK identity: ext::auth::Identity { CREATE CONSTRAINT std::exclusive; }; CREATE ACCESS POLICY self_has_full_access ALLOW ALL USING ((.identity ?= GLOBAL default::caller)); CREATE ACCESS POLICY signed_in_can_read ALLOW SELECT USING (EXISTS (GLOBAL default::caller)); CREATE REQUIRED PROPERTY name: std::str; }; CREATE TYPE default::Note { CREATE REQUIRED LINK author: default::Person; CREATE ACCESS POLICY author_has_full_access ALLOW ALL USING ((.author.identity ?= GLOBAL default::caller)); CREATE MULTI LINK shared_with: default::Person; CREATE ACCESS POLICY shared_can_read ALLOW SELECT USING (((GLOBAL default::caller IN .shared_with.identity) ?? false)); CREATE PROPERTY body: std::str; CREATE PROPERTY pinned: std::bool; CREATE REQUIRED PROPERTY title: std::str; }; › Apply the migration to notes? [y/N] y ✓ Migrated notes: 4 changes ``` **Issue a service key and run a query** A service key authenticates requests to one project and branch. Pass `--save` to store the credential locally for `napalm query`, `napalm call` and `napalm mcp`. Your terminal ``` $ napalm keys create notes --label laptop --read-only --save ✓ Created laptop for notes, read-only, for 30 days ndb_Qm9zZS1yZWQtZXhhbXBsZS1rZXk Saved for napalm query and napalm mcp. $ napalm query notes "select Note { title } order by .title limit 2" [ { "title": "Launch checklist" }, { "title": "Pricing notes" } ] ``` **Next steps** Read the Primer and the six pillars for the full architecture. Save application queries with `optional` filter parameters in `dbschema/queries/*.edgeql` and run napalm generate to build a typed client, or send parameterized ad-hoc statements directly to `POST /query`. Run napalm init to connect Claude Code, Cursor or VS Code to `