Skip to the page

Learn · Logic

Hosted handlers

Napalm runs an action’s handler for you on machines that sleep between calls. The handler acts as the caller.

In the schema
—

Deployment#

An action pairs a deployed gatekeeper query with a handler. PostgreSQL runs the query first as the caller under your schema’s access policies, and the handler then performs the external work an EdgeQL statement cannot do directly. Serve the handler from your own server, or place the handler in a handlers folder beside your queries so Napalm builds and runs it for you.

Sleep-when-idle hosted handlers

Deploy a handlers folder beside your queries. Handler instances sleep between calls, stay asleep when a gatekeeper query matches zero rows, and wake with verified ES256 assertions when permitted rows arrive.

  1. Deploy the gatekeeper query

    dbschema/queries/sendReceipt.edgeql
    # Select the caller's own order only when no receipt has been sent yet.select Order { id, total, buyer: { email } }filter .id = <uuid>$order and not exists .receipt_time

    When the query matches zero rows for a caller, Napalm rejects the call immediately with 403 nothing_found and never wakes the handler.

  2. Write the handler in a file named for the query

    handlers/sendReceipt.ts
    import type { Handler } from 'napalm-client' type Order = { id: string; total: number; buyer: { email: string } } const sendReceipt: Handler<Order> = async (call) => {  const [order] = call.rows  const sent = await fetch('https://api.resend.com/emails', {    method: 'POST',    headers: {      Authorization: `Bearer ${process.env.RESEND_KEY}`,      'Content-Type': 'application/json',      // A queued job preserves call.job.id across retry attempts.      'Idempotency-Key': call.job?.id ?? order.id,    },    body: JSON.stringify({      from: 'shop@example.com',      to: order.buyer.email,      subject: 'Your receipt',      text: `Total: ${order.total}`,    }),  })  if (!sent.ok) throw new Error(`Receipt delivery failed with status ${sent.status}`)   // Write back as the original caller under the schema's access policies.  const db = await call.db()  await db.fetch(`${call.address}/query/markReceiptSent`, {    method: 'POST',    headers: { 'Content-Type': 'application/json' },    body: JSON.stringify({ variables: { order: order.id } }),  })  return { sent: true }} export default sendReceipt

    The runtime library verifies each ES256 assertion against the branch’s JWKS and raw body SHA-256 digest before invoking your function. Your return value becomes the HTTP response of the action call.

    Write a handler as an async function* to stream the answer frame by frame as values are yielded. See Streamed answers.

  3. Deploy the folder

    Terminal
    napalm queries push notesnapalm handlers secrets set notes RESEND_KEYnapalm handlers deploy notes

    The CLI packages the folder for Linux and uploads the bundle. Each handler’s query becomes an action on the branch and replaces the previous hosted deployment atomically, so any handler removed from the folder reverts to an ordinary deployed query. Stage each secret first so environment variables are present on first wake.

Invoke a hosted handler like any action over POST /query/sendReceipt, as an MCP or A2A agent tool or from a queued job. See Actions & background jobs for multi-step workflows and cron schedules, and Actions, handlers & schedules for the Control API contracts.

Languages#

Every supported runtime ships a lightweight handler library that verifies incoming assertions and exchanges caller tokens on demand. The CLI detects the runtime from the folder layout and builds Linux artifacts automatically.

LanguageFolder layoutLibraryBuilt with
TypeScriptOne file per handler named after the deployed query.Librarynapalm-clientBuilt withesbuild
Pythonhandlers.py exporting one function per query plus requirements.txt.Librarynapalm_handlersBuilt withpip Linux wheels
GoGo module whose main calls napalm.Serve.Librarynapalmdata.com/go/napalmBuilt withgo build
RustCargo binary crate calling napalm_handlers::serve.Librarynapalm-handlersBuilt withcargo musl
Dartbin/handlers.dart calling serve from handlers.dart.Librarypackage:napalm_clientBuilt withdart compile exe
handlers/handlers.py
import json, os, urllib.request def sendReceipt(call):    order = call.rows[0]    request = urllib.request.Request(        'https://api.resend.com/emails',        data=json.dumps({'to': order['buyer']['email'], 'subject': 'Your receipt'}).encode(),        headers={'Authorization': f"Bearer {os.environ['RESEND_KEY']}", 'Content-Type': 'application/json'},    )    urllib.request.urlopen(request)    call.db().query('markReceiptSent', {'order': order['id']})    return {'sent': True}
handlers/main.go
package main import (	"context"	"log" 	"napalmdata.com/go/napalm") type order struct {	ID string `json:"id"`} func sendReceipt(ctx context.Context, call *napalm.HandlerCall) (any, error) {	var orders []order	if err := call.DecodeRows(&orders); err != nil {		return nil, err	}	db, err := call.DB(ctx)	if err != nil {		return nil, err	}	var marked []order	variables := map[string]string{"order": orders[0].ID}	if err := db.Query(ctx, "markReceiptSent", variables, &marked); err != nil {		return nil, err	}	return map[string]bool{"sent": true}, nil} func main() {	log.Fatal(napalm.Serve(map[string]napalm.Handler{"sendReceipt": sendReceipt}))}
handlers/src/main.rs
use napalm_handlers::{serve, HandlerCall, Handlers};use serde::Deserialize;use serde_json::{json, Value}; #[derive(Deserialize)]struct Order {    id: String,} #[tokio::main]async fn main() -> std::io::Result<()> {    let handlers = Handlers::new().on("sendReceipt", |call: HandlerCall| async move {        let orders: Vec<Order> = call.call.rows_as()?;        let db = call.db().await?;        db.query::<Value>("markReceiptSent", &json!({ "order": orders[0].id })).await?;        Ok(Some(json!({ "sent": true })))    });    serve(handlers).await}
handlers/bin/handlers.dart
import 'package:napalm_client/handlers.dart'; Future<void> main() async {  await serve({    'sendReceipt': (call) async {      final order = call.call.rows.first as Map<String, Object?>;      final db = await call.db();      await db.query('markReceiptSent', {'order': order['id']});      return {'sent': true};    },  });}

Go, Rust and Dart compile into a single native binary whose registered handler names cannot be inferred from filenames, so declare the served queries with --handler or inside handlers.json.

Terminal
napalm handlers deploy notes --handler sendReceipt --handler refundOrder

Handler settings#

Each handler defaults to isWrite: true, a 30-second timeout and an untyped JSON response. Override any handler’s defaults in handlers/handlers.json.

handlers/handlers.json
[  { "query": "sendReceipt" },  {    "query": "lookUpPrice",    "isWrite": false,    "timeoutSeconds": 10,    "answerSchema": {      "type": "object",      "required": ["cents"],      "properties": { "cents": { "type": "integer" } }    }  }]

A handler

querystringrequired
Name of the deployed query served by this handler.
isWriteboolean
Whether the handler mutates external or database state (default true). Read-only keys and read-only agent grants may call only handlers with isWrite: false.
timeoutSecondsinteger
Per-call execution limit, 1 to 30 seconds (default 30), including cold-wake milliseconds.
answerSchemaobject
OpenAPI 3.0 schema describing the handler’s JSON output, up to 16 KiB without $ref, published to generated SDKs and MCP tool schemas.

Napalm reads handlers.json directly from the uploaded bundle so code and action metadata never drift apart across deploys.

The caller’s identity#

Hosted handlers never hold a standing database superuser credential. Calling call.db() exchanges the invocation’s ES256 assertion at POST /sign-in/agents/token for a 60-second client bound to the exact caller.

Signed invocation capsule

Each handler call arrives with a branch-signed ES256 assertion and napalm_body_sha256 payload digest rather than raw caller credentials.

60-second caller session

call.db() exchanges that assertion at POST /sign-in/agents/token for a short-lived session bound to the caller’s Identity, AgentGrant and read-only rules.

Invoked byHandler session acts asExchange refused when
Signed-in personThat ext::auth::Identity.Exchange refused whenThe identity was deleted after invocation.
Authorized agentThat person, bounded by the AgentGrant.Exchange refused whenThe person revoked or expired the grant.
Service key or cron scheduleThat branch service key.Exchange refused whenThe manager revoked or expired the key.

Access policies apply to every follow-up query run through call.db(), and read-only callers receive read-only exchanged tokens.

Secrets#

Handler secrets inject third-party API keys as environment variables without storing plaintext in git or exposing values through read endpoints. Set secrets with napalm handlers secrets set or on the Queries tab in the web console. Updating a secret restarts the branch’s handler machines with the new environment.

Variable names accept up to 64 characters except PORT and prefixes NAPALM_ or FLY_. Every branch maintains an isolated secret store so preview branches never inherit production payment or mail keys.

Handler machines#

Each branch runs dedicated handler machines isolated from database compute, other organizations and sibling branches. Handlers talk to PostgreSQL solely through the branch’s HTTPS Project API.

Idle machines go to sleep after one second of quiet (or ten seconds under bursty traffic) and wake within a few hundred milliseconds on the next request with warm memory intact. Scale memory, CPU class or machine count when handlers process heavy payloads or concurrent bursts.

Terminal
napalm handlers size notes --memory 512 --machines 2

A branch’s machines

memorysize
Per-machine RAM (256 MiB, 512 MiB, 1 GiB, 2 GiB).
cpushared | performance
Shared fractional CPU or a dedicated performance core at 2 GiB.
machines1 to 8
Additional machines wake only when active calls saturate earlier instances.

Branches#

Hosted handlers are scoped per branch alongside actions and cron schedules. Pull-request branches start with zero handlers and zero secrets, so you can rehearse schema changes, gatekeeper queries and handler code together against cloned data using sandbox API keys before touching main.

Isolated handler bay

Every branch maintains an isolated handler deployment, secret store and action bindings so preview rehearsals never touch main keys.

Per-branch handler routing

Requests to /branches/{name}/query/{action} route strictly to the gatekeeper queries and handlers deployed on that branch.

Terminal
# Clone main onto an isolated preview branch and stage test secretsnapalm branches create pr-12 --data --previewnapalm queries push notes --branch pr-12napalm handlers secrets set notes RESEND_KEY --branch pr-12napalm handlers deploy notes --branch pr-12 # Exercise the branch's isolated handler pool before merging to mainnapalm call notes sendReceipt --branch pr-12 --order 2f1c7a9e-4b8d-4e2a-9c10-8a7b6c5d4e3f

Custom containers#

Package arbitrary system binaries or custom runtimes as an OCI container image, deploy by SHA-256 digest and list the served action names.

Terminal
napalm handlers deploy notes \  --image ghcr.io/acme/handlers@sha256:6b1f…c2e4 \  --handler sendReceipt

Napalm copies the image into an internal registry during deploy so cold wakes never depend on external registries. For private registries, supply --registry-user. Napalm uses the credential once during the image copy and discards the password immediately.

Terminal
napalm handlers deploy notes \  --image ghcr.io/acme/handlers@sha256:6b1f…c2e4 \  --registry-user acme-bot

Custom containers follow five runtime steps matching the official SDKs.

Listen
Bind HTTP on PORT (8080) and accept POST /<action>.
Check each call
Verify the ES256 Authorization bearer token against <NAPALM_URL>/.well-known/jwks.json, and check iss (NAPALM_URL), aud (<NAPALM_HANDLERS_URL>/<action>) and napalm_body_sha256 against the raw body.
Read the body
Parse { action, variables, data, job }, the same payload shape as external action deliveries.
Trade for a session
Exchange the assertion at <NAPALM_URL>/sign-in/agents/token with NAPALM_HANDLER_SECRET as the bearer.
Sleep when idle
Exit or go idle promptly after answering so the machine sleeps without accruing awake seconds.

Napalm injects PORT, NAPALM_URL, NAPALM_HANDLERS_URL and NAPALM_HANDLER_SECRET on every container machine. See Actions for assertion claim details.

Errors and retries#

Direct callers receive the status and error code immediately, while background jobs retry failed attempts with exponential backoff until the job’s expire_time.

A handler claims long-running job work by answering 202 Accepted. The run stays open until the handler finishes it or its deadline expires. See Long jobs.

Status and codeWhen returnedQueued job behavior
403 nothing_foundGatekeeper query matched zero permitted rows (for example, already processed or unauthorized).Queued job behaviorCompletes without calling the handler or retrying.
403 read_onlyA read-only key or read-only agent grant invoked a handler with isWrite: true.Queued job behaviorMarks the attempt failed and retries until expire_time.
413 request_too_largeGatekeeper query rows plus variables exceeded 64 KiB. Project fewer columns or pass IDs and fetch inside call.db().Queued job behaviorMarks the attempt failed and retries until expire_time.
502 answer_too_largeHandler response body exceeded 1 MiB. Write large artifacts through ext::files::File instead.Queued job behaviorMarks the attempt failed and retries.
502 action_unreachableHandler crashed, refused the connection or ran past timeoutSeconds.Queued job behaviorRetries with backoff using the same call.job.id.

Charges#

Handler machines bill per awake second by memory tier. Sleeping machines bill only unpacked image storage, and branches without deployed handlers incur zero handler charges.

ChargeRateCounted as
Awake time, shared CPU$2.75 per GiB / dayCounted asSeconds awake per machine as a fraction of a day, scaled by memory.
Awake time, performance CPU$4.50 per GiB / dayCounted asSame calculation for a dedicated performance core.
Calls$3 per millionCounted asEvery invocation that reaches a handler machine.
Code at rest$1 per GB / monthCounted asUnpacked image size while the machine sleeps.

A 256 MiB machine kept awake continuously for 24 hours costs $0.69, or $0.03 per awake hour. Grouped bursts share the short post-call awake window and amortize cold-wake time across requests.

Limits#

LimitValue
One call30 seconds. A job’s attempt has 120 seconds for the query and handler together.
Request to a handler64 KiB.
Handler response1 MiB.
Deploy size128 MiB, built.
Handlers128 per branch, matching actions.
Container image256 layers.
Handler machines1 to 8 per branch, 256 MiB to 2 GiB each.
RegionCo-located in the same region as the branch’s database engines.

Limits lists every project, organization and Control API quota on one page.

Type a word or two to search every docs page.