Hot-Path Routes
Standalone actions that run ahead of the database, auth and services middleware, authorized by a signed principal alone. For high-frequency endpoints that must not touch the database to decide who the caller is.
A hot-path route is a standalone action marked hotPath: true. It registers ahead of the database, auth, principal and services middleware, so a call does no session lookup, builds no scoped db and loads no services. The caller presents a signed principal, and the route checks it with a signature and a clock.
Use a hot path for endpoints called many times a second by the same few callers, such as presence pings, cursor updates and live counters. Use an ordinary standalone action for everything else.
Define one
// quickback/features/workspaces/actions/livePing.ts
import { z } from "zod";
import { defineAction } from "../.quickback/define-hot-path-action";
export default defineAction({
description: "Echo the caller's principal for one workspace.",
path: "/live/:workspaceId/ping",
method: "POST",
hotPath: true,
access: { roles: ["scope:workspace:member"] },
rateLimit: { key: "subject", limit: 100, period: 60 },
audit: "full",
input: z.object({ note: z.string().max(200).optional() }),
async execute({ input, params, principal, env, request }) {
return { workspaceId: params.workspaceId, subjectId: principal.subjectId, note: input.note ?? null };
},
});Import defineAction from ../.quickback/define-hot-path-action, not from the ordinary helper. The compiler generates that file per feature and refuses a hot-path action that imports anything else (HOT_PATH_HELPER_IMPORT).
execute receives exactly five arguments, and the helper's types enforce them:
| Argument | Value |
|---|---|
input | The parsed input schema. The query string on GET, the JSON body otherwise (at most 1 MiB). |
params | Path parameters, typed from path. |
principal | The verified principal: subjectId, kind, instanceId, roles, source, expiresAt. |
env | The Worker bindings. |
request | The raw Request. |
There is no ctx, db, services or c. ctx.userId is never set. Return a JSON-serializable value (200), or a Response. Throw an ActionError for a coded refusal; its statusCode and code reach the response and the audit row.
Options
Only these keys are accepted on a hot-path action. Any other key is a compile error (HOT_PATH_UNSUPPORTED_OPTION).
| Key | Rule |
|---|---|
path | Required. Must name the kind's requestField as a parameter (/live/:workspaceId/ping). Its first segment must be static. |
method | GET, POST (default), PUT, PATCH or DELETE. |
hotPath | true. Only on standalone actions; a record action is refused (HOT_PATH_RECORD_ACTION). |
access | { roles: ["scope:<kind>:<role>", …] }, all of one kind. Nothing else. |
rateLimit | See Rate limits. |
audit | "full" (default). See Audit. |
input, execute, description | As for any action. |
Access and the instance
access.roles must name scope roles of one kind, scope:<kind>:<role>. It may include the kind's access-code role; the route then needs :<requestField> in its path (ACCESS_CODE_ROLE_INSTANCE_UNBOUND) and a rate limit that includes "instance" (HOT_PATH_CODE_ROLE_NEEDS_RATE_LIMIT, HOT_PATH_CODE_ROLE_SUBJECT_ONLY_RATE_LIMIT; an inherited project default is subject-only, so declare one). PUBLIC, org roles, record predicates and function access are refused (HOT_PATH_ACCESS_NEEDS_SCOPE). Roles of two kinds are refused (HOT_PATH_ACCESS_ONE_KIND). The kind must declare principal (HOT_PATH_KIND_NO_PRINCIPAL).
At request time the route checks, in order:
Authorization: Bearer <principal>is present and verifies. A cookie or session is never read.- The principal's kind is the route's kind, and it holds one of the listed roles.
- The
requestFieldpath parameter equals the principal'sinstanceId. A principal for workspace A cannot call/live/B/ping. An access-code principal must also carry the instance's current code epoch (one cached KV read); otherwise 401PRINCIPAL_EPOCH_STALE. - Rate limits, charged only for a call that passed steps 1–3. A code principal refused at step 2 or 3 never spends the instance bucket the route's other callers share, so a code holder cannot lock members out of a members-only route.
- Input parsing and validation.
execute.
Rate limits
Hot-path rate limits are keyed on the principal, never on the caller's IP.
// excerpt
rateLimit: { key: "subject", limit: 100, period: 60 },key | Bucket |
|---|---|
"subject" (default) | One per subject per instance |
"instance" | One shared by every caller on the instance |
["subject", "instance"] | Both. A call must pass each. |
One limit and period apply to every key listed: ["subject", "instance"] is two counters with the same limit, not a per-subject limit under a larger instance limit. Since the instance counter counts every subject's calls, it always fills first, so the subject counter adds nothing, and one busy subject can use up the instance's whole budget for everyone. Use "subject" to cap each caller, or "instance" to cap an instance's total. A separate limit per key is not supported in this release.
limit and period (10 or 60) select the same RL_<limit>_<period> binding as other rate limits. delta weights a call. An omitted rateLimit uses the project-default update bucket, keyed by subject.
Compile errors:
| Code | Cause |
|---|---|
HOT_PATH_RATE_LIMIT_BY_IP | key: "ip". |
HOT_PATH_RATE_LIMIT_REQUIRED | rateLimit: false. A hot path always has a limit. |
HOT_PATH_RATE_LIMIT_INVALID | Any other key, a repeated key, a bad limit, period or delta, or a bucket. |
If the project's own rate limiting is turned off (rateLimit: false at project level) and the action omits rateLimit, the route is not limited. If the RL_* binding is missing at runtime, the call is not limited, as with other actions, except for an access-code principal, which is refused with 503 HOT_PATH_RATE_LIMIT_UNAVAILABLE.
Audit
Every call that presents a verified principal writes one security-audit row with eventKind: "hot_path", after the response, through waitUntil. That covers successes and every refusal after verification: role, instance mismatch, rate limit, body, validation, an ActionError, and a thrown error. A Response that execute returns is audited by its status: error for 5xx, denied for 4xx, success otherwise. The row's actor (actor_user_id) is the principal's subject, and target_record_id is the instance. The row also carries the route, status and code. It never carries the principal token.
A missing, invalid or stale principal (PRINCIPAL_MISSING, PRINCIPAL_INVALID, PRINCIPAL_EPOCH_STALE, PRINCIPAL_KEYS_MISCONFIGURED) is not audited. An unauthenticated caller could otherwise fill the audit database with one row per request. Those refusals are logged (hot_path_refused) with the exact reason and request id.
The same holds for every refusal of an access-code principal (source: "code"), since anyone can mint one: role, instance mismatch, rate limit, body and validation refusals are logged, not audited. Its successful calls are audited.
audit: "full" is the only mode in this release. "aggregate" and { sampled: n } are compile errors (HOT_PATH_AUDIT_UNSUPPORTED, "not yet supported"). Outside a hot path, audit is accepted only on a PUBLIC standalone action, where 'full' opts into a row per call (Public Access); anywhere else it is refused (ACTION_AUDIT_UNSUPPORTED).
Errors
| Status | Code | When |
|---|---|---|
| 401 | PRINCIPAL_MISSING | No Authorization: Bearer. Sends WWW-Authenticate: Bearer realm="principal". |
| 401 | PRINCIPAL_INVALID | Bad signature, expired, unknown kid, wrong typ, aud or iss, or any other verifier refusal. Sends WWW-Authenticate: Bearer error="invalid_token". |
| 401 | PRINCIPAL_EPOCH_STALE | An access-code principal minted before the code was rotated or closed with revoke. Join again with the current code. |
| 403 | HOT_PATH_ROLE_REFUSED | Wrong kind, or none of the listed roles. |
| 403 | HOT_PATH_INSTANCE_MISMATCH | The path's instance is not the principal's. |
| 429 | RATE_LIMITED | With Retry-After. |
| 413 | PAYLOAD_TOO_LARGE | Body over 1 MiB. A Content-Length over the cap is refused before any byte is read; a body without one (chunked) is read only up to the cap. |
| 400 | INVALID_CONTENT_LENGTH | Content-Length is not a plain decimal number. |
| 400 | INVALID_JSON | Body is not JSON, or not valid UTF-8. |
| 400 | VALIDATION_FAILED | input refused it. details.fields lists each field. |
| 500 | PRINCIPAL_KEYS_MISCONFIGURED | QB_PRINCIPAL_PUBLIC_KEYS is missing or malformed. |
| 500 | INTERNAL_ERROR | execute threw something other than an ActionError. |
| 503 | ACCESS_CODE_UNAVAILABLE | An access-code principal's epoch could not be checked (KV unbound or unreadable). |
| 503 | HOT_PATH_RATE_LIMIT_UNAVAILABLE | An access-code principal called a route whose RL_* binding is not bound. |
In production, a PRINCIPAL_INVALID body does not say why the principal failed, so the route cannot be used to probe tokens. The log line (hot_path_refused) carries the exact reason with the request id. With EXPOSE_ERROR_STACK set (dev, preview), the reason is in details.reason too. Every response is Cache-Control: no-store, including a Response that execute returns (its own Cache-Control is replaced). A 101 upgrade response is returned as is.
The import check
A hot-path action must not reach the database, Better Auth or services, even by accident. The compiler walks the action file's imports, transitively, and refuses (HOT_PATH_FORBIDDEN_IMPORT) any that reaches:
src/db,src/middleware,src/lib/auth, the scoped db, services, the security-audit writer, scope admission or OAuth, tenant routing, or the principal signer;- an ORM or query builder (
drizzle-orm,drizzle-kit,kysely,knex,prisma,@prisma/*,typeorm,sequelize,@mikro-orm/*,mongoose,objection); - a database driver or client (
postgres,pg,pg-*,@neondatabase/*,@planetscale/*,mysql,mysql2,@libsql/*,better-sqlite3,sqlite3,sql.js,@electric-sql/*,@tursodatabase/*,@vercel/postgres,@supabase/*,mongodb); - an auth server (
better-auth,@better-auth/*,@auth/*,next-auth,lucia,@clerk/*,firebase-admin).
The package list is a denylist: a handler may use any other library (zod, jose, …). The error prints the chain, for example features/workspaces/actions/livePing.ts → lib/helpers.ts → db.
The walk covers .ts, .tsx, .js, .mjs and .cjs files, static imports, re-exports, import() and require() with a literal specifier, and class extends clauses (they run at load time). Type-only imports and other type positions are allowed. Refused because the compiler cannot follow them:
- a computed
import()orrequire()specifier; requireused as a value, such asconst r = require;- a relative or aliased specifier that resolves outside the generated
src/(for example intonode_modules), or names a file the compiler did not emit, including a case variant of an emitted file.
env still holds the database bindings. The import check stops the usual ways of using them, but a handler that calls env.DB.prepare(…) directly is not refused. Don't.
Routing
A hot path mounts at /api/v1<path>, ahead of every other route, so the compiler refuses one that could shadow or be shadowed by another (HOT_PATH_ROUTE_CONFLICT):
- the first segment is a parameter;
- the first segment is a feature, table, resource or namespace segment, or a built-in one (
auth,admin,storage,health, …); - the pattern overlaps another standalone or hot-path action with the same method.
Hot-path actions are not in OpenAPI, MCP tools or the CMS.
Requirements
| Code | Cause |
|---|---|
HOT_PATH_PROVIDER_UNSUPPORTED | Not Cloudflare + cloudflare-d1 + Better Auth, or the kind's principal config failed. |
HOT_PATH_PATH_MISSING_INSTANCE | path does not name the kind's requestField. |
HOT_PATH_PATH_INVALID | Malformed path, or a repeated parameter. |
Limitations
- A principal stays valid until it expires. Removing a member does not stop their hot-path calls until then. See revocation.
- Hot paths run before the CMS-domain block and the security-headers middleware.
- Project middlewares do not run. Hot paths are mounted before every
app.use(): yourquickback/middlewares/files, idempotency (Idempotency-Keyis ignored), database, auth and services. Anything a middleware enforces, such as extra headers, request logging or a custom check, must be done in the handler. When a project has both, the compile warns withHOT_PATH_SKIPS_MIDDLEWARE, naming each middleware and each hot-path route.