Skip to content
betterstack-alchemyUnofficial

Cloud.Service

Kind ResourceType id BetterStack.Cloud.ServiceSource src/Cloud/Service.tsLive test gated Lifecycle test runs against the offline mock; a live run exists but is gated behind BETTERSTACK_TEST_CLOUD_SERVER=1 because it runs live only in the shared server suite (test/Cloud/live), one billed server per run (test/Cloud/Service.test.ts).

Your own code on a Better Stack Cloud server: an Effect program Alchemy bundles with Rolldown, copies over SSH to a Server, and runs as a systemd unit with Restart=always. HTTP Services (fetch, gated on /health at deploy), background Services (ServerHost.run), env and Config, several Services per server, volumes through Cloud.MountVolume, a container form (context) and an async form (a plain fetch(request, env) handler). The port of @alchemy.run/hetzner’s Service: switching providers is changing the import and the server.

A Service is a class: an id, the infrastructure props, and the program. server is the machine (a Cloud.Server, or the module-scope declaration of one); main: import.meta.url makes this file the bundle’s entry; port is written to PORT. Returning fetch boots an HTTP server on that port. The resolved Service exposes url, port, unitName, serverId, ipv4/ipv6 and the bundle’s code.hash.

An HTTP Service

src/server.ts
export const Box = BetterStack.Cloud.Server("Box", {
serverType: "AM1",
image: "ubuntu-26-04",
});
// src/api.ts
export default class Api extends BetterStack.Cloud.Service<Api>()(
"Api",
{ server: Box, main: import.meta.url, port: 3000 },
Effect.gen(function* () {
return {
fetch: Effect.gen(function* () {
const request = yield* HttpServerRequest;
if (new URL(request.url, "http://x").pathname === "/health") {
return yield* HttpServerResponse.json({ ok: true });
}
return HttpServerResponse.text("hello");
}),
};
}),
) {}
// alchemy.run.ts
const api = yield* Api;
// api.url === "http://<server ipv4>:3000"

One SSH session as root with the server’s Alchemy-managed deploy key:

  1. Bundle main with Rolldown into one ESM file, index.mjs. A generated entry imports only betterstack-alchemy/Cloud/Bootstrap and your module; the bootstrap wires the Node HTTP server, logging, and Config from the environment.

  2. Wait for SSH, then for cloud-init (cloud-init status --wait: the server’s bootstrap installs Node.js), install curl/unzip if missing, and Node.js 26 from NodeSource if missing or older (a server with its own userData has none).

  3. Attach and mount any bound volumes (see “Volumes”).

  4. Copy bundle.zip, the env file and the unit, unpack into /opt/<unitName>/, systemctl daemon-reload, enable --now, restart. The unit:

    [Service]
    Type=simple
    WorkingDirectory=/opt/<unitName>
    EnvironmentFile=-/opt/<unitName>/env
    Environment=HOST=0.0.0.0
    Environment=ALCHEMY_SHUTDOWN_TIMEOUT_MS=30000
    ExecStart=/usr/bin/env node /opt/<unitName>/index.mjs
    KillSignal=SIGTERM
    TimeoutStopSec=30
    Restart=always
    RestartSec=5
  5. Wait until the unit is active and, when port is set, http://127.0.0.1:<port>/health answers 2xx (60 seconds, polled every 2). Otherwise the deploy fails with ServiceNotHealthy, whose message holds systemctl status and the unit’s last 80 journal lines.

On later deploys Alchemy compares the bundle’s content hash with the deployed one: unchanged code, env and bindings are a no-op with no SSH at all; changed code or env re-copies and restarts the unit, a few seconds end to end. A new server replaces the Service (deployed on the new server, then removed from the old). Deleting stops and disables the unit and removes its files.

systemctl stop and every redeploy’s restart send SIGTERM. The process then stops accepting connections, lets in-flight requests finish, stops ServerHost.run loops and closes its scopes, so finalizers run (a Telemetry.ShipLogs / OTLP exporter flushes its buffer) before it exits. The budget is 30 seconds (ALCHEMY_SHUTDOWN_TIMEOUT_MS, alchemy’s managed shutdown): connections still open at 80% of it are closed, and at 90% the process exits anyway, before systemd’s TimeoutStopSec would kill it. An async Service’s fetch handler gets the same drain.

