# Load S3 JSON files continuously with ClickHouse S3Queue

Use the `S3Queue` table engine in [ClickHouse](../querying/clickhouse.md) to watch a bucket for new gzip NDJSON files. A materialized view writes incoming rows to MergeTree. ClickHouse Keeper tracks which files the queue has processed.

## The files

The examples load gzip NDJSON objects under date and hour prefixes:

```text
s3://<bucket>/<prefix>/date=2026-11-23/hour=00/<file>.ndjson.gz
```

Each line is one JSON object with nested fields. These come from Send2Bucket's sample dataset, so each event sits inside a small envelope:

```json
{"v":1,"delivery_batch_id":"dlv_00361pk2klrlp0eurim3mi7all8f0","stream_id":"3f6c2a9e-8b1d-4e7a-9c55-0d2b7e41a8f3","batch_id":"bat_00361pk2dn7r4395obrtf0h1kfmp0","received_at":"2026-11-23T00:16:47.243186Z","signal":"event","data":{"event":"order.paid","user_id":"usr_0003","plan":"team","ts":"2026-11-19T13:05:00Z","order_id":"ord_20005","cents":19900,"currency":"usd","items":[{"sku":"sku_1","qty":1}]}}
```

## How S3Queue works

A pipeline is three objects:

| Object | Role |
|---|---|
| `S3Queue` table | Lists the path on a timer and reads each file it has not processed. It stores nothing, and a plain `SELECT` on it is refused by default. |
| Materialized view | Attaching it starts the queue. It runs on each batch of rows the queue reads and inserts the result into the target table. |
| Target table | A MergeTree table that holds the rows and answers queries. |

The queue records which files it processed in ClickHouse Keeper (or ZooKeeper), not in the table. That state is what keeps a file from loading twice, so the queue needs Keeper even on one server.

## Set up Keeper on a single server

