Analytics store
Last updated: 2026-11-27T14:42:00-03:00 (UTC-3)
PostgreSQL is the gateway’s database and stays the source of truth for usage, money, quotas, receipts, identity and configuration. On large deployments, usage analytics over 30 or 90 days and sparse log filters over long windows outgrow it (see the measured comparison: at 10 million events the 30-day Usage view no longer fits its 5-second deadline). The analytics store is an optional read store for those reads: the gateway copies the usage events from PostgreSQL into it, and each purpose that reads it is turned on by its own flag. ClickHouse is its only engine today. The parameters are named by their function (analytics_store, analytics_store_usage), and engine: clickhouse selects what serves it, so another engine would change a value, never a name; until 0.0.1-rc.2 the block was clickhouse: and the flags clickhouse_analytics and clickhouse_request_logs, which are now refused naming the new names (upgrading from 0.0.1-rc.2).
ClickHouse is never inside the gateway image and never written by a request: the copy reads committed PostgreSQL rows in the background. Turning it off, or losing it, leaves every write and every PostgreSQL read as they are.
| Flag | Default | What it turns on |
|---|---|---|
analytics_store_usage |
false |
The copy, and usage analytics read from it (requires usage_analytics) |
analytics_store_request_logs |
false |
The copy, and request log pages read from it (requires request_logs) |
Both are operator controls under plan entitlements and can be changed at runtime from Settings → Features. The copy runs while at least one of them is on and the analytics_store block names an endpoint.
Configure
Section titled “Configure”ClickHouse may be self-hosted (the Compose and Helm profiles can run it beside the gateway) or a managed service. The gateway needs the native protocol port and an existing database; it creates its own table, gateway_usage_events_v1, at the first copy.
features: usage_analytics: true analytics_store_usage: trueanalytics_store: engine: clickhouse addresses: ["clickhouse.internal:9440"] database: gateway username_env: ANALYTICS_STORE_USER password_env: ANALYTICS_STORE_PASSWORD tls: mode: verify_fullEvery field below sits under analytics_store in the gateway YAML (boot configuration: there is no environment variable or console editor for them, and the console and GET /api/v1/admin/analytics-store show only the safe view; the Usage panel lists the four copy.* bounds from it, read-only).
| Field | Default | Bounds | Meaning |
|---|---|---|---|
analytics_store.engine |
none | clickhouse |
The analytics store engine. Required once addresses is set; any other value is refused naming the engines. The fields below are the ones the clickhouse engine reads; a future engine would refuse those it does not support (analytics_store.copy is not supported by the analytics store engine ...) |
analytics_store.addresses |
[] |
one host:port |
Native protocol endpoint (9000 plain, 9440 TLS). Empty means the analytics store is not configured. One server: the copied table is a local MergeTree, so a replicated cluster is not supported yet |
analytics_store.database |
gateway |
1–63 letters, digits, _ |
Database that holds the copied table; it must exist |
analytics_store.username_env |
"" |
environment variable name | Variable (or <NAME>_FILE with secret_files) holding the user; empty uses default |
analytics_store.password_env |
"" |
environment variable name | Variable (or <NAME>_FILE) holding the password. In both fields the names 0.0.1-rc.2 shipped, GATEWAY_CLICKHOUSE_USER and GATEWAY_CLICKHOUSE_PASSWORD, are refused at load naming GATEWAY_ANALYTICS_STORE_USER and GATEWAY_ANALYTICS_STORE_PASSWORD |
analytics_store.tls.mode |
verify_full |
verify_full, disable |
verify_full checks the server certificate against the system roots or root_cert_file_env; disable is plain TCP for a private network |
analytics_store.tls.root_cert_file_env |
"" |
environment variable name | Variable holding the path of a PEM CA bundle (self-signed or private CA) |
analytics_store.tls.server_name |
"" |
host name | Name checked in the certificate when it differs from the address |
analytics_store.dial_timeout |
5s |
100ms–1m | One connection attempt |
analytics_store.query_timeout |
30s |
100ms–5m | One copy statement |
analytics_store.max_open_connections |
8 |
1–128 | Connections of one replica |
analytics_store.copy.batch_size |
5000 |
100–100000 | Events one copy pass reads |
analytics_store.copy.interval |
2s |
200ms–5m | Pause between passes once the copy has caught up; a pass that stopped at its batch bound is followed at once |
analytics_store.copy.gap_grace |
10m |
1m–24h | Age past which an open gap is reported as stuck (oldest_gap_seconds); a gap never closes by age alone (see below) |
analytics_store.copy.max_lag |
5m |
10s–24h | How far behind PostgreSQL the copy may be for reads to use ClickHouse |
The block is read at start-up: restart to apply a change. Configure every replica alike. A replica without the block turns the change log off only after no replica has copied for 10 minutes, and a replica whose block fails to open leaves the copy to the others; a replica that sees both flags off turns it off after one minute without a pass. Each turn-off makes the next enable copy everything again.
Managed ClickHouse (for example ClickHouse Cloud): use the service’s native TLS endpoint (port 9440) with tls.mode: verify_full; the public CA is in the system roots.
The ClickHouse user needs, on its database, CREATE TABLE, SELECT, INSERT, ALTER DELETE and ALTER UPDATE (lightweight deletes for redactions and retention), ALTER TTL (to move the retention of the span copy when analytics_store.spans_retention_days changes), ALTER ADD COLUMN (to add a column a release adds to an existing span copy table) and TRUNCATE; nothing on other databases and no URL, S3, FILE, REMOTE or SYSTEM grants.
Run the analytics store beside the gateway
Section titled “Run the analytics store beside the gateway”Both profiles can run a ClickHouse server next to the gateway, off by default and never inside the gateway image (clickhouse/clickhouse-server:25.12.11.4, pinned by digest, about 1 GB). scripts/bootstrap-local-secrets.py writes GATEWAY_ANALYTICS_STORE_PASSWORD next to the PostgreSQL password.
Both use the same server files (deploy/helm/gateway/files/clickhouse/): only the native (9000) and HTTP (8123, used by the image’s first-start setup and the health checks) listeners, console logs at warning, and one user, gateway, limited to the gateway database with the grants above; the image’s passwordless default user is removed. The server runs as the image’s non-root user with every capability dropped and a read-only root filesystem, and refuses to start when its password is empty. A local secret file written before this option existed lacks GATEWAY_ANALYTICS_STORE_PASSWORD: run scripts/bootstrap-local-secrets.py again (it keeps existing values).
Docker Compose (deploy/docker/compose.yaml): the clickhouse service runs only with the analytics-store profile (named clickhouse until 0.0.1-rc.2), with its data in the gateway_clickhouse volume; no port is published. The gateway gets GATEWAY_ANALYTICS_STORE_USER (default gateway, or the value in your environment).
docker compose -f deploy/docker/compose.yaml --env-file deploy/docker/.env.local --profile analytics-store up -dHelm (deploy/helm/gateway): analyticsStore.bundled.enabled: true adds a one-replica StatefulSet and its Service gateway-clickhouse (values under analyticsStore.bundled: image, pullPolicy, serviceName, storage 20Gi, storageClassName, resources 250m/1Gi requests and 2/4Gi limits, nodeSelector, tolerations, affinity). analyticsStore.engine (default clickhouse, the only value) must match analytics_store.engine in gateway.config when the YAML sets one. Its password is GATEWAY_ANALYTICS_STORE_PASSWORD in gateway.existingSecret, and the chart sets GATEWAY_ANALYTICS_STORE_USER=gateway on the gateway Pods. With networkPolicy.enabled, ClickHouse accepts only the gateway Pods on port 9000, and gateway egress to it is allowed when egress rules are on; without it, any Pod that can reach the ClickHouse Pod can try both ports, which still require the password.
In both, point the gateway at it and turn a purpose on:
features: analytics_store_usage: trueanalytics_store: engine: clickhouse addresses: ["clickhouse:9000"] # Helm: ["gateway-clickhouse:9000"] database: gateway username_env: GATEWAY_ANALYTICS_STORE_USER password_env: GATEWAY_ANALYTICS_STORE_PASSWORD tls: mode: disable # private network between the two containersSize the server for the volume; through the gateway the store’s latency, resource use and copy cost are measured at 1 and 10 million events. In the engine comparison, 50 million events took 3.4 GiB of ClickHouse disk against 27 GiB in PostgreSQL, and ClickHouse is an addition, not a replacement: PostgreSQL keeps every event.
Retention and deletion
Section titled “Retention and deletion”The copy follows PostgreSQL: the metadata retention purge and the end-user deletion job change PostgreSQL first, and their triggers carry each deleted or redacted event to ClickHouse at the next pass. ClickHouse has no retention of its own to configure. Lightweight deletes hide rows at once and remove them from disk at the part’s next merge.
How the copy works
Section titled “How the copy works”- One pass at a time. Every replica runs the copy loop; a pass locks the single state row in PostgreSQL, so only one runs at a time across replicas and a pass that dies leaves the state as it was.
- Its own connection. The copy uses one PostgreSQL connection of its own (with the
storage.databasesettings, application nameai-gateway-analytics-copy), opened on first use, so a pass waiting on a slow ClickHouse never holds a connection that requests wait for. Count one more connection per replica in the database’s limit. - New events are read after an identifier cursor, in identifier order. An identifier is taken before its transaction commits, so a smaller one can appear after a larger one: every identifier missing between copied events is kept as a gap and looked for again on each pass; an identifier found is copied and taken out of its gap. A gap closes only when every transaction older than the pass that recorded it has ended (PostgreSQL’s snapshot horizon passed that pass’s transaction ID) and at least 30 seconds have passed; age alone never closes one. A transaction left open (or a long one anywhere in the cluster, which holds the horizon back) keeps its gaps open and shows as
oldest_gap_seconds; past 50000 open gaps the cursor waits. - Changes. End-user redaction and retention deletes are logged by PostgreSQL triggers while the copy is on; the next pass deletes those events in ClickHouse and writes their current row again.
- Idempotent and resumable. A pass asks ClickHouse which of its events are already there and writes only the others, then commits the cursor in PostgreSQL. A pass that crashed after writing to ClickHouse is repeated without duplicates.
- Off and on again. When both flags are off, the copy turns the change log off. The next enable empties the ClickHouse table and copies every event again, because changes made meanwhile were not logged. Before it reads anything, an enable waits until every transaction older than itself has ended, so a redaction or delete whose statement ran just before the enable is part of the copy.
- Money columns (T160.003). With
budget_charge_reports, each copied event also carriesquota_reservation_id,valuation_state,estimated_usd(the known estimate, as exact decimal text) and its budget side,budget_charge_stateandbudget_charge_units(1e-12 USD), as they stand when the event is copied: a later reconciliation of its reservation shows in the PostgreSQL reports, not in the copy. A table created by an older release gains these columns (ALTER TABLE ... ADD COLUMN IF NOT EXISTS) at the first pass with the flag on; with the flag off the copy neither alters the table nor writes the columns, so an older table keeps working with a user withoutALTERrights. Earlier rows, and rows copied with the flag off, keep them empty. - While ClickHouse is unreachable, passes fail and nothing is lost: the cursor waits and retention deletes and redactions accumulate in the change log (
pending_changes) until it answers again.
Usage analytics from the analytics store
Section titled “Usage analytics from the analytics store”With analytics_store_usage on, GET /api/v1/admin/analytics (the Usage page) decides per request where to read:
| Condition | Store | read_store.fallback_reason |
|---|---|---|
The copy is current (lag within copy.max_lag) |
ClickHouse | — |
No analytics_store addresses, or the store failed to open |
PostgreSQL | not_configured |
| The copy is filling after an enable | PostgreSQL | copying |
Lag over copy.max_lag, or a redaction or delete not yet applied to the copy |
PostgreSQL | behind |
| ClickHouse failed or timed out on any statement (it gets at most half of the read’s deadline, so PostgreSQL still has time to answer), and for 30 seconds after such a failure, or after a copy pass failed on ClickHouse, on that replica | PostgreSQL | unavailable |
The whole view comes from one store: summary, timeline, the six rankings, the end-user and tag rankings, the 50 most recent events, the comparison summary (analytics_comparison) and the status panel (analytics_status_breakdown). From ClickHouse, p95 is computed over the whole window, so analytics_rollup_reads is not used and p95_unavailable never appears; rollup reads still apply when PostgreSQL answers. A ClickHouse failure is logged as analytics_store_read_failed with its class and the view is answered again from PostgreSQL within its own 5-second deadline.
The report names the store:
"read_store": {"source": "clickhouse", "lag_seconds": 1.8}"read_store": {"source": "postgresql", "fallback_reason": "behind", "lag_seconds": 912.4}read_store is absent while the flag is off, so existing clients see the same report as before. The Usage page shows the store under the time window. GET /api/v1/admin/analytics/export follows the same store and names it in the X-Analytics-Read-Store response header.
Same answers, same authorization. ClickHouse statements return the rows PostgreSQL returns for the same filter: equal counts, sums, names, order and times, with averages and p95 equal within a relative 1e-9 (p95 is quantileExactInclusive, PostgreSQL’s percentile_cont). The team a session may see, a named team or an organization is part of the WHERE clause in both stores, so it applies before any aggregation. Each copied row carries the organization its request ran in, so a team that moved is split between its former and its new organization exactly as in PostgreSQL (when a team moves); the team’s current organization, or an organization’s current teams, is read from PostgreSQL first. Data is only as recent as the copy: events committed in the last lag_seconds are not in a ClickHouse answer.
Limits.
- Ties in a ranking (equal request counts) are ordered by bytes in ClickHouse and by the database collation in PostgreSQL. They agree for lower-case ASCII names; with mixed case or accents a tie at the 20th place may name a different entry.
- A completed end-user deletion is in PostgreSQL at once and in ClickHouse at the next pass (normally seconds); while that redaction waits, reads stay on PostgreSQL. ClickHouse keeps deleted rows on disk until its next merge of that part.
- If a copy pass loses its PostgreSQL session while its ClickHouse write is still in flight, another replica may write the same events again; the table is a
ReplacingMergeTree, so such duplicates disappear at the next merge, but until then a ClickHouse answer may count them twice.
Request logs from the analytics store
Section titled “Request logs from the analytics store”With analytics_store_request_logs on, these read the copy under the same conditions as analytics (copy current, ClickHouse answering, otherwise PostgreSQL with the reason):
| Endpoint | From ClickHouse | Still from PostgreSQL |
|---|---|---|
GET /api/v1/admin/logs |
Every filter (window, principal, team or organization, key, model, provider, operation, request and trace ID, status, exact status code, owner, end user, session, tags), the three orderings and offsets up to 10000; attempts and timing columns | The client address filter (client_ip), whose table is not copied: fallback_reason: unsupported_filter |
GET /api/v1/admin/logs/export |
The same rows as the page; the store is in the X-Read-Store header |
As the page |
GET /api/v1/admin/requests/{id}, request journeys, session summaries, agent graphs |
— | Always: a reused request ID’s newest event may be newer than the copy, exact lookups are faster in PostgreSQL, and the others join tables that are not copied |
A page carries read_store like the analytics report; the Logs page shows it under the table. Pages hold the same rows in the same order as PostgreSQL for the events the copy holds; a duplicate a lost copy session may leave is never shown twice (LIMIT 1 BY id). Two consequences of the lag: a ClickHouse page lacks the events of the last lag_seconds (on the default newest-first page, the most recent seconds), and because each page decides its store on its own, paging by offset while the store changes between pages (a fallback starting or ending) can skip or repeat up to that many rows. As the measured comparison showed, PostgreSQL answers index-friendly pages and exact lookups in under 3 ms where ClickHouse has a floor of about 3 ms per statement; ClickHouse pays off for sparse filters over long windows (a 90-day page filtered by status, provider and operation took 12.5 s in PostgreSQL at 50 million events and 30 ms in ClickHouse). Turn this purpose on only when such pages are slow.
Spans written straight to the analytics store
Section titled “Spans written straight to the analytics store”With spans.engine: analytics_store (span store), the span writer inserts each batch into this database instead of PostgreSQL, and every span read answers from here: no copy, no lag behind the database. The writer creates gateway_spans_v1 (shared with the span copy; its own rows have copy_id 0), gateway_trace_summaries_v1 and gateway_spans_retained_v2, with a table TTL equal to spans.retention_days; it needs no grant beyond the list above (ALTER TTL when the retention changes, ALTER DELETE for erasure). A copy reset (turning analytics_store_spans on after moving back to engine: database) deletes only copied rows and keeps the engine’s own. While ClickHouse is unreachable, span batches are dropped and counted, requests are unaffected, and span reads answer 503 analytics_store_unavailable. The measured trade-off is in Span store engines. Request logs and evaluation results still live in PostgreSQL and reach ClickHouse through the copy.
Lag and status
Section titled “Lag and status”GET /api/v1/admin/analytics-store (console permission analytics:read) reports the engine, where reads go and how far behind the copy is. The Usage page shows the same panel, titled Analytics store · clickhouse (the engine is a value; an answer without it, from a replica older than the rename, shows only Analytics store), when either flag is on.
{ "configured": true, "engine": "clickhouse", "state": "current", "purposes": {"analytics": true, "request_logs": false}, "max_lag_seconds": 300, "lag_seconds": 1.8, "reachable": true, "copy": {"enabled": true, "cursor": 912045, "pending_rows": 0, "pending_rows_capped": false, "open_gaps": 0, "pending_changes": 0, "copied_total": 912040, "resets": 1, "last_pass_at": "2026-11-15T21:00:02Z"}, "settings": {"configured": true, "engine": "clickhouse", "database": "gateway", "tls_mode": "verify_full", "copy": {"batch_size": 5000, "interval": "2s", "gap_grace": "10m0s", "max_lag": "5m0s"}, "restart_required": true}}lag_secondsis the time since the start of the latest pass that found nothing more to copy: every event committed before it is in ClickHouse. It is absent until the first complete pass.engineis theanalytics_store.enginevalue, absent while the block names none.stateisnot_configured,off,copying(filling after an enable),unreachable,behind(lag overcopy.max_lag) orcurrent.pending_rowscounts events after the cursor and stops at 100000 (pending_rows_capped);oldest_gap_secondsis the age of the oldest open gap.organization_backfill_pendingis present (true) while rows copied by a release before migration 214 are being copied again with their organization;stateis thencopyingand reads use PostgreSQL.- A team-scoped session gets only
state,purposesand the lag; the counts and settings describe the whole deployment. No address, environment variable name or file path is ever returned. - A failed pass records a class such as
clickhouse_unreachable,clickhouse_authentication_failed,clickhouse_unknown_database,clickhouse_access_denied(a grant is missing; the ClickHouse server log names it) orpostgres_error, and logsanalytics_copy_failedonce per class.
Upgrade
Section titled “Upgrade”Migration 214 renames the copy’s cursor column and adds the organization to the copied request log. The gateway adds the column to the ClickHouse table at start (ALTER TABLE … ADD COLUMN IF NOT EXISTS, which needs the ALTER grant the copy user already has) and copies again, once, the rows the earlier release had copied that record an organization; nothing is copied again in a deployment that never had organizations on. Reads stay on PostgreSQL until it ends (organization_backfill_pending). A replica still on the earlier release stops copying (analytics_copy_failed in its log, 503 on its status view) until it is replaced; the upgraded replicas copy meanwhile. Measured cost and the full note: when a team moves.
Migration 159 adds the copy state, the gap ranges, the change log and two statement triggers on gateway_usage_events; with the flags off the triggers write nothing. Migrate and upgrade every replica before turning a flag on.
From 0.0.1-rc.2: the clickhouse: block, the two clickhouse_* flags, the GATEWAY_CLICKHOUSE_PASSWORD and GATEWAY_CLICKHOUSE_USER names, the Helm clickhouse: values and the Compose profile clickhouse were renamed (table and steps in upgrading from 0.0.1-rc.2). Migration 195 renames feature overrides stored under the old flag ids, keeping their value. With the bundled server, add GATEWAY_ANALYTICS_STORE_PASSWORD with the value of GATEWAY_CLICKHOUSE_PASSWORD before the upgrade (in the vault when a secret manager writes the Secret), and keep the old key until a rollback is no longer possible: a rolled-back StatefulSet still reads it. The ClickHouse Pod restarts once during the upgrade; its data volume and Service keep their names.