Skip to content
betterstack-alchemyUnofficial

Part 4: Watch It with Better Stack

Your app from Part 3 runs, but nobody would notice if it stopped. In this last part the rest of Better Stack watches it: an uptime monitor on /health, a status page that shows it, a heartbeat that a background worker reports to, the Services’ own traces, logs and metrics exported with Effect’s OpenTelemetry to a source, and error tracking. All of it lives in the same Stack as the server.

Add an uptime monitor on the Service’s /health to the Stack:

alchemy.run.ts
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 "./src/api.ts";
// …
const volume = yield* Data;
const api = yield* Api;
const uptime = yield* BetterStack.Incidents.Monitor("ApiUp", {
url: Output.interpolate`${api.url}/health`,
monitorType: "status",
checkFrequency: 60,
});
return {
ipv4: server.ipv4,
url: api.url,
volumeId: volume.id,
monitorId: uptime.id,
};
}),
);

A status monitor requests the URL every checkFrequency seconds from Better Stack’s regions and opens an incident when it fails. Output.interpolate builds the URL from api.url, which is only known after the Service is deployed, so Alchemy creates the monitor after it. Who is alerted, and how, follows your team’s settings and the monitor’s props. See Monitors.

Add a status page with a section that shows the monitor:

alchemy.run.ts
checkFrequency: 60,
});
const page = yield* BetterStack.Incidents.StatusPage("Status", {
companyName: "My App",
timezone: "UTC",
});
const section = yield* BetterStack.Incidents.StatusPageSection("Core", {
statusPageId: page.id,
name: "Core services",
});
yield* BetterStack.Incidents.StatusPageResource("ApiItem", {
statusPageId: page.id,
statusPageSectionId: section.id,
resourceType: "Monitor",
resourceId: uptime.id,
publicName: "API",
});
return {
ipv4: server.ipv4,
url: api.url,
volumeId: volume.id,
monitorId: uptime.id,
statusPage: page.publicUrl,
};
}),
);

A status page shows your users the health of your services. What it shows is organized in sections, each listing resources: here one section, “Core services”, holding the monitor under the public name “API”. subdomain is left out, so Alchemy generates a unique one, and page.publicUrl is where the page lives. See Status pages.

A monitor checks from the outside; a heartbeat waits to be called. Create src/monitoring.ts:

src/monitoring.ts
import * as BetterStack from "betterstack-alchemy";
/** The worker reports to it every minute; silence past the grace period opens an incident. */
export const WorkerAlive = BetterStack.Incidents.Heartbeat("WorkerAlive", {
period: 60,
grace: 60,
});

Better Stack alerts when no ping arrives within grace seconds after each period. The heartbeat’s url is the whole credential, so it is a secret and comes back Redacted. See Heartbeats.

Create src/worker.ts, a second Service on the same server, with no port:

src/worker.ts
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 Schedule from "effect/Schedule";
import { WorkerAlive } from "./monitoring.ts";
import { Box } from "./server.ts";
/** The worker's job, run every minute: replace it with your own. */
const runJob = Effect.fn("runJob")(function* () {
yield* Effect.logInfo("job done");
});
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(runJob()).pipe(
Effect.ignore,
Effect.repeat(Schedule.spaced("1 minute")),
Effect.asVoid,
),
),
);
}).pipe(
Effect.provide(
Layer.mergeAll(
BetterStack.Incidents.SendHeartbeatHttp,
BetterStack.Incidents.ReportHeartbeatHttp,
),
),
),
) {}

Incidents.heartbeatJob wraps the job: 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 binding gives the worker only the heartbeat’s URL, as a secret in its environment; SendHeartbeatHttp and ReportHeartbeatHttp are the layers that send the pings. ServerHost.run registers the loop, and withHostRuntime gives it the host’s runtime, which the binding needs. If the worker or the whole server stops, the pings stop and the heartbeat opens an incident after the grace period.

runJob is written with Effect.fn("runJob"), Effect’s way to name a unit of work. That name becomes a span once the worker exports its telemetry, a few steps below.

Yield the worker in the Stack:

