The platform · the server
Roc compiled to native code, in a Rust host
An app's server is one executable: your Roc compiled to machine code, linked with a Rust host (tokio and hyper). The host answers HTTP, runs your code for each request, keeps a crash to its request, and frees the memory used. Your Roc decides what each request gets; the host carries it out.
Running it#
rocx dev runs the server with --dev. A built executable takes these options (with the environment variable that does the same in parentheses):
<app> --port 8080 --host 127.0.0.1 where to listen (PORT)
--static DIR, --file /PATH=FILE files served as they are
--context-file FILE what the app's init! is given, once, as it starts
--env-file FILE settings for the environment, read as it starts (none without it: a .env here isn't read unless named); the environment wins
--database-url URL the database (DATABASE_URL): postgres://…, or sqlite:<path> (turso:<path>) for a SQLite (Turso) app's file elsewhere
--actor-idle-ms 900000 an actor idle this long is let go (0: never; kept in the database)
--kv-max-mb 64 Kv's limit (KV_MAX_MB): the least recently used goes past it
--images-dir data/images where enhanced:src's copies of photos are kept
--images-max-mb 1024 the most they take: the least recently used go past it
--images-wait a page waits for its photos' copies (a static build's server)
--max-body 16MiB the most a request's body may be (MAX_BODY): bytes, or KiB, MiB, GiB; 413 beyond
--public-url https://app.example where the app is, for links it sends (PUBLIC_URL; else where it listens)
--dev reload pages on restart, show crashes, plugins' dev pages (/__rocx/mail)
--debug GET /__rocx/allocations and /__rocx/plugin-files, and plugins' debug paths
--live-beat-ms 15000 how often a channel stream beats, and its checks run again
--roc-threads N the threads Roc runs on (ROCX_ROC_THREADS; one a core)- Request bodies. The host reads a body whole before your code runs: up to 16 MiB, or
--max-body(bytes, KiB, MiB or GiB, as in64MiB). A larger body gets 413. - Static files.
--staticand--fileserve files typed by their extension (cache-control: no-storeunder--dev). A file directly under/rocx/whose name ends in a dash and 16 hex digits (styles-0123456789abcdef.css, as rocx build names the stylesheet) is cached for a year (cache-control: public, max-age=31536000, immutable). - Proxies. Outgoing requests use
HTTPS_PROXYorHTTP_PROXYwhen set, except to hosts inNO_PROXY(HTTP). - Starting. The server reads the file
--env-filenames, if any, into its environment (settings), and takes its port, stopping if the port is in use. Then it opens the database, checks the plugins, applies migrations, runs the app'sinit!, starts the background loops, and answers requests. - Stopping. On SIGTERM or Ctrl-C, it stops listening and taking jobs, then waits up to ten seconds for running requests, streams and jobs.
- Without a database (a Postgres app with no URL), a server whose app or plugins have tables doesn't start, and says which have them; under
--devor--debugit starts and logs a line. Without tables, it starts, and what needs the database says so when used.
The log#
Every line on stderr is an event: a level, a message and fields, from your app, the host (starting, stopping, a crash with its method, URL and error) or a plugin (a migration applied, a failed job). Keep messages fixed and details in fields, for log collectors to filter on. Log with Log.info!, Log.debug!, Log.warn! or Log.error!, a message and a record of fields ({} for none); Log.line! logs a message alone. The program sets the format:
Log.info!("gate failed", { path: request.path, error: why })
program = {
..App.program({ init! }),
logs: { format: Auto }, # or Pretty, or Json
}14:03:12 info gate failed path=/admin error="no session"
{"time":"2026-11-21T13:03:12.345Z","level":"info","msg":"gate failed","error":"no session","path":"/admin"}Auto, the default, follows ROCX_LOG (pretty or json) if set; otherwise pretty lines to a terminal, and JSON elsewhere. A field named time, level or msg is written as fields.msg and so on, so it can't replace the line's own.
A pretty line is the time, the level, the message, then the fields. At a terminal the time and the fields' names are dimmed and the level coloured, so the message and the values stand out. A request's path, method and status come first, then durations: a number named <x>_ns, <x>_us or <x>_ms is shown in the unit that reads best (duration_ns=12345 is duration=12µs). JSON keeps the fields as they are.
10:36:32 info rocx plugins: jobs, email, auth
10:36:32 info rocx server: http://127.0.0.1:8080 (Roc, native)
➜ Stories http://127.0.0.1:8080/__rocx/stories
➜ OpenAPI http://127.0.0.1:8080/openapi.html
➜ Mailbox http://127.0.0.1:8080/__rocx/mail
➜ Sign in http://127.0.0.1:8080/sign-inUnder --dev, the server lists the places to open under its address: the app's stories, its OpenAPI page if a route serves one, what plugins add (the dev mailbox, the sign-in page) and the app's own (App.program({ links: [{ label: "Jobs", path: "/admin/jobs" }] })).
Logging never waits for stderr: a thread of its own writes queued events in order, flushing when the queue empties and before exit. When the queue is full (64k events), the caller waits rather than lose a line.
Deploying#
rocx build writes dist/server, migrations inside, and dist/static (rocx). --target arm64musl (or x64musl) makes a static Linux executable, from macOS too: the prebuilt host carries musl's C library and unwinder. To deploy:
- Put it in a container with the app's static files:
rocx build --imagewrites an image of nothing else, without a Dockerfile, fordocker load -i my-app.tar(rocx). With only the app's database engine and no debug info, a hello world's image is 3.7 MB to send. - Give a Postgres app a
DATABASE_URL, a SQLite app a file on a volume (--database-url sqlite:/data/app.db). - Pass settings (
APP_SECRET,SMTP_URL, an API's key) as environment variables, or in a file read at start (--env-file; the environment wins). A plugin missing a setting stops the start, naming it. - Put a TLS proxy in front, and set
PUBLIC_URLto the public address for the links the app sends (settings). - Run one instance. Live state,
Kvand actors' mailboxes live in its memory, so an app runs as one server, not as copies behind a load balancer.
CI builds and tests every example app on Linux (arm64).
An app whose pages need no server once rendered (docs, a blog, a landing page) can be deployed as files: rocx build app --static writes every page, its data and what it loads, for GitHub Pages or a CDN (a static copy).
What is Rust, what is Roc#
The host gives Roc general building blocks. Everything built on them is Roc, in the platform or packages, and an app could write its own:
- Rust (
server/host): HTTP; threads; the database (a pool of Postgres connections plus one listening for notifications, or SQLite's file in the process, its calls on threads of their own); time zones; TCP and TLS sockets; live topics and rooms; channels' streams; background loops and isolated calls; actors' mailboxes and timers; values in memory (Kv); secure random numbers, AES-GCM and P-256; reading a settings file (--env-file); rendering pages of components; photos' copies. - Roc (
server/platform/*.roc): migrations, plugins (checking and running them), actors' state and messages, decoding database rows. Jobs, cron and email (an SMTP client, MIME) are Roc packages on the same effects (packages/jobs, packages/email).
The platform reference lists every effect, with its type.
A call pauses while it waits#
Your Roc runs on threads of its own (one per CPU core, or --roc-threads / ROCX_ROC_THREADS), beside tokio's, which handle HTTP, sockets and timers. Each call into Roc (a request and its page, a stream, an actor's turn, a background loop) is a coroutine with its own stack.
When an effect waits (a query, a socket, another server, a sleep), the call pauses and its thread runs other calls; it resumes on the same thread when the wait ends. A waiting call holds no thread, so any number can wait at once. In the tests, eight requests each waiting 0.3 s on Postgres take about 0.3 s together, and 2,000 each waiting a second, on two threads, about a second.
The costs:
- Roc computing for long without an effect (a long pure loop) can't pause, so calls queued on its thread wait. New calls go to Roc's other threads.
- A call with a time limit (a job's) still ends on time: the server interrupts its thread and, in the app's code, ends the call as a crash would.
- Each stack reserves 8 MiB (Roc's default; a page is a deep tree to render), but a paused call costs only the memory its stack touched.
- Profilers and debuggers see calls on their own stacks, not on threads.
- A stack overflow still ends the process, saying so on stderr first.
Each call has its own context (its open transaction, rooms joined, topics listened to, sockets), given back when it ends. A value Roc makes belongs to its call until the call returns; then the host owns it, and may move it to another call (a stream's, to the call that sends it) but never shares it.
A crash ends one call#
In Roc, a crash or an integer overflow stops the program, but Roc's ABI lets the host choose how: roc_crashed must never return, so it can end the process or jump out of the Roc code that called it. This host jumps. A guard (server/host/src/guard.c) sets a jump target around every call into Roc, so a crash ends only that call:
- A request is answered 500 (with the crash's message under
--dev). - A stream ends.
- A job counts as failed and runs again later.
- An actor's turn is logged and reported to whoever asked; the actor's state stays as it was.
- A transaction the call had open is rolled back.
A crash skips only Roc's frames and a small trampoline's, so no Rust destructor is skipped.
Memory#
So that a crash leaks nothing, every allocation a call makes goes into a list the call owns. When the call returns, the answer's strings are copied out and the list is freed (a stream's once the call sending it is done); when it crashes, everything in the list is freed. Roc's reference counts are atomic in native builds, so a value moved to another thread stays correct.
The tests crash 200 requests at once, half after allocating 2,000 strings, then check that Roc holds no allocation (--debug serves the count at /__rocx/allocations). This site's tests check the same after rendering its pages over and over.
Streams of events#
An endpoint can answer with server-sent events: a loop, Events.stream(|{ send!, sleep! }| …), which the host runs as its own call while the stream is open. send! writes an event; sleep! pauses. When the client leaves, sleep! wakes early and the next send! returns Err(Gone), so ? ends the loop. A sleeping stream holds no thread: the tests keep 2,000 open on two threads and still answer a request at once. Events shows one, with a component listening.
For live data that pages follow, a channel is usually better: a tab's channels share one stream the host keeps without a call, and Roc runs only briefly, for a check or hook.
Pages, rendered on the server#
A page is one tree of components: its layouts, the page, and what they contain. The host renders it whole with rocx-engine, the engine the browser and the phones run, in its server mode (engine/src/server.rs): each component and hole runs once, nothing is tracked or waits, and a memo is computed when made. HTML comments mark each hole for hydration; markup inside <NoHydration> is plain HTML, never hydrated. The site's tests check that the host and the site's browser half, rendering in Node with the same engine, write every page the same, byte for byte.
A component's endpoint read (.read!(), a GET of the app's own path) is made in-process: through the app's respond! and the route directories' middleware, with accept: application/json, the page's headers (cookies included) and the app's context, so it gets the answer the browser would. Each URL is asked once per render. The answers go, by URL, into a script at the end of the page, before /rocx/start.js, and the browser reads them there instead of asking again. Reads inside a <NoHydration> aren't recorded: the browser never makes them.
On a failure (a context nothing provides, a failed memo, an endpoint answering anything but 200), the nearest <Errored> shows its fallback, as in the browser. An endpoint's redirect redirects the page; a crash ends the render with a 500.
Photos' copies#
Write a photo as <img enhanced:src={path} alt="…" /> and the server makes smaller WebP copies of it, 160 to 1920 pixels wide. The first page to show it gets the plain src, and the photo joins a queue two of the host's workers take from. Later pages get the copies: a srcset, sizes, and the photo's width and height, so the layout keeps its room. No page waits, and there is nothing to set up: no job, no build step.
- Whose photos: files in the app's
static/, or what the app's routes answer someone signed out (the server asks itself, without cookies). Never another site's, and never a photo only signed-in users may see: its copies would be anyone's. - Where they're kept:
data/images, named by content and served at/rocx/images/…for browsers to cache for good. The directory is its own index, so a restarted server has the copies on its first page. - Pruning: photos no page named for 30 days go, then the least recently used while the directory is over 1 GiB (
--images-max-mb). A removed one is made again the next time a page shows it. - A changed photo (a rewritten file, a route's new answer) gets new copies; its page shows the plain
srcuntil they exist. - A static build (
rocx build --static) waits for every photo's copies and ships them with the pages.
Every so often, and as it stops#
Process.set_interval!(ms, tick!) runs tick! every ms milliseconds while the server runs, and Process.on_stop!(last!) runs last! once as it stops: a buffer kept in memory, written now and then, and once more on the way out. Both are set at the start, in your init! or a plugin's start; the auth plugin writes who was last seen this way, and the PostHog plugin sends the errors it kept.
init! = |started| {
_clear = Process.set_interval!(10_000, flush!) # clear!() stops it
Process.on_stop!(flush!)
Ok(started)
}- Each run is a call of its own, so it may use the database,
KvorHttp. It startsmsafter the last one ended, so runs never overlap; one that crashes is logged, and the next runs as set. - The function
set_interval!returns stops it, from anywhere: the run under way finishes, and none follows. - When the server stops, no run starts; one under way finishes. Then the stop hooks run, in the order they were set, within the server's ten seconds of grace.
- Set anywhere but the start, the call crashes: the host keeps the function, and one a request made could be freed by that request crashing. Nothing polls: the host waits on a timer, the interval being cleared and the stop at once.
- It is in memory, for this process. A schedule that must hold across restarts is a job's (the jobs plugin's
crons).
Background loops and isolated calls#
At start, the server asks the platform's Roc which loops to run in the background: plugins' loops (the jobs plugin's workers, schedules and hourly sweep of finished jobs) and checks (the email plugin's look at the SMTP server). Each runs as its own call until the server stops; one that crashes restarts a second later. A loop sleeps with Live.next!, which wakes on a publish to a topic it listens to, when its time is up, or with Gone at shutdown. Db.notify! (and Postgres's NOTIFY) publish on db:<channel>: that is how job workers sleep until a job is queued.
An isolated call runs Roc inside another call, guarded on its own: a crash ends it alone, and the caller learns why. Plugins use them (Plugin.isolated!); the jobs plugin runs each job in one, so a crashing job just fails and the worker goes on.
An actor's turn is a guarded call too: its mailbox, in the host, runs it with the kind, key, state and message as strings, so a crash frees them all. No lock is taken: one task routes each message to its actor's mailbox, and each actor handles its messages one at a time (actors).
Plugins#
A plugin is a package that adds what only the server runs: tables, background loops, files, scripts every page loads, development pages, work at start, checks; never a route. Name the package in the app's header and list its plugin in the program. The jobs, email, auth, push, Stripe and audio packages, among others, are plugins.
app [program] { pf: platform "../server/platform/main.roc", acme: "../packages/acme/main.roc" }
import acme.Acme
program = App.program({
init!,
plugins: [Acme.plugin({})],
})A plugin is one value, a Plugin.Value, made by its package from its own options:
- No routes. Every URL is a file under the app's
routes/(D-116). A package that answers requests offers handlers for the app's own route files (respond! = |{ request, .. }| JobsPage.respond!(request, { mount: "/admin/jobs" })), wherever the app puts them, behind that folder's middleware. - Tables (migrations) are applied after the platform's and before the app's, recorded under the plugin's name; a plugin may list one per database flavor.
- Calls, loops, starts and checks get the app's context (from its
init!) without knowing its type (Plugin.Value(context)). - Needs the compiler can't check: an environment variable, a database (any, or Postgres or SQLite only), another plugin.
- Files and scripts, below.
At start, the server checks every plugin and stops on any problem, listing them all: two development pages at one method and path, a file at the root where the app has a route, two files at one place, a name used twice, a need not met. Then it names the plugins on one line of the log (what each added too, under --debug).
A plugin package names the server platform in its header, as an app does; a second header, browser.roc, lists the modules the browser's copy of the app can compile too.
A plugin's files are embedded at build (with an import … : List(U8), below) and handed to the host at start. The host serves them before anything else, the app's middleware included, so a sign-in guard never blocks a service worker or script: at /rocx/plugins/<plugin>/<path>, or /<path> with at: Root (a service worker, whose scope is where it is), to GET and HEAD, with its content type and an ETag of its bytes (304 when the browser has them). Every server-rendered page loads the files listed as scripts, as modules before start.js. Such a script can register browser effects that Browser.call! finds as <plugin>.<effect>; each gets { under }, which puts a URL under the site's base path. The push plugin serves its service worker at the root and its script this way, and the audio plugin its player.
import "static/push-sw.js" as worker : List(U8)
import "static/push.js" as script : List(U8)
files: [
{ path: "push-sw.js", at: Root, content_type: "text/javascript", body: worker },
{ path: "push.js", at: Plugin, content_type: "text/javascript", body: script },
],
scripts: ["push.js"],Sockets and randomness#
Tcp.connect! (or connect_tls!, or start_tls! on an open socket) opens a socket for the call. write_bytes!, read_exactly!, read_up_to! and read_until! pause the call while they wait; close! closes it, and the call's end closes any left open. read_within!(tcp, max, ms) waits ms milliseconds at most and answers TimedOut if nothing came, the connection still open and nothing lost, so a loop can send a heartbeat and read on (the WebSocket package does). TLS is rustls, checked against the web's certificate authorities. Random.bytes! and Random.seed_u64! are the OS's secure randomness (crypto). The email package's SMTP client, the WebSocket package's client and roc-pg, a Postgres client in Roc, are built on these.
Not yet#
- HTTP/1.1 only, and no TLS: put the server behind a proxy that terminates TLS.
- A stack overflow in Roc still ends the process (it says so first).
- Photos' copies take a photo's colours as sRGB: one in a phone's wider colour space comes out slightly paler. No AVIF, no HEIC, no photos of other sites yet.