Every SSH connection a deploy makes requires the server’s host key (StrictHostKeyChecking=yes against a per-session known_hosts): the key Alchemy generated and installed through the server’s bootstrap (hostKeyTrust: "pinned"), or the one recorded at the server’s first login ("first-use", a server with your own userData). A server that presents another key gets nothing — no bundle, no env file — and the deploy fails with SshError reason: "host-key-mismatch". A server with no recorded key (created before host keys were pinned, bootstrap: false) is trusted on first use for that deploy, with a warning.

On one AM1 (2026-12-01): an HTTP Service with /health and a background worker deployed, updated with new code and env, and removed cleanly (units, files and the mount gone); Cloud.MountVolume at a custom path with our fstab line once; the unit’s 30 s stop timeout; a Website.StaticSite on the same server. NOT live-verified: the container form, the async form, host-key pinning (added after that run), a step timeout, build.install.

A Service with a port must serve /health: the deploy polls it and fails, with the unit’s journal, when it never answers. Keep it trivial.

url is the server’s public IP and the Service’s port: no proxy in between. A Better Stack Cloud server with a Cloud.Firewall attached admits only what its rules allow, so open the port (and keep tcp/22 open to the deploying machine, which the deploy needs):

Open the Service’s port

const firewall = yield* BetterStack.Cloud.Firewall("Fw", {});
yield* BetterStack.Cloud.FirewallRule("Ssh", {
firewallId: firewall.id,
direction: "inbound",
protocol: "tcp",
portFrom: 22,
ipAddresses: ["0.0.0.0/0", "::/0"],
});
yield* BetterStack.Cloud.FirewallRule("Api", {
firewallId: firewall.id,
direction: "inbound",
protocol: "tcp",
portFrom: 3000,
ipAddresses: ["0.0.0.0/0", "::/0"],
});

For a stable front door with health checks and TLS, put a Cloud.LoadBalancer in front and allow the port from the private network only.

Pass values with env and read them through Effect’s Config (the runtime’s ConfigProvider reads the process environment). Alchemy also sets PORT (with port), HOST, ALCHEMY_STACK_NAME, ALCHEMY_STAGE and ALCHEMY_PHASE=runtime. A Config read in the implementation at deploy time is captured into the env as well. Redacted values (an Errors DSN, a source token, a value a binding sets through RuntimeContext) land in clear text only in the env file on the server (/opt/<unitName>/env, mode 600), never in SSH command lines, the Service’s attributes or the plan output (shown (redacted)). The state file keeps them inside the state store’s __redacted__ marker — in clear text there with the default local state, as it keeps every secret (the server’s deploy key included): protect .alchemy/state.

env + Config

export default class Api extends BetterStack.Cloud.Service<Api>()(
"Api",
{ server: Box, main: import.meta.url, port: 3000, env: { GREETING: "hello" } },
Effect.gen(function* () {
return {
fetch: Effect.gen(function* () {
const greeting = yield* Config.String("GREETING");
return HttpServerResponse.text(greeting);
}).pipe(Effect.orDie),
};
}),
) {}

Leave out port and fetch and register a long-running loop with ServerHost.run: a worker, a queue consumer, a scheduler. systemd supervises it: when the loop exits or crashes, the unit restarts after 5 seconds.

A worker

export default class Worker extends BetterStack.Cloud.Service<Worker>()(
"Worker",
{ server: Box, main: import.meta.url },
Effect.gen(function* () {
const host = yield* ServerHost;
yield* host.run(
Effect.gen(function* () {
yield* Effect.log("tick");
}).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.asVoid),
);
}),
) {}

Each Service is its own unit with its own bundle, env file and lifecycle. Point several at the same server; two Services mounting the same volume at the same path share one attach and one mount.

Bind a Cloud.Volume with Cloud.MountVolume inside the implementation and use it as a directory. The deploy attaches it to the Service’s server (Cloud API), mounts its device at the path and adds a nofail /etc/fstab line; when no Service binds the path any more it is unmounted again.

