# 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 is a compiler for distributed infrastructure. Write your data model, access rules and queries once, and Napalm compiles a complete backend on PostgreSQL 18. [Diagram: An engraving of the database’s machines. 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 data transfer pipe. One bus cables the bays. Every request passes a 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 shard ranges transfer smoothly across primaries. The first lock turns some requests back. The drawing starts at one engine over one shard and grows through the Production and Scale cluster sizes to eight engines over eight shards. Embers rise around the lit frame.] Building a backend usually means wiring together separate services for sign-in, database queries, background jobs, search and live updates. You copy permission checks across every service by hand, and one missed check exposes another person’s data. **Try it** Napalm replaces that stack with one schema file and four saved queries. Run one command to create a working notes app and set up the 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 answers four questions, and typical stacks wire a separate service to each. Napalm answers all four from one schema. | | A typical stack | Napalm | |---|---|---| | Who is calling? | External sign-in service | Sign-in built into every project | | What is allowed? | Checks repeated in each route | Access rules declared on each type | | What changed? | Separate queue or polling job | Ordered change log of every saved write | | Who responds? | Custom workers and socket servers | Live queries, webhooks and jobs after each save | Mobile apps, background workers, analytics warehouses, training pipelines and AI agents all read those same records. Keeping rules inside route code forces you to rewrite every check for every new caller. ## A compiler for distributed infrastructure Most backend bugs come from splitting ownership across tools. Databases hold rows, routes check permissions, presigners guard files, vector stores rank embeddings, queues hold jobs and socket servers push updates. Napalm keeps every rule in one schema and compiles your backend the way a language compiler builds a program. | A compiler | Napalm | |---|---| | Reads source files | Reads your schema and saved query files | | Catches type errors before a run | Checks every query against the schema and access rules on push | | Emits machine instructions | Compiles each query and its matching rules into one SQL statement | | Runs on target hardware | Runs across engines, replicas, shards, storage and agent endpoints | [Diagram: Cut directly from the cover plate’s vocabulary: requests enter past the Policy Lock into the chamfered Query Engine, commit ember writes on the Primary with synchronous confirmation to the Replica, and route bookmarked reads straight to the caught-up Replica.] **One compiled path from schema to shard** Requests enter through the project endpoint, compile with matching access policies inside an engine, commit synchronously across primary and replica, and serve bookmarked reads from caught-up replicas. PostgreSQL 18 enforces one source of truth. Every EdgeQL expression carries a static type and cardinality without SQL NULLs, and Napalm runs the compiled queries across engines, replicas, shards and object storage. ## One question across every caller The chapters ahead follow the notes app you just created. Two users named Ada and Ben save private notes and files, edit together across web and mobile screens, trigger background jobs and warehouse syncs, invite customer organizations and train custom models. Ada’s AI agent is the sharpest test. Ada wants an assistant to read her notes, tidy titles and add follow-ups while she travels. A database password would expose Ben’s notes too, and a broad API key would expose every route. [Diagram: Person Medallion: Single 3D extruded double-rimmed circular medallion with crescent hatch and geometric head-and-shoulders bust.] **People on web and mobile** Built-in sign-in sessions bind `global caller` to the verified user identity 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 and pipelines** Branch-scoped `ndb_…` service keys authenticate workers, schedules and warehouse syncs under explicit rules. [Diagram: AI Agent Core: Single watertight 8-sided 3D basalt core with optical iris spark wrapped by two intersecting 3D gimbal rings.] **AI agents and copilots** Approved OAuth consent and expiring grants keep every agent tool call inside exact row access. Every chapter tests one question on a new caller. Can people, services, pipelines and agents share one database under access rules you write once? Six design rules keep one schema consistent across every caller, machine and failure. 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 design rules shape every part of Napalm and compile one schema file into a verified backend. Most databases let you drop a column while live queries still read it. Adding separate object storage, job queues and read replicas splits permissions and transactions across half a dozen systems. **Try it** Remove `body` from `Note` in your starter app and push the schema. Napalm 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 reads body and leaves the database untouched. ## One typed graph Rows, binary files (`ext::files::File`), search indexes (`ext::ai::index`), background jobs, agent grants and tenant roots all live as typed entities and links in one schema. 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); } ``` Notes, search indexes and binary file attachments share one typed graph. Files, search indexes, background jobs and grants obey the same access rules and transaction snapshots as your rows without separate sync workers. ## Caller-bound Every stored type starts closed. Napalm binds verified caller identity (`global caller` or service globals) inside PostgreSQL, and access rules walk links in the same EdgeQL language as queries. dbschema/default.gel ``` global caller := global ext::auth::ClientTokenIdentity; type Note { access policy owner_has_full_access allow all using (.owner ?= global caller); } ``` Permissions and queries walk links from verified caller identity. [Diagram: Schema Tablet: Single extruded 3D architectural tablet with hatched bevels, flame header bar and recessed linked entity nodes.] **One typed schema** Rows, files, indexes, jobs and grants share one graph in `dbschema/default.gel`. [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** Every stored type stays locked until an `access policy` opens a path from caller identity. Those rules govern reads, writes, signed file URLs, vector search, actions, background jobs and MCP tools while planning in a fraction of the memory of nested SQL policies. Expiring rules check `datetime_of_statement()` without a cleanup job, and org tokens (`napalm_…`) manage clusters without reading customer field values. ## Compiled Your schema and `.edgeql` files carry static types and cardinalities, so Napalm checks every query against the schema and access policies before anything runs. Terminal ``` napalm generate notes --lang ts ``` Generate typed clients, CLI commands and MCP tools from checked query files. `napalm schema push` rejects breaking migrations before applying changes, compiles each read and every touched policy into one SQL statement and type-checks generated `/ask` queries before execution. ## Commit-atomic Every write commits or rolls back as one atomic unit across rows, queued jobs, webhooks and live subscriptions. A rolled-back write sends no webhooks, queues no jobs and changes nothing on live screens. Dry-run proposals return exact before-and-after rows and roll back. 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 } ``` Data writes, wallet debits and delayed jobs commit together in one statement. After commit, `Napalm-Bookmark` and `Napalm-Position` carry the commit position across reads and workers. Live queries on one screen advance at the same commit, replicas never serve state older than a caller’s writes, webhook workers read up-to-date rows and backups retain deleted files across your restore window. ## Distributed from links Traditional sharding adds a `tenant_id` column to every table and every query. In Napalm, your schema declares ordinary required links while cluster topology scales underneath. Terminal ``` napalm clusters scale --engines 2 --replicas 1 ``` Scale stateless engines and cross-zone replicas behind one unchanging address. [Diagram: Unifies the scale plate’s isometric Root Hex territories with the cover plate’s Shard Bays: busy tenant hexes split cleanly between cells along a flame seam—never cutting through a tenant’s linked tree—and rebalance across two Shard Bays behind one unchanged Endpoint.] **Topology scales beneath unchanged links** Required links co-locate each tenant’s graph so Napalm splits busy roots across shards behind one unchanging endpoint. Required links place and move customer graphs across shards, bookmarks route reads to caught-up replicas and search indexes grow past 100 million vectors without changing a query. ## Checked and fault-tested Napalm verifies access and durability mechanically before and after deploy. Schema pushes reject broken queries and unplaceable links before touching data. Terminal ``` napalm schema push notes --review napalm explain-access notes --as ben@example.com ``` Verify migrations statically in CI or audit live rule traces without reading private values. [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.] **Value-blind rule traces** `explain-access` and `people reach` audit policies without exposing customer 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.] **Automated fault campaigns** Every release faces bounded faults in the public chaos lab before rollout. In production, `explain-access`, `people reach`, `insights` and dry-run `/ask` inspect permissions and query plans without changing `main` or exposing field values. Every release also runs automated fault campaigns in the public chaos lab. Incomplete evidence is marked Inconclusive, never Passed. Every person, service, operator and agent enters your system through a distinct boundary. 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 branches. Every project gives people, services and agents one HTTPS address governed by one schema. Typical stacks scatter credentials across separate tools: user sessions live in an auth service, API keys sit in a gateway and database passwords live in environment secrets where admin keys can read private user notes. **Try it** Napalm separates infrastructure control from application data on your very first command. Sign the CLI in to your org. 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 ``` Approve the login once in your browser to save an org token that manages projects and never reads user notes. ## Orgs, projects and branches Signing in connects the CLI to your org. Four resources organize your projects and databases. | Part | Purpose | |---|---| | Org | Holds your projects, clusters, org tokens, teammates and billing | | Project | Serves one complete backend at `notes.napalmdata.com` | | Cluster | Provides the machines underneath, from single-machine `solo` to sharded `scale` | | Branch | Runs an isolated database beside `main` with separate records, keys and sessions | [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** Isolated compute, disks, TLS keys and storage buckets behind one project address. [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 runs beside `main` with separate records, keys and sessions. Ada and Ben use `main`. Schema pushes and test writes on other branches never touch `main`, and every cluster runs on dedicated compute, disks, TLS keys and storage buckets. ## Callers and credentials Pillar at work: Caller-bound Once a project is running, four kinds of callers talk to Napalm. Each caller brings a distinct credential, and Napalm turns that credential into typed globals before any query runs. | Caller | Credential | Bound globals | |---|---|---| | Ada and Ben | Session from built-in sign-in | The signed-in person in `global caller` | | Backend service | Project service key | Empty `global caller`, plus scoped service globals | | Ada’s agent | Token approved by Ada | Ada in `global caller` | | You or CI | Org token for the control API | Nothing, because org tokens cannot query project data | [Diagram: Person & Client App: Person Medallion wired directly into a bevelled Client Viewport Slate holding live UI cells.] **User sessions** Built-in sign-in binds the signed-in person in `global caller`. [Diagram: Three Credential Planes: Credential bay contrasting the gold User Session Capsule, fluted ndb_… Service Key and octagonal napalm_… Org Control Token.] **Service keys and org tokens** Service keys query one branch, while org tokens (`napalm_…`) manage clusters without reading row values. [Diagram: Scoped Agent Grant: Flame grant perimeter encircling only two chosen File Monoliths beside excluded records, crowned by a countdown Cron Clock.] **Approved agent tokens** OAuth consent binds the approving person or a time-limited grant. Every stored type starts closed to application callers. Org tokens (`napalm_…`) inspect schemas, counts and rule traces without reading field values. ## Schema and query files Pillar at work: One typed graph Those types, rules and queries live as plain files in your repository alongside your app code. The starter notes app begins with five files. Your repository ``` dbschema/ default.gel # types, links and access rules queries/ addFile.edgeql addNote.edgeql myFiles.edgeql myNotes.edgeql ``` One schema file and four EdgeQL files define notes, file attachments and access rules. Pushing to `main` checks every query against the new schema, applies the migration in one transaction and deploys each query by name at `POST /query/{name}`. Pushing to another branch checks the queries and migrates only that branch. When Ada adds a note, her session reaches `main`, Napalm runs `addNote` and the ownership rule in one SQL statement, and the saved note streams to her other open tabs. Next, Ben tries to read Ada’s private notes. 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 rules sit on your data types instead of inside route handlers. Saved EdgeQL files turn those rules into named endpoints, direct file uploads and typed client functions. Route-level permission filters and hand-written client types drift as soon as a second endpoint or screen ships. One forgotten owner check on an export route exposes Ada’s private notes to Ben, and one renamed column crashes the client at runtime. **Try it** Napalm attaches access rules directly to each type, so even an unfiltered query leaks nothing. Sign up as Ada to save a note, then sign in as Ben in a private window and query every note. Ben’s query ``` select Note { title } ``` Ben gets none of Ada’s notes, even when asking for her note’s id directly. ## Rules on the type Pillar at work: Caller-bound Moving the rule onto the type closes every route at once. Access policies walk links in the same EdgeQL language as queries, so one rule on `Note` and `Attachment` (`ext::files::File`) governs every read, write, search and download link. 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 rule governs both Note records and uploaded Attachment files. [Diagram: A Client Viewport calls a Deployed Query Stencil through the Query Engine: linked Stored Records under an open gold Policy Lock return in one snapshot, while an unpolicied type stays sealed behind a shut flame Policy Lock and Refuse seal.] **Policies compile directly into every query** Saved queries traverse linked rows under open access policies in one snapshot while unpolicied types stay closed. Every stored type starts closed, so a type without a matching rule returns zero records. Napalm verifies the session credential before binding `global caller`, so no request can impersonate Ada. ## Rules in every statement Pillar at work: Checked and fault-tested Declaring the rule on `Note` and `Attachment` works because Napalm compiles that rule straight into each SQL statement. PostgreSQL attaches that ownership filter to every query, download link, search, live subscription, update and delete from Ben. If Ben tries to insert a note naming Ada as the owner, PostgreSQL refuses the write before anything saves. Non-human callers hit the exact same rule. Because a backend service key belongs to no user, `global caller` is empty on worker calls and a worker sees zero records until you add a policy checking service globals. When Ada approves an AI agent instead, `global caller` carries Ada and the agent stays inside her exact access. As you add rules for teammates or services, run `napalm people reach notes ben@example.com` to count reachable rows or `explain-access` to trace why a note stayed hidden without reading 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 ``` Trace every rule on Ada’s note as Ben’s session without adding debug routes or weakening policies. ## Saved queries and typed clients Pillar at work: Compiled Production apps save every read and write as an `.edgeql` file in `dbschema/queries`. Four lines load Ada’s notes list. dbschema/queries/myNotes.edgeql ``` select Note { id, title, body } order by .title ``` The query never filters by owner because the rule on Note already scopes the records. A saved query traverses links, backlinks and counts across any depth and compiles into one SQL statement without N+1 round trips or torn reads. Pushing deploys each file at `POST /query/{name}`. Callers send only JSON variables while the query text stays on the server, so user input cannot alter the query. 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" } }' ``` Ada’s session calls `addNote` by name using typed variables. From those same files, `napalm generate` writes typed functions across eight languages, plus commands in your project’s CLI and tools on your MCP server. Terminal ``` napalm schema push notes npm run generate ``` Push the schema and queries, then generate typed client functions. ## Files as records Pillar at work: One typed graph Adding PDF or image attachments usually splits permissions between database rows and S3 presigning code. In Napalm, `Attachment` extends `ext::files::File` to own metadata and access rules while raw bytes live in dedicated object storage. dbschema/queries/addFile.edgeql ``` select (insert Attachment { owner := global caller, file_name := $name, file_size := $size, }) { id, file_upload } ``` Setting file_size checks the insert rule and returns a one-time upload plan straight to object storage. [Diagram: After receiving a one-time upload plan from the Query Engine, the Client Viewport streams ember byte chunks straight into the open-top 3D Object Bucket; completion verifies the File Monolith’s leading magic bytes before stamping Ready.] **Direct-to-bucket uploads under schema rules** Inserting a `File` record checks insert policies and returns a one-time upload plan straight to your dedicated object bucket, verifying leading magic bytes before marking the record `Ready`. Browser and mobile uploads stream bytes directly to your cluster’s private bucket without passing through engines. On completion, Napalm inspects the uploaded bytes rather than trusting upload headers and checks any `file_format` constraint before marking the record `Ready`. dbschema/queries/myFiles.edgeql ``` select Attachment { id, file_name, file_size, file_status, file_download_url } order by .file_name ``` Signed download URLs come back only on Attachment records the caller’s select rule allows. Ben never receives a link to Ada’s PDFs because the URL is signed inside the policy-filtered query. Stored objects never overwrite in place, so point-in-time restores and data-cloned branches always resolve the exact file bytes from that moment. ## Checks in CI and production Because Napalm knows every deployed query, every push validates your whole query folder before migrating data. Passing `--review` in CI writes the migration plan for pull requests and fails the build if a change would break any saved query. Terminal ``` napalm schema push notes --review > review.md ``` Block pull requests in CI whenever a schema change would break a query. Once every screen calls deployed endpoints by name, one command turns off raw EdgeQL strings for browser and mobile sessions while keeping full query access open for backend service keys. Terminal ``` napalm endpoint notes --passthrough keys ``` Restrict user sessions to deployed queries while service keys keep full access. [Diagram: Checked Schema Push: v1 → v2 Schema Tablets bridged through a Query Engine that verifies Deployed Query Stencils at an Admit seal before apply.] **Query-checked pushes** Schema pushes check every saved query before migrating data and block breaking pull requests in CI. [Diagram: Query Lockdown & Codegen: Endpoint rack admitting named deployed-query stencils in gold and ember while refusing raw ad-hoc EdgeQL strings at a sealed port.] **Deployed-query lockdown** Closing raw EdgeQL passthrough limits user sessions strictly to deployed query endpoints. Under live traffic, `napalm insights notes` reports per-query latency, replica read share, the heaviest access rule on each statement and suggested indexes. Next, keep Ada and Ben’s screens updated live as notes change. 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 saved query can stay open as a live subscription across web and mobile. Live updates, sharing and presence obey the same access rules as an ordinary read. Keeping collaborative screens current usually means polling on a timer or running a separate WebSocket server. Every write route must remember to publish an event, and that second server must duplicate your database’s access rules. **Try it** Live updates stream straight from your saved queries without a second server. Open the starter notes app as Ada in two browser tabs, save a note in the first tab and watch it appear in the second. ## Live queries Pillar at work: Commit-atomic Any saved query from Rules, queries and files can stay open as a live subscription. Two lines subscribe the notes screen to `myNotes`. src/Notes.tsx ``` const myNotes = deployed>('myNotes') const { rows, error, isLoading } = useLiveQuery(myNotes, {}) ``` Two lines keep Ada’s notes list current as changes are saved. [Diagram: Multiplexed SSE Conduit: Single coaxial three-line channel: bright gold inner core flanked by two fine parallel steel guard rails.] **Multiplexed SSE conduit** One long-lived `POST /subscribe` channel multiplexes every open live query and presence room on the page. [Diagram: Realtime Live Stream: Query Engine driving a Multiplexed SSE Conduit and concentric commit wavefronts into subscriber Stored Records with instant policy revocation.] **Commit-ordered live patches** Saved queries emit atomic ID-based patches only after a transaction commits, so rolled-back writes never reach open screens. Separate socket servers often race ahead of database commits or update one widget on a page before another. Napalm pushes changes only after commit, so rolled-back writes never flicker on screen. Every live query on a page advances at the same commit, keeping lists and detail views in sync. ## Sharing and revocation Pillar at work: Caller-bound Sharing a note with Ben takes one `editors` link and one extra rule on the `Note` type from Rules, queries and files. 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); } ``` Add multi editors and one policy to open shared notes for reading and editing. Sharing a note with Ben is now an ordinary update. dbschema/queries/shareNote.edgeql ``` update Note filter .id = $note and .owner ?= global caller set { editors += identity_by_id($person) } ``` Only the note’s owner can add Ben as an editor. As soon as Ada saves the share, the note appears on Ben’s open screen. When Ada removes Ben, the note vanishes from his screen at that exact commit because live subscriptions walk the same caller-bound rules as every other read. ## Presence Live cursors and viewer lists do not belong in database tables. Every record has 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 note’s presence room as the signed-in person. [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 rooms under read rules** Live viewers and cursors stay off disk while enforcing the record’s `select` policy, evicting removed editors on the same commit. Joining a room still checks read access on that note. When Ada removes Ben from the note, Napalm evicts him from the room at the same moment. ## Web and mobile Pillar at work: Compiled Those same saved query files power phones and tablets without extra backend code. Web apps and React Native share the same `useSession` and `useLiveQuery` hooks from `napalm-client/react`, while Flutter apps subscribe to typed Dart streams compiled straight from your query folder. Every screen on every device stays current under one set of rules. Next, trigger emails, webhooks and background jobs only after writes commit. 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 Side effects run only when permitted records save. Actions, background jobs and an ordered change log connect emails, webhooks and warehouses without polling. Sending emails, queueing background work and syncing a warehouse usually force bad trade-offs. Workers holding broad database keys can act on records the caller cannot see. Jobs queued before a rollback fire on data that never saved, and warehouse connectors either bypass schema policies or poll tables on a timer. **In practice** Napalm guards external code with a saved query inside PostgreSQL before your handler ever wakes up. When Ben calls `emailNote` with the ID of Ada’s private note, he receives a `403 nothing_found` error, and no email code runs. When Ada calls `emailNote` on that same note, the email goes out. ## Actions and hosted handlers Pillar at work: Caller-bound An action solves the permission problem by pairing a saved query with your handler code. PostgreSQL runs the query first under the caller’s access, and Napalm invokes your handler only when permitted records match. dbschema/queries/emailNote.edgeql ``` select Note { title, body } filter .id = $note ``` When access rules hide the note from the caller, the handler never runs. [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 action handlers** Handlers wake on demand and exchange the ES256 call token via `call.db()` for a 60-second session bound to the caller. [Diagram: Heat Comet & Verdict Seal: Single tapered 7-segment heat comet arriving at a machined circular escutcheon (gold Admit tick vs flame Refuse cross).] **Query-guarded admit or refuse** PostgreSQL runs the saved query first under `global caller`, admitting matching rows or refusing with `403 nothing_found` before the handler wakes. The handler holds no standing database key. To write a result back, the handler exchanges the call token for a 60-second session bound to that same caller. Put a matching file in `handlers/` so Napalm deploys and runs the code on demand and sleeps between calls, or point the action at your own HTTPS server. Terminal ``` # handlers/emailNote.ts pairs with dbschema/queries/emailNote.edgeql napalm handlers deploy notes ``` Deploy TypeScript, Python, Go, Rust or Dart handlers in one command. ## Jobs and schedules Pillar at work: Commit-atomic Pushing to an external queue from an HTTP route risks losing jobs on a crash or running jobs after a rollback. In Napalm, jobs are records in `ext::napalm::Job` that commit together with user writes and run only after the transaction finalizes. 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 } ``` The note and the reminder save together or fail together. [Diagram: Job Queue & Cron Schedule: Queue Shard Bay holding three queued job Stored Records wired into a circular 3D Cron & Backoff Clock.] **Commit-atomic background jobs** `ext::napalm::Job` records commit atomically alongside user writes and execute as the original caller only after finalization. A failed write leaves no queued job behind. When the scheduled time arrives, the job runs as Ada and retries carrying the same job id so your handler never sends the same email twice. Scheduled tasks without a user session, such as a morning digest, run on cron under a scoped service key. Terminal ``` napalm schedules add notes sendDigest '0 8 * * *' --key ``` Run sendDigest every day at 08:00 UTC under a given service key. ## Notify and webhooks Downstream systems that watch every change to `Note` need no polling loop either. Declare a `notify` line on the type so Napalm notifies subscribers whenever a write saves. 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 rules notify note_changed after insert, update, delete; } ``` One line in the schema names the post-save change event. Subscribed HTTPS webhooks receive a signed ping carrying a causal `Napalm-Position` bookmark as soon as an insert, update or delete on `Note` commits. Rolled-back writes send nothing. ## Reading the change log Pillar at work: Compiled Every saved insert, update and delete appends to an ordered branch change log. From the CLI, one command summarizes recent transactions without exposing field 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 saved transaction lists the commit time, the caller kind and short id and the record counts per type. [Diagram: Change Log & Bookmark: Ordered rail of five chained 3D Commit Blocks tracked by an advancing gold Causal Bookmark Pin.] **Commit-ordered change log** Every commit appends caller kind, short ID and mutated type counts to an ordered log queried via `Napalm-Position` bookmarks. When a webhook ping arrives, your worker passes that `Napalm-Position` as `reach` alongside its saved cursor and sees every write covered by the ping, even when a replica answers. No connection stays open between writes, and Napalm compiles your schema’s access rules into every page read. Terminal ``` curl "https://notes.napalmdata.com/changes?since=2026-11-08T00:00:00Z&types=Note&limit=100" \ -H "Authorization: Bearer $NAPALM_KEY" ``` Pull the next page of changes using a saved bookmark. ## Warehouse sync Create a dedicated read-only service key so your warehouse worker reads permitted changes without writing back. Terminal ``` napalm keys create notes --label warehouse --read-only ``` Create a read-only service key for warehouse sync. After one initial copy, the worker applies each new page as changes save. Re-applying a page overwrites the same warehouse rows without harm, and if a bookmark falls behind log retention, the worker starts a fresh copy cleanly. In JSON change pages, each entry also records how the write arrived, such as `http` from the app, `mcp` from an agent or `job` from background work. Ada’s personal app handles live screens, background jobs and change streams. Now whole customer companies want workspaces, roles and usage billing. 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 links in the schema isolate every customer organization without manual filters. Single-statement updates keep invites, roles and credit balances exact. Most B2B applications add an organization column to every table and filter every query by hand. Usage billing adds a second risk when a separate billing service allows two concurrent requests to spend the final credit twice. **In practice** In Napalm, required links between types isolate every company without manual filters. Ada creates an organization and invites Ben. Ben sees only the pending invite until he accepts it, and then he reads the organization and his role through `myOrganizations`. 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 decide both visibility and role without any tenant filter in the query. ## Organizations and roles Pillar at work: One typed graph Instead of copying organization ids across every table, you wrap `Note` inside `Workspace` and `Organization` using required links in the same typed graph. dbschema/default.gel ``` type Organization { required name: str; required slug: str { constraint exclusive; }; multi members := . Workspace -> Organization` so Napalm infers `Organization` as the shard root without `tenant_id` columns. `Membership` assigns each user `Owner`, `Admin` or `Member` on an organization. Because `Note` walks `.workspace.org.members`, your queries need no tenant filters and one company never sees another company’s notes. ## Invites Adding teammates builds directly on the transactional jobs from Actions, jobs and webhooks. One statement creates the invite record and queues the invitation email together. dbschema/queries/inviteMember.edgeql ``` with invite := ( insert Invite { org := (select Organization filter .id = $org), email := str_lower($email), role := $role, } ), email := ( insert ext::napalm::Job { query := 'sendInviteEmail', variables := (invite := invite.id), } ), select invite { id, email, role, expires } ``` When the invite fails, no invitation email goes out. Access rules let the invited person see the invite and join at the offered role, or companies can enable domain sign-in so teammates join without an invite. ## Credits Pillar at work: Commit-atomic Checking a wallet balance in application code before subtracting credits creates a read-modify-write race where two parallel requests spend the final credit twice. Metered features charge the organization’s `CreditWallet` by inserting a ledger entry and subtracting credits in one statement. 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 entry and the wallet debit save together on the organization’s wallet. [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.] **Single-statement seat & credit ledger** Ledger inserts and `CreditWallet` debits commit in one EdgeQL statement with an exclusive `idempotency_key` and non-negative balance constraint. A schema constraint stops the balance from dropping below zero, and an exclusive idempotency key blocks duplicate charges on network retries. ## Roots Pillar at work: Distributed from links `Organization` has no outbound required links, while `Membership`, `Workspace`, `Note` and `CreditWallet` all chain up to `Organization` through required links. Napalm infers `Organization` as the shard root for every tenant record without adding shard keys to your 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 walks required links in dbschema/default.gel to prove every tenant type co-locates under Organization. Customer data stays isolated, credit balances stay exact and your schema is ready to spread organizations across shards in Scale and the chaos lab. Customer workspaces are isolated and billed cleanly. Those same workspace records can power search, model training and live feature serving. Learn more **Multi-tenant B2B SaaS** Organizations, roles, invites, company sign-in and roots. **Billing & payments** Plans, checkout and credit balances that never go negative. **Schema** Root declarations and the required links behind placement. --- Source: https://napalmdata.com/developers/primer/search Feature by feature Chapter 8 of 11 # Search and models Semantic and keyword indexes live in the schema and stay current after each write. Training exports, model features and evals read the same records under the same rules. Running a separate vector store or search index alongside your database creates a second copy of your data that lags behind deletes and skips schema policies. Filtering top search hits in application code afterward can return an empty page when restricted records occupy the top ranks. **Try it** Because Napalm builds search indexes directly into the schema, access rules run during the scan. Send a half-remembered phrase as Ada, and you will receive matching notes ranked by semantic meaning. 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 user at another company sending the exact same words gets none of Ada’s notes. ## Search indexes Pillar at work: One typed graph Keeping search inside the typed graph avoids maintaining a separate sync pipeline. On `Note`, two index lines declare meaning search and weighted keyword search across every workspace. 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) )); ``` The first index matches notes by meaning and the second matches by keyword. [Diagram: Vector Index Plane: Single tilted basalt coordinate slab with a 36-tick graduated target reticle, sweeping radar hand and neighbor points.] **Background-refreshed vector index** `ext::ai::index` refreshes embeddings in the background and scales from ten rows to tens of millions of vectors with no schema change. [Diagram: Hybrid RRF Search: Tilted Vector Index Plane and lexical Query Stencil converging into a Query Engine emitting top-k Stored Records.] **Policy-filtered hybrid RRF** `ext::ai::hybrid_search` fuses `fts::index` keyword ranks with vector distance while evaluating `access policy` rules during scoring. Callers reach embeddings through each `Note` record under that record’s access rules. An index scales from a few rows to tens of millions of vectors without schema changes. Napalm refreshes embeddings in the background through Napalm’s models or your own provider key. Napalm evaluates access rules during candidate scoring. Asking for ten notes returns ten permitted notes, even when closer vectors belong to other companies. Deleting a note removes it from search in the same commit. ## Training data Pillar at work: Caller-bound To train a custom model that suggests workspace tags on new notes, store customer opt-in on `Organization` from Organizations and billing. One policy on `Note` restricts service keys carrying `global role = 'service'` to organizations that opted in. dbschema/default.gel ``` type Organization { required name: str; required slug: str { constraint exclusive; }; required allows_training: bool { default := false; }; # …members and access rules } 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 rules access policy service_reads_consenting allow select using (global role ?= 'service' and .workspace.org.allows_training); } ``` The export key reads notes only from organizations where allows_training is true. [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.] **Policy-gated Parquet exports** Service keys carrying `global role = 'service'` export Parquet rows strictly from organizations where `.allows_training` is `true`. Your pipeline exports permitted notes to Parquet and trains on your own GPUs. When a company turns `allows_training` off, later training runs exclude every note across that company’s workspaces without changing your export script. ## Features and evals Pillar at work: Compiled When Ada saves a note for live tag scoring, one saved query loads the record, workspace context, author history and the active model version in `Slot` together under Ada’s access. 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() )); } ``` Open three named notes for reading until an exact deadline. [Diagram: Scoped Agent Grant: Flame grant perimeter encircling only two chosen File Monoliths beside excluded records, crowned by a countdown Cron Clock.] **Statement-clock AgentGrant** `AgentGrant` opens chosen `Note` records to an agent identity and enforces `.expires > datetime_of_statement()` without a cleanup job. [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.] **Instant revocation on delete** Deleting an `AgentGrant` or withdrawing OAuth consent drops restricted notes from open live streams on that commit. Allowing `select` alone blocks edits, and comparing `.expires` against `datetime_of_statement()` inside the rule cuts off access on the exact statement clock without a cleanup job. ## Revoking access Ending a grant early takes one delete. dbschema/queries/revokeGrant.edgeql ``` delete AgentGrant filter .agent.id = $agent ``` Open live queries held by the agent drop the three notes as soon as the delete saves. The travel agent’s next read returns empty, and Ada can disconnect her personal MCP assistant at any time by withdrawing consent. Ada’s agent answers the question from chapter 1. People on web and mobile, backend services, warehouse syncs, training exports, copilots and background agents all share one database under access rules you wrote once. Every caller obeys one schema on one machine. Production has to hold those rules across branches, shards and real hardware failures. 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, replicas and shards scale one schema behind one address. Database branches verify every migration ahead of main, and automated fault campaigns prove durability and failover in public. Teams scaling a backend often test migrations against staging mocks and trust failover plans that have never been tested under load. **Try it** Create an isolated database branch and push a schema change without touching production. 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 change lands on pr-12 alone while Ada and Ben keep working on main. ## Branches Pillar at work: Compiled Every branch is an independent database beside `main` with separate records, keys and sessions. Each developer works on a personal branch locally while pull request CI spins up `pr-12` to review migrations and check saved queries. Before a major launch, your team can run a release rehearsal on a branch cloned from the live records in `main`. [Diagram: Isolated Branch Database: Branch Fork Rail splitting off main’s Primary into an isolated dashed Shard Bay holding its own branch Primary.] **Isolated branch databases** Each branch (`dev-ada`, `pr-12`, `rehearsal`) runs beside `main` with separate records, service keys and session signing keys. [Diagram: Checked Schema Push: v1 → v2 Schema Tablets bridged through a Query Engine that verifies Deployed Query Stencils at an Admit seal before apply.] **Query-checked branch pushes** `napalm schema push --branch` validates every file in `dbschema/queries` against the branch schema before touching `main`. Every push checks your saved queries against the branch’s schema first, so broken queries fail on the branch long before reaching `main`. ## Shards Pillar at work: Distributed from links Once hundreds of customer companies outgrow one primary server, the `Organization` root links from Organizations and billing allow Napalm to spread companies across shards without changing your schema or queries. Terminal ``` napalm placement enable notes napalm placement keep notes --region iad napalm placement restore-root notes --to 2026-11-10T17:20:00Z ``` Spread tenants across shards, pin one organization to a region or restore one customer to a point in time. [Diagram: Replicated Shard Group: Shard bay crowned by a policy lock holding an ember primary streaming synchronous commits down to a gold replica.] **Root-mapped shard bays** Tenant graphs map to primary-replica shards by root ownership behind one project URL, and moving an `Organization` pauses its writes for only a few seconds at cutover. Every record owned by one organization stays together on one shard. Moving a busy organization happens behind the same project address without changing your queries. Reads continue without interruption while writes for the moving organization pause for a few seconds. The branch-wide change log runs only on single-shard branches today. ## Engines and replicas Pillar at work: Commit-atomic Stateless engines compile and route queries in front of your shards, and each replicated shard runs a primary and replicas across availability zones. Confirmed writes save to both the primary and a replica in the same region before returning. If no replica answers for 5 seconds, the primary commits alone until a replica returns. Terminal ``` napalm clusters scale --engines 4 --replicas 2 ``` Add engines and cross-zone replicas online. [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 compiler engines** Compile EdgeQL and touched policies into single SQL statements, scaling connections and SSE streams without moving 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 replica routing** Replicas confirm synchronous commits, serve reads caught up to `Napalm-Bookmark` and promote automatically if a primary stops answering. Generated clients pass an opaque `Napalm-Bookmark` header automatically so read queries route only to replicas caught up to the caller’s own writes. When a primary stops answering for 30 seconds, a replica takes over behind the same address. ## Fault campaigns and promises Every Napalm release runs an automated fault campaign before rollout, and nightly campaigns test the live release again. Every run appears on the public 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-campaign verdicts** Release and nightly chaos campaigns inject crashes, zone splits and full disks into fresh clusters, and mark incomplete evidence Inconclusive rather than Passed. | 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 an engine 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 builds fresh clusters from the release under test while clients send continuous reads and writes and record every acknowledged write. Halfway through the workload, the run injects one bounded fault, such as a database server crash, a frozen server, a dropped cross-zone network link, or a full disk. Once the fault ends, the run reads back every acknowledged write and checks every access rule. 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 ``` Every published run pairs the scenario’s promises with the exact counts measured after the fault. Every scenario records one of three verdicts. Passed confirms both that the fault took effect and that every durability, latency and access promise held. Failed means at least one promise broke. Inconclusive means incomplete evidence prevented a clean check and never counts as a pass. Failed and inconclusive runs stay on the public record beside passes, and failed evidence is kept until the underlying bug is fixed. In the Access group, fault injection pairs network splits and server crashes with credential revocation so even a lagging replica must refuse every read from a grant Ada just revoked. Next, review every guarantee and pick a guide for your stack. Learn more **Branches** Personal branches, pull request branches and copied data. **Release rehearsals** Rehearsing a full release on a data-cloned branch. **Schema** Declaring roots and ownership links. **Scale & recovery** Engines, replicas, shards, failover and restores. **Distribution** Spreading, pinning and restoring organizations by root. **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, then explore the guides and reference for your stack. When a backend is built out of separate services for sign-in, APIs, queues, search, and agent tools, no single timeline or permission boundary exists. Each service maintains a partial log and a partial copy of your rules. **Try it** Because every caller in Napalm runs through one compiled engine, one command reads a full day of activity 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), assistant tool calls (mcp) and scheduled jobs (schedule) share one ordered log without exposing note values. ## Six pillars and six guarantees Six guarantees held from Ada’s first note through multi-shard failover. | Pillar | Guarantee | Chapter | |---|---|---| | One typed graph | Rows, files, search indexes, jobs and grants live in one schema under shared access rules and snapshots | Search and models | | Caller-bound | Access rules walk the graph from verified identity across reads, writes, file links, actions and expiring grants | Rules, queries and files | | Compiled | Static checks block breaking pushes, compile policies into one SQL statement per request and generate typed clients and MCP tools | Agents and copilots | | Commit-atomic | Live screens, webhooks, delayed jobs, wallet debits and causal replicas advance on one commit timeline | Actions, jobs and webhooks | | Distributed from links | Required ownership links place and move customer graphs across shards behind one unchanging address | Organizations and billing | | Checked and fault-tested | Schema push checks, reach counts, dry-run previews and public fault campaigns verify every promise | Scale and the chaos lab | ## Cross-layer guarantees Keeping data, identity and commit order in one engine connects features that normally require custom glue across separate services. Deleting an `AgentGrant` in Agents and copilots removes restricted notes from an agent’s open live query in the same commit. Queueing a delayed job in Actions, jobs and webhooks commits or rolls back alongside the note write. [Diagram: Scoped Agent Grant: Flame grant perimeter encircling only two chosen File Monoliths beside excluded records, crowned by a countdown Cron Clock.] **Revocation drops live rows** Deleting an `AgentGrant` evicts restricted notes from an agent’s open `/subscribe` stream on that exact commit. [Diagram: Job Queue & Cron Schedule: Queue Shard Bay holding three queued job Stored Records wired into a circular 3D Cron & Backoff Clock.] **Jobs commit with writes** `ext::napalm::Job` rows commit or roll back inside the user statement and never fire on rolled-back data. [Diagram: Point-in-Time Root Rewind: Central tenant root hex rewinding from a faulted commit block to a verified gold commit while neighboring roots stay untouched.] **Per-customer root rewind** `restore-root` rewinds one `Organization` and descendant rows while co-located customers keep serving. Setting `allows_training` to `false` on an organization in Search and models excludes every note across that customer’s workspaces from your next Parquet export without pipeline changes. When one customer makes a bad bulk edit in Scale and the chaos lab, point-in-time root restore rewinds that organization alone while every other customer keeps working. ## Guides by use case Build your own project locally in one command, then follow Your first app for the five setup steps or start at the quickstart to install the CLI and sign in. Terminal ``` napalm new notes-app notes ``` Create your own copy of the starter notes app in seconds. From there, pick the step-by-step guide that matches your stack. | Use case | 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 Alongside the guides, Learn explains each subsystem in depth, Testing verifies policies and releases against isolated branches, and Reference covers every schema extension, HTTP route, generated SDK method, CLI flag and limit. | Surface | Covers | |---|---| | Schema & extensions | Napalm schema declarations, access policy clauses, files, vector indexes, jobs, agent grants and roots | | Testing & verification | Branch test harnesses, caller-matrix policy checks, dry-run previews and pull-request CI gates | | Project API | Project endpoints for queries, live streams, files, search and `/ask` | | Control API | Control endpoints for projects, schemas, branches, clusters and orgs | | SDKs | Typed client libraries written by `napalm generate` across eight languages | | CLI reference | Every command, flag and exit code in `napalm` | Coding agents can also read the docs directly as files. openapi.yaml describes every HTTP route, and llms-full.txt holds the complete documentation as plain text. Known boundaries and deliberate trade-offs live under Known limits. Run `napalm new` and ship 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 once 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`. `napalm schema push` plans the migration on the server and previews each change before applying it. dbschema/default.gel ``` using extension auth; using extension napalm; using future simple_scoping; module default { global caller := global ext::auth::ClientTokenIdentity; type Person { # Not required: a caller reads their own identity alone, so another person's reads as empty. 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); } } ``` 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. Put queries in `dbschema/queries/*.edgeql` and run napalm generate to build a typed client, or run napalm init to connect Claude Code, Cursor or VS Code to `