Building Applications
Building Applications
How to turn business requirements into a working application on Toa: what to write, which files to create, how to run and test it. Why the runtime behaves the way it does, and what it guarantees, is in the mental model.
Read it in order. Every example comes from the same application — a small shop with orders and customer accounts — which grows as requirements arrive.
§Chapter I. First Steps
From one command to a tested, configured component behind an HTTP API, one small step at a time.
- Create an Application — summary: what the machine needs; creating an application with one command; starting it; the two processes; the first requests; running its tests; the commands of every day; what was created and where each file is explained.
- Run It and Make a Change — summary: an operation and its file; restarting after a change; calling an operation from the command line; the manifest; an entity and the operations a component inherits; adding a property; what a restart generates.
- Create a Component — summary: a manifest with an entity; creating objects by forwarding to
transit; an operation with a business rule; returning and declaring an error; calling it; what a reply, an error and an exception look like. - Expose It over HTTP — summary: the smallest exposition for listing, reading, creating and approving; where routes are mounted; the gateway; requests with curl; how a returned error and other failures are answered.
- Write a Test — summary: a scenario that sends http requests and matches responses; the steps the application came with; what a scenario runs against; running scenarios; calling an operation directly; the stage api; the agent’s request text, captures, pipelines and matching.
- Add Configuration — summary: declaring a configuration schema and defaults; reading
context.configuration; setting values in the context; one value per environment with the@environmentsuffix; where secrets and runtime changes are described.
§Chapter II. Business Logic
What a component is made of, one requirement at a time: state, operations, refusals, calls, events, and what follows from them.
- Describe State — summary: the entity schema, required properties and blank; system properties; associated entities and identifiers of your own; moments; storage; every manifest key.
- Write Operations — summary: a file is an operation; choosing a type and a scope; declaring input, output, concurrency and query; classes and factories; shared code; rules for operation code.
- Refuse a Request — summary: returning and declaring an error; handling an error from a call; exceptions and their http statuses; deciding not to write with discard; the four outcomes.
- Call Operations and Select State — summary: local and remote calls; input and query; criteria, sorting and paging; creating an object; versions; deleted objects; trimming the reply; every request property.
- Use the Inherited Operations — summary: transit, observe, enumerate, assign, terminate and the rest; narrowing and forwarding them; replacing one; inherited events; a prototype of your own.
- Protect an Invariant — summary: a guard file that every write must pass; what a refused write looks like; choosing between a guard, the schema and an operation.
- Announce a Change — summary: an event file with a condition; a payload of your own; trailers; inherited events; naming events for consumers outside the application; rules for conditions.
- React to an Event — summary: binding an event to an operation; building the request; skipping events; shared operations with arguments; own events; events from other systems; what the operation must expect.
- Do Work in the Background — summary: handing a call over with
task: true; tasks to your own component; getting the result; what a task’s operation must handle; calls that cannot be tasks. - Handle Repeated Calls — summary: why an operation can run again; setting instead of adding; skipping by
VERSION; keying a change by what it is for; declaringonce, how long a call is remembered and why a transition that retries does not call it; theidempotency-keyheader; keys for external services. - Call an External Service — summary: requests with
context.fetch; address and key from configuration; stubbing the provider locally and in tests; retries and timeouts; what a repeated operation means for a provider; traces and metrics. - Write a Multi-Step Workflow — summary: an effect under
continuitythat goes on from the step that failed; starting it as a task or from a receiver; what counts as a step; time, randomness and ids from the context; what can still repeat; what it needs to run. - Run Work on a Schedule — summary: pulses at a regular interval and cron schedules under
cadence; what must be configured and run; writing for missed and repeated calls; spreading work over a cycle; per- replica pulses; several entries; regions. - Do Something Later — summary: arming a call with
context.delayand cancelling it; choosingoverdue; timing and discreteness; calls that re-arm themselves; where a delay is refused; thecadencesettings of the Context. - Read a Large Collection — summary: reading a collection as a stream of parts; operations with the
streamscope; tokens and reading only what changed; windows, order andstop; what a reader handles; turning changes on with images. - Stream a Reply or an Input — summary: answering with a generator or a
Readableand reading it; operations that take a stream withstreamand thehttpbinding; how to call them; what such a call lacks; addresses for a local run. - Keep Something in a Process — summary: run commands in
rc/;context.state; releasing indispose;pauseandresume; stateful operations called by process name, their failures, timeouts and limits. - Loops and Read-Only Calls — summary: reading and fixing a
LoopException;unchainedoperations and delays; the trail limits;SafetyExceptionfrom a safe operation and underGETandHEAD;io:readonly. - Use TypeScript — summary: operations in typescript without a build step; generating types from manifests; type checking with tsc; the three rules of erased types.
- Indexes and Data Migrations — summary: declaring indexes, unique values and expiry; changing stored data; the rules a migration must follow.
- The Operation Context — summary: everything on the context argument and the article that teaches each member: calls, ids and time, where it runs, what extensions add.
§Chapter III. The API
Serving the application over HTTP: routes, what they accept and return, files, live updates, and tools for AI assistants.
- Build an API for a Component — summary: more routes and methods; the two defaults, no body and no access; where a component is mounted and the trailing slash; a scenario that creates and reads; the host; routes of the context; the long form.
- Lay Out the Routes — summary: nested and flat routes; route variables and wildcards; which route answers; forwarding; intermediate nodes; how directives are inherited and how to avoid it; shortcuts; sharing declarations.
- Map Methods to Operations — summary: short and long form of a method; which operation suits which method; changing only some fields with patch; the body as input; route variables; read-only get; statuses of replies; retrying with an idempotency key.
- List with Filters, Sorting and Paging — summary: the standard parameters; criteria, fixed and open; sort; omit and limit with bounds; fixed queries; identifier; text search; projection; parameters of the operation; queries of collection streams.
- What a Client Sends and Receives — summary: formats and content negotiation; every status; the three kinds of failure; debug; headers on every reply and the ray; multipart responses; browsers on other origins; a halted deployment; a client’s checklist.
- Choose What a Route Accepts and Returns — summary: naming the properties a route returns; narrowing the input; choosing the status from the output; throttling by address, route or identity; read-only calls.
- Pass Headers, Language and Host to an Operation — summary: headers, route variables, the language, the host, token claims and the raw body as input properties; requiring headers.
- Cache Replies and Prevent Lost Updates — summary: declaring how long a reply is kept; what authenticated requests get; an exact value; etag and not modified; writing only if unchanged with the version; a checklist.
- Stream Through the API — summary: reply streams; a collection read in windows, or its newest window with
stop, and a token that continues with the next window or with changes; one value composed from a stream; request bodies streamed into an operation and bytes answered; calling one particular process; answering with content fetched elsewhere. - Keep Files in a Storage — summary: declaring a storage and using it from an operation; entries; put, head, get and delete; providers and their options; a storage per environment; secrets; installing a provider’s sdk.
- Upload and Download Files — summary: a file resource in three declarations; where a file is stored; accepted types and the size limit; naming and describing an upload; uploading by url; downloads, ranges and variants; the entry; deleting.
- Process an Uploaded File — summary: operations called with a reference to a stored file; parallel and sequential steps; the multipart reply and one composed reply; steps as tasks; workflows on delete and without storing; a scenario that uploads.
- Push Changes to the Browser — summary: routing events to keys; serving the stream of a key; an identity’s own stream; literal keys; reading a stream and reconnecting with a token; rules for the client; a copy of a collection loaded with a stream and kept by events, never read for one: a list scrolled a window at a time, or the newest entries and what changed since the last launch; redis and expiry.
- Call the API as Procedures — summary: turning json-rpc on; how a route names a procedure; parameters and results; batches and notifications; errors; the rules shared with http.
- Let an AI Assistant Call the API — summary: turning mcp on and publishing a method as a tool; describing tools; what a tool takes and answers; hints; instructions; credentials, anonymous access and browser origins; a host of its own; icons; the protocol in brief.
- Describe the API — summary: asking a resource with options; the whole tree and its page; what a caller is shown; describing resources, methods and parameters; hiding a method.
- Run and Configure the Gateway — summary: running the gateway locally; ports; authorities; ingress, resources and http/2 in a deployment; readiness; the client address; the censor; stubs, delays and faults for development; every key of the context’s exposition.
§Chapter IV. Users and Access
Signing users up and in, keeping them signed in, and deciding who may call what: owners, staff, other applications.
- Sign Users Up and In — summary: the token key; a sign-up route that creates an account and its identity; signing in with a username and password; reaching the caller’s own account by path or by delegation; guests; sign in or up with one request; a scenario that signs up and in; where to go next; refusals of a sign-up.
- Manage Passwords — summary: rules for usernames and passwords; whether a username is free; changing, adding and removing a password; listing the ways to sign in; limiting password guessing; an identity without an account; the first administrator; hashing settings; the authentication schemes.
- Keep Users Signed In — summary: what a client does with the token; how long a sign-in lasts; signing a user out everywhere; token keys and replacing them; custom tokens for scripts limited to roles and paths; acting for another identity; listing and revoking custom tokens.
- Sign In with Google or Apple — summary: trusting a provider; signing in with its token; creating the account together with the identity; reading claims into the input; several client ids; exchanging an authorization code; adding, listing and removing providers of an account; a provider’s account as the first administrator; why a token was refused.
- Sign In with an Emailed Code or a Passkey — summary: an operation that gets a code and emails it; signing in with the code; making an address a way into an account; moving a sign-in to another device; limits on codes; adding a passkey, signing up and signing in with one; listing and removing passkeys; passkey settings and refusals.
- Restrict Who Can Call a Route — summary: routes are closed until they say who; a customer reaches only their own orders; a scenario with the refusals; several ways in and why nesting cannot narrow; public routes; any signed-in user; roles; several conditions at once; who may send a property; asking for the password again; recording who called; admitting by a provider’s token; access for the whole application; what a caller is shown; all directives.
- Give Staff Wider Access — summary: requiring a role on a route; the first administrator; granting a role; when a change reaches a signed-in user; a scenario with the principal; naming roles from general to specific; roles per resource; reading roles; letting staff pass roles on; revoking; banning a user; the system roles.
- Serve Several Domains and Screen Requests — summary: authorities and hosts per environment; users belong to an authority; telling an operation which domain was asked; the header that holds the client address; refusing requests by country; requiring a header; scenarios for the refusals.
- Let Another App Act for a User — summary: turning the authorization server on; which programs are known; the four steps of the consent page; what the program gets; limiting a token to roles and to one entry; connecting an AI assistant over MCP; showing and revoking what a user allowed; a scenario of the whole exchange; the requests a program makes; settings.
- Users and Access Reference — summary: every identity resource with its access; operations an application calls; directives; annotation keys; configuration of the identity components; secrets; statuses a client handles.
§Chapter V. Platform Features
Features the platform brings and a component switches on: settings, a cache, coordination, telemetry, a map of itself, a log to query.
- Turn On a Platform Feature — summary: declaring an extension in the manifest; setting it up in the context; values per environment; the full form; supplied extensions and connectors; ports that are taken.
- Keep Settings and Secrets out of the Code — summary: secret values and
$NAMEreferences;unwrap; supplying secrets locally and to a deployment; schema, defaults, nested values, prototypes; values in the context; resources of the values service; trying a component with other values. - Change a Setting without Redeploying — summary: creating, reading and resetting configuration over http; roles; the configuration page; changing values from an operation; the change event; what happens on the next deployment and after a schema change.
- Cache Something All Replicas Share — summary: turning the stash on; redis commands on
context.stash; storing objects; keys private to a component; a redis per component; behaviour when redis is away. - Coordinate Replicas — summary: letting only one replica do something at a time; splitting work between replicas;
limiting calls across replicas; the
atomicityannotation; behaviour without redis. - Write Logs — summary: writing entries with
context.logs; reading them on the console; finding everything about one request; levels per environment and per component; sending entries to a backend; finding why a process failed; writing good entries. - Follow a Request through the Application — summary: seeing spans on the console; what is traced without code; adding spans with
context.span; sending traces to a backend; sampling; tracing the start of a process. - Count Things and Alert on Them — summary: declaring and recording a counter; turning metrics on; labels; histograms and gauges; declaration reference; choosing intervals, buckets and labels; the metrics recorded for every application.
- Send Telemetry to Grafana — summary: wiring logs, traces and metrics to tempo, prometheus and loki; linking traces and
logs; the whole
telemetryannotation;otlpexporter options; loss and outages; resource attributes; the readiness probe. - See What Is Deployed and How Components Talk — summary: the topology page and api; nodes and observed edges; leaving a component out; the
introspectionannotation; what to use the graph for. - Change the Storage, the Transport or the Language — summary: the default storage and what it asks of you; storing nothing; the broker and brokers of other systems; the http binding for streamed calls; shell scripts as operations.
- Point the Application at Its Database, Broker and Cache — summary: one address for everything; addresses per environment, namespace and component; several addresses under one key; credentials locally and as deployed secrets; secret names.
- Write an Extension of Your Own — summary: an aspect of your own; declaring and calling it; annotations and deployment variables; validating declarations; tenants, services and residents; pausing; a storage of your own.
- Keep a Log of What Happens and Query It — summary: the store and its provider; the
chroniclesannotation and service; declaring what a component logs, typed and described; keeping personal data out;context.chronicles.send; encounters from the storefront, visitors and sessions, and their documentation; theevents,statesandencounterstables and the views of what is declared; the dialect; tools for an agent and their roles; views.
§Chapter VI. Shipping
From “it works on my machine” to production: describe the application, deploy it, release new versions safely and look after it.
- Describe the Application — summary: the context file; name and version; addresses of the broker and the database; keys of connectors and extensions; events another application reads; runtime settings; every top- level key.
- Give Each Environment Its Values — summary: the
@environmentsuffix at any depth; the local environment and.env; several local environments; derived environments as a chain; default environment of each command. - Decide What Runs Together — summary: grouping components into compositions; replicas; cpu and memory; extension services inside a composition; ports; leaving components out of a deployment; one process for everything; how to group.
- Deploy — summary: what must exist before the first deploy; the keys a deploy needs;
toa deployand what you see; checking the result; options; what gets deployed; start and stop limits; ingress; single-image deployment; pipelines; running without kubernetes. - Build Images — summary: the registry; building and pushing; tags; what goes into an image; platforms; private registries; base images; extra build steps and arguments; private npm registry; published service images; registry retention.
- Supply Secrets — summary: what is a secret; listing what a deployment needs; putting secrets in the cluster; the check before a deploy; changing a value; secrets for a local run; names of credential secrets; checklist for a new environment.
- Release a New Version — summary: what to do when you change code, add an operation, add a required input, remove or rename an input, change the entity, add a migration or change an event; changes that cannot be rolled; going back; the component map and versions.
- Run in More Than One Region — summary: declaring regions and ranks; requirements; concurrent writes in two regions; writing components for several regions; adding a region step by step; adding a component later; removing a region.
- Stop Everything for Maintenance — summary: turning halt on and its limits; requesting a halt over the gateway; what you and
clients see;
pauseandresumerun commands; choosing the numbers; deploying a release that cannot be rolled; rehearsing. - Look After a Running Application — summary: what is running and at which version; a pod that does not become ready; a message that keeps failing and the parked queue; events that are not published and outbox settings; rolling back; changes without a release; an isolated second copy; alerts to have.
- The CLI — summary: installing; common options; every command with its arguments and options, grouped as preparing, running, inspecting, building and deploying, secrets and the cluster; variables the cli reads; exit codes.
§Chapter VII. Patterns
How typical problems are solved: when to call and when to announce, what repeats, races and late messages ask of the code, and how to say no.
- Call, Event, or Task — summary: the one rule for choosing; what goes wrong with calls only; what a call, an event and a task each give; a table of situations; the same operation called on one path and received on another.
- Reply Before the Work Is Done — summary: storing what is wanted and replying; an event of your own that starts the slow part; writing the result and the failure into state; telling the client; why not a task from the operation.
- Events Worth Subscribing To — summary: conditions that fire when a fact becomes true; trailers for what the states cannot
say; payloads as contracts; receivers that filter and translate; why not subscribe to
updated. - The Same Message Twice — summary: why messages repeat; setting and looking before writing, by itself or under a
key;
oncefor what accumulates and how long it remembers; a record under the other system’s id; deduplicating where the effect is. - Two Writers at Once — summary: the read-check-write race; one transition with
concurrency: retry; keeping the fact in one object; what a second run repeats; forms edited by people; when a lock is the answer. - Messages Out of Order — summary: why arrival order means nothing; carrying the version and skipping older messages; treating an event as a signal and asking the owner; values that only move forward; not creating the dependency.
- Saying No — summary: five ways to refuse and what each answers; schema and route, guard, returned error, success without a write, exception; refusals nobody hears; passing a refusal on; refusing before the work and settling after.
- Ask the Owner, or Keep a Copy — summary: using a fact another component owns; a call to the owner that keeps the rule; freezing an answer; a copy kept current by a receiver; entities that need no creation; a limit checked where its counter lives.
- Keep Data About a Customer without Creating It — summary: why records made at sign-up do not hold; an entity identified by the customer’s id; a blank that says what is true before anything happened; what disappears; what a list and an assignment do not do; when existence means something.
- A Process Across Components — summary: a business process of several steps without a transaction; a status for every stage; steps that react to events and report back; the owner of the process decides; failure as one more step, with compensation; steps that repeat, race, refuse or never finish.
- Reservations — summary: setting money aside now and taking or releasing it later;
hold,settleandreleasekeyed by the order; asking before the work and settling after it; the late hold; a guard for the sum; when a debit with a refund or charging afterwards is enough. - Work on the Clock — summary: expiry as a stored moment compared on use; counters that renew at their next use; sweeps on a pulse that select by state; a delay per object; reconciling a copy with an outside truth; finding work that stopped.
- A Gateway to an External Service — summary: one entity-less component that alone holds a provider’s keys; operations and errors in the application’s words; an error for “ask again later”; a stub when the key is empty; a composition so secrets reach one process.
- Receiving Webhooks — summary: an anonymous route with the raw body; verifying the signature by a call; storing
every notification and announcing it; one record per provider object under a derived id; why
onceis not enough; refusing so the provider sends again. - Mirroring a Provider’s Object — summary: a server-side copy of an object an outside service keeps, such as a subscription at a payment provider; when that service says the object changed, asking it for the object instead of trusting what it said; an associated mirror merged by a retried transition; signalling from the webhook, the customer’s return and the shop’s own change; announcing only what changed; a copy that refuses older reads; expiry as a date.
- A Wallet and Its Ledger — summary: a stored balance in an associated entity;
creditas aoncetransition anddebitkeyed by what it is for, both withconcurrency: retry; a guard; trailers that say what moved; ledger lines derived from the wallet’s event underid:VERSION; a unique index; corrections as new lines. - Taking a Payment, End to End — summary: a checkout started by a call; the result by webhook, by the customer’s return and by a sweep, all ending in one record; consequences fanned out by events to the wallet, the ledger, the receipt and the page; which mechanism at each step; failures walked through; limits.
- A List That Stays Current — summary: a list in the client loaded with a collection stream and kept current by realtime
events; never reading on an event, never asking a token on a timer; an endless list read a
window at a time as the user scrolls; the newest hundred read with
stop, and what changed since by the kept token when the client starts.