Mount a volume

export default class Api extends BetterStack.Cloud.Service<Api>()(
"Api",
{ server: Box, main: import.meta.url, port: 3000 },
Effect.gen(function* () {
const mount = yield* BetterStack.Cloud.MountVolume(Data, { path: "/data" });
return {
fetch: Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const text = yield* fs.readFileString(`${mount.path}/hello.txt`);
return HttpServerResponse.text(text);
}).pipe(Effect.orDie),
};
}).pipe(Effect.provide(BetterStack.Cloud.MountVolumeLive)),
) {}

A Service logs to the systemd journal. Read it over SSH:

Terminal window
ssh root@<sshHost> journalctl -u <unitName> -f

or from a stack with Cloud.Ssh. Ship the logs to Better Stack with a Telemetry.Source (see “Observability”). A failed deploy already prints the last 80 journal lines.

A Dockerfile build, run with Docker on the server

const worker = yield* BetterStack.Cloud.Service("Worker", {
server,
context: "./worker",
env: { QUEUE: "jobs" },
});

The image is built with the local Docker CLI for platform, saved, copied over SSH and docker loaded; the unit runs docker run --network host with the env (multi-line values included) and the bound volumes as -v <path>:<path>.

You don’t have to use Effect. Call Service with main pointing at a file and no implementation: the file is bundled with a small node:http adapter and no Effect runtime. A default export with fetch(request, env) is served on PORT; any other module simply runs (a plain Node program). InferEnv types env.

Declare an async Service

export const Ping = BetterStack.Cloud.Service("Ping", {
server: Box,
main: "./src/ping.ts",
port: 3001,
env: { GREETING: "pong" },
});
export type PingEnv = BetterStack.Cloud.InferEnv<typeof Ping>;

The handler

import type { PingEnv } from "../alchemy.run.ts";
export default {
async fetch(request: Request, env: PingEnv) {
if (new URL(request.url).pathname === "/health") return new Response("ok");
return new Response(env.GREETING);
},
};

Better Stack is also where the Service is watched from. Instrument the code with Effect’s own OpenTelemetry — a named span per unit of work (Effect.fn), attributes on the span, structured logs with annotations, Metrics — and provide ONE Telemetry.Export layer: traces, logs and metrics reach an OpenTelemetry source with that source’s own token. Error tracking (Errors.Dsn), a heartbeat (Incidents.heartbeatJob) and an uptime monitor complete it (examples/observability is this stack, runnable). Each credential arrives through a binding, as a secret in the env file only.

Spans, logs and metrics of the Api, exported to one source

export const Otel = BetterStack.Telemetry.Source("Otel", { platform: "open_telemetry" });
export const Errors = BetterStack.Errors.Application("Errors", { platform: "node_errors" });
const ordersPlaced = Metric.counter("orders_placed", { incremental: true });
const placeOrder = Effect.fn("orders.place")(function* (orderId: string) {
yield* Effect.annotateCurrentSpan({ "order.id": orderId });
yield* Metric.update(ordersPlaced, 1);
yield* Effect.logInfo("order placed").pipe(Effect.annotateLogs({ orderId }));
});
export default class Api extends BetterStack.Cloud.Service<Api>()(
"Api",
{ server: Box, main: import.meta.url, port: 3000 },
Effect.gen(function* () {
yield* BetterStack.Errors.Dsn(Errors); // SENTRY_DSN for a Sentry SDK
return {
fetch: Effect.gen(function* () {
yield* placeOrder("o-1");
return HttpServerResponse.text("ok");
}),
};
}).pipe(
Effect.provide(
Layer.mergeAll(
BetterStack.Errors.DsnLive,
BetterStack.Telemetry.Export({ source: Otel, serviceName: "api" }),
),
),
),
) {}

A heartbeat for the worker’s job, a monitor on the Api

