Observability for Edge Functions: Logs, Traces, and Metrics
Edge code runs in hundreds of PoPs, lives for milliseconds, and gives you no shell. Here's how we get logs, traces, and metrics out of it anyway.
Key takeaways
- Edge functions have no shell, no disk and short lifetimes, so telemetry has to be designed in.
- Emit structured JSON logs through waitUntil after the response, sample successes, and move to platform log export such as Cloudflare Logpush as volume grows.
- Propagate a W3C traceparent header to origin from day one, and use RUM for real latency by region.
On this page
To observe edge functions, ship structured JSON logs from waitUntil after the response is sent, keep every error and sample successes, and switch to platform export (Cloudflare Logpush, Vercel drains) once volume grows. Propagate a W3C traceparent header to origin from day one. Use real-user monitoring for latency by region, because server timings can't show it.
Verified against
Cloudflare Workers runtime limits and ctx.waitUntil docs, Cloudflare Logpush (Workers Trace Events dataset), @vercel/functions waitUntil, and W3C Trace Context Level 1. Checked October 2026.
The failure that teaches this lesson usually goes the same way: a Worker starts throwing 500s, someone reaches for SSH to tail a log, and there is nothing to SSH into. The code is running in hundreds of points of presence, each invocation lives for milliseconds, and all you have is a spike on a dashboard and a customer complaint from São Paulo.
Edge functions are the least observable place your code will ever run, and the usual playbook (attach a debugger, grep a log file, add a console.log and redeploy) mostly does not apply. You have to design the telemetry in from the start.
Why this is harder than a server
A normal service runs on a box you can name. An edge function runs everywhere and nowhere. A few constraints drive everything else:
- Hundreds of locations. A single deploy is live in every PoP the platform runs. "Which server?" is not a useful question anymore. "Which region, which colo?" is.
- Short lifetimes. An invocation handles one request and disappears. There is no long-lived process holding a metrics buffer you can scrape.
- No shell, no disk. You cannot exec into it. There is no local file to write to and rotate.
- Tight CPU budgets. As of October 2026, Cloudflare's Workers Free plan allows 10 ms of CPU per request; Workers Paid defaults to 30 seconds and can be raised to 5 minutes. On the free tier especially, blocking to flush a batch of spans eats the budget you needed for the actual work.
- Limited async time after the response. Cloudflare gives
waitUntilwork up to 30 seconds after the response is sent, shared across everywaitUntilcall in the request, and cancels anything still pending. On Vercel,waitUntilpromises share the function's own timeout. Anything you send has to fit in that window.
That last point is the one people trip on, so start there.
The waitUntil pattern
You cannot block the response to ship telemetry. If you await a log POST before returning, every user pays for your observability in latency. The fix on both Cloudflare and Vercel is waitUntil (ctx.waitUntil on Workers, waitUntil from @vercel/functions on Vercel): hand it a promise, return the response now, and the runtime keeps the invocation alive long enough to finish the send.
export default {
async fetch(request, env, ctx) {
const start = Date.now();
const response = await handle(request, env);
ctx.waitUntil(
fetch("https://logs.internal.example.com/ingest", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
ts: Date.now(),
colo: request.cf?.colo,
country: request.cf?.country,
status: response.status,
dur_ms: Date.now() - start,
ray: request.headers.get("cf-ray"),
}),
}).catch(() => {}) // never let telemetry take down the request
);
return response;
},
};
Two rules we enforce. The telemetry send is always after the response is built, never in its path. And it always swallows its own errors: a dead log endpoint should never turn a 200 into a 500.
Logs
Firing a POST per request from every PoP works until traffic grows, and then it becomes a bill and a firehose. Two things keep it sane.
Structured logs, always. Emit JSON, not strings, with fields you will actually filter on: colo, country, status, route, request id. Prose logs are useless at edge volume because you cannot aggregate them.
Sampling for the boring case. Keep every error and a small fraction of successes:
const sample = response.status >= 500 || Math.random() < 0.02;
if (sample) ctx.waitUntil(shipLog(record));
For high volume, stop hand-rolling the transport and let the platform push logs for you. Cloudflare Logpush batches Workers Trace Events straight to your sink. It is an account-scoped dataset, so the job is created on the account endpoint, not a zone:
curl -X POST \
"https://api.cloudflare.com/client/v4/accounts/$ACCT/logpush/jobs" \
-H "Authorization: Bearer $CF_TOKEN" \
-d '{
"name": "workers-to-r2",
"destination_conf": "r2://edge-logs/{DATE}?account-id='$ACCT'&access-key-id='$AK'&secret-access-key='$SK'",
"dataset": "workers_trace_events",
"output_options": {
"field_names": ["EventTimestampMs","Outcome","ScriptName","Logs","Exceptions"],
"timestamp_format": "rfc3339"
}
}'
wrangler tail is the live view for debugging a specific bad deploy. Tail Workers, which Cloudflare recommends for logs and exceptions because they run even when your Worker throws, sit between the two. Logpush is the durable stream you query later. Vercel exposes runtime logs and drains you point at the same downstream. Use both for what each is good at.
Traces
A request that touches the edge and then your origin is one story told in two places. Without a shared trace id you are guessing at the seam.
Propagate W3C traceparent from the edge into origin. The edge function is where the trace starts, so it is where you mint or forward the header. The format is version-traceid-parentid-flags: a 32-hex-character trace id and a 16-hex-character parent id, neither of which may be all zeros:
const traceparent =
request.headers.get("traceparent") ??
`00-${crypto.randomUUID().replace(/-/g, "")}-${rand16()}-01`;
const originReq = new Request(originURL, request);
originReq.headers.set("traceparent", traceparent);
const res = await fetch(originReq);
OpenTelemetry runs at the edge, but the CPU budget fights you. A full OTel SDK with a batching span processor is heavy for a Worker, and exporting spans synchronously blows the limit. The move is to build minimal spans, hand the export to ctx.waitUntil, and send OTLP over HTTP after the response. Keep spans few and coarse (one for the edge handler, one for the origin call) rather than instrumenting every function.
Metrics
Server-side timings tell you what your code did. They do not tell you what the user in São Paulo felt. For that you need two things.
RUM for real latency by region. Real-user monitoring from the browser captures actual TTFB and load time per country, which is the only number that reflects whether the edge is buying you anything. If your p75 in one region is triple the rest, that is a routing or PoP problem no server metric will show.
Per-PoP error rates. Aggregate your structured logs by colo and status. A global error rate of 0.3% can hide one unhealthy colo sitting at 12%. The average lies; the breakdown does not.
Gotchas we hit
- You cannot block to flush. Every flush goes through
waitUntil, and its time is bounded. Batch small and send often. - Cardinality is the cost. Tagging metrics with request id or full URL explodes series count and the invoice with it. Tag with colo, country, route template, status. Nothing unbounded.
- Correlating edge and origin. Without a propagated trace id, edge logs and origin logs are two disconnected piles. The
cf-rayandtraceparentin both sides are what stitch them.
This is the observability layer for the edge functions you have already decided to run at the edge; the harder question of what to run there lives in that playbook. Once edge and origin share ids, correlating logs, metrics and traces across the whole stack is the same discipline.
Questions people ask
How do I log from a Cloudflare Worker without slowing down responses?
Build the response first, then pass the log send to ctx.waitUntil() and return immediately. The runtime keeps the invocation alive for up to 30 seconds after the response, shared across all waitUntil calls, and cancels anything still pending. Catch errors inside the promise so a failing log endpoint never changes the status code. For high volume, use Logpush or Tail Workers instead of per-request POSTs.
Can I run OpenTelemetry in edge functions?
Yes, but keep it light. A full SDK with a batching span processor competes with the CPU budget, which is 10 ms per request on Cloudflare's Workers Free plan as of October 2026. Create one or two coarse spans per request, export them over OTLP/HTTP inside waitUntil, and propagate the W3C traceparent header to origin so the backend can join the two halves of the trace.
Why is my global error rate fine when one region is failing?
Averages hide localized failures. A healthy global error rate can contain one colo failing at many times the baseline, because that colo carries a small share of traffic. Group structured logs by colo or region and status, and alert on the per-location rate. Pair that with RUM by country, since a routing problem shows up as user-facing latency, not as server errors.
The call we'd make
Start with structured logs shipped through waitUntil, sample successes hard, and move to Logpush the moment volume hurts. Add traceparent propagation on day one even before you have a trace backend, because retrofitting trace ids across the edge/origin seam later is miserable. Hold traces until logs and RUM are boring. Instrument the seam, not every line, and let the platform carry the firehose so your CPU budget goes to the request.
Sources
Cite this article
Kiril Urbonas (2026). Observability for Edge Functions: Logs, Traces, and Metrics. DevOpsNess. Updated 2026-10-31. https://www.devopsness.com/blog/observability-for-edge-functions-logs-traces-metrics
[Observability for Edge Functions: Logs, Traces, and Metrics](https://www.devopsness.com/blog/observability-for-edge-functions-logs-traces-metrics) (Kiril Urbonas, DevOpsNess, updated 2026-10-31)
More from Cloud
Explore more articles in this category
Catching AWS Cost Spikes Before the Invoice
The bill arrives weeks late. By then a runaway logging pipeline has already burned thousands. Here is how to catch spikes in hours, not weeks.
Cloudflare Workers vs Vercel Edge: A Latency-Cost Comparison
We deployed the same edge function on both platforms and measured for a quarter. Where each wins, where each loses, and the surprises along the way.
Secrets Management in Practice: From .env Files to Vault
We had .env files in three repos, AWS keys in Slack DMs, and a postgres password etched into a Confluence page. Cleaning it up took a sprint and changed how we think about secrets.
You might have missed
Evergreen posts worth revisiting.