ClickHouse Cloud provides Keeper; skip to the next section. Self-hosted ClickHouse ships Keeper in the server binary. Following [ClickHouse Keeper](https://clickhouse.com/docs/guides/oss/deployment-and-scaling/keeper), add a `<keeper_server>` section with one server, and point the server's `<zookeeper>` client at it, in a file such as `/etc/clickhouse-server/config.d/keeper.xml`:

```xml
<clickhouse>
    <keeper_server>
        <tcp_port>9181</tcp_port>
        <server_id>1</server_id>
        <log_storage_path>/var/lib/clickhouse/coordination/log</log_storage_path>
        <snapshot_storage_path>/var/lib/clickhouse/coordination/snapshots</snapshot_storage_path>
        <raft_configuration>
            <server>
                <id>1</id>
                <hostname>clickhouse-1</hostname>
                <port>9234</port>
            </server>
        </raft_configuration>
    </keeper_server>
    <zookeeper>
        <node>
            <host>clickhouse-1</host>
            <port>9181</port>
        </node>
    </zookeeper>
</clickhouse>
```

Replace `clickhouse-1` with the server's hostname and restart ClickHouse. `SELECT * FROM system.zookeeper_connection` then returns one row. A single Keeper node has no failover: if its disk is lost, so is the record of processed files.

## Connect to the bucket

Store the bucket location and a read-only key in a [named collection](https://clickhouse.com/docs/concepts/features/configuration/server-config/named-collections):

```sql
CREATE NAMED COLLECTION events_bucket AS
  url = 'https://<bucket>.s3.<region>.amazonaws.com/<prefix>/',
  access_key_id = '<access_key_id>',
  secret_access_key = '<secret_access_key>';
```

For S3-compatible storage, put the endpoint and bucket in the URL, path-style: `https://<endpoint>/<bucket>/<prefix>/`. Before building the queue, check what your glob matches with the [`s3` table function](https://clickhouse.com/docs/reference/functions/table-functions/s3), which takes the same arguments:

```sql
SELECT _path, count() AS rows
FROM s3(events_bucket, filename = 'date=*/hour=*/*.ndjson.gz', format = 'JSONEachRow')
GROUP BY _path;
```

`*` matches within one folder, so `date=*/hour=*/*.ndjson.gz` matches files exactly two folders down. ClickHouse picks gzip from the `.gz` extension.

## Create the target table

The target holds the fields you query as typed columns and keeps the rest of the record in a [`JSON` column](https://clickhouse.com/docs/reference/data-types/newjson):

```sql
CREATE DATABASE IF NOT EXISTS ingest;

CREATE TABLE ingest.events
(
    file        String,
    record_hash UInt64,
    received_at DateTime64(6, 'UTC'),
    signal      LowCardinality(String),
    event       LowCardinality(String),
    user_id     String,
    cents       Nullable(Int64),
    items       Array(Tuple(sku String, qty UInt32)),
    data        JSON
)
ENGINE = ReplacingMergeTree
PARTITION BY toYYYYMM(received_at)
ORDER BY (signal, event, file, record_hash);
```

`file` and `record_hash` identify each row, so a row loaded twice has the same sorting key as the first copy. [`ReplacingMergeTree`](https://clickhouse.com/docs/reference/engines/table-engines/mergetree-family/replacingmergetree) keeps one of them; see [Duplicates](#duplicates-and-at-least-once). If you never expect duplicates, `MergeTree` with the same columns works too.

## Create the queue

The queue table lists only the top-level keys you read; `JSONEachRow` skips the others:

```sql
CREATE TABLE ingest.events_queue
(
    received_at DateTime64(6, 'UTC'),
    signal      LowCardinality(String),
    data        JSON
)
ENGINE = S3Queue(events_bucket, filename = 'date=*/hour=*/*.ndjson.gz', format = 'JSONEachRow')
SETTINGS
    mode = 'unordered',
    tracked_files_limit = 100000,
    polling_max_timeout_ms = 60000;
```

`mode` has no default and must be set. The two settings after it matter for most buckets:

| Setting | Default | Why change it |
|---|---|---|
| `tracked_files_limit` | 1000 | In `unordered` mode, the queue keeps one Keeper node per processed file. Past the limit it forgets the oldest files and loads them again. Set it above the number of files the path will hold, or delete old files with a lifecycle rule. `tracked_file_ttl_sec` forgets by age instead. |
| `polling_max_timeout_ms` | 600000 | Each empty poll adds `polling_backoff_ms` (30 s) to the wait, up to this cap. On a quiet bucket, a new file can wait 10 minutes. 60 s caps the wait at a minute, at the cost of more list requests. |

### Unordered or ordered

| | `unordered` | `ordered` |
|---|---|---|
| Keeper state | Every processed file name | The largest processed name, plus files waiting for a retry |
| A file whose name sorts before one already processed | Loaded | Skipped (see below) |
| Use when | Files can arrive in any order, or you are unsure | File names always increase, such as a timestamp per file from one writer |

`ordered` stores far less in Keeper, but only works when every new file sorts after every older one. Date and hour folders do not guarantee that: two writers, a retried upload or a backfill can put a file under an hour that is already loaded. In our test with `buckets = 1` and `processing_threads_num = 1`, such a late file was skipped. With the default settings, a late file was loaded. Neither result is something to rely on, so use `unordered` unless your file names are strictly increasing.

## Start loading

The materialized view parses the nested fields on the way in. A path in a `JSON` column reads as `data.event`, and its type is decided when you cast it. `data.items[]` reads an array of objects as an array of `JSON` values:

```sql
CREATE MATERIALIZED VIEW ingest.events_consumer TO ingest.events AS
SELECT _path AS file,
       cityHash64(_path, received_at, signal, data) AS record_hash,
       received_at,
       signal,
       data.event::String AS event,
       data.user_id::String AS user_id,
       data.cents::Nullable(Int64) AS cents,
       arrayMap(i -> (i.sku::String, i.qty::UInt32), data.items[]) AS items,
       data
FROM ingest.events_queue;
```

Loading starts as soon as the view exists. A path missing from a record reads as an empty string, `NULL` or `[]`, depending on the cast. To pause, run `DETACH TABLE ingest.events_consumer`; `ATTACH TABLE ingest.events_consumer` resumes from where it stopped, and files added in between load then.

## Query the table

Events by name, with revenue from `order.paid`. With the one sample file loaded, the 300 events give:

```sql
SELECT event, count() AS events, sum(cents) / 100 AS revenue_usd
FROM ingest.events
WHERE signal = 'event'
GROUP BY event
ORDER BY events DESC;
```

```text
┌─event──────┬─events─┬─revenue_usd─┐
│ page.view  │    177 │        ᴺᵁᴸᴸ │
│ order.paid │     53 │        4161 │
│ email.sent │     47 │        ᴺᵁᴸᴸ │
│ signup     │     23 │        ᴺᵁᴸᴸ │
└────────────┴────────┴─────────────┘
```

Units sold per SKU, one row per array element with `ARRAY JOIN`:

```sql
SELECT item.sku AS sku, sum(item.qty) AS units
FROM ingest.events
ARRAY JOIN items AS item
WHERE event = 'order.paid'
GROUP BY sku
ORDER BY units DESC;
```

```text
┌─sku───┬─units─┐
│ sku_1 │   108 │
└───────┴───────┘
```

Fields you did not extract are still in `data`: `data.plan::String` or `data.path::String` work in any query.

## Check progress

[`system.s3queue_log`](https://clickhouse.com/docs/reference/system-tables/s3queue_log) keeps one row per attempt at a file, with its row count and any error. It is flushed every few seconds; `SYSTEM FLUSH LOGS` writes it now. The server config must enable it with an `<s3queue_log>` section, which the default config and the official Docker image include.

```sql
SELECT replaceRegexpOne(file_name, '.*/', '') AS file,
       count() AS attempts,
       argMax(status, event_time) AS status,
       argMax(rows_processed, event_time) AS rows,
       argMax(left(exception, 50), event_time) AS last_error
FROM system.s3queue_log
WHERE database = 'ingest' AND table = 'events_queue'
GROUP BY file
ORDER BY file;
```

After we added a second file and a file that is not JSON (`bad.ndjson.gz`), it returned:

```text
┌─file────────────────────────────────────────┬─attempts─┬─status────┬─rows─┬─last_error─────────────────────────────────────────┐
│ bad.ndjson.gz                               │       11 │ Failed    │    0 │ Code: 27. DB::Exception: Cannot parse input: expec │
│ dlv_00361pk2klrlp0eurim3mi7all8f0.ndjson.gz │        1 │ Processed │  380 │                                                    │
│ dlv_00361pl1ee1lq992omluah5eopacs.ndjson.gz │        1 │ Processed │    3 │                                                    │
└─────────────────────────────────────────────┴──────────┴───────────┴──────┴────────────────────────────────────────────────────┘
```

The second file loaded within a minute of its upload. A file that fails is retried up to `loading_retries` times (10 by default, so 11 attempts here), while the other files keep loading. After the last retry the file stays failed; fix it and upload it under a new name. [`system.s3_queue_metadata`](https://clickhouse.com/docs/reference/system-tables/s3_queue_metadata) counts the files recorded in Keeper, and [`system.s3queue_metadata_cache`](https://clickhouse.com/docs/reference/system-tables/s3queue_metadata_cache) shows this server's in-memory state per file, including files being processed now:

```sql
SELECT processed_nodes_count, processing_nodes_count, failed_nodes_count
FROM system.s3_queue_metadata;
```

```text
┌─processed_nodes_count─┬─processing_nodes_count─┬─failed_nodes_count─┐
│                     2 │                      0 │                  1 │
└───────────────────────┴────────────────────────┴────────────────────┘
```

Each target row carries its `file`, so the table can be checked against the log:

```sql
SELECT replaceRegexpOne(file, '.*/', '') AS file, count() AS rows
FROM ingest.events FINAL
GROUP BY file;
```

## Duplicates and at least once

S3Queue loads each file at least once, not exactly once. The [S3Queue documentation](https://clickhouse.com/docs/reference/engines/table-engines/integrations/s3queue) lists, among others, two ways a file can load twice: a parse error partway through a file followed by a retry, and an abnormal server stop. Two more cases come from setup: `unordered` mode loads files again past `tracked_files_limit` or `tracked_file_ttl_sec`, and dropping and recreating the queue table starts with empty state. In our test, recreating the queue loaded every file again.

The target table above absorbs those repeats. A row loaded twice has the same `file` and `record_hash`, and `ReplacingMergeTree` keeps one copy when it merges parts. Merges run in the background, so add `FINAL` when a count must be exact now:

```sql
SELECT count() AS raw_rows, (SELECT count() FROM ingest.events FINAL) AS unique_rows
FROM ingest.events;
```

After we dropped and recreated the queue, `raw_rows` was 766 and `unique_rows` 383, and the events query above counted 112 `order.paid` events instead of 56. `OPTIMIZE TABLE ingest.events FINAL` forces the merge, after which both counts were 383. Two identical lines in one file also share a key and collapse into one row; if that can happen legitimately in your data, add a field that tells them apart to the hash. Duplicates that are already in the files, such as a client sending the same event twice, have different keys. Remove those with an ID of your own in each record.

## Where Send2Bucket fits

Send2Bucket is a hosted endpoint for JSON events and OpenTelemetry that writes them to your own bucket in this layout, so the pipeline above works on its objects. Per [Delivery format](../delivery-format.md):

- Each delivery batch is one gzip NDJSON object at `<prefix>/s2b/stream=<stream_id>/date=YYYY-MM-DD/hour=HH/<delivery_batch_id>.ndjson.gz`. Point the named collection at `<prefix>/s2b/` and use `filename = 'stream=*/date=*/hour=*/*.ndjson.gz'`, which leaves out the destination's test objects under `_verify/`.
- `data` is the JSON you sent, unchanged; `signal` is `event`, `log`, `span` or `metric`; `resource` and `scope` are set on OpenTelemetry records.
- Use `unordered` mode. Keys start with the stream ID, so a new object in one stream sorts before older objects in another, and a retried upload can land after a newer object in the same stream.
- A retried delivery writes the same bytes under the same key, so it never adds an object. A client that resends a request does store its records twice, under a new `delivery_batch_id`; see [Delivery semantics](../delivery-semantics.md).

The [ClickHouse querying guide](../querying/clickhouse.md#continuously-with-s3queue) has the S3Queue setup for the full envelope, with `stream` and `date` cut from `_path`, a scheduled alternative with a refreshable materialized view, and queries for logs, spans and metrics. To send data in the first place, start with [Quick start](../quick-start.md).

## Notes

- Each poll lists the objects under the path, which your provider bills as list requests. A lower `polling_max_timeout_ms` means more of them on a quiet bucket.
- `after_processing = 'delete'` removes each file once loaded, which keeps the listing short. Use it only on a copy of the data you do not need elsewhere; the default is `keep`.
- A new column in the files needs no change while it stays inside `data`. To promote it to a typed column, add it to the target table with `ALTER TABLE … ADD COLUMN`, then recreate the materialized view with the new expression. Rows already loaded keep the column's default.
- `SELECT * FROM system.s3_queue_settings WHERE table = 'events_queue'` shows the settings the queue runs with, including defaults.
