# Logs, spans and metrics with OpenTelemetry

- Published: 2026-11-22
- Updated: 2026-11-26
- Tags: Effect on the Backend, Effect, TypeScript
- URL: https://devtrillo.com/writing/effect-backend-15-logs-spans-and-metrics/

> Part 15 of a series that builds one backend server on Node with Effect 4. The code is in [devtrillo/effect-on-the-backend](https://github.com/devtrillo/effect-on-the-backend/tree/part-15), and this part is the `part-15` tag.

Every service method since [part 2](/writing/effect-backend-2-effect-fn-functions-with-names-and-traces/) is an `Effect.fn` with a `Service.method` name, and every one of them makes a span. [Part 14](/writing/effect-backend-14-background-jobs-and-graceful-shutdown/) ended with none of them ever leaving the process. This part ships them to an OpenTelemetry collector, with the logs and one metric.

Then it follows a single `POST /users` from the request to the welcome mail the worker sends after it.

## No new dependency

The plan for this part said `@effect/opentelemetry`. Effect 4 doesn't need it.

`effect/observability` has an OTLP exporter of its own that speaks the protocol over the `HttpClient` the server already has, with no OpenTelemetry SDK underneath. The observability page in the package's `ai-docs` says to use those `Otlp` modules in new projects and to reach for `@effect/opentelemetry` when you're joining an existing OpenTelemetry setup. This server has nothing to join.

```ts title="src/Telemetry.ts"
import { Layer } from "effect"
import { FetchHttpClient } from "effect/http"
import { Otlp, OtlpSerialization } from "effect/observability"

// Logs, spans and metrics over OTLP/HTTP, set up by the standard OTEL_* environment variables.
// Without OTEL_EXPORTER_OTLP_ENDPOINT it exports nothing, and the server runs as it did in part 14.
export const TelemetryLive = Otlp.layerFromConfig({
  resource: { serviceName: "effect-on-the-backend" },
}).pipe(Layer.provide([OtlpSerialization.layerJson, FetchHttpClient.layer]))
```

`main.ts` gains one `Layer.provide`, on the outside of everything:

```ts title="src/main.ts (excerpt)"
// Telemetry is provided last, so it's built first and closed last: the drain's spans and logs still get out.
Layer.launch(Server.pipe(Layer.provide(TelemetryLive))).pipe(NodeRuntime.runMain)
```

The order matters for the same reason it did in part 14. Layers close in reverse, so the HTTP server stops first, then the welcome queue drains. Only then does the exporter do its final flush, with 3 seconds to finish it.

Until then it batches: spans go out every 5 seconds, logs every second, metrics every 10. `effect/observability` is `@stability unstable` in 4.0.5, like `effect/http`.

## Four environment variables, not one

`layerFromConfig` reads the variables every OpenTelemetry SDK reads, so the same image can point at a different collector without a code change. I set `OTEL_EXPORTER_OTLP_ENDPOINT` and sent a few requests. The collector got nothing. No warning either.

The exporter also checks `OTEL_TRACES_EXPORTER`, `OTEL_LOGS_EXPORTER` and `OTEL_METRICS_EXPORTER`, and installs itself only when the value includes `otlp`. In the [OpenTelemetry spec](https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/) all three default to `otlp`. In Effect 4.0.5 they default to an empty list (`internal/otlpEnv.ts`), so each signal stays off until you name it:

```sh title=".env.example"
DATABASE_URL=postgres://app:change-me@localhost:5432/app
# Part 15: send logs, spans and metrics to the collector in compose.yaml.
# Remove these four lines and the server exports nothing.
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
OTEL_TRACES_EXPORTER=otlp
OTEL_LOGS_EXPORTER=otlp
OTEL_METRICS_EXPORTER=otlp
```

I'm keeping the off-by-default behaviour. The tests and a plain `npm start` without the lines export nothing, which is what I want from both.

The collector is `grafana/otel-lgtm` 0.38.1 in `compose.yaml`: an OpenTelemetry Collector with Tempo for traces, Loki for logs and Prometheus for metrics, all behind Grafana. It's a development image, not something to run in production. Grafana goes on port 3030, because 3000 is the server.

## One POST /users

With the fake mail service on its default `503,hang`, one `POST /users` answered 201 in 17 ms. Tempo then had this trace (from its API, indented by parent):

```text title="One POST /users in Tempo, 14 spans"
POST                         +0.0 ms     16.4 ms  201
  Authorization.bearer       +0.5 ms     15.5 ms
    Tokens.verify            +0.6 ms      3.8 ms
      postgres               +0.8 ms      3.3 ms  SELECT u.id::text, u.name, u.email FROM api_tokens ...
    Users.create             +5.4 ms     10.1 ms
      sql.transaction        +5.5 ms     10.0 ms  user.id 30
        postgres             +7.0 ms      1.9 ms  INSERT INTO users ...
        postgres             +9.0 ms      2.9 ms  INSERT INTO user_events ...
    WelcomeJobs.enqueue     +15.7 ms      0.2 ms
      WelcomeJobs.send      +16.8 ms   2699.1 ms
        Mailer.welcome      +17.1 ms   2698.6 ms  user.id 30
          POST              +17.5 ms      6.7 ms  503, error
          POST             +255.9 ms   2006.1 ms  (timed out)
          POST            +2712.1 ms      3.4 ms  202
```

I wrote five of those names.

The server span comes from the HTTP server's tracer middleware, named after the method and carrying `http.route: /users`. The `postgres` spans come from `effect/sql`, with the statement in `db.query.text` and the values left out, since they're bound as `$n` parameters. The three client `POST`s are part 13's retries, one span per attempt, and the backoff shows in the gaps between them.

`Authorization.bearer` wraps everything else because the middleware runs the handler inside itself.

The client also sends the trace on: pointed at a server that logged headers, the mail request arrived with `traceparent: 00-5bf92f35...-01`, the same trace id as the incoming request. A mail service that also exported spans would show up in this trace too.

## The worker had no span

The bottom five spans weren't there on the first try.

Part 14 left a note about this. The worker runs on its own fiber, forked when the layer was built, and no request was in flight at that point. So `send` had no current span to be a child of, and every `WelcomeJobs.send` became the root of a new trace.

In Tempo that was a 9-span trace for the request and a separate 5-span trace for the mail, with nothing linking them except the user id.

The fix is to carry the span through the queue:

```ts title="src/WelcomeJobs.ts (excerpt)"
// The span that was current when the job was queued travels with it, so the send joins the request's trace.
interface Job {
  readonly welcome: Welcome
  readonly parent: Tracer.Span
}

// in the worker
Effect.flatMap((job) => send(job.welcome).pipe(Effect.withParentSpan(job.parent))),

// in the service
enqueue: Effect.fn("WelcomeJobs.enqueue")(function* (welcome: Welcome) {
  // Inside a named Effect.fn there is always a current span: this one, WelcomeJobs.enqueue.
  const parent = yield* Effect.orDie(Effect.currentSpan)
  yield* Queue.offer(queue, { welcome, parent })
}),
```

`Effect.currentSpan` can fail with `NoSuchElementError` when there's no span, and the `orDie` keeps that out of the handler's error type. It can't happen here, since the code runs inside its own named `Effect.fn`.

A span link would be the other option: `Effect.linkSpans` puts the send in its own trace with a pointer back to the request. OpenTelemetry's messaging conventions allow both. I picked the child. One request queues exactly one mail, and I want to see them together.

The cost is that the trace now lasts 2.7 seconds while its root span lasts 16 ms, so anything that reads the trace's total duration as request latency will be wrong. Read the server span instead.

This only works because the queue lives in memory and a `Tracer.Span` is an object. Part 14's outbox idea would store jobs in Postgres, and then the job would carry the `traceparent` string instead.

**Quiz:** The new WelcomeJobs test runs enqueueThenShutDown inside a span named request. With withParentSpan removed, the server puts each send in a trace of its own. What's the send's parent in the test?

- None, same as on the server
- The request span
- WelcomeJobs.enqueue

**Answer:** The request span — The test builds WelcomeJobs.layer inside the request span, so the worker is forked under it and inherits it. That's why the test asserts the parent is WelcomeJobs.enqueue rather than only checking that some parent exists. I checked: with the fix removed, it fails with expected 'request' to equal 'WelcomeJobs.enqueue'.

- Not "None, same as on the server": That's what the server does, but the test builds the layer differently.
- Not "WelcomeJobs.enqueue": Only withParentSpan makes it that.

## Logs know their trace

None of the `Effect.log` calls changed. The OTLP logger is added next to the console logger, not in place of it, so the terminal looks like it did in part 14 and Loki gets a copy of every line. Each record logged inside a span carries `trace_id` and `span_id`.

With `MAIL_FAILS=422`, the mail service rejected the send.

The warning `welcome mail not sent` landed in Loki with `trace_id 4bf92f35...`, the trace of the `POST /users` that queued it. Searching Loki for that one id gives you two lines: the request's `Sent HTTP response` and the worker's warning. Before the fix, the warning would have had the mail's separate trace id instead.

Logs also become events on their span, so the same warning shows up in Tempo on `WelcomeJobs.send`. Logs from outside any request, like `Listening on` or `draining welcome queue`, reach Loki with no trace id at all.

## One metric

The HTTP server makes spans but no metrics. After all that traffic, Prometheus had exactly one series from the server, and I'd put it there.

Request rates and latency histograms can come from the spans (the collector's spanmetrics connector does that), so the server only counts what the spans can't easily answer, which is how many welcome mails failed today:

```ts title="src/WelcomeJobs.ts (excerpt)"
// One counter, split by result. Prometheus shows it as welcome_mails_total{result="sent"|"failed"}.
const mails = Metric.counter("welcome_mails", { description: "Welcome mails, by result", incremental: true })
const sent = Metric.withAttributes(mails, { result: "sent" })
const failed = Metric.withAttributes(mails, { result: "failed" })
```

`send` calls `Metric.update(sent, 1)` after the mail goes out and `Metric.update(failed, 1)` next to the warning.

After the 422 run, Prometheus answered `welcome_mails_total` with one series per result, both at 1. The `_total` suffix comes from the collector's Prometheus translation, not from Effect. Interrupted mails aren't counted: part 14 already logs their ids, and they only happen at shutdown.

## Tests

Two new tests in `test/WelcomeJobs.test.ts`.

One gives the layer an in-memory `Tracer` (part 2's `spans.ts` trick) and checks that `WelcomeJobs.send` is a child of `WelcomeJobs.enqueue` and shares the request's trace id. The other provides a fresh `Metric.MetricRegistry`, queues two mails and reads `{ count: 2 }` back from `Metric.snapshot`. Both fail when I remove the line they test.

`npm test` is 36 passed plus part 12's expected fail.

## Gotchas

- **A dead collector is silent.** Point the endpoint at a port with nothing on it and the server runs normally, logs nothing and exports nothing. After a failed export the exporter turns itself off for 60 seconds, and it says so only at `Debug`.
- **`annotateCurrentSpan` annotates whatever span is current.** `Users.create` sets `user.id`, but `sql.withTransaction` runs the body inside a `sql.transaction` span, so that's where it ended up (see the trace above). `Users.create` itself only has `db.system`.
- **The server span is called `POST`.** The route is in `http.route`, not in the name, so a list of traces in Grafana shows a column of identical names. Filter on the attribute.
- **Telemetry didn't slow shutdown down.** `kill -TERM` with no traffic: 0.16 s to exit with the exporter on, 0.09 s with it off.

**Quiz:** You set OTEL_EXPORTER_OTLP_ENDPOINT and OTEL_TRACES_EXPORTER=otlp, and nothing else. What reaches the collector?

- Spans, logs and metrics
- Only spans
- Nothing, the endpoint needs /v1/traces at the end

**Answer:** Only spans — Each signal checks its own OTEL_*_EXPORTER. Logs and metrics stay off, and nothing in the log tells you.

- Not "Spans, logs and metrics": The OpenTelemetry spec would say yes, since the other two default to otlp there. In Effect 4.0.5 they default to nothing.
- Not "Nothing, the endpoint needs /v1/traces at the end": That's for OTEL_EXPORTER_OTLP_TRACES_ENDPOINT. The base endpoint gets /v1/traces, /v1/logs and /v1/metrics added for you.

## Run it

```sh
git clone https://github.com/devtrillo/effect-on-the-backend
cd effect-on-the-backend
git checkout part-15
npm install
npm test
docker compose up -d --wait
cp .env.example .env
npm run mail
```

Then `npm start` in a second terminal, part 11's curl in a third, and open Grafana on http://localhost:3030. Explore → Tempo → search for `WelcomeJobs.send` finds the trace above, and the `user.id` attribute narrows it to one user. The repo stays on `effect` 4.0.5; 4.0.6 is out, and nothing here needed it.

The `traceparent` header already crosses from this server to the mail service. If that service were also written with Effect, the next question is whether its callers should talk HTTP to it at all.

Next in the series: RPC or HttpApi?

- **Part 16 — RPC or HttpApi?**: The users endpoints served a second time over effect/rpc, next to the HttpApi: a smaller contract, errors as classes and one trace across two processes, but every answer is a 200.
