Back to Cloudflare

Turn Events Into Analytics With Basin

November 5, 2026 Wasil Zafar 28 min read

Follow ingestion through Iceberg tables to analytical queries

Table of Contents

  1. Operational Data and Analytical Data Have Different Needs
  2. Pipelines Ingest and Transform Events
  3. Catalog Manages Iceberg Tables in R2
  4. Basin SQL and Compatible Query Engines
  5. Design a Small Request-Analytics Pipeline
  6. Reconcile Ingested Events With a Deterministic Query Result

Operational Data and Analytical Data Have Different Needs

Two questions land on the same engineering team in the same afternoon.

The first comes from a customer: "Order 8412 still says pending. Can you fix it?" Someone opens an admin page, reads one row, changes one field, and the next page load shows the new state. The answer has to be correct at this instant, for that one row.

The second comes from the head of engineering: "Last Tuesday between 14:00 and 15:00, which routes returned the most 5xx responses from Singapore, and did that change after we shipped the retry fix?" Nobody can answer that by opening a row. The answer requires reading every request record in a one-hour window, grouping by route, and comparing two periods. It has to match the raw records in aggregate, not reproduce a single row.

Same company, same traffic, two different data problems. The first is operational data: small, current, mutable, read and written one row at a time. The second is analytical data: large, historical, append-only, read in scans and aggregations. D1 is built for the first. Basin is built for the second.

Think of a shop. The till drawer is operational: you count it, correct it, and reconcile it against today's receipts. The annual accounts are analytical: every drawer, every day, collapsed into totals you can compare across months. You would not audit the year by opening the drawer, and you would not price a single sale by running the year-end report.

Basin is Cloudflare's serverless analytics platform, and it is three products with three separate jobs. The names matter because each one is a separate failure boundary:

  • Basin Pipelines receives events from a Worker binding, an HTTP endpoint, or Logpush, transforms them with SQL, and delivers them to R2 as Apache Iceberg tables or as Parquet and JSON files.
  • Basin Catalog is a managed Apache Iceberg catalog that lives inside an R2 bucket and speaks the standard Iceberg REST interface. It tracks which metadata file is current and runs compaction and snapshot expiration.
  • Basin SQL is a read-only, distributed query engine that scans tables registered in Basin Catalog.

Basin went generally available on 1 October 2026, when Cloudflare Pipelines became Basin Pipelines, R2 Data Catalog became Basin Catalog, and R2 SQL became Basin SQL. Existing resources keep working, and the older APIs remain valid while they are deprecated.

Figure 1 shows why the two lanes should not share a data path. The operational lane is synchronous and user-visible: a failed write is an error the customer sees. The analytical lane is asynchronous and lag-tolerant: a delayed file is a dashboard that is ninety seconds stale. That difference in tolerance is the whole design.

