clickhouse-reference-architecture

jeremylongshore/claude-code-plugins-plus-skills

Референсная архитектура приложений на ClickHouse: структура, потоки, мультитенантность.

Звёзды2 926
Авторjeremylongshore

Установка

SKILL.md

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:

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.

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:

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.

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.

Architecture Decision Records

DecisionChoiceWhy
EngineMergeTree (raw) + AggregatingMergeTree (rollups)Best for append + pre-agg
Multi-tenantShared table + tenant_id in ORDER BYScales to 10K+ tenants
IngestionBuffer + batch INSERTAvoids "too many parts"
AggregationMaterialized views (not cron)Real-time, zero-lag
FormatJSONEachRowClient support, debugging
CompressionZSTD(3) for strings, Delta for ints10-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

IssueCauseSolution
Cross-tenant data leakMissing WHERE tenant_idUse row policies or middleware
Stale dashboard dataMV not createdVerify MV exists and is attached
Schema driftManual DDL changesUse migration runner
Slow dashboard queriesQuerying raw tableQuery 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 for the full three-layer DDL and 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 implements:

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 SELECTs in the API layer; flag queries hitting events_raw instead of an aggregate table against the Error Handling table above.

Resources

  • ClickHouse Architecture
  • SharedMergeTree (Cloud)
  • Materialized Views
  • references/schema-design.md — full 3-layer DDL
  • references/multi-tenant-patterns.md — tenancy trade-offs
  • 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.

Вставить в README

Ссылка на карточку для вашего README — без картинок и счётчиков.

[DarkPlay: clickhouse-reference-architecture](https://darkplay.ru/ai/skills/jeremylongshore-claude-code-plugins-plus-skills-clickhouse-reference-architecture)

Похожие скиллы и другие разделы каталога

Популярное в разделе «Скиллы»

Самые востребованные скиллов раздела по установкам и звёздам.

find-skillsvercel-labs · Помогает находить и устанавливать навыки агентов по запросам вроде «как сделать X»…
4 400 000 устан.
grill-memattpocock · Настойчивое интервью для доработки плана или дизайна.
1 600 000 устан.
hyperframesheygen-com · Обязательная точка входа для любых задач по видео, анимации и motion-графике в…
1 600 000 устан.
hyperframes-cliheygen-com · Цикл разработки HyperFrames CLI: init, add, render, preview, publish и другие команды.
1 600 000 устан.
agent-browservercel-labs · CLI для автоматизации браузера для ИИ-агентов: навигация по страницам, заполнение форм…
1 600 000 устан.
media-useheygen-com · Agent Media OS: единый навык для медиа в HyperFrames — BGM, SFX, изображения, голос, LUT.
1 500 000 устан.
hyperframes-registryheygen-com · Установка и подключение блоков реестра в композиции HyperFrames через add и catalog.
1 400 000 устан.
grill-with-docsmattpocock · Настойчивое интервью для доработки плана или дизайна, попутно создающее документацию (ADR…
1 300 000 устан.
improve-codebase-architecturemattpocock · Поиск в кодовой базе возможностей для углубления, визуальный HTML-отчёт о них и детальный…
1 300 000 устан.
tddmattpocock · Разработка через тестирование (TDD): red-green-refactor и интеграционные тесты.
1 300 000 устан.
Похожее в других разделах каталога

Соседние разделы каталога: возможно, нужный инструмент живёт там.

Architectaffaan-m · Специалист по архитектуре ПО для проектирования систем, масштабируемости и принятия…
225 587 ★
Code Architectaffaan-m · Проектирует архитектуру функций, анализируя существующие паттерны и соглашения кодовой…
225 587 ★
Code Exploreraffaan-m · Глубоко анализирует существующие функции кодовой базы, прослеживая пути выполнения…
225 587 ★
Csharp Revieweraffaan-m · Ревьюер C#: конвенции .NET, async, безопасность, nullable-типы, производительность.
225 587 ★
Flutter Revieweraffaan-m · Ревьюер кода Flutter и Dart: виджеты, управление состоянием, идиомы и архитектура.
225 587 ★
Java Revieweraffaan-m · Ревьюер Java для Spring Boot и Quarkus: архитектура, JPA, безопасность и конкурентность.
225 587 ★
Kotlin Revieweraffaan-m · Ревьюер Kotlin и Android/KMP: корутины, Compose, архитектура и типичные ошибки.
225 587 ★
Network Architectaffaan-m · Проектирует корпоративные и распределённые сети с маршрутизацией и автоматизацией.
225 587 ★
Network Config Revieweraffaan-m · Проверяет конфигурации роутеров и свитчей: безопасность, ошибки и риски изменений.
225 587 ★
Opensource Forkeraffaan-m · Форкает проект для open-source: чистит секреты, ссылки и историю git.
225 587 ★

Лучшие ИИ-инструменты для генерации видео

Генерация видео

Подборка нейросетей для генерации и монтажа видео. Инструменты, которые превращают текст в готовые ролики, экономят часы на съемках и постпродакшне. Подходит для SMM-специалистов,

VEED.IOVeed
По запросу
5.0
MootionMootion
По запросу
5.0
FlyviFlyvi
Есть бесплатный тариф
4.9
Google Veo 3.1Google
Платно
4.9
Sora (OpenAI)OpenAI
Платно
4.9
PikaPika
Платно
4.9
captions space
Есть бесплатный тариф
4.8
Клайп
Есть бесплатный тариф
4.8
viralpulse.appViralpulse
По запросу
4.8
Viral Maker AIViral-maker
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации текста и копирайтинга

Генерация текста и копирайтинг

Подборка нейросетей для генерации текстов и копирайтинга. Сервисы, которые помогают создавать статьи, посты и рекламные объявления с нуля или по черновику, экономя часы рутинной ра

NeuroscribeNeuroscribe
Есть бесплатный тариф
5.0
GoGPTGogpt
По запросу
5.0
ChatsonicChatsonic
По запросу
4.9
НейроТекстерNeuro-texter
По запросу
4.9
ChatGPTOpenAI
По подписке
4.9
Редактум
Есть бесплатный тариф
4.8
ChadGPTChadgpt
По запросу
4.8
Cosmo ScribeCosmoscribe
Есть бесплатный тариф
4.8
Memo HelperCopilot33
По запросу
4.8
LibraChatLibrachat
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации изображений

Генерация изображений

Подборка нейросетей для генерации изображений от фотореализма до концепт-арта. Сервисы, которые экономят часы ручной работы, создавая визуал для блогов, рекламы и дизайна за минуты

MagviMagvi
По запросу
5.0
DALL-E 3OpenAI
По подписке
5.0
SupaLabSupalab
По запросу
5.0
Freestyling.aiFreestyling
Есть бесплатный тариф
4.9
ArtGeneration.meArtgeneration
Есть бесплатный тариф
4.9
BigjpgBigjpg
По запросу
4.9
Художник от VKVK
Бесплатно
4.9
Wonderink — ИИ-книги
Есть бесплатный тариф
4.8
Avato AI12ai
По запросу
4.8
Virton AIVirton
По запросу
4.8