Operate ClickHouse analytics
Configure analytics modes, schema migrations, privacy, retention, and recovery.
- 8 min read
- Updated
On this page
Postgres owns accounts, projects and publishing. ClickHouse stores analytics. Analytics unavailable means your documentation site is fine. Unknown metrics must not be interpreted as zero. The reader never connects to ClickHouse.
This page describes current-source analytics, including the November insights
and chat tables. The pinned v0.2.1 production Compose file has no ClickHouse
service, no analytics environment mappings, and no analytics-tools profile.
Setting ANALYTICS_MODE in its .env alone has no effect. Provision ClickHouse
and a reviewed compatible image, and pass the analytics settings to API and
worker. Source quickstart and Coolify include the service and migration profile.
Keep the pinned release file intact and use a separate override for custom wiring.
| Mode | When to use it |
|---|---|
disabled | Keep relational analytics; no ClickHouse ingestion or boot migrations. |
dual_write | Write both stores while validating and backfilling ClickHouse. Legacy dashboards use Postgres; insights are not configured. |
shadow_read | Compare legacy reads while validating ClickHouse. The new insights dashboard reads ClickHouse. |
clickhouse | After reconciliation, use ClickHouse analytics and stop relational analytics writes. |
Back up both stores before advancing. From an installed source checkout, export
POSTGRES_URL, ANALYTICS_HASH_SALT, and the ClickHouse connection variables
for the intended databases. These scripts do not load the root .env themselves.
Enter the project ID from /app/projects/<projectId> in your dashboard URL:
read -r -p 'Project ID from the site dashboard URL: ' PROJECT_ID
test -n "$PROJECT_ID"
pnpm analytics:backfill -- --project="$PROJECT_ID"
pnpm analytics:reconcile -- --project="$PROJECT_ID"
The backfill copies retained relational events and never recreates historic
consent or raw search text. Reconciliation compares relational event IDs against
ClickHouse; it does not prove every insight dimension or post-cutover event.
Observe a full reporting window and keep relational history through rollback.
Returning to dual_write cannot restore relational events missed in
ClickHouse-only mode.
The worker starts migrations in the background when analytics is enabled and
CLICKHOUSE_MIGRATE_ON_BOOT=true (default). It creates the database if missing,
applies pending versions and reapplies retention TTLs. Retry delay grows from
one second to a maximum of 60 seconds. Neither migration nor ClickHouse health
gates core startup. All workers and the migration CLI must share the same
Postgres database: a transaction-scoped PostgreSQL advisory lock serializes
migration work for the ClickHouse database name. Lock contention retries without
running DDL. The lock transaction has a one-hour ceiling; investigate hung work
well before that ceiling and never launch an overlapping manual migration.
For a dedicated migration identity, disable boot migrations and run:
# Source quickstart only; use the Coolify deployment job for its Compose file.
docker compose --profile analytics-tools run --rm analytics-migrate
# Or from a source checkout with POSTGRES_URL and ClickHouse writer credentials:
pnpm --filter @nibleaf/clickhouse migrate
The CLI waits up to ten minutes for another migration process, retrying every
five seconds, then exits with an error if the lock is still held. Investigate
the holder before retrying. The worker's /health and the API's authenticated
/health/details include this independent field. The API route requires the
x-nibleaf-internal header; see
Health probes and private diagnostics:
{"analytics":{"configured":true,"latencyMs":4,"status":"ok"}}
disabled means off; migrating means this process is applying the schema;
schema_outdated means at least one migration version is missing (including an
uninitialized database); unavailable means connection, credentials or schema
probing failed; ok means every code migration is recorded. The API independently
probes the database, so it can report schema_outdated while a worker migrates.
Schema probes share a result for ten seconds per process, including failures.
The local worker migration flag is reflected immediately; its completion clears
the cache. Each probe has a 750 ms deadline to stay inside the container
healthcheck timeout. Core readiness and its HTTP status continue to
depend on core services only.
Generate an independent ANALYTICS_HASH_SALT with openssl rand -hex 32. Preserve
existing salts and keys; changing a salt splits historical visit identities.
Without ANALYTICS_HASH_SALT while ClickHouse analytics is enabled, events are
dropped, not hashed with a fallback; core documentation delivery stays healthy.
Restore the existing secret before enabling ingestion. A new salt is for a new
installation, not a replacement for a lost production value.
Session and anonymous identifiers are created and accepted only with consent
granted or not_required. Visits therefore count only identifiable visits.
For denied or unknown, content-free page views and search counts still count,
without session or anonymous-user hashes; the server discards identifiers even
if a client sends them. Consented sessions use salted hashes and a per-tab session
identifier. Sensitive search text also requires granted or not_required.
Public search terms require a public site and the project setting
analytics.storePublicSearchTerms=true. Private sites never store raw terms.
Terms are normalized (NFKC, lowercase, trimmed, collapsed whitespace), and emails,
URLs and digit runs of six or more characters are redacted before hashing and
storage. Text appears only after at least 2 distinct visits searched the term;
others contribute to hidden-term totals. Sensitive text has its own short TTL.
No document bodies, prompts or answers belong in product analytics events.
Compose bootstraps a writer identity; it does not provision a separate reader. Create roles and assign them to separately provisioned users. Database-level grants cover new analytics tables without forgetting deletion tombstone reads:
CREATE ROLE IF NOT EXISTS nibleaf_analytics_reader;
GRANT SELECT ON nibleaf_analytics.* TO nibleaf_analytics_reader;
CREATE ROLE IF NOT EXISTS nibleaf_analytics_writer;
GRANT INSERT ON nibleaf_analytics.* TO nibleaf_analytics_writer;
GRANT SELECT ON nibleaf_analytics.analytics_deletion_tombstones TO nibleaf_analytics_writer;
GRANT SELECT ON nibleaf_analytics.usage_deletion_tombstones TO nibleaf_analytics_writer;
CREATE ROLE IF NOT EXISTS nibleaf_analytics_erasure;
GRANT ALTER DELETE ON nibleaf_analytics.* TO nibleaf_analytics_erasure;
The reader includes analytics_deletion_tombstones, migration versions and the
sensitive table needed for eligible terms. SQL privileges are database-wide;
Nibleaf queries enforce tenant/project scope. Set the matching
CLICKHOUSE_READER_USERNAME and CLICKHOUSE_READER_PASSWORD. The runtime writer
needs INSERT plus SELECT on tombstones; deletion tooling additionally needs
SELECT to check erasure and the erasure role above, covering every project
table. Assign the reader and erasure roles to the worker identity if it runs
rollup reads and project deletion. Do not give erasure privileges to the dashboard
reader. Keep passwords in deployment secrets.
Migration execution separately needs CREATE/ALTER and reads/writes on migration
versions, including rights to create the database when absent. With boot
migrations enabled, provision those rights to the worker writer identity. If
runtime DDL is prohibited, set CLICKHOUSE_MIGRATE_ON_BOOT=false and run the CLI
with a dedicated migration identity. The runtime INSERT role alone cannot migrate.
Deleting a project erases its raw, sensitive and rollup analytics with a deletion fence. Verify ClickHouse mutations finish before closing an erasure request. Restoring an older backup can resurrect erased records: replay deletions before connecting restored data to the application.
| Variable | Default days | Allowed range |
|---|---|---|
CLICKHOUSE_RAW_RETENTION_DAYS | 180 | 7-730 |
CLICKHOUSE_CRAWLER_RETENTION_DAYS | 90 | 7-730 |
CLICKHOUSE_ROLLUP_RETENTION_DAYS | 730 | 30-3650 |
CLICKHOUSE_SENSITIVE_RETENTION_DAYS | 30 | 1-90 |
AI_CONVERSATION_RETENTION_DAYS | 90 | 1-365 |
Every migration run reapplies TTLs with materialize_ttl_after_modify=0.
Changes affect subsequent merges without an immediate rewrite; deletion is
asynchronous. Shortening retention permanently removes older history.
Source quickstart and Coolify Compose limit ClickHouse to 1.5 GiB container memory, with a 1 GiB server budget and 128 MiB mark cache, and rotates warning logs. Noisy system log tables are disabled for new writes; existing system tables still occupy disk and need operator review. These are starting limits, not a capacity guarantee. Monitor free bytes, queue age, failed jobs, parts, merges and mutations. Never delete files under the ClickHouse data volume to free space. See backups and troubleshooting.
Origin-side crawler capture cannot see requests served entirely from a CDN or edge cache in front of Nibleaf. Crawler counts therefore describe requests that reach Nibleaf, not all edge traffic. Compare CDN logs separately when assessing coverage; do not read missing origin requests as an absence of crawlers.
The app server reports crawler visits to published pages, page Markdown,
llms.txt, sitemaps and robots files to the API with INTERNAL_API_SECRET.
Set the same random value (openssl rand -hex 32) on the app and API services.
Without it, only crawlers that call the API directly are counted, and the app
logs a warning once at startup.
The current source also stores AI turns, feedback and daily model usage. Text
capture needs the site setting, permitted visitor consent, and the same
AI_CONVERSATION_ENCRYPTION_KEY (or integration-derived fallback) on API and
worker. The queue is encrypted; redacted ClickHouse text columns are readable
to database readers. Restrict access and use your storage encryption policy.
Content-free turn facts can be recorded without transcript capture. See
chat privacy and budgets for the exact gates.
A healthy schema is not an ingestion test. Check a consented fictional visit, a search, a crawler request and an AI turn in the dashboard. Unknown figures show as unavailable or partial; they are not proof of zero traffic. Crawler identity is classified by user agent, not verified against vendor IP feeds. The maintained snapshots do not establish large-site capacity; measure your reporting ranges and restore on the exact ClickHouse version you deploy.