Back

Every Failed Email, Traced

By Pablo Fernandez7 min read

A reply sent from the Gmail app sat on "Sending" long enough that I went looking for where Mailingest had lost it. It hadn't. Mailingest records a row per stage of every message in ClickHouse, and those rows said the reply was accepted in a second and delivered to Gmail in three. The wait was the app's.

That answered when. It couldn't answer the question that comes next, the one I'll need the day the slow part really is mine: inside those three seconds, which service was working, which was waiting, and on what? Rows per stage don't show that. A trace does: one tree of spans per message, from the SMTP door to the remote mail server, across every service it touches. The trouble is that a trace for every message is a lot of data to keep for the few you'll ever open, and the obvious fix, keeping a random few percent, throws away exactly the ones you'd open.

One message, one trace

A trace only helps if a message stays one trace as it crosses services, and Mailingest's services talk through NATS JetStream, not HTTP. So every message published to a stream carries a W3C traceparent header, and the consumer on the other side opens its consume span as a child of the publisher's. Mail that comes in by SMTP starts its own trace with a root span, smtp.message; mail sent through the API starts it at the HTTP request.

span service──────────────────────────────── ────────http POST /v1/emails api└─ consume delivery-outbound delivery └─ consume egress-shared egress └─ the remote MX, or back in through the routerevery hop between services is a JetStream messagewith a traceparent header
A message sent through the API, as one trace: each service's span is a child of the one that handed it the message.

In the dev stack, with a collector and Grafana Tempo running, that holds for the three paths I care about: incoming mail (door, then router), SMTP submission (submission, delivery, egress, router) and the API (API, delivery, egress, router). One message, one trace: on a freshly started dev stack, an API send to a local mailbox took 1.4 seconds end to end, and a full second of it was the router waiting for rspamd. That's the kind of thing the stage rows never showed.

Why a random sample misses

The usual way to keep tracing affordable is head sampling: decide at the first span, roll a die, keep 5% of traces. It's cheap because nothing waits. It's also blind, because at the first span nobody knows how the message will end. If one message in a thousand is deferred by a remote server, a 5% head sample keeps one in twenty of those, and the trace you want is almost never there.

Tail sampling decides at the end. Every service sends all its spans to an OpenTelemetry Collector, the collector holds each trace for a while as its spans arrive, and only then asks whether it's worth keeping. The cost moves from storage to memory: you pay for holding a few seconds of traffic instead of storing days of it.

Five reasons to keep a trace

The collector's tail sampling processor runs a list of policies against each finished trace, and if any of them says sample, the trace is kept. This is the list, from otel-collector.yaml in my infrastructure repo:

otel-collector.yaml
tail_sampling:
  decision_wait: 30s
  num_traces: 50000
  expected_new_traces_per_sec: 50
  decision_cache:
    sampled_cache_size: 100000
  policies:
    - name: errors
      type: status_code
      status_code:
        status_codes: [ERROR]
    - name: failed-mail
      type: boolean_attribute
      boolean_attribute:
        key: mail.failed
        value: true
    - name: not-handled-at-once
      type: string_attribute
      string_attribute:
        key: outcome
        values: [retry, dropped, buried]
    - name: slow
      type: latency
      latency:
        threshold_ms: 5000
    - name: some-of-the-rest
      type: probabilistic
      probabilistic:
        sampling_percentage: 5

Each one exists because of a different way a message goes wrong:

  • An error inside a span: any span whose status is error, which in Mailingest is what an ERROR log inside a span produces.
  • Mail that didn't get through somewhere: this one needed code. Ten stages count as a failure for a message or one of its recipients (refused at the door, rejected by the router, a failed delivery, a deferral or a bounce at egress or relay, a webhook that failed), and when any of them is recorded, the current span gets mail.failed = true. A remote server answering "try again later" isn't an error in the code; it's a perfectly normal outcome, and it's also exactly the message someone will ask about.
  • Not handled at once: every consume span records how the handler finished. done is the normal case; retry means it'll be redelivered later, dropped that it can never succeed, buried that it can never succeed and was set aside in the dead letters to look at.
  • Slow: more than five seconds from the trace's first span to its last.
  • Five percent of everything else: the boring, healthy traces, so there's always a normal one to compare a bad one against.

