---
name: clickhouse-reference-architecture
description: |-
  Production reference architecture for ClickHouse-backed applications —
  project layout, data flow, multi-tenant patterns, and operational topology.
  Use when designing a new ClickHouse system, reviewing an existing analytics
  architecture, or establishing standards for ClickHouse integrations.
  Trigger with "clickhouse architecture", "clickhouse project structure",
  "clickhouse design", "clickhouse multi-tenant", "clickhouse reference".
allowed-tools: Read, Grep
version: 1.7.0
license: MIT
author: Jeremy Longshore <jeremy@intentsolutions.io>
tags:
  - saas
  - database
  - analytics
  - clickhouse
  - olap
compatibility: Designed for Claude Code
title: clickhouse-reference-architecture
canonical_url: https://skilld.dev/gh/jeremylongshore/tons-of-skills-marketplace/clickhouse-reference-architecture
last_updated: 2026-10-07T06:06:28.000Z
---

> Index of every page on this site: [llms.txt](https://skilld.dev/llms.txt)

> **Skill from skilld.dev.** Follow the user's requested action.
> If the user asked to fork this Skill, follow the fork workflow below. Do not execute the Skill instructions while copying it.
> Otherwise, follow the instructions below for this session. You do not need to install anything.
>
> Supporting files, fetch one when the Skill refers to it: [references/client-module.md](https://skilld.dev/api/skills-raw/jeremylongshore/tons-of-skills-marketplace/clickhouse-reference-architecture/references/client-module.md), [references/multi-tenant-patterns.md](https://skilld.dev/api/skills-raw/jeremylongshore/tons-of-skills-marketplace/clickhouse-reference-architecture/references/multi-tenant-patterns.md), [references/schema-design.md](https://skilld.dev/api/skills-raw/jeremylongshore/tons-of-skills-marketplace/clickhouse-reference-architecture/references/schema-design.md).
>
> If the user asked to install this Skill, run `npx skilld install jeremylongshore/tons-of-skills-marketplace/clickhouse-reference-architecture`. Install writes the Skill files into the project, so every session loads them.
>
> ## Fork workflow
>
> A fork creates an editable local Skill with its original author and licence. The request authorizes copying and local installation.
> 1. Check `./skills/clickhouse-reference-architecture`, the project lockfile, and selected Agent targets together. If the local directory or installed Skill exists, stop. Never overwrite an existing directory or Agent target.
> 2. Read [source metadata](https://skilld.dev/api/v1/skills/jeremylongshore/tons-of-skills-marketplace/clickhouse-reference-architecture) once. Use sourceUrl, sourceCommit, skillPath, sourceGone, and license. If the source is gone or its path is missing, stop. If license is null, read licence files at the source commit.
> 3. Fetch only the source commit into a temporary Git repository. Do not clone full history. Derive repository_url from sourceUrl, including repository renames. If sourceCommit is absent, resolve the sourceUrl ref once. Set source_commit to that actual commit. Run these commands in one shell call:
>
> ```sh
> git init --quiet "$temporary_dir"
> git -C "$temporary_dir" fetch --quiet --depth=1 "$repository_url" "$source_commit"
> git -C "$temporary_dir" checkout --quiet --detach FETCH_HEAD
> ```
>
> Read applicable licence declarations and notices at that commit. If copying is not permitted, report the restriction and stop.
> 4. Inspect source entries together, then copy the directory containing skillPath into `./skills/clickhouse-reference-architecture`. Use the user's path if selected. Keep the original SKILL.md, relative links, scripts, binary assets, and executable modes. Exclude .git metadata. Reject symlinks and paths outside the Skill directory. After checking entries, use cp -a where available. A regular source directory needs no custom copy script. Do not save this page wrapper as SKILL.md.
> Preserve author credit, notices, and applicable licence files from repository or parent directories. Add PROVENANCE.md with the Skill page, source URL, actual commit, original path, and licence. Retain any existing PROVENANCE.md and record new provenance separately. Batch source inspection, copying, and provenance work where practical.
> 5. In the project root, run `skilld install ./skills/clickhouse-reference-architecture --mode copy --plain`. If skilld is unavailable, use `npx skilld install ./skills/clickhouse-reference-architecture --mode copy --plain`. This known command needs no help lookup. Install does not support --json. Use detected Agent targets, or add --agent for the targets the user selected. Install the local path, never the upstream selector. If installation fails, preserve the local copy and report the exact failure.
> 6. Confirm the local lockfile source and installed Agent copies once. Report the local path, actual commit, and Agent targets. After edits, reinstall the same local path. Upstream updates must not replace it. Do not publish or push unless the user asks.

# ClickHouse Reference Architecture

## Overview

Production-grade architecture for ClickHouse analytics platforms covering project
layout, data flow, multi-tenancy, and operational patterns. Work through the five
steps below to get the high-level shape, then drill into the linked reference files
for the full DDL, client code, and tenancy trade-offs.

## Prerequisites

- Understanding of ClickHouse fundamentals — table engines, `ORDER BY` sort keys,
  and partitioning.
- A TypeScript/Node.js project (the client examples use `@clickhouse/client`).
- When reviewing an existing codebase, `Grep` for `createClient(` to locate the
  current client module and `Read` the SQL files under `clickhouse/schemas/`.

## Instructions

### Step 1: Project Structure

Keep SQL DDL as the source of truth under `clickhouse/schemas/`, named query
functions under `clickhouse/queries/`, and ingestion/API/jobs in sibling modules.

```
my-analytics-platform/
├── src/
│   ├── clickhouse/
│   │   ├── client.ts           # Singleton client with health checks
│   │   ├── schemas/            # SQL DDL files (source of truth)
│   │   │   ├── 001-events.sql
│   │   │   ├── 002-users.sql
│   │   │   └── 003-materialized-views.sql
│   │   ├── queries/            # Named query functions
│   │   └── migrations/         # Schema migrations (runner.ts + *.sql)
│   ├── ingestion/              # webhook-receiver, kafka-consumer, buffer
│   ├── api/                    # routes.ts, middleware.ts (auth, rate limit)
│   └── jobs/                   # daily-rollup.ts, cleanup.ts (TTL enforcement)
├── tests/                      # unit/ + integration/
├── docker-compose.yml          # Local ClickHouse
├── init-db/                    # Docker init scripts
└── config/                     # development / staging / production .env
```

### Step 2: Data Flow Architecture

Data moves in one direction: sources → a batching ingestion layer → ClickHouse
(raw MergeTree → materialized views → aggregate tables) → an API that reads only
the aggregate tables → dashboards.

```
Data Sources (Webhooks, API, Kafka, S3)
        │
Ingestion Layer (Buffer + batch, 10K+ rows/insert)
        │
ClickHouse Server
   Raw Event Tables (MergeTree, append-only)
        │  auto-aggregate on INSERT
   Materialized Views (hourly, daily, tenant-level)
        │
   Aggregate Tables (AggregatingMergeTree)
        │
API Layer (queries aggregate tables, never raw events)
        │
Dashboards / Client Apps
```

### Step 3: Schema Design (3-Layer Pattern)

Three layers — raw append-only events, hourly aggregation, and a daily rollup for
dashboards — with materialized views auto-populating each aggregate on INSERT.
The essential raw-table skeleton:

```sql
CREATE TABLE analytics.events_raw (
    event_id    UUID DEFAULT generateUUIDv4(),
    tenant_id   UInt32,
    event_type  LowCardinality(String),
    user_id     UInt64,
    properties  String CODEC(ZSTD(3)),
    created_at  DateTime64(3) DEFAULT now64(3)
)
ENGINE = MergeTree()
ORDER BY (tenant_id, event_type, toDate(created_at), user_id)
PARTITION BY toYYYYMM(created_at)
TTL created_at + INTERVAL 90 DAY;
```

Full three-layer DDL, materialized views, and the rationale: see
[references/schema-design.md](https://skilld.dev/api/skills-raw/jeremylongshore/tons-of-skills-marketplace/clickhouse-reference-architecture/references/schema-design.md).

### Step 4: Multi-Tenant Patterns

Choose an isolation strategy. Default to Approach A (shared table, `tenant_id`
first in `ORDER BY`) — it scales to 10K+ tenants:

```sql
ORDER BY (tenant_id, event_type, created_at)
SELECT count() FROM events_raw WHERE tenant_id = 42;  -- scans only tenant 42
```

Database-per-tenant (strict isolation) and row-level security (RBAC) alternatives
with trade-offs: see [references/multi-tenant-patterns.md](https://skilld.dev/api/skills-raw/jeremylongshore/tons-of-skills-marketplace/clickhouse-reference-architecture/references/multi-tenant-patterns.md).

### Step 5: Client Module

Use a singleton `@clickhouse/client` instance and parameterized queries that read
from the aggregate tables. Full client + query-function code:
[references/client-module.md](https://skilld.dev/api/skills-raw/jeremylongshore/tons-of-skills-marketplace/clickhouse-reference-architecture/references/client-module.md).

## Architecture Decision Records

| Decision | Choice | Why |
|----------|--------|-----|
| Engine | MergeTree (raw) + AggregatingMergeTree (rollups) | Best for append + pre-agg |
| Multi-tenant | Shared table + tenant_id in ORDER BY | Scales to 10K+ tenants |
| Ingestion | Buffer + batch INSERT | Avoids "too many parts" |
| Aggregation | Materialized views (not cron) | Real-time, zero-lag |
| Format | JSONEachRow | Client support, debugging |
| Compression | ZSTD(3) for strings, Delta for ints | 10-20x compression |

## Output

Applying this skill produces a concrete architecture plan for a ClickHouse system:

- A **project directory layout** (Step 1) with DDL as the source of truth.
- A **3-layer schema** — raw MergeTree table, hourly and daily
  `AggregatingMergeTree` tables, each fed by a materialized view.
- A chosen **multi-tenant isolation strategy** (shared table / database-per-tenant /
  row policy) with the reasoning recorded.
- A **singleton client module** plus named, parameterized query functions that read
  only from aggregate tables.
- A filled-in **Architecture Decision Record** table capturing engine, tenancy,
  ingestion, aggregation, format, and compression choices.

## Error Handling

| Issue | Cause | Solution |
|-------|-------|----------|
| Cross-tenant data leak | Missing WHERE tenant_id | Use row policies or middleware |
| Stale dashboard data | MV not created | Verify MV exists and is attached |
| Schema drift | Manual DDL changes | Use migration runner |
| Slow dashboard queries | Querying raw table | Query aggregate tables instead |

## Examples

**Design a new multi-tenant analytics platform.** Start from the Step 1 layout and
the Step 3 raw-table skeleton, then open [references/schema-design.md](https://skilld.dev/api/skills-raw/jeremylongshore/tons-of-skills-marketplace/clickhouse-reference-architecture/references/schema-design.md)
for the full three-layer DDL and [references/multi-tenant-patterns.md](https://skilld.dev/api/skills-raw/jeremylongshore/tons-of-skills-marketplace/clickhouse-reference-architecture/references/multi-tenant-patterns.md)
to pick an isolation strategy.

**Query a tenant dashboard from Node.js.** Read from the daily rollup, not the raw
table — the pattern the client module in
[references/client-module.md](https://skilld.dev/api/skills-raw/jeremylongshore/tons-of-skills-marketplace/clickhouse-reference-architecture/references/client-module.md) implements:

```sql
SELECT date, sum(total) AS events, uniqMerge(users) AS unique_users
FROM analytics.events_daily
WHERE tenant_id = {tid:UInt32} AND date >= today() - {days:UInt32}
GROUP BY date ORDER BY date;
```

**Review an existing ClickHouse integration.** `Grep` for `createClient(` and any
raw-table `SELECT`s in the API layer; flag queries hitting `events_raw` instead of
an aggregate table against the Error Handling table above.

## Resources

- [ClickHouse Architecture](https://clickhouse.com/docs/development/architecture)
- [SharedMergeTree (Cloud)](https://clickhouse.com/docs/cloud/reference/shared-merge-tree)
- [Materialized Views](https://clickhouse.com/blog/using-materialized-views-in-clickhouse)
- [references/schema-design.md](https://skilld.dev/api/skills-raw/jeremylongshore/tons-of-skills-marketplace/clickhouse-reference-architecture/references/schema-design.md) — full 3-layer DDL
- [references/multi-tenant-patterns.md](https://skilld.dev/api/skills-raw/jeremylongshore/tons-of-skills-marketplace/clickhouse-reference-architecture/references/multi-tenant-patterns.md) — tenancy trade-offs
- [references/client-module.md](https://skilld.dev/api/skills-raw/jeremylongshore/tons-of-skills-marketplace/clickhouse-reference-architecture/references/client-module.md) — client + query code

## Next Steps

For multi-environment configuration, layer on the `clickhouse-multi-env-setup`
skill, which covers per-environment `.env` files, staging/production connection
settings, and migration promotion between environments.
