Watching your services
Better Stack is both where your code can run and what watches it. A
Cloud.Service on a Better Stack Cloud server can export
its traces, logs and metrics to a telemetry source, report exceptions to an
error-tracking application, prove it’s alive to a heartbeat, and be checked from
outside by an uptime monitor, all declared in the same stack as the server
itself.
Effect has tracing, structured logging and metrics built in, and its OTLP
exporters send spans, Effect.log* lines and Metrics as OpenTelemetry. You
instrument with Effect itself and provide one export layer, Telemetry.Export, that sends all
three signals to a source.
Take one small app: an Api and a Worker on one server. Both export to the
Otel source; the Api reports exceptions to Errors; the Worker’s job reports
to WorkerAlive; a monitor checks the Api’s /health.
- Apitraces · logs · metrics →Otel
- Apireports →Errors
- Workertraces · logs · metrics →Otel
- Workerreports each run →WorkerAlive
- ApiUpchecks /health →Api
The least credential for each wire
Section titled “The least credential for each wire”Better Stack has no IAM and no workload identity, so a host always gets a credential in its environment. Which one is decided per binding, and it is always the narrowest the platform offers:
| Wire | The host receives | What it can do |
|---|---|---|
OpenTelemetry into a Telemetry.Source (Telemetry.Export) |
the source’s /v1/* endpoints and its token, as a secret Authorization header |
write into that one source |
Pings and reports to an Incidents.Heartbeat |
the heartbeat’s secret url |
ping that one heartbeat |
Exceptions to an Errors.Application |
the application’s dsn |
report events into that one application |
| Incidents, status reports, queries, releases | the API token you pass explicitly | whatever that token can do; use a team-scoped token of the right product |
No binding ever passes your own deploy credentials to a host.
Declare what watches the Services
Section titled “Declare what watches the Services”The server and the three watchers are module-scope declarations both Services import:
/** One server; Alchemy gives it a deploy key so Services can reach it. */export const Wall = BetterStack.Cloud.Firewall("Wall", {});
export const Box = BetterStack.Cloud.Server( "Box", Effect.gen(function* () { const firewall = yield* Wall; return { serverType: "AM1", image: "ubuntu-26-04", firewallIds: [firewall.id] }; }),);/** Where the Services' traces, logs and metrics go: one OpenTelemetry source takes all three. */export const Otel = BetterStack.Telemetry.Source("Otel", { platform: "open_telemetry" });
/** Where their exceptions go (a Sentry-compatible DSN). */export const Errors = BetterStack.Errors.Application("Errors", { platform: "node_errors" });
/** The worker's job reports here every minute; a missed or failed run opens an incident. */export const WorkerAlive = BetterStack.Incidents.Heartbeat("WorkerAlive", { period: 60, grace: 60,});An open_telemetry source takes traces, logs and metrics, so one source is
enough. platform can’t change: changing it replaces the source, which deletes
its data. See Sources & ingest.
Instrument the Api with Effect
Section titled “Instrument the Api with Effect”Name each unit of work with Effect.fn("…"): every call is a span, and a
call inside another becomes its child. Put what you know about the work on the
span with Effect.annotateCurrentSpan instead of formatting it into a log
message, log with Effect.logInfo and attach fields with Effect.annotateLogs,
and count with Metric.counter and Metric.histogram, updated with
Metric.update. A typed failure stays a value you can handle, and it is
recorded on the span it left:
const ordersPlaced = Metric.counter("orders_placed", { description: "Orders accepted", incremental: true,});const orderValue = Metric.histogram("order_value_eur", { description: "Value of accepted orders, in EUR", boundaries: [10, 50, 100, 500, 1000],});
class InvalidOrder extends Data.TaggedError("InvalidOrder")<{ readonly reason: string }> {}
/** Check an order: a span of its own, the reason on the span when it fails. */const validateOrder = Effect.fn("orders.validate")(function* (valueEur: number) { if (!Number.isFinite(valueEur) || valueEur <= 0) { yield* Effect.annotateCurrentSpan({ "order.rejected_reason": "non-positive value" }); return yield* new InvalidOrder({ reason: "non-positive value" }); }});
/** Place an order: a span with the order's id and value, two metrics, a log line. */const placeOrder = Effect.fn("orders.place")(function* (orderId: string, valueEur: number) { yield* Effect.annotateCurrentSpan({ "order.id": orderId, "order.value_eur": valueEur }); yield* validateOrder(valueEur); yield* Metric.update(ordersPlaced, 1); yield* Metric.update(orderValue, valueEur); yield* Effect.logInfo("order placed").pipe(Effect.annotateLogs({ orderId, valueEur })); return { orderId, valueEur };});The handler calls it. Effect.withSpan("api.request") wraps the whole request
in a span, so orders.place and orders.validate appear as its children, and a
refused order is logged with Effect.logWarning and its reason as a field.
Nothing in this code knows where the data goes:
fetch: Effect.gen(function* () { const request = yield* HttpServerRequest; const url = new URL(request.url, "http://api"); if (url.pathname === "/health") { return yield* HttpServerResponse.json({ ok: true }); } if (url.pathname === "/orders" && request.method === "POST") { const order = yield* placeOrder( url.searchParams.get("id") ?? crypto.randomUUID(), Number(url.searchParams.get("value") ?? "0"), ); return yield* HttpServerResponse.json(order, { status: 201 }); } return HttpServerResponse.text("Not found", { status: 404 });}).pipe( Effect.catchTag("InvalidOrder", (error) => Effect.logWarning("order refused").pipe( Effect.annotateLogs({ reason: error.reason }), Effect.andThen(HttpServerResponse.json({ error: error.reason }, { status: 422 })), ), ), Effect.withSpan("api.request"), Effect.orDie,),Export it to the source
Section titled “Export it to the source”Provide Telemetry.Export on the Service’s implementation, merged with its
other binding layers. It is the only wiring: traces, logs and metrics all go to
Otel, under service.name api:
Effect.provide( Layer.mergeAll( BetterStack.Telemetry.Export({ source: Otel, serviceName: "api" }), BetterStack.Errors.DsnLive, ),),At deploy, the layer binds the source’s endpoints,
https://<ingestingHost>/v1/traces, /v1/logs and /v1/metrics, and
Authorization: Bearer <source token> (a secret) onto the host. At runtime
Alchemy’s exporter batches the signals for the process’s life and flushes them
when the Service stops. These are the endpoints and header
Better Stack’s OpenTelemetry guide
gives. That guide does not say which OTLP encoding it accepts over HTTP; this
export sends traces and logs as OTLP/JSON and metrics as OTLP/protobuf (Alchemy’s
runtime exporter, which doesn’t let a caller change it).
On 2026-12-01 that exact export was run against a real Better Stack
open_telemetry source: traces, logs and metrics were all accepted (2xx) and
the rows were queried back through the Query API seconds later. The exporter
ran in a local Node process with exactly the environment the layer binds onto a
host, not inside a Service on a Better Stack server. See
Live verification.
Every span, log line and metric series counts against your team’s telemetry ingestion. Sample high-volume traces, and keep metric attributes low-cardinality.
Report exceptions
Section titled “Report exceptions”Errors.Dsn binds the Errors application’s DSN into the Api’s environment as
SENTRY_DSN, the variable every Sentry SDK reads, so a Sentry SDK you install
and initialize in the Api reports its exceptions without a dsn option. That is
the bind line in the Api above:
// Binds SENTRY_DSN into the Api's environment; a Sentry SDK's init() reads it.yield* BetterStack.Errors.Dsn(Errors);DsnLive is provided next to the export layer. A DSN can only report events
into its application. A failure inside an Effect span is also recorded on that
span (as orders.validate records InvalidOrder), so you see it in the trace
as well. See
Applications and
Better Stack’s Sentry SDK guide.
Watch the Worker with a heartbeat
Section titled “Watch the Worker with a heartbeat”The Worker runs a job every minute under Incidents.heartbeatJob: a run that
succeeds pings WorkerAlive, a run that fails reports exit code 1 with the
failure’s cause, which opens an incident at once. The job is a span of its own
with a run counter, and the Worker exports to the same source under
service.name worker:
import { ServerHost } from "alchemy/Runtime/Process";import * as BetterStack from "betterstack-alchemy";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";import * as Metric from "effect/Metric";import * as Schedule from "effect/Schedule";import { Box, Otel, WorkerAlive } from "./shared.ts";
const syncRuns = Metric.counter("inventory_sync_runs", { description: "Runs of the inventory sync", incremental: true,});
/** The job: a span of its own, what it did as an attribute, a metric and a structured log line. */const syncInventory = Effect.fn("inventory.sync")(function* () { const items = 42; // your job's real work goes here yield* Effect.annotateCurrentSpan({ "inventory.items": items }); yield* Metric.update(syncRuns, 1); yield* Effect.logInfo("inventory synced").pipe(Effect.annotateLogs({ items }));});
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(WorkerAlive); const inHost = yield* BetterStack.withHostRuntime; const host = yield* ServerHost; yield* host.run( inHost( watched(syncInventory()).pipe( Effect.ignore, Effect.repeat(Schedule.spaced("1 minute")), Effect.asVoid, ), ), ); }).pipe( Effect.provide( Layer.mergeAll( BetterStack.Telemetry.Export({ source: Otel, serviceName: "worker" }), BetterStack.Incidents.SendHeartbeatHttp, BetterStack.Incidents.ReportHeartbeatHttp, ), ), ),) {}When the Worker stops or the server goes down, the pings stop and Better Stack
opens an incident after the grace period. withHostRuntime gives the
background loop the host’s runtime, which the heartbeat binding needs. See
Heartbeats.
Check the Api from outside
Section titled “Check the Api from outside”The monitor’s URL is the Api’s url attribute, so it follows the server’s
address:
const uptime = yield* BetterStack.Incidents.Monitor("ApiUp", { url: Output.interpolate`${api.url}/health`, monitorType: "status", checkFrequency: 60,});The whole stack, with the firewall rules that open SSH (the deploy needs it) and the Api’s port:
import * as Alchemy from "alchemy";import * as Output from "alchemy/Output";import * as BetterStack from "betterstack-alchemy";import * as Effect from "effect/Effect";import Api from "./api.ts";import { Wall } from "./shared.ts";import Worker from "./worker.ts";
export default Alchemy.Stack( "MyApp", { providers: BetterStack.providers(), state: Alchemy.localState() }, Effect.gen(function* () { const firewall = yield* Wall; for (const [id, port] of [ ["Ssh", 22], ["Http", 3000], ] as const) { yield* BetterStack.Cloud.FirewallRule(id, { firewallId: firewall.id, direction: "inbound", protocol: "tcp", portFrom: port, ipAddresses: ["0.0.0.0/0", "::/0"], }); } const api = yield* Api; const worker = yield* Worker;
const uptime = yield* BetterStack.Incidents.Monitor("ApiUp", { url: Output.interpolate`${api.url}/health`, monitorType: "status", checkFrequency: 60, });
return { apiUrl: api.url, workerUnit: worker.unitName, monitorId: uptime.id }; }),);See it in Better Stack
Section titled “See it in Better Stack”After alchemy deploy, send the Api a few orders
(curl -X POST "http://<ipv4>:3000/orders?value=42", and one with value=0
that is refused), then in Better Stack:
- Logs and spans: open the
Otelsource in Live tail.order placedarrives withorderIdandvalueEuras fields,order refusedwithreason; filter on them instead of searching the message text. - Traces:
api.requestwith its childrenorders.placeandorders.validate, and the Worker’sinventory.sync, carrying theorder.*andinventory.itemsattributes; filter by service (api,worker) or operation name. See Tracing. - Metrics: chart
orders_placed,order_value_eurandinventory_sync_runson a dashboard, or declare that dashboard in the stack withTelemetry.Dashboard. - Uptime and heartbeats:
ApiUpandWorkerAliveare under Uptime; exceptions are in theErrorsapplication.
Export logs without OpenTelemetry
Section titled “Export logs without OpenTelemetry”Telemetry.ShipLogs sends a host’s Effect.log lines to an http source as
plain JSON events, without traces or metrics. Pick one log path per host:
with alchemy@2.0.0-beta.87, ShipLogs and Telemetry.Export cannot share a
host. Both reach Alchemy’s runtime as telemetry layers that each provide the
host’s logger set, the runtime merges them with Layer.mergeAll, and the later
logger set replaces the earlier one instead of adding to it (ShipLogs’s
JSDoc in src/Telemetry/ShipLogs.ts names the runtime functions). The
bindings for sending your own events are in
Sources & ingest.
Which token deploys it
Section titled “Which token deploys it”The stack creates Cloud, Telemetry, Errors and Uptime resources, so the token in your profile must reach all four APIs: a global API token. A Cloud-only team token can’t create the source, application, heartbeat or monitor. See Teams, tokens & zones.
The bindings on this page are tested against the offline mock; of them, only
the OTLP export (and IngestLogs) has been run against a real source (see
Live verification). The same layout, as a runnable project, is
examples/observability.
Where next
Section titled “Where next”- Part 4 of the tutorial: the same wiring, step by step, on the tutorial’s app.
- Services: how a Service is deployed and run.
- Sources & ingest, Applications, Heartbeats, Monitors: each wire in depth.
- Reference:
Errors.Dsn,Incidents.SendHeartbeat,Incidents.ReportHeartbeat,Telemetry.Source.