A Grafana-style Tempo trace view of a message sent through the API: three spans, http POST /v1/emails in the api service for 239 ms, consume delivery-outbound in delivery for 98 ms, and consume egress-shared in egress for 4.18 s, which is selected and shows its attributes: consumer egress-shared, subject egress.deliver, outcome done, and mail.failed true, highlighted
A trace the slow policy would have dropped: 4.53 seconds is under the bar. It's kept because egress marked it mail.failed.

The screenshot is a mock-up in Grafana's style: the span names, consumers and attributes are Mailingest's, the ids and timings are made up. It shows why the policies overlap on purpose. That message took 4.53 seconds, under the slow bar, and its handler finished done, because a deferral is a handled outcome, not a crash. Only mail.failed catches it.

Thirty seconds of memory

Deciding at the end means deciding when the end has come, and a collector can't know that a trace has no more spans on the way. So it waits a fixed time from a trace's first span, 30 seconds here, and decides then. Thirty seconds is longer than any healthy message takes, so by then the trace is complete.

That wait is paid in memory: every trace of the last 30 seconds is held in full. The config sizes it for 50 new traces a second, room for 50,000 traces at once, and a memory limiter in front:

otel-collector.yaml
memory_limiter:
  check_interval: 1s
  limit_mib: 300
  spike_limit_mib: 60

The container itself gets 384 MiB. If a burst ever fills that, the limiter starts refusing spans before the process runs out of memory: a burst costs some traces, never the collector.

There's one kind of message for which 30 seconds is not the end. A deferred message is tried again minutes or hours later, and the retry adds spans to the same trace, long after its decision. The collector keeps a cache of the last 100,000 trace ids it decided to keep, so late spans of a kept trace are kept too. If the first attempt wasn't kept, the late spans are decided again as a trace of their own, and since a retry that fails again marks mail.failed, it's kept then.

0 s first span arrives, the trace starts waiting0-30 s the other services' spans join it in memory30 s five policies asked, any yes keeps it kept ──▶ Tempo, 7 days not kept ──▶ droppedlater a retry adds spans trace was kept ──▶ kept as well it wasn't ──▶ decided again, alone
The life of a trace in the collector: held for 30 seconds, then kept or dropped; a retry hours later joins it or is decided on its own.

What a trace is allowed to say

Traces get looked at by people who shouldn't be reading mail, so they carry span names, ids, timings and outcomes, and no message content or addresses. The HTTP span is the one place that needed care: it records the route as written, /unsubscribe/{token}, never the path that was asked for, because some paths carry single-use tokens (unsubscribing, confirming a destination, signing out everywhere), and anyone who could read a trace could have used them.

Tempo keeps what the collector sends for seven days, on local disk, which is the same time the per-stage rows are kept in ClickHouse. That's deliberate: the staff screen that shows a message's stages links to its trace, and a link that opens nothing on day five would be worse than no link. Grafana, which reads Tempo, is reachable only over Tailscale: anyone on the private network can read traces, and changing anything takes the admin password.

All of this is written and checked with otelcol validate, and proven in the dev stack, where every path above produces one trace. It isn't in production yet; that's the next deploy. One property I like is written in a comment next to the endpoint: while the collector is down, spans are dropped and nothing else notices. Tracing is something Mailingest does for me, so it's never allowed to be something mail waits on.

The trade underneath is small and worth stating. A random sample saves storage and loses the traces that matter. Tail sampling keeps those by holding 30 seconds of traffic in memory and asking five plain questions about each message once it's done. Most of the work wasn't the config; it was making the code say, on the span, what went wrong in a way a policy can match, so that a deferral counts as a failure even when no code failed.

Related articles

Every AI Call Gets a Receipt

One AI bill a month, twenty kinds of model call. How Sumalos prices every attempt as it happens and caps spending per person and per company.

AI in Every Mail Client

Email AI lives in the app you read with, so switching apps loses it. I moved it into Mailingest's server, and IMAP had a rule against it.

Every File in S3 Gets Its Own Key

Sumalos encrypts every file in its bucket with its own key, wrapped by the organization's, wrapped by a master key. A leaked bucket is noise.