export const JobDone = BetterStack.Incidents.Heartbeat("JobDone", { period: 300, grace: 120 });
const runJob = Effect.fn("worker.export")(function* () {
yield* Effect.logInfo("export finished");
});
export default class Worker extends BetterStack.Cloud.Service<Worker>()(
"Worker",
{ server: Box, main: import.meta.url },
Effect.gen(function* () {
const watched = yield* BetterStack.Incidents.heartbeatJob(JobDone);
const inHost = yield* BetterStack.withHostRuntime;
const host = yield* ServerHost;
yield* host.run(
inHost(watched(runJob()).pipe(Effect.ignore, Effect.repeat(Schedule.spaced("5 minutes")))),
);
}).pipe(
Effect.provide(
Layer.mergeAll(
BetterStack.Incidents.SendHeartbeatHttp,
BetterStack.Incidents.ReportHeartbeatHttp,
BetterStack.Telemetry.Export({ source: Otel, serviceName: "worker" }),
),
),
),
) {}
// alchemy.run.ts
const api = yield* Api;
yield* BetterStack.Incidents.Monitor("ApiUp", {
url: Output.interpolate`${api.url}/health`,
monitorType: "status",
});

The source token, DSN and heartbeat URL are Redacted: they reach the server only inside the env file. A failed or missing job run raises an incident; a dead Api fails the monitor.

server Server | Effect<Server, never, Providers> required

The Cloud.Server this Service runs on: the resource, or an Effect that produces it (a module-scope Cloud.Server(...) declaration). The server must have Alchemy's deploy key (the default bootstrap: true); a server with its own userData works too, and the deploy installs Node.js over SSH when it is missing. Changing the server replaces the Service.

build CloudBuildOptions

Bundler configuration for main: rolldown input/output overrides, pure-annotation options (pure), and install for packages that must ship as real node_modules (installed with npm on the server).

context string

A Docker build context the Service runs as a container instead of a bundled main: built on the deploying machine for platform, copied over SSH, loaded into Docker (installed if missing) and run under systemd on the host network. The image's own CMD runs, with env. Set this or main.

dockerfile string

The Dockerfile for context, relative to it unless absolute. Default: "Dockerfile".

env Env

Environment variables of the process, written to the unit's EnvironmentFile (mode 0600 under /opt/<unitName>/env). Values may be strings, Redacted secrets (written in clear text to that file only, never to logs or attributes), Outputs of other resources, or anything JSON-serializable. Merged after binding-injected env and Alchemy's own (ALCHEMY_STACK_NAME, ALCHEMY_STAGE, PORT), so these win.

extraFiles Array<{ source: string; destination: string; }>

Extra local files or directories packed into the unit's archive next to the entry (e.g. static assets). Hashed into code.hash, so a change redeploys. destination is relative to /opt/<unitName>/.

handler string

Named export of main to run. Default: "default".

isExternal boolean

Default: false.

main string

Module entrypoint, usually import.meta.url. Bundled with Rolldown into one ESM file and run by node under systemd. Set this or context.

platform "linux/amd64" | "linux/arm64"

The platform a context image is built for. Default: "linux/amd64".

port number

Port the HTTP server listens on. Written to PORT, gates the deploy on GET http://127.0.0.1:<port>/health, and builds the url attribute. Leave it out for a background Service (the bootstrap still serves a returned fetch on 3000, without the health gate). Default: 3000.

prebuilt boolean

main is an already-built Node program (a framework's server output): copy it and extraFiles as they are instead of bundling. Cloud.Website.* sets it. Default: false.

availabilityZone string always set

Zone the server lives in.

code { hash: string; } always set

Content hash of the deployed program (bundle + extra files, or the image's inputs).

ipv4 string always set

The server's public IPv4, if it has one.

ipv6 string always set

The server's public IPv6, if it has one.

port number always set

Port the process listens on.

serverId string always set

ID of the Cloud.Server the unit runs on.

unitName string always set

systemd unit name (<unitName>.service, files under /opt/<unitName>).

url string always set

http://<ipv4>:<port> (or http://[<ipv6>]:<port> on an IPv6-only server).

volumes Array<{ volumeId: string; path: string; }> always set

Volumes this Service mounted (from Cloud.MountVolume).