Operational Data and Analytical Data Have Different Needs
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    subgraph OP["Operational lane - request time"]
        W1["Worker handles POST /orders"] --> V["Validate against the current row"]
        V --> D1[("D1: orders table")]
        D1 --> R1["Read back one order
target: milliseconds"] end subgraph AN["Analytical lane - batch time"] W2["Same Worker emits an event"] --> S["Basin stream
durable buffer"] S --> P["Pipeline SQL
filter and reshape"] P --> ICE[("Iceberg table in R2
partitioned by day")] ICE --> Q["Basin SQL or external engine
scan: seconds to minutes"] end W1 -.->|"append-only emit"| W2 P -->|"schema mismatch"| X["Event accepted, then dropped
visible only in user error metrics"] classDef primary fill:#132440,color:#ffffff,stroke:#0b172b; classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a; classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f; classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420; classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f; class W1,R1,W2,S,P,Q secondary; class V ok; class X danger;

Figure 2 makes the same split concrete as layers and ownership. The arrows only ever point downward, and the only crossing arrow carries facts from the operational lane into the analytical lane. Nothing in a request handler should read the analytics table.

Operational and analytical data paths cross different boundaries Four layers in two lanes. The operational lane runs from a Worker through a synchronous call into D1 and serves point lookups. The analytical lane runs from the same Worker through a stream and pipeline into an Iceberg table in R2 and serves column scans. A dashed arrow labelled emit crosses from left to right at the application layer. OPERATIONAL LANE ANALYTICAL LANE App Ingest Store Read Worker reads and writes rows Synchronous call the user waits for the result D1 row store, indexes, transactions Point lookups milliseconds, one row at a time Same Worker emits an append-only event Stream to pipeline SQL filter and reshape Iceberg table in R2 columnar Parquet, partitioned by day Column scans seconds, millions of rows emit

Pipelines Ingest and Transform Events

An event is a fact that already happened. The schema should be shaped by the questions you intend to ask, not by whatever JSON the application happened to produce.

Basin Pipelines is composed of three objects, and it helps to keep their responsibilities separate. A stream is a durable, buffered queue that receives JSON through an HTTP endpoint or a Worker binding. A pipeline is a SQL statement that reads from a stream and writes to a sink. A sink is the destination: an Iceberg table managed by Basin Catalog, or raw Parquet and JSON files in R2.

A structured stream declares fields and types, so every event is validated against them. An unstructured stream accepts any valid JSON and stores it in a single value column.

A schema mismatch is accepted, then dropped

Events that fail a structured schema are still accepted during ingestion and dropped during processing; they do not bounce back to the producer. Your only evidence is the user error metrics, which makes a schema mismatch one of the quietest ways to lose data in this stack.

Three schema decisions pay for themselves later:

DecisionWhat to doWhy it pays
Event timeAdd your own ts column and keep it distinct from the append columnThey answer different questions, and the append column is the partition key
IdentifiersStore request_id and order_id as stringsThey are opaque handles, not numbers you will sum
Filterable fieldsGive method, path, status, and colo their own typed columnsA JSON blob is opaque to pruning, so anything you filter on belongs in a column

A pipeline can hold more than one INSERT statement. Each statement reads the same stream and writes a different sink, which lets you fan one stream out into several tables and pay for the transform once rather than once per destination.

ProductUnit it storesDelivery and retentionQuery surfaceReach for it when
D1Rows in a relational tableSynchronous writes, transactions, row updatesIndexed SQL, point lookups and small rangesThe same row is read and rewritten by live requests
QueuesIndividual messages as units of workAt-least-once delivery, per-message retry, dead-letter handlingNone; consumers are WorkersA job must be retried and tracked one message at a time
K2Records in a durable event logRetention window, independent subscriptions, replayNone; consumers read batchesSeveral consumers must read the same events, and replay matters
Basin PipelinesEvents appended to a tableExactly-once delivery to R2, buffered stream plus Iceberg snapshotsBasin SQL or any Iceberg-compatible engineYou need aggregates over history rather than one row at a time

Figure 3 traces a single event through those objects and marks where it can disappear: a schema mismatch before the pipeline sees the row, and a WHERE clause or failed cast inside it. Both look like "the data never arrived" from the query side.

Pipelines Ingest and Transform Events
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    A["Client or Worker calls env.STREAM.send(events)"] --> B{"Matches the
stream schema?"} B -->|"no"| B1["Accepted into the stream,
then dropped in processing"] B1 --> J["Query user error metrics
to find the bad producer"] B -->|"yes"| C["Stream buffers events
durable and replayable"] C --> D["Pipeline runs INSERT ... SELECT"] D --> E{"Passes WHERE
and casts?"} E -->|"no"| E1["Filtered out by SQL
never reaches the sink"] E -->|"yes"| F["Sink writes Parquet
every 60s or at roll size"] F --> G["Iceberg commit through Catalog
exactly-once delivery"] G --> H["Visible to Basin SQL
and external engines"] F -->|"write or commit fails"| I["Sink retries
no partial commit"] I --> F classDef primary fill:#132440,color:#ffffff,stroke:#0b172b; classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a; classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f; classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420; classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f; class A,B,C,D,E,E1,F,G,H,I secondary; class B1,J danger;

The widget below holds the two artifacts this section argues for: the pipeline SQL that shapes the event, and a producer that sends a deterministic batch so the result can be reconciled later. Note what the SQL does not do: it does not write __ingest_ts, because the sink adds it, and it does not cast status, because the stream schema already typed it.

-- pipeline.sql
-- One stream feeds two tables. Basin Pipelines bills the transform once,
-- not once per INSERT statement.
-- __ingest_ts is appended by the sink and becomes the DAY partition key.

INSERT INTO request_events_sink
SELECT
    request_id,
    CAST(ts AS TIMESTAMP)   AS event_ts,
    UPPER(method)           AS method,
    path,
    status,
    duration_ms / 1000.0    AS duration_s,
    CASE
        WHEN status >= 500 THEN 'server_error'
        WHEN status >= 400 THEN 'client_error'
        WHEN status >= 300 THEN 'redirect'
        ELSE 'success'
    END                     AS outcome,
    colo
FROM request_events_stream
WHERE path IS NOT NULL;

INSERT INTO slow_requests_sink
SELECT
    request_id,
    CAST(ts AS TIMESTAMP) AS event_ts,
    path,
    duration_ms
FROM request_events_stream
WHERE duration_ms >= 1000;
"""Send a fixed batch to a Basin stream, then read it back with Basin SQL."""
import os
import time

import requests

STREAM_URL = os.environ["BASIN_STREAM_URL"]
API_TOKEN = os.environ["BASIN_TOKEN"]
ACCOUNT_ID = os.environ["CF_ACCOUNT_ID"]
BUCKET = os.environ["BASIN_BUCKET"]

BASE_TS = "2026-11-02T14:00:00Z"
TOTAL = 200
SLOW = 40


def build_events():
    """160 successes, 24 client errors, 16 server errors; the first 40 are slow."""
    events = []
    for i in range(TOTAL):
        status = 500 if i < 16 else 404 if i < 40 else 200
        events.append(
            {
                "request_id": f"req-{i:04d}",
                "ts": BASE_TS,
                "method": "get",
                "path": "/api/orders",
                "status": status,
                "duration_ms": 1500.0 if i < SLOW else 120.0,
                "colo": "SIN",
            }
        )
    return events


def post_batch(events, batch_size=50):
    headers = {
        "Authorization": f"Bearer {API_TOKEN}",
        "Content-Type": "application/json",
    }
    for start in range(0, len(events), batch_size):
        chunk = events[start : start + batch_size]
        response = requests.post(STREAM_URL, headers=headers, json=chunk, timeout=30)
        response.raise_for_status()
        print(f"sent {len(chunk)} events, status {response.status_code}")


def query(sql):
    url = (
        "https://api.sql.cloudflarestorage.com/api/v1/accounts/"
        f"{ACCOUNT_ID}/basin-sql/query/{BUCKET}"
    )
    headers = {
        "Authorization": f"Bearer {API_TOKEN}",
        "Content-Type": "application/json",
    }
    response = requests.post(url, headers=headers, json={"query": sql}, timeout=120)
    response.raise_for_status()
    return response.json()


if __name__ == "__main__":
    post_batch(build_events())
    time.sleep(180)  # longer than the 60 s roll interval plus commit time

    events = query("SELECT COUNT(*) AS n FROM default.request_events")
    slow = query("SELECT COUNT(*) AS n FROM default.slow_requests")
    print("expected:", {"request_events": TOTAL, "slow_requests": SLOW})
    print("observed:", {"request_events": events, "slow_requests": slow})

Everything in this section is append-only and configured once. Stream schemas cannot be modified after creation, pipeline SQL cannot be edited, and sink configuration cannot be changed. The only way to change any of them is to create a replacement and cut over, so treat these resources as versioned artifacts named for the generation that produced them rather than settings you will tune in place.

Availability and limits sit at the same boundary. Basin Pipelines requires the Workers Paid plan. The published account limits are 20 streams, 20 sinks, and 20 pipelines, a 5 MB maximum payload per request, and up to 1 GB/s ingest per stream — current as of the writing date, not permanent.

Catalog Manages Iceberg Tables in R2

The catalog is the part people skip, and it is the part that decides whether the table stays fast.

An Apache Iceberg table is not a file. It is a tree: a metadata.json pointer, snapshot files, manifest lists, manifest files that record per-file statistics, and Parquet data files underneath. A catalog is the single authority for which metadata.json is current. Without one, two engines writing to the same bucket would each believe their own pointer was truth. Basin Catalog provides that authority through the standard Iceberg REST interface, which is why Spark, Trino, DuckDB, Snowflake, PyIceberg, and StarRocks can all attach to the same bucket.

Two maintenance operations keep that tree healthy, and both are worth turning on deliberately.

Compaction merges small Parquet files into larger ones. Every write produces new files, and a sink writing every sixty seconds produces a lot of them. Too many files means more manifests to read during planning, more objects opened per query, and worse compression. Basin Catalog compaction accepts a target file size between 64 MB and 512 MB, with 128 MB as the default. The right target depends on the reader: 64–128 MB for latency-sensitive small result sets, 128–256 MB for streaming ingest, 256–512 MB for scan-heavy OLAP.

Snapshot expiration deletes old snapshots and the data files they alone reference. It is configured with two conditions that must both be satisfied: an age threshold, defaulting to 30 days, and a minimum number of retained snapshots, defaulting to five. Expiration is free; compaction is billed on both data processed and objects processed.

Partition on the column the sink appends

A Basin Pipelines sink appends __ingest_ts and partitions the table by day on that column. A predicate on your own event time may still prune through Parquet min/max statistics, but only the append column prunes at the partition level, before any data file is opened. Partitioning starts to matter once a table grows past roughly a thousand files; unpartitioned tables stay queryable.

That leaves three different retention clocks running at once, and confusing them is how teams lose data:

Three retention clocks, and only one is your archive

The stream buffer absorbs downstream delay; it is not your archive. Snapshot retention defines your time-travel window, which is not the same as your data-retention policy. R2 object lifetime is a storage concern — never point a lifecycle rule at the metadata/ prefix or at the data files, because it deletes objects without asking the catalog, which is exactly the direct deletion that corrupts a table.

Deletion has three different outcomes. A plain delete marks rows and creates a new snapshot; the bytes stay in R2 until snapshot expiration removes the files. DROP TABLE removes the catalog entry and keeps the data. Only DROP TABLE ... PURGE removes the bytes and is irreversible.

Basin SQL and Compatible Query Engines

Basin SQL is read-only. It cannot write, cannot run DDL, and reads Parquet only. It gives you a distributed scan over the Cloudflare network with no cluster to size, and a cost model with exactly one input: compressed bytes read from R2.

That single input is the whole optimization story. Two queries can be identical in SQL and differ enormously in price, because one never opens the files that hold the other ninety-nine days. Three levers move that number:

  • Filter on the partition column. A predicate on the append column prunes files at the catalog layer.
  • Compact the table. Fewer, larger files mean less planning overhead and better compression.
  • Name your columns. Parquet is columnar, so SELECT path, status reads two columns where SELECT * reads all of them.

A fourth failure mode is querying raw events instead of the shaped table. An unstructured stream keeps everything in one value column, so a query that parses JSON at read time cannot project columns and cannot prune on a field it must parse first. The Iceberg table exists precisely so the read path never does that work twice.

The two shapes below differ only in what they touch:

-- Expensive: no partition predicate, every column, every file.
SELECT * FROM default.request_events;

-- Cheap: one day partition, two columns, one aggregate.
SELECT path, COUNT(*) AS n
FROM default.request_events
WHERE __ingest_ts >= '2026-11-02'
GROUP BY path
ORDER BY n DESC
LIMIT 20;
# Plan first (metadata only), then run the pruned query.
npx wrangler basin sql query "<WAREHOUSE>" \
  "EXPLAIN SELECT * FROM default.request_events"
npx wrangler basin sql query "<WAREHOUSE>" \
  "SELECT path, COUNT(*) AS n FROM default.request_events \
   WHERE __ingest_ts >= '2026-11-02' GROUP BY path ORDER BY n DESC LIMIT 20"

Price is per byte scanned. Basin SQL charges $0.0025 per GB scanned, $2.50 per TB, with 10 GB included per month and a 10 MB minimum charge per query. Metadata-only statements scan no data and cost nothing, so checking the plan before the scan is free. D1 bills rows read instead: the levers there are indexes and query shape, not file pruning. Figure 4 shows the same table under both query shapes.

Partition pruning changes how many files a query reads Two panels over the same ten-file table. The left panel has no partition filter and every file is shaded, meaning ten files are scanned. The right panel adds a predicate on the ingest timestamp and only one file is shaded. A note below states that billing is based on compressed bytes read with a ten megabyte minimum, and that metadata-only statements are free. Query A: no partition filter Query B: WHERE __ingest_ts >= ... 10 files scanned, every day in the table 1 file scanned, one day partition filter Billed bytes are the compressed bytes actually read from R2, with a 10 MB minimum per query. Failure branch: budget-gated aggregates return HTTP 400 before execution. EXPLAIN, SHOW, and DESCRIBE scan no data, so check the plan before you pay for the scan.

Failure behavior is documented, which makes it testable. The error code names the layer that refused the query:

CodeMeaningWhat to do
40003Syntax errorFix the statement; nothing ran
40004Unsupported feature, unknown column, or type mismatchRewrite the expression or cast the column
80001Edge connection failureRetry; the failure is not in the query

Heavy queries can also time out. Multi-way joins across three or more large tables, COUNT(DISTINCT) across joins, large sorts, and window functions over large partitions are the usual suspects, and they fail by timing out rather than by returning an error.

Budget-gated features are rejected before they run

Basin SQL estimates memory first and returns a 400 rather than letting a heavy query burn compute. Exact percentiles and MEDIAN, distinct aggregates, and all window functions sit in that group, so reduce the rows they process or use an approximate equivalent before you retry.

Two syntax substitutions are mandatory. Use NOT EXISTS instead of NOT IN on a nullable column, and write window frames inline rather than in a named clause.

Two features are simply absent. Lateral derived tables are unsupported, and now() is quantized to 10 ms boundaries and forced to UTC, so it is not a high-resolution clock.

Compatible engines cover the other half of the tradeoff. The same catalog serves Spark, Trino, Snowflake, DuckDB, PyIceberg, and StarRocks. Those engines can write, run MERGE, and issue DDL that Basin SQL cannot, at the cost of operating the compute yourself. Because R2 charges no egress, reading the same bucket from another cloud costs storage and Class B operations rather than transfer, which is what makes the external-engine path practical.

One credential detail is easy to get wrong. Basin Catalog supports read-only and read-write tokens, and the SigV4 credentials it vends to an engine inherit the R2 permissions of the token that authenticated. A read-only catalog token paired with a read-write R2 token can still write objects into the bucket. If you want read-only, scope both halves to read-only.

Design a Small Request-Analytics Pipeline

This exercise is design-only. The commands follow the published CLI flow, and the expected numbers are the designed targets for a deterministic fixture, not measurements from a hosted run. No Basin resources were created for this article.

Guided exercise

Design a Small Request-Analytics Pipeline

Status: design-only, not executed. Prerequisites: a Cloudflare account with Workers Paid, R2 enabled, a linked payment card (required by Basin Catalog and Basin SQL), Node.js with a Wrangler-supported version, and an API token carrying Basin Pipelines Read/Send/Edit, Basin Catalog Read/Edit, Basin SQL Read, and Workers R2 Storage Read/Edit.

Setup. Pick a unique bucket name, for example basin-lab-<your-initials>-01, and save this as schema.json:

  • request_id — string, required
  • ts — string
  • method — string
  • path — string, required
  • status — int32
  • duration_ms — float64
  • colo — string

Actions.

  1. Bucket and catalog. Create the bucket, enable the catalog, and record the warehouse name.
  2. Stream. Create the stream from the schema file and record the ingest endpoint.
  3. Sinks. Create both sinks: one for all events, one for slow requests, both rolling every 60 seconds.
  4. Pipeline. Create it from the SQL panel above.
  5. Fixture. Run the Python panel with the four environment variables set; it sends 200 events in four batches of 50.
  6. First query. Wait at least 180 seconds, then count the table.
  7. Classification. Group by outcome and order by count.

Expected results.

CheckExpectedEvidence to record
Rows in request_events200The count returned by the first query
Rows in slow_requests40The count from the filtered table
Outcome groups160 / 24 / 16The three group counts, in order
Columns__ingest_ts is present, though you never sent itThe column list the catalog reports

A first query that returns "table not found" or zero rows is the single most common false alarm: the sink has not committed its first file yet.

Failure checks are the point of the fixture. Send one event with a string status and confirm the stream accepts it while the pipeline drops it, leaving the row count unchanged and the user error metrics higher. Query before the roll interval and confirm the table is absent or empty. Re-run a query with a token lacking Basin SQL Read and confirm an authorization error rather than an empty result. Finally, compare the plan for the grouped query with the plan for the same query using every column.

Cost dimensions. Transforms are billed per GB processed, sinks per GB delivered (uncompressed, higher for Iceberg than JSON), Basin SQL per GB scanned with a 10 MB floor per query, and Basin Catalog per million operations plus compaction data and objects. A 200-event fixture should land in the cents range, but confirm against billing rather than trusting an estimate.

Cleanup. Delete the pipeline, then both sinks, then the stream. Deleting a stream permanently discards any buffered events and removes dependent pipelines, so do it after the sinks are gone. Then run npx wrangler basin catalog disable <BUCKET>, delete the bucket, and revoke the API token.

Run the commands in order, and record each identifier as it is printed.

# 1. Bucket and catalog. The output names the warehouse.
npx wrangler r2 bucket create <BUCKET>
npx wrangler basin catalog enable <BUCKET>

# 2. Stream. The output names the ingest endpoint.
npx wrangler basin pipelines streams create request_events_stream \
  --schema-file schema.json --http-enabled true --http-auth true

# 3. Sinks. Repeat for slow_requests_sink, table slow_requests.
npx wrangler basin pipelines sinks create request_events_sink \
  --type basin-catalog --bucket <BUCKET> --namespace default \
  --table request_events --roll-interval 60 --catalog-token <TOKEN>

# 4. Pipeline, from the SQL panel above.
npx wrangler basin pipelines create request_events --sql-file pipeline.sql

# 5. Fixture: save the Python panel as send_events.py first.
export BASIN_STREAM_URL="<INGEST_ENDPOINT>"
export BASIN_TOKEN="<API_TOKEN>"
export CF_ACCOUNT_ID="<ACCOUNT_ID>"
export BASIN_BUCKET="<BUCKET>"
python3 send_events.py

# 6. Wait past the roll interval, then count and classify.
npx wrangler basin sql query "<WAREHOUSE>" "SELECT COUNT(*) AS n FROM default.request_events"
npx wrangler basin sql query "<WAREHOUSE>" "SELECT outcome, COUNT(*) AS n FROM default.request_events GROUP BY outcome ORDER BY n DESC"

Reconcile Ingested Events With a Deterministic Query Result

The point of sending a fixed fixture is that the answer is knowable in advance. Reconciliation is the act of comparing four independent assertions, not one:

  1. Row count. COUNT(*) equals 200.
  2. Filtered count. COUNT(*) on slow_requests equals 40.
  3. Distribution. The outcome groups sum to the total and match 160 / 24 / 16.
  4. Identity. COUNT(DISTINCT request_id) equals 200, which is the actual check for exactly-once behavior. A count of 200 with 198 distinct identifiers means duplicates replaced losses.

All four passing is the only honest pass. Three of four is a fail, and the failing assertion tells you which layer to inspect: a low row count with a correct distribution points at the producer; a correct count with a wrong distribution points at the SQL transform; duplicates point at the sink or a replayed batch; a missing table points at the roll interval or the sink credentials.

A short self-check, with answers:

Where does the partition boundary come from? Basin Pipelines appends __ingest_ts to Iceberg sinks and partitions by day on that column, so filtering on it prunes partitions. Filtering on your own event time may still prune through file statistics, but it does not use the partition spec.

You need a new country field on every event. What changes? A new stream with the field in its schema, a new sink, and a new pipeline, because stream schemas and pipeline SQL are immutable after creation. Then reconcile the old and new tables in the query layer, for example with UNION ALL, or backfill into the new table.

A query fails with a budget-gated 400. What are two legitimate fixes? Add a predicate on the partition column or a grouping that reduces the rows processed, and replace exact aggregates with approximate equivalents such as approx_percentile_cont.

Why not serve the order-status page from this table? Because the analytical path is asynchronous and lag-tolerant, partitioned for scans rather than point lookups, and read-only. The page needs a transactional row read with a sub-second budget, which is D1's job.

Unresolved limitations, stated plainly. The exercise above was not executed, so no observed timings, file counts, byte counts, or compaction behavior are reported. The exact retention duration of a stream buffer is not documented at the level this article would need, so the prose treats it as transient rather than as an archive. Product naming is mid-transition: legacy names and APIs remain valid, and their deprecation dates were not published at the time of writing. Prices and limits are dated, not timeless.

Verification date: 5 November 2026. Planning baseline: 2 November 2026. Products described at Basin general availability, published 1 October 2026. No tested tool versions exist for this article because no commands were run against a hosted account.

References:

  • Basin overview: https://developers.cloudflare.com/basin/
  • Basin Pipelines: https://developers.cloudflare.com/basin-pipelines/
  • Basin Pipelines limits: https://developers.cloudflare.com/basin-pipelines/platform/limits/
  • Basin Catalog sinks, rolling policy and format: https://developers.cloudflare.com/basin-pipelines/sinks/available-sinks/r2-data-catalog/
  • Writing to streams and schema validation: https://developers.cloudflare.com/basin-pipelines/streams/writing-to-streams/
  • Basin Catalog: https://developers.cloudflare.com/basin-catalog/
  • Table maintenance, compaction and snapshot expiration: https://developers.cloudflare.com/basin-catalog/table-maintenance/
  • Deleting data and Iceberg metadata: https://developers.cloudflare.com/basin-catalog/deleting-data/
  • Basin Catalog pricing: https://developers.cloudflare.com/basin-catalog/platform/pricing/
  • Basin SQL: https://developers.cloudflare.com/basin-sql/
  • Basin SQL limitations and best practices: https://developers.cloudflare.com/basin-sql/reference/limitations-best-practices/
  • Basin SQL pricing: https://developers.cloudflare.com/basin-sql/platform/pricing/
  • Basin request-analytics CLI guide: https://developers.cloudflare.com/basin/get-started/guide/
  • Choosing a data or storage product: https://developers.cloudflare.com/workers/platform/storage-options/
  • Basin general availability announcement: https://developers.cloudflare.com/changelog/post/2026-10-01-basin-ga/

Next in the Series

In Run AI Inference With Workers AI, we'll explore Choose models, request shapes, streaming, and evaluation data.