alchemy.run.ts
import * as Effect from "effect/Effect";
import Api from "./src/api.ts";
import { Box, Data } from "./src/server.ts";
import Worker from "./src/worker.ts";
export default Alchemy.Stack(
"MyApp",
// …
const server = yield* Box;
const volume = yield* Data;
const api = yield* Api;
const worker = yield* Worker;
const uptime = yield* BetterStack.Incidents.Monitor("ApiUp", {
url: Output.interpolate`${api.url}/health`,
// …
volumeId: volume.id,
monitorId: uptime.id,
statusPage: page.publicUrl,
workerUnit: worker.unitName,
};
}),
);

Effect has tracing, structured logging and metrics built in, and its OTLP exporters send spans, Effect.log* lines and Metrics as OpenTelemetry. They only need a destination. Add a source to src/monitoring.ts:

src/monitoring.ts
period: 60,
grace: 60,
});
/** Where the Services' traces, logs and metrics go. */
export const Otel = BetterStack.Telemetry.Source("Otel", { platform: "open_telemetry" });

A source is a stream of logs, metrics or traces ingested into Better Stack. platform: "open_telemetry" sets it up for OpenTelemetry, and one such source takes all three signals. platform can’t change later: changing it replaces the source and deletes its data. See Sources & ingest.

Name the file write with Effect.fn, put its path and size on the span, count it with two metrics, log it with structured fields, and provide Telemetry.Export on the Api:

src/api.ts
import * as FileSystem from "effect/FileSystem";
import { HttpServerRequest } from "effect/http/HttpServerRequest";
import * as HttpServerResponse from "effect/http/HttpServerResponse";
import * as Metric from "effect/Metric";
import { Otel } from "./monitoring.ts";
import { Box, Data } from "./server.ts";
const filesWritten = Metric.counter("files_written", {
description: "Files stored on the volume",
incremental: true,
});
const fileSize = Metric.histogram("file_size_bytes", {
description: "Size of the stored files",
boundaries: [1_000, 10_000, 100_000, 1_000_000],
});
/** Store one file: a span named `writeFile`, its path and size on the span, two metrics, a log line. */
const writeFile = Effect.fn("writeFile")(function* (file: string, body: string) {
const fs = yield* FileSystem.FileSystem;
yield* fs.writeFileString(file, body);
const bytes = new TextEncoder().encode(body).byteLength;
yield* Effect.annotateCurrentSpan({ "file.path": file, "file.bytes": bytes });
yield* Metric.update(filesWritten, 1);
yield* Metric.update(fileSize, bytes);
yield* Effect.logInfo("file written").pipe(Effect.annotateLogs({ file, bytes }));
});
export default class Api extends BetterStack.Cloud.Service<Api>()(
"Api",
{ server: Box, main: import.meta.url, port: 3000 },
// …
if (request.method === "PUT") {
const body = yield* request.text;
yield* writeFile(file, body);
yield* fs.writeFileString(file, body);
return HttpServerResponse.empty({ status: 204 });
}
// …
return HttpServerResponse.text("Hello from Better Stack Cloud!");
}).pipe(Effect.orDie),
};
}).pipe(
Effect.provide(BetterStack.Cloud.MountVolumeLive),
Effect.provide(BetterStack.Telemetry.Export({ source: Otel, serviceName: "api" })),
),
}).pipe(Effect.provide(BetterStack.Cloud.MountVolumeLive)),
) {}
  • Effect.fn("writeFile") makes every call a span named writeFile.
  • Effect.annotateCurrentSpan puts what you know about the work on that span as attributes, instead of formatting it into a log message.
  • Effect.logInfo with Effect.annotateLogs writes a log line whose file and bytes are fields you can filter on.
  • Metric.counter and Metric.histogram, updated with Metric.update, become the metrics files_written and file_size_bytes.
  • Telemetry.Export({ source: Otel, serviceName: "api" }) is the only wiring: at deploy it binds the source’s OTLP endpoints, https://<ingestingHost>/v1/traces, /v1/logs and /v1/metrics, and Authorization: Bearer <source token> as a secret onto the Api, and at runtime Alchemy’s exporter sends all three signals in batches.

The Api receives only the source’s own token, which can only write into that source, never your API token. Every span, log line and metric series counts against your team’s telemetry ingestion.

The same layer on the worker, under its own service name:

src/worker.ts
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schedule from "effect/Schedule";
import { Otel, WorkerAlive } from "./monitoring.ts";
import { WorkerAlive } from "./monitoring.ts";
import { Box } from "./server.ts";
/** The worker's job, run every minute: replace it with your own. */
// …
}).pipe(
Effect.provide(
Layer.mergeAll(
BetterStack.Telemetry.Export({ source: Otel, serviceName: "worker" }),
BetterStack.Incidents.SendHeartbeatHttp,
BetterStack.Incidents.ReportHeartbeatHttp,
),

Each runJob is now a span, and its job done line a log record, in the same source as the Api’s.

Add an error-tracking application to src/monitoring.ts:

src/monitoring.ts
/** Where the Services' traces, logs and metrics go. */
export const Otel = BetterStack.Telemetry.Source("Otel", { platform: "open_telemetry" });
/** Where the Api's exceptions go: a Sentry-compatible DSN. */
export const Errors = BetterStack.Errors.Application("Errors", { platform: "node_errors" });

and bind its DSN in the Api:

src/api.ts
import { HttpServerRequest } from "effect/http/HttpServerRequest";
import * as HttpServerResponse from "effect/http/HttpServerResponse";
import * as Metric from "effect/Metric";
import { Errors, Otel } from "./monitoring.ts";
import { Otel } from "./monitoring.ts";
import { Box, Data } from "./server.ts";
const filesWritten = Metric.counter("files_written", {
// …
{ server: Box, main: import.meta.url, port: 3000 },
Effect.gen(function* () {
const mount = yield* BetterStack.Cloud.MountVolume(Data, { path: "/data" });
yield* BetterStack.Errors.Dsn(Errors);
return {
fetch: Effect.gen(function* () {
// …
}).pipe(
Effect.provide(BetterStack.Cloud.MountVolumeLive),
Effect.provide(BetterStack.Telemetry.Export({ source: Otel, serviceName: "api" })),
Effect.provide(BetterStack.Errors.DsnLive),
),
) {}

Errors.Dsn puts the application’s DSN into the Api’s environment as SENTRY_DSN, the variable every Sentry SDK reads, so a Sentry SDK you add and initialize in the Api reports its exceptions to Better Stack without a dsn option. A DSN can only report events into its application. See Applications.

Terminal window
bun alchemy deploy

The plan creates the monitor, the status page with its section and resource, the heartbeat, the worker, the Otel source and the Errors application, and updates the Api. The deploy prints the status page’s URL and the worker’s unit name.

Terminal window
# Store a file: one writeFile span, one log line, two metric updates
curl -X PUT --data 'hello' http://<ipv4>:3000/hello.txt
# The worker's runs, from its journal
ssh root@<ipv4> journalctl -u <workerUnit> -f

Then look in Better Stack:

  • Logs and spans: open the Otel source in Live tail. file written arrives with file and bytes as fields, and every minute a job done from the worker.
  • Traces: writeFile and runJob are spans with their attributes; filter by service (api, worker) or operation name. See Tracing.
  • Metrics: chart files_written and file_size_bytes on a dashboard.
  • Uptime: open the statusPage URL to see the API listed under “Core services”. Stop the worker with systemctl stop <workerUnit> and, after the grace period, the heartbeat opens an incident.

The endpoints and the Authorization header are the ones Better Stack’s OpenTelemetry guide gives. That guide doesn’t say which OTLP encoding it accepts over HTTP; the export sends traces and logs as OTLP/JSON and metrics as OTLP/protobuf. On 2026-12-01 this export was run against a real Better Stack source: all three signals were accepted (2xx) and the rows were queried back seconds later. It ran from a local Node process with the environment the layer binds onto a host, not from a Service on a server; see Live verification.

Telemetry.Export is the one log path on these hosts. Telemetry.ShipLogs, which sends Effect’s log lines as plain JSON events, can’t share a host with it in this Alchemy beta: each installs the host’s logger set, and the later one replaces the other. See Sources & ingest.

When you’re done, delete everything so the server and volume stop billing:

Terminal window
bun alchemy destroy

Alchemy deletes in reverse dependency order. The Services go first: their units are stopped and disabled, and their files and the /data mount removed. Then the rest: the monitoring resources, the volume (detached first), the server with its deploy key, the firewall and your SSH key.

Over four parts you built one app on Better Stack:

  • An AM1 server behind a firewall, with an Alchemy-managed deploy key
  • An HTTP Service and a background worker, bundled, shipped over SSH and supervised by systemd
  • A volume mounted at /data whose files outlive deploys
  • An uptime monitor, a status page and a heartbeat watching it all
  • Spans, structured logs and metrics written with Effect, exported to one OpenTelemetry source, and a DSN for error tracking