Cloudflare 19 ☁️ Observability, Tail Workers & Multi-Tenancy — Inspecting real-time logs, Workers Analytics, Logpush, and scaling SaaS via Workers for Platforms
A Worker is the least observable thing you will ever deploy. It has no filesystem, no long-lived process, no SSH, and no log file that survives the request — console.log goes somewhere, and the question of where is the whole subject of this chapter. Cloudflare offers four answers that look similar and are not: a live stream you watch while debugging, a dashboard buffer that keeps three days, a Worker that consumes other Workers’ traces and can forward them anywhere, and an export pipeline that ships every trace to storage you own. Picking the wrong one for the job means either paying for storage you never read or discovering during an incident that the log you needed aged out eight hours ago.
The multi-tenancy half of the chapter is a consequence of the first half. When you run one Worker, observability is a convenience. When you run a thousand Workers — one per customer, each with its own code, deployed by an API you built — observability becomes the only way to answer the two questions that decide whether the platform is viable: which tenant is responsible for the load, and which tenant just broke. Workers for Platforms is the product that makes that arrangement possible, and Tail Workers are the mechanism that makes it legible, because a dispatch namespace can attach a tail consumer to every script inside it at once.
The two ideas meet in the same place: a request from tenant A arrives at a dispatch namespace, runs a tenant-owned Worker, produces a trace item, and that trace item is the only evidence of what happened. If the platform did not collect it, nobody did. This is why the chapter treats the event shape before it treats the multi-tenant architecture — you cannot design the aggregation until you know what one record contains, and the record is larger than most people assume.
The sections that follow work through the four observability surfaces and when each one is the right tool, then the Tail Worker event itself with its outcomes and its trace identifiers, then Analytics Engine as the queryable counter that survives longer than three days, then Workers for Platforms with its dispatch namespace, per-tenant limits, and outbound Worker. The final section assembles them into a platform shape where every tenant is metered, alerted on, and attributable.
Key point: A Tail Worker receives one event per request, not one per log line, and that event carries the outcome, the exceptions, and the execution context — so the fan-out design is “route events to a sink” rather than “collect strings”, and the same tail consumer can serve a single Worker, an entire dispatch namespace, or a thousand tenants at once.
Why it exists
The no-server-to-log-into problem. Every other runtime gives you a machine you can shell into, tail -f a file on, and read after the fact. A Worker runs on one of a hundred thousand isolates in a datacenter you did not choose, for 400 milliseconds, and then the isolate is reused by someone else’s code. There is no file to append to and no process to attach to. Observability has to be an explicit emission step rather than an ambient side effect, which is why console.log is a binding-level concern and not a language feature.
The retention-versus-cost problem. Keeping every request for ninety days is a storage bill; keeping it for ten minutes is useless during an incident. The four surfaces exist precisely because no single retention answers both. The live stream is for the ten minutes you are actively debugging. The dashboard is for the four days after a deploy. A Tail Worker is for the arbitrary retention you choose by writing it somewhere. Logpush is for the compliance window. Designing an observability strategy is choosing which of those four owns which question.
The fan-out problem. Once an event exists, more than one consumer wants it — a logger that writes to R2, a metrics writer that increments an Analytics Engine counter, an alerter that pages on a spike in exceededCpu. Composing that inside each Worker means duplicating the logic a hundred times and hoping it does not throw. A Tail Worker separates the emission from the consumption, so the application Worker does nothing but console.log and the consumers are ordinary Workers with their own deployment cycle and their own failure domain.
The tenancy problem. A single-tenant application can attribute every error to itself. A platform with a thousand customers cannot, and the two questions that matter — “which tenant is expensive” and “which tenant is broken” — have no answer unless the trace carries the tenant’s identity and unless the aggregation is keyed on it. That is not a logging detail; it is an architectural requirement that shapes the dispatch call, the binding, and the metric schema from the first line of code.
The untrusted-code problem. A platform that runs customer code is running code it did not write, on infrastructure it is responsible for, with credentials it must not leak. Workers for Platforms exists because the alternative — one big Worker with a tenant dimension in every query — cannot isolate CPU, cannot isolate a deploy, and cannot isolate a compromise. A dispatch namespace gives each tenant a separate script with its own limits, and an outbound Worker gives the platform one place to inspect every subrequest a tenant makes.
The cost-attribution problem. Per-tenant billing requires per-tenant measurement, and measurement requires a record that survives the request. A counter incremented in memory dies with the isolate. Analytics Engine is the write-once-read-many store for that counter, and its sampling model — the _sample_interval column — is the detail that separates a correct invoice from one that is off by the sampling rate.
The trade-off. Every observability choice costs something. A Tail Worker is another deployed Worker that can fail. Analytics Engine is a write per request that adds latency and a SQL API that is not a real-time query. Logpush is a paid entitlement with a batching delay measured in minutes. Workers for Platforms is an upload API, a migration, and a per-tenant limit scheme that has to be tuned. The design question is not whether to observe but which surface owns which question and what you are willing to pay for the answer.
a. The four surfaces and when each one is correct
The surfaces differ in retention, in latency, and in who pays for the storage.
┌────────────────────────────────────────────────────────────┐
│ THE FOUR OBSERVABILITY SURFACES │
│ │
│ wrangler tail live, one session, dev only │
│ Workers Logs dashboard, 3-day retention, paid │
│ Tail Worker a Worker that consumes traces │
│ Logpush continuous export to your sink │
│ │
│ Analytics Engine counters and histograms, query with SQL │
└────────────────────────────────────────────────────────────┘
wrangler tail streams live from the running deployment and ends when you close the terminal. It is the right tool for watching a change land and the wrong tool for anything that happened before you started it.
# Live stream, human-readable; Ctrl-C ends it
wrangler tail my-worker
# JSON per line, so it can be piped into jq for filtering
wrangler tail my-worker --format json | jq 'select(.outcome != "ok")'
# Only the failures, only the status codes that matter
wrangler tail my-worker --status error --method POST
# A tenant Worker inside a dispatch namespace
wrangler tail tenant-a --dispatch-namespace my-platform
Workers Logs is the dashboard buffer, enabled per Worker with an observability block and retained for three days on the Workers Paid plan. It captures console.log output plus the request metadata without any code change, which is why it is the default answer for “what happened after the deploy” and why it stops being useful the moment the incident is older than three days.
// wrangler.jsonc — logs are captured for the Worker with this block
{
"observability": {
"enabled": true,
// 1 = every request is logged; 0.1 = a tenth of them
"head_sampling_rate": 1
}
}
Logpush ships a dataset continuously to storage you own — R2, S3, GCS, Datadog, Splunk, BigQuery — on a batching schedule that is minutes rather than seconds. It is the compliance answer and the long-retention answer, and it is billed as an entitlement plus the destination’s own storage. The two datasets that matter for Workers are workers_trace_events, which is the same event a Tail Worker receives, and http_requests, which is the HTTP analytics record with cache status and edge timing.
# Create a Logpush job for the Worker trace dataset, hourly batches, gzipped
curl -X POST "https://api.cloudflare.com/client/v4/accounts/$ACCT/logpush/jobs" \
-H "Authorization: Bearer $CF_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"name": "workers-traces-r2",
"dataset": "workers_trace_events",
"destination_conf": "r2://my-logs/{DATE}?account-id='"$ACCT"'&access-key-id='"$KEY"'&secret-access-key='"$SECRET"'",
"output_options": { "field_names": ["EventTimestamp", "Outcome", "ScriptName", "Logs", "Exceptions"] },
"max_upload_interval_seconds": 3600
}'
Analytics Engine is the odd one out because it is not logs at all. It is a columnar store you write data points into from inside a Worker, and query later with SQL over a ninety-day window. It answers “how many” and “how slow” rather than “what did the request say”, which makes it the right surface for per-tenant metering and the wrong surface for debugging a single failure.
CHOOSING A SURFACE
I need to watch a change land now → wrangler tail
I need yesterday's errors → Workers Logs
I need to page someone at 3 a.m. → Tail Worker + alerter
I need 12 months for the auditor → Logpush
I need p99 latency per tenant → Analytics Engine
b. The Tail Worker event — the shape, the outcome, and the trace
A Tail Worker is an ordinary Worker that declares itself a consumer of another Worker’s traces. The declaration lives in the producer’s config, not the consumer’s, which is the detail that catches people out the first time.
// wrangler.jsonc of the PRODUCER — it names its consumers
{
"name": "api",
"main": "src/index.ts",
"tail_consumers": [
{ "service": "log-sink" }, // writes to R2
{ "service": "metrics-sink" } // writes to Analytics Engine
]
}
The consumer exports a tail handler rather than a fetch handler, and the argument is an array of trace items — one per request that finished in the sampling window.
// The consumer: exports `tail`, not `fetch`
export default {
async tail(events: TraceItem[], env: Env, ctx: ExecutionContext) {
for (const ev of events) {
// Every field below is available on the item; nothing is inferred
const record = {
script: ev.scriptName,
outcome: ev.outcome, // ok, exception, exceededCpu, ...
when: ev.eventTimestamp, // epoch ms of the request start
url: ev.event?.request?.url,
method: ev.event?.request?.method,
// The cf object carries the colo, the country, and the ray id
colo: ev.event?.request?.cf?.colo,
ray: ev.event?.request?.cf?.rayId,
// console.log output, in order, with the level each call used
logs: ev.logs.map(l => `${l.level}: ${l.message}`),
// Only uncaught errors land here; a caught one is just a log line
errors: ev.exceptions.map(e => `${e.name}: ${e.message}`),
};
// ctx.waitUntil is what keeps the write alive past the handler's return
ctx.waitUntil(env.BUCKET.put(`logs/${ev.eventTimestamp}-${ev.ray}.json`,
JSON.stringify(record)));
}
},
};
┌────────────────────────────────────────────────────────────┐
│ THE TRACE ITEM A TAIL WORKER RECEIVES │
│ │
│ scriptName which Worker produced the event │
│ outcome ok | exception | exceededCpu | canceled │
│ eventTimestamp epoch ms of the request │
│ logs[] { message, level, timestamp } │
│ exceptions[] { name, message, timestamp } │
│ event request url, method, headers, cf │
│ dispatchNamespace set when the Worker is a tenant │
│ │
│ One item per request. Not one item per log line. │
└────────────────────────────────────────────────────────────┘
The outcome field is the one to build the alerting on, because it distinguishes failures the application never sees. ok is a normal completion. exception is an uncaught throw. exceededCpu and exceededMemory are the isolate being killed mid-request — the client gets a 1102 or a 1101 and the application code gets nothing, so the only place those appear is here. canceled is the client disconnecting. scriptNotFound is the dispatch namespace failing to find a tenant script, which is the single most useful signal a platform has.
// The alert that only a tail consumer can raise
const killed = events.filter(e =>
e.outcome === "exceededCpu" || e.outcome === "exceededMemory");
if (killed.length > 0) {
// ev.scriptName identifies the tenant when this is a dispatch namespace
await env.PAGER.alert({
severity: "warning",
title: `${killed.length} isolates killed in the last window`,
tenants: [...new Set(killed.map(e => e.scriptName))],
});
}
Three constraints shape what a tail consumer can be. It cannot tail itself, so the logger cannot log its own failures to itself. Every consumer in the tail_consumers array fires independently, so one failing consumer does not stop the other. And the consumer’s own CPU budget applies, which means a consumer that does a synchronous R2 write per event will hit its own limit during a traffic spike — the batching in the array form (events is already an array) exists for that reason.
// Batched write: one R2 operation per batch, not one per event
const body = events.map(ev => JSON.stringify({ o: ev.outcome, s: ev.scriptName,
t: ev.eventTimestamp, r: ev.event?.request?.cf?.rayId })).join("\n");
ctx.waitUntil(env.BUCKET.put(`logs/${Date.now()}.ndjson`, body));
scriptTags and dispatchNamespace are the multi-tenant fields. A tag is set on upload and echoed on every trace item, so a platform can stamp plan:enterprise or region:eu on a tenant Worker and filter on it without maintaining a lookup table.
c. Analytics Engine — the counter that outlives three days
Analytics Engine is a write-once store with a fixed schema per dataset: up to twenty string columns (blob1…blob20), up to twenty numeric columns (double1…double20), and up to twenty indexed columns that queries can filter on efficiently.
// wrangler.jsonc — the binding names the dataset, which must already exist
{
"analytics_engine_datasets": [
{ "binding": "METRICS", "dataset": "request_metrics" }
]
}
// One data point per request; indexes are what WHERE clauses can push down on
env.METRICS.writeDataPoint({
indexes: [tenantId], // the column you will filter by
blobs: [
url.pathname, // blob1
req.method, // blob2
tenantId, // blob3
String(res.status), // blob4
],
doubles: [
Date.now() - start, // double1 = duration ms
res.status >= 500 ? 1 : 0, // double2 = error flag
bytes, // double3 = response size
],
});
The query is SQL against the account’s dataset endpoint, and it is answered from the columnar store rather than from the live data, so a query over a day of traffic is cheap and a query over a single recent minute is approximate.
-- p99 latency and error rate per tenant over the last hour
SELECT
blob3 AS tenant,
count() AS requests,
-- quantile takes the column name, not a value
quantile(0.99)(double1) AS p99_ms,
sum(double2) / count() AS error_rate,
-- The sample interval must be applied for a true count
sum(_sample_interval) AS sampled_requests
FROM request_metrics
WHERE timestamp > NOW() - INTERVAL '1' HOUR
GROUP BY tenant
ORDER BY requests DESC
# The SQL API is a plain POST with a bearer token
curl -sS "https://api.cloudflare.com/client/v4/accounts/$ACCT/analytics_engine/sql" \
-H "Authorization: Bearer $CF_TOKEN" \
--data "SELECT blob3, count() FROM request_metrics WHERE timestamp > NOW() - INTERVAL '1' DAY GROUP BY blob3"
The _sample_interval column is the detail that ruins invoices when missed. Writes are sampled under load, and a query that returns count() = 100 may represent a thousand requests with a sample interval of 10. A metering query that ignores it under-bills by the sampling rate; a query that multiplies by it correctly gives the true count. Every billing-grade query multiplies; every dashboard query can ignore it and display an estimate.
WRITE PATH AND QUERY PATH
Worker ──► writeDataPoint ──► columnar store ──► SQL API
(adds latency) (90 days) (batched)
Numbers are doubles. Strings are blobs. The index is the
only column the WHERE clause can cheaply filter on, so
the tenant id belongs in `indexes`, not only in `blobs`.
Three limits shape the schema. There is no schema migration, so a column added later arrives as NULL for all existing rows — plan the blob layout once. Retention is ninety days and not configurable. And a high-cardinality index is expensive, so a path with a million distinct values belongs in a blob and not in indexes; the tenant id belongs in both, because it is the filter and it is bounded.
d. Workers for Platforms — the dispatch namespace, per-tenant limits, and the outbound Worker
Workers for Platforms is a dispatch namespace: a container for customer Workers, where the platform calls env.DISPATCHER.get(name) and receives a Fetcher bound to that tenant’s script.
┌────────────────────────────────────────────────────────────┐
│ WORKERS FOR PLATFORMS │
│ │
│ control plane Worker (yours) │
│ │ │
│ ▼ │
│ DISPATCHER.get("customer-a") ──► tenant Worker A │
│ DISPATCHER.get("customer-b") ──► tenant Worker B │
│ │
│ per tenant: cpu_ms, subrequests, tags, outbound Worker │
│ shared: the namespace, the metric dataset, the sink │
│ │
│ The platform owns the namespace; the tenant owns the code │
└────────────────────────────────────────────────────────────┘
// The platform's own Worker declares the namespace as a binding
{
"dispatch_namespaces": [
{
"binding": "DISPATCHER",
"namespace": "my-platform",
// Every subrequest a tenant Worker makes passes through this Worker
"outbound": { "service": "egress-proxy" }
}
]
}
// The router: hostname in, tenant Fetcher out, request proxied through
export default {
async fetch(req: Request, env: Env, ctx: ExecutionContext) {
const host = new URL(req.url).hostname;
// A real implementation reads tenant -> hostname from a KV or D1 lookup
const tenant = await resolveTenant(host, env);
if (!tenant) return new Response("unknown host", { status: 404 });
// The stub is a Fetcher: same signature as any other binding
const stub = env.DISPATCHER.get(tenant.scriptName);
// Tags and limits were set at upload time; the trace carries the tag
return stub.fetch(req, {
// The platform injects identity the tenant cannot forge
headers: { "x-tenant-id": tenant.id },
});
},
};
A tenant Worker is uploaded through the REST API with its modules, a compatibility date, and — critically — its limits. The upload is what a control plane does on behalf of a customer, and it is the one place where a platform decides how much CPU one tenant may consume before being killed.
# Upload a tenant Worker into the dispatch namespace
curl -X PUT "https://api.cloudflare.com/client/v4/accounts/$ACCT/workers/dispatch/namespaces/my-platform/scripts/customer-a" \
-H "Authorization: Bearer $CF_TOKEN" \
-F 'metadata={
"main_module": "index.mjs",
"compatibility_date": "2025-04-01",
"limits": { "cpu_ms": 50, "subrequests": 20 },
"tags": ["plan:pro", "tenant:customer-a"]
};type=application/json' \
-F 'index.mjs=@./tenant/index.mjs;type=application/javascript+module'
// The router that receives a tenant subrequest; one policy applies to all
export default {
async fetch(req: Request, env: Env) {
const url = new URL(req.url);
// A tenant Worker may only reach the destinations the platform allows
if (!ALLOWED_HOSTS.has(url.hostname)) {
return new Response("egress blocked", { status: 403 });
}
// Credentials are injected here; the tenant never sees the secret
return fetch(url, {
method: req.method,
headers: { ...req.headers, authorization: `Bearer ${env.API_KEY}` },
body: req.body,
});
},
};
The outbound Worker is the security boundary and the observability boundary at once: every subrequest is visible in one place, so a tenant attempting to reach an internal address, a metadata endpoint, or a competitor’s API is blocked at a single choke point rather than audited after the fact. It is also where per-tenant rate limiting on outbound traffic belongs, because the limiter can key on the injected x-tenant-id rather than on an IP that all tenants share.
Tailing a dispatch namespace is the piece that ties the chapter together: attaching a Tail Worker to the namespace means every tenant Worker’s traces arrive, each carrying dispatchNamespace and scriptName, so one consumer handles a thousand tenants without a thousand configuration entries.
# A consumer attached to the namespace, not to one script
wrangler tail --dispatch-namespace my-platform --format json
Complete Example Session
// ============================================
// PART 1: THE PRODUCER DECLARES ITS CONSUMERS
// ============================================
// wrangler.jsonc
// { "name": "api", "main": "src/index.ts",
// "tail_consumers": [{ "service": "log-sink" },
// { "service": "metrics-sink" }],
// "observability": { "enabled": true, "head_sampling_rate": 1 } }
// ============================================
// PART 2: THE APPLICATION DOES NOTHING SPECIAL
// ============================================
export default {
async fetch(req: Request, env: Env) {
// The log line is the only emission the application performs
console.log("handling", req.method, new URL(req.url).pathname);
return handle(req, env);
},
};
// ============================================
// PART 3: THE LOG SINK — BATCHED R2 WRITE
// ============================================
export default {
async tail(events: TraceItem[], env: Env, ctx: ExecutionContext) {
// One object per batch, not one per event; NDJSON so it streams on read
const body = events.map(ev => JSON.stringify({
script: ev.scriptName,
outcome: ev.outcome,
ts: ev.eventTimestamp,
url: ev.event?.request?.url,
colo: ev.event?.request?.cf?.colo,
ray: ev.event?.request?.cf?.rayId,
logs: ev.logs.map(l => `${l.level}:${l.message}`),
errors: ev.exceptions.map(e => `${e.name}:${e.message}`),
})).join("\n");
// waitUntil keeps the write alive after the handler returns
ctx.waitUntil(env.BUCKET.put(`trace/${Date.now()}.ndjson`, body));
},
};
// ============================================
// PART 4: THE METRICS SINK — ANALYTICS ENGINE
// ============================================
export default {
async tail(events: TraceItem[], env: Env) {
for (const ev of events) {
const req = ev.event?.request;
env.METRICS.writeDataPoint({
// The tenant is the filter, so it is an index and not only a blob
indexes: [ev.scriptName ?? "unknown"],
blobs: [
req?.url ? new URL(req.url).pathname : "", // blob1
req?.method ?? "", // blob2
ev.scriptName ?? "", // blob3
ev.outcome, // blob4
],
doubles: [
ev.eventTimestamp, // double1
ev.outcome === "ok" ? 0 : 1, // double2
ev.exceptions.length, // double3
],
});
}
},
};
// ============================================
// PART 5: THE ALERTER — OUTCOME-BASED
// ============================================
function pageOnKills(events: TraceItem[], env: Env) {
const killed = events.filter(e =>
e.outcome === "exceededCpu" || e.outcome === "exceededMemory");
if (killed.length === 0) return;
// scriptName is the tenant when this is a dispatch namespace
const tenants = [...new Set(killed.map(e => e.scriptName))];
return env.PAGER.alert({ title: `${killed.length} isolates killed`, tenants });
}
// ============================================
// PART 6: THE PLATFORM ROUTER
// ============================================
export default {
async fetch(req: Request, env: Env) {
const tenant = await resolveTenant(new URL(req.url).hostname, env);
if (!tenant) return new Response("unknown host", { status: 404 });
// The stub is a Fetcher bound to one tenant script
return env.DISPATCHER.get(tenant.scriptName).fetch(req, {
headers: { "x-tenant-id": tenant.id },
});
},
};
// ============================================
// PART 7: THE TENANT UPLOAD
// ============================================
// PUT /accounts/{acct}/workers/dispatch/namespaces/my-platform/scripts/{name}
// metadata: { limits: { cpu_ms: 50, subrequests: 20 },
// tags: ["plan:pro", "tenant:customer-a"] }
// ============================================
// PART 8: THE OUTBOUND WORKER
// ============================================
export default {
async fetch(req: Request, env: Env) {
const url = new URL(req.url);
if (!ALLOWED_HOSTS.has(url.hostname)) {
return new Response("egress blocked", { status: 403 });
}
// The tenant never holds the credential; the platform injects it
return fetch(url, {
method: req.method,
headers: { ...req.headers, authorization: `Bearer ${env.API_KEY}` },
body: req.body,
});
},
};
// ============================================
// PART 9: THE METERING QUERY
// ============================================
// SELECT blob3 AS tenant,
// sum(_sample_interval) AS requests, -- the sampling correction
// quantile(0.99)(double1) AS p99
// FROM request_metrics
// WHERE timestamp > NOW() - INTERVAL '1' DAY
// GROUP BY tenant;
// ============================================
// PART 10: THE TAIL ON THE NAMESPACE
// ============================================
// wrangler tail --dispatch-namespace my-platform --format json
// One consumer, every tenant, each event carrying scriptName.
The ten parts covered the producer-side consumer declaration, an application that emits nothing but a log line, a batched R2 sink, an Analytics Engine sink that writes the tenant into the index, an alerter keyed on the outcomes the application cannot see, the platform router that resolves a hostname to a tenant stub, the upload with its per-tenant limits and tags, the outbound Worker that gates every subrequest, the metering query with its sampling correction, and the namespace-wide tail that makes a thousand tenants legible at once.
Quick Reference
The Four Surfaces
| Surface | Retention | Latency | Cost |
|---|---|---|---|
wrangler tail | Session only | Live | Free |
| Workers Logs | 3 days | Seconds | Workers Paid |
| Tail Worker | You choose | Per request | The consumer’s own usage |
| Logpush | Your bucket | Minutes | Entitlement + storage |
| Analytics Engine | 90 days | Batched | Workers Paid |
Trace Item Fields
| Field | Type | Meaning |
|---|---|---|
scriptName | string | The Worker, or the tenant |
outcome | enum | ok, exception, exceededCpu, … |
eventTimestamp | number | Epoch ms of the request |
logs[] | array | { message, level, timestamp } |
exceptions[] | array | { name, message, timestamp } |
event | object | Request url, method, headers, cf |
dispatchNamespace | string | Set for a tenant Worker |
scriptTags | array | Upload-time tags, echoed |
Outcomes Worth Alerting On
| Outcome | Cause | Signal |
|---|---|---|
ok | Normal completion | — |
exception | Uncaught throw | Application bug |
exceededCpu | CPU limit hit | Tenant needs a higher limit |
exceededMemory | Memory limit hit | Leak or oversized payload |
canceled | Client disconnected | Timeout or a slow upstream |
scriptNotFound | No such tenant script | Routing or provisioning bug |
Analytics Engine Schema
| Column | Type | Use |
|---|---|---|
blob1–blob20 | string | Dimensions you display |
double1–double20 | number | Metrics you aggregate |
indexes | string[] | Columns WHERE pushes down on |
_sample_interval | number | Multiply for a true count |
timestamp | time | The query window column |
Workers for Platforms
| Concept | Meaning |
|---|---|
| Dispatch namespace | Container for tenant Workers |
env.DISPATCHER.get(name) | Returns a Fetcher for one tenant |
limits.cpu_ms | Per-tenant CPU ceiling |
limits.subrequests | Per-tenant fetch ceiling |
tags | Upload-time labels on the trace |
| Outbound Worker | Intercepts every tenant subrequest |
| Upload API | PUT …/dispatch/namespaces/{ns}/scripts/{name} |
Best Practices
✅ Do This:
// Emit one log line per request, not per operation
console.log("handling", req.method, new URL(req.url).pathname); // ✅
// Batch the sink write; one R2 operation per array
ctx.waitUntil(env.BUCKET.put(`trace/${Date.now()}.ndjson`, body)); // ✅
// Keep the write alive past the handler's return
ctx.waitUntil(writePromise); // ✅
// Put the tenant in the index, not only in a blob
indexes: [tenantId], blobs: [path, method, tenantId], // ✅
// Alert on the outcomes the application never sees
e.outcome === "exceededCpu" || e.outcome === "exceededMemory" // ✅
// Multiply by the sample interval for a billing-grade count
sum(_sample_interval) AS requests // ✅
// Set per-tenant limits at upload time
limits: { cpu_ms: 50, subrequests: 20 } // ✅
// Gate egress in one place
if (!ALLOWED_HOSTS.has(url.hostname)) return blocked(); // ✅
❌ Don’t Do This:
// A synchronous R2 write per event during a spike
for (const ev of events) await env.BUCKET.put(key(ev), body(ev)); // ❌
// A tail consumer that tails itself
"tail_consumers": [{ "service": "log-sink" }] on log-sink // ❌
// Trusting the application log for an OOM
// (the isolate was killed; nothing was logged) // ❌
// Ignoring the sample interval in a metering query
count() AS requests // ❌
// A million-value column as an index
indexes: [urlPathname] // ❌
// One shared Worker with a tenant dimension in every query
// (no CPU isolation, no deploy isolation, no compromise isolation) // ❌
// Letting a tenant Worker call fetch without a gate
// (the metadata endpoint is one subrequest away) // ❌
// A limit set globally rather than per tenant
limits: { cpu_ms: 1000 } for every plan // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Logs missing after a deploy | Tail was not running | Workers Logs or a Tail Worker |
| OOM with no error logged | Isolate killed, nothing ran | Alert on outcome, not on logs |
| Sink times out under load | Synchronous write per event | Batch, then waitUntil |
| Invoice off by 10× | Sample interval ignored | sum(_sample_interval) |
| Query slow on path filter | High-cardinality index | Move the path to a blob |
| Tenant cannot be identified | No tag at upload | tags: ["tenant:…"] |
| All tenants share a limit | Global config, not per upload | limits in the metadata |
| Tenant reaches internal host | No outbound Worker | Bind one and allowlist |
| Old incident unreadable | Logs aged out at 3 days | Logpush to R2 |
Real-World Examples
1. Live stream, failures only
wrangler tail api --format json | jq 'select(.outcome != "ok")'
2. Consumer declaration
{ "tail_consumers": [{ "service": "log-sink" }] }
3. Tail handler
async tail(events: TraceItem[], env: Env, ctx: ExecutionContext) { … }
4. Batched sink
ctx.waitUntil(env.BUCKET.put(`trace/${Date.now()}.ndjson`, body));
5. Outcome alert
events.filter(e => e.outcome === "exceededCpu")
6. Data point
env.METRICS.writeDataPoint({ indexes: [tenantId], blobs: [...], doubles: [...] });
7. Sampling correction
sum(_sample_interval) AS requests
8. Tenant dispatch
env.DISPATCHER.get(tenant.scriptName).fetch(req);
9. Per-tenant limit
"limits": { "cpu_ms": 50, "subrequests": 20 }
10. Egress gate
if (!ALLOWED_HOSTS.has(url.hostname)) return new Response("blocked", { status: 403 });
Visual
The Four Surfaces
┌────────────────────────────────────────────────────────────┐
│ THE FOUR OBSERVABILITY SURFACES │
│ │
│ wrangler tail live, one session, dev only │
│ Workers Logs dashboard, 3-day retention, paid │
│ Tail Worker a Worker that consumes traces │
│ Logpush continuous export to your sink │
│ │
│ Analytics Engine counters and histograms, query with SQL │
└────────────────────────────────────────────────────────────┘
The Fan-Out
┌────────────────────────────────────────────────────────────┐
│ TAIL FAN-OUT │
│ │
│ worker-a ──┐ │
│ worker-b ──┼──► log-sink ──► R2 (arbitrary retention) │
│ worker-c ──┘ │
│ └──► metrics-sink ──► Analytics Engine (SQL) │
│ └──► alerter ──► PagerDuty │
│ │
│ Each consumer is its own Worker: own CPU budget, own │
│ deployment, own failure domain. One failing does not │
│ stop the others. │
│ │
│ A consumer cannot tail itself. │
└────────────────────────────────────────────────────────────┘
Sampling
┌────────────────────────────────────────────────────────────┐
│ THE SAMPLING CORRECTION │
│ │
│ at low traffic: interval = 1 count() = true count │
│ at high traffic: interval = 10 count() = 1/10th │
│ │
│ SELECT count() → 100 (wrong) │
│ SELECT sum(_sample_interval) → 1000 (correct) │
│ │
│ Dashboards may show the estimate. Invoices may not. │
└────────────────────────────────────────────────────────────┘
The Platform
┌────────────────────────────────────────────────────────────┐
│ WORKERS FOR PLATFORMS │
│ │
│ request ──► router ──► DISPATCHER.get("customer-a") │
│ │ │
│ ▼ │
│ tenant Worker │
│ │ │
│ ▼ every subrequest │
│ outbound Worker │
│ │ │
│ ▼ │
│ allowlisted host │
│ │
│ trace ──► namespace tail ──► R2 + Analytics Engine │
│ (scriptName is the tenant, on every event) │
└────────────────────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Live logs | wrangler tail <worker> |
| Dashboard retention | 3 days, Workers Paid |
| Consumer declaration | tail_consumers on the producer |
| Consumer handler | export default { tail(events, env, ctx) } |
| Fatal outcomes | exceededCpu, exceededMemory, scriptNotFound |
| Logpush Workers dataset | workers_trace_events |
| Analytics Engine retention | 90 days |
| Analytics Engine columns | 20 blobs, 20 doubles, 20 indexes |
| Sampling column | _sample_interval |
| Tenant dispatch | env.DISPATCHER.get(name) → Fetcher |
| Per-tenant limits | cpu_ms, subrequests in upload metadata |
| Egress control | Outbound Worker on the namespace |
Key takeaways:
- A trace item is one request, not one log line. It carries the outcome, the log array, the exceptions, and the request context together, which is why a tail consumer routes events to a sink rather than collecting strings. The array argument exists so the sink can batch.
exceededCpuandexceededMemoryappear nowhere else. The isolate is killed mid-execution, so the application never runs acatch, never logs, and never reports. A tail consumer readingoutcomeis the only mechanism that sees the failure at all.- The producer declares the consumer.
tail_consumerslives in the emitting Worker’s config, and several consumers can attach to one producer, each failing independently. A consumer cannot tail itself, so the logger’s own errors need the dashboard. - Analytics Engine is a counter store, not a log store. Twenty string columns, twenty numeric, twenty indexes, ninety days, SQL over the lot. Put the tenant in
indexesbecause that is the columnWHEREpushes down on, and put a high-cardinality path in a blob because indexing it is expensive. _sample_intervaldecides whether the invoice is right. Writes are sampled under load, socount()is an estimate andsum(_sample_interval)is the true number. Every billing query multiplies; every dashboard may not.- A dispatch namespace is per-tenant isolation of code and CPU. One Worker with a tenant dimension in every query cannot isolate a limit, a deploy, or a compromise. A namespace gives each tenant a script with its own
cpu_msandsubrequests, and ascriptNameon every trace item that identifies it. - The outbound Worker is the security boundary. Every subrequest a tenant makes passes through one Worker, which is where an allowlist lives and where credentials are injected so the tenant never holds them. Without it, a tenant’s
fetchis one request away from the metadata endpoint. - One namespace tail covers a thousand tenants. Attaching a consumer to the dispatch namespace rather than to each script means the aggregation is a query over
scriptNamerather than a configuration entry per customer.
Remember: Observability on a Worker is an explicit emission rather than an ambient side effect, because there is no machine to log into and no file to append to — the isolate exists for four hundred milliseconds and is then reused. So the design is a chain: the application writes a log line, the runtime wraps the request in a trace item that carries the outcome and the exceptions, a Tail Worker routes that item to a sink the platform controls, and Analytics Engine reduces it to the counters that survive past the retention window. On a platform, the same chain carries the tenant’s name on every event, and the dispatch namespace supplies the isolation that makes the name meaningful. The detail that ties it all together is that the most important failures never reach your code, which is why the outcome field and not the log line is where the alerting belongs.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!