Skip to content
AnswerWell geo Documentation

Research · 8 min read · Answerwell

SQL API Analytics Datasets, Engine Metrics and Monitors

How Cloudflare SQL API, Workers Analytics Engine, and Worker bindings write custom metrics, query datasets, and power scheduled monitors.

This page summarizes Cloudflare documentation on querying analytics and observability data with SQL, recording custom metrics from Workers with Workers Analytics Engine, and alerting with Monitors. Cloudflare exposes two related SQL surfaces: the account-wide SQL API for platform datasets and Monitors, and a separate Workers Analytics Engine SQL API for datasets you create from writeDataPoint(). Choosing the right write path and query endpoint avoids broken queries, permission errors, and misleading counts on sampled data.

SQL API: what it queries and when to use it

Section titled “SQL API: what it queries and when to use it”

The SQL API lets you query Cloudflare analytics and observability datasets with a supported subset of SQL—filter, aggregate, group, and sort through one HTTP endpoint at https://api.cloudflare.com/client/v4/analytics/sql.

The SQL API lets you query Cloudflare analytics and observability data using SQL. Use the API to select fields, filter events, calculate aggregates, group results, and integrate analytics data with your applications.

— Cloudflare, SQL API

Every query must include an account or zone scope, a lower time bound on the dataset timestamp, and one schema-qualified dataset (for example events.httpRequests). Dataset and field availability depends on your plan and API token permissions. The API uses a deliberately limited dialect; it does not pass arbitrary SQL to the underlying store. For discovery, use the introspection endpoint or cf sql datasets --account-tag "<ACCOUNT_TAG>" from the Get started flow.

Dataset prefix Typical use Sampling notes
events. Dashboards, aggregates, some row-level reads Often adaptively sampled; COUNT, SUM, AVG use sample weights
states. Point-in-time state (for example D1 storage) Valid aggregates vary by dataset
logs. Fine-grained logs (Workers logs, Log Explorer) Usually unsampled; some logs use adaptive sampling
events.analyticsEngine.<name> Custom Engine datasets from Workers Sampled; extra compatibility for some aggregates and ORDER BY

Monitors and direct API access are available on all plans; the SQL API also powers Monitors under Alerts.

Workers Analytics Engine: custom metrics from Workers

Section titled “Workers Analytics Engine: custom metrics from Workers”

Workers Analytics Engine is Cloudflare’s time-series store for unlimited-cardinality custom analytics written from Workers or Pages Functions.

Workers Analytics Engine provides unlimited-cardinality analytics at scale, via a built-in API to write data points from Workers, and a SQL API to query that data.

— Cloudflare, Workers Analytics Engine

Use it when you need per-customer KPIs, usage-based billing, SaaS tenant breakdowns, or high-cardinality dimensions (customer IDs, API keys, hostnames) without adding latency to requests. Platform metrics in Account and zone analytics or the GraphQL Analytics API answer “how is my zone performing?”; Analytics Engine answers “how is my product behaving per tenant or feature?”

Common motivations from Cloudflare use cases include usage-based billing, SaaS usage analytics, and custom Worker observability.

writeDataPoint(): blobs, doubles, and indexes

Section titled “writeDataPoint(): blobs, doubles, and indexes”

Bind a dataset via Wrangler (analytics_engine_datasets) or the Pages dashboard as described in Pages Functions bindings and Wrangler configuration. Then call writeDataPoint() on env.<BINDING_NAME>.

A data point is a structured event that consists of: Blobs (strings) — The dimensions used for grouping and filtering. Doubles (numbers) — The numeric values that you want to record. Indexes — (strings) — Used as a sampling key.

— Cloudflare, Get started with Workers Analytics Engine

You do not need to await writeDataPoint(); the runtime writes in the background. Provide consistent array order for blobs and doubles. Only one index per data point is supported today—multiple indexes are not recorded. For SaaS billing, put the customer ID in indexes so sampling is per customer rather than globally blended (usage-based billing recipe).

Analytics Engine bindings cannot be used locally on Pages; for Workers, optional remote: true on dataset bindings controls remote writes during dev (Wrangler configuration).

Two SQL endpoints: platform SQL API vs Analytics Engine SQL API

Section titled “Two SQL endpoints: platform SQL API vs Analytics Engine SQL API”

A frequent mistake is sending Engine dataset SQL to the wrong host.

Platform SQL API — https://api.cloudflare.com/client/v4/analytics/sql — queries events.httpRequests, logs.workersLogs, events.analyticsEngine."my-dataset", and other catalog datasets (Datasets, Query the API).

Workers Analytics Engine SQL API — https://api.cloudflare.com/client/v4/accounts/<account_id>/analytics_engine/sql — queries tables created when you write to a bound dataset name; supports SHOW TABLES and Engine-specific SQL (SQL API for Analytics Engine, SQL Reference).

This endpoint and its SQL dialect are separate from the Analytics SQL API. To query Analytics Engine data through that API, use events.analyticsEngine.<DATASET_NAME>.

— Cloudflare, Workers Analytics Engine SQL API

The unified SQL API path is useful for joining Engine data with HTTP traffic in one toolchain (for example Grafana against platform endpoints) and for Monitors. The Engine-native endpoint matches examples in Get started and Querying from Grafana (ClickHouse-style plugin to the Engine SQL URL).

Sampled aggregates: COUNT and _sample_interval

Section titled “Sampled aggregates: COUNT and _sample_interval”

Adaptively sampled datasets require weighted aggregates. On Engine datasets, examples use SUM(_sample_interval) for counts and custom weighted averages (Get started, usage-based billing). The platform SQL API applies sample weights automatically for COUNT, SUM, and AVG on sampled datasets (SQL API Beta announcement). Row-level SELECT * on sampled event data returns only retained samples and cannot reconstruct unsampled events (Event datasets).

Query from HTTP, CLI, Worker binding, or fetch

Section titled “Query from HTTP, CLI, Worker binding, or fetch”

Send one SELECT per request with a Bearer token that includes Account Analytics Read (and zone or product permissions as needed). Prefer POST JSON with query, params, optional scope, and time_range (Query the API, Get started).

Do not duplicate tenancy or time bounds in SQL and JSON: the API returns HTTP 422 if accountTag appears both in SQL and scope, or if time_range conflicts with a timestamp predicate (Request-level scope, Error responses).

The Cloudflare CLI offers cf sql query with --scope-account or --scope-zone and --time-since, omitting those predicates from SQL when flags supply them.

Analytics SQL binding: query without an API token

Section titled “Analytics SQL binding: query without an API token”

For Workers, the Analytics SQL binding (analytics.binding in Wrangler, Wrangler 4.145.0+) calls the platform SQL API from env.ANALYTICS_SQL.query() with account scope inferred from the Worker.

The Analytics SQL binding lets a Cloudflare Worker query SQL API datasets without making an HTTP request or managing an API token. Each binding is scoped to the Cloudflare account that owns the Worker.

— Cloudflare, Workers binding

Do not include accountTag or zoneTag in binding SQL—the API rejects combined tenancy. Include the lower time bound in SQL; the binding does not expose request-level time_range. Log Explorer-backed datasets are not supported through the binding. On failure, check error.retryable and use bounded exponential backoff; the binding does not auto-retry (Analytics SQL binding, Workers binding).

Alternatively, query Engine data from a Worker via fetch to the Engine SQL URL with a token (Querying from a Worker).

SQL API query limits that break dashboards

Section titled “SQL API query limits that break dashboards”
Limit Value Source
Statements per request 1 SQL API limits
Statement length 10 KiB Same
ORDER BY Requires LIMIT (except Engine datasets via SQL API) Same
Lower timestamp bound Required SQL language reference

Rate or resource exhaustion returns HTTP 429, 503, or 507; narrow time range or row count and honor Retry-After when present (SQL API limits).

Monitors evaluate a SQL API query on a schedule and send notifications when results match threshold, anomaly, or SLO criteria (Alerts overview).

Monitors evaluate a SQL API query on a schedule. Cloudflare sends a notification when the query result meets your detection criteria.

— Cloudflare, Monitors

Custom monitor SQL must return one numeric column named value, read one schema-qualified dataset, include account or zone filter (for manual time mode), use supported syntax, and omit a trailing semicolon. Automatic time range mode omits the timestamp filter so Cloudflare supplies a window per evaluation (Custom SQL).

Example pattern for 5xx rate:

SELECT COUNT(*) AS value
FROM events.httpRequests
WHERE accountTag = '<ACCOUNT_TAG>'
AND timestamp >= NOW() - INTERVAL '5' MINUTE
AND edgeResponseStatus >= 500

Validation before save catches unsupported syntax, bad scope, and unavailable fields—similar in spirit to Logpush transformer validation (Transformers).

  • Using bare dataset names instead of events.httpRequests or events.analyticsEngine."my-dataset" (Error responses).
  • Mixing scope / time_range in JSON with the same predicates in SQL (HTTP 422).
  • Putting accountTag in Analytics SQL binding queries (Workers binding).
  • Treating raw COUNT(*) on Engine data without _sample_interval when building bills (usage-based billing).
  • Multiple indexes in one writeDataPoint() (Get started).
  • ORDER BY without LIMIT on platform datasets (SQL API limits).
  • Assuming Analytics Engine bindings work in local Pages dev without remote configuration (Pages bindings).
  1. Create an API token with Account Analytics Read (and zone permissions if you query by zoneTag) using Get started, then run the sample curl against Query the API and confirm data, rows, and statistics in the response.
  2. List datasets with cf sql datasets --account-tag "<ACCOUNT_TAG>" or the introspection call; open one dataset with include_columns=true and verify field names match your SELECT.
  3. After deploying a Worker with an Analytics Engine binding, POST SHOW TABLES to the Engine SQL API or query via events.analyticsEngine."<dataset>" on the platform SQL API; confirm rows appear after traffic and that aggregates use sampling rules from Datasets.
  4. If you use Monitors, save a test query in Monitors that returns value and fix any validation errors shown inline.
  5. You can check automatically in Answerwell (our tool): https://answerwell.org/workspace

If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact statement you are questioning so it can be checked against the linked Cloudflare docs.