generating-clickhouse-query-performance-reports

posthog/posthog

Формирует и структурирует отчёты о производительности медленных запросов для production ClickHouse PostHog (US и EU). Используй для анализа медленных запросов за последние N дней, стоимости запросов по командам, разбора OOM и таймаутов.

Звёзды40 862
Авторposthog
Установок141

Установка

SKILL.md

Generating ClickHouse query performance reports

This skill is the methodology for investigating slow ClickHouse queries and writing up a performance report. It pairs with query-clickhouse-via-metabase, which is the mechanism (SSO-gated auth and hogli metabase:query). Run every query in this skill through that one.

Reports themselves are not public. When it exists, the private PostHog/query-performance-analysis repo holds the historical reports and example query IDs; this repo holds only the tooling and methodology. That repo is usually checked out as a sibling folder to the posthog checkout (e.g. ../query-performance-analysis relative to the repo root, or alongside it under the same parent directory). Look for a sibling directory named query-performance-analysis containing an analysis/ folder of dated reports. If you find it, add the new report there as a new markdown file under analysis/, named <YYYY-MM-DD>-<topic>.md (match the existing naming, e.g. 2026-05-27-slow-queries-14d.md).

The sibling repo may not exist, and that is fine. If you cannot find it, do not write into the public posthog repo and do not block on it: write the report to a temp folder instead (e.g. /tmp/<YYYY-MM-DD>-<topic>.md), tell the user where you put it, and skip the previous-report comparison in step 9 (there is no history to diff against).

Data source: posthog.query_log_archive (not system.query_log)

system.query_log on the production clusters retains only a few hours, so it cannot answer a multi-day question. Use the Distributed archive table instead:

FROM posthog.query_log_archive

It retains roughly three weeks and exposes log_comment as typed columns, so you skip JSONExtract. Query it directly (it already fans out across the cluster). Always filter is_initial_query so distributed sub-queries are not double-counted. Confirm current retention with a per-day count() before trusting a window (see references/query-patterns.md).

Key columns (full list via system.columns WHERE table='query_log_archive'):

ColumnMeaning
team_id (Int64)Tenant. 0 / empty means internal or unattributed.
lc_kindHow the query was issued: request (sync API/web), celery (async refresh), temporal, cohort_calculation, dagster.
lc_productproduct_analytics, warehouse, experiments, messaging, web_analytics, replay, llm_analytics, cohorts, ...
lc_access_methodpersonal_api_key, oauth, sharing_token, or empty (logged-in web).
lc_query__kindProduct query type: TrendsQuery, FunnelsQuery, RetentionQuery, HogQLQuery, ...
lc_workloadWorkload.OFFLINE / ONLINE.
lc_feature, lc_temporal__workflow_type, lc_route_id, lc_api_key_labelOrigin detail for attribution.
lc_dashboard_id, lc_insight_id, lc_experiment_id, lc_cohort_idLink a query back to the object that triggered it.
query, query_duration_ms, read_bytes, read_rows, memory_usage, exception_codeThe query and its cost.

Both regions have the archive. US and EU are separate clusters with different workloads and materialized columns; run cross-region comparisons against both. Discover the current ClickHouse database id per region with hogli metabase:databases (ids are not stable). Note that the ONLINE and OFFLINE Metabase connections for a region fan out to the same logical cluster, so they return the same query_log_archive data.

What counts as a slow query

query_duration_ms > 30000 OR exception_code IN (159, 160, 241)
CodeMeaning
159TIMEOUT_EXCEEDED
160TOO_SLOW
241MEMORY_LIMIT_EXCEEDED

Do not add type = 'QueryFinish': OOM and timeout rows are type = 'ExceptionWhileProcessing', so that filter silently drops every failure. The duration/exception predicate already excludes QueryStart rows (duration 0). Exclude the cluster health-poll query by normalized_query_hash (pattern in references/query-patterns.md).

Producing the report

The standard workflow, building from coarse to specific. Each step's SQL is in references/query-patterns.md.

Do not read previous reports until step 9. Steps 1-8 should run against the raw data with fresh eyes, so the analysis captures the largest surface area rather than re-walking last report's findings. Reading the prior report early anchors you to its categories and makes it easy to miss a new problem it never mentioned. Diff against history only after the independent pass is done.

  1. Confirm the window. Per-day count() over the intended range to verify the archive actually covers it (retention can be shorter than you expect).
  2. Headline summary. Total slow queries, total cluster query-hours, bytes read, teams touched, and the split across succeeded-but-slow / timeouts / OOMs / other. Also capture the cluster-wide totals across all queries (not just the slow set): total query-seconds, total CPU-seconds (typed ProfileEvents_OSCPUVirtualTimeMicroseconds column, not the Map lookup), total bytes read, and total OOMs (references/query-patterns.md §1b). The slow-set sums are a biased subset; the all-query totals are the honest "busier / reading more this period?" denominator and the baseline future reports diff against. They cannot be backfilled once a window ages past retention, so record them every run.
  3. Date distribution. Slow count, timeouts, and OOMs per day. This is where incidents announce themselves: a multi-day OOM or timeout surge against a flat baseline.
  4. Categorize. Group by lc_kind × lc_product × lc_access_method. This separates background work (data modeling, dagster pre-aggregation, batch exports) from synchronous user-facing queries.
  5. Attribute. Drill into the worst categories by team_id. Rank by total cluster-hours (sum(query_duration_ms)) and by OOM count separately. Before calling anything systemic, check whether one team or one API key dominates a metric: a single integration querying via a personal_api_key can account for the large majority of cluster OOMs, and the "incident" is then really one tenant. Attribute by team_id + lc_api_key_label first. Then add a top-consumers view over all queries (not just the slow set): top teams, top API keys (lc_api_key_label), and top tools (lc_product) ranked by bytes, CPU-seconds, and wall-time (references/query-patterns.md §4c). This is where the heavy-but-fast consumers show up: a tenant or integration can dominate cluster CPU or bytes through millions of cheap queries while never crossing the slow threshold, so it is invisible to the slow-set ranking. The CPU:wall ratio per row separates compute-bound from wait/IO-bound load.
  6. Characterize user-facing slowness. For lc_kind='request' AND lc_product='product_analytics' with empty lc_access_method (logged-in web), break down by lc_query__kind and flag breakdown_value usage and JSONExtract over person_properties. This is the product-actionable bucket. Always include the JSON-extracted property breakdown (references/query-patterns.md §7): the top event vs person property names pulled from JSON blobs in the slow set, and which teams use each. These are the materialization candidates and a required report output. HogQLQuery (arbitrary user- and AI-authored SQL) deserves its own deep dive, including how much is AI-written and why it is slow; see references/hogql-deep-dive.md.
  7. Root-cause the worst offenders. For the top findings, do not stop at "team X is slow": pull the full query and form a hypothesis for why, then test it with EXPLAIN. Root-causing an individual query is the optimizing-clickhouse-and-hogql-queries skill's job; its references/investigation-playbook.md is the playbook (pull the full query, bytes vs CPU vs duration, the runtime causes, origin tracing, EXPLAIN). A useful finding includes a why ("scans full history because the time filter is function-wrapped and can't prune granules"), even if stated as a hypothesis.
  8. Examples + write-up. Capture query_id + event_date for the worst offenders in each finding, then write the report (structure below). Because system.query_log retention is short, examples are resolved from query_log_archive (WHERE query_id = '…' AND event_date = '…'), not the old Metabase lookup card. Link each example to a shareable self-contained Metabase URL (the query_link recipe in references/query-patterns.md) so a reader clicks straight through to the query. When you draft the recommendations, ground the researchable ones in code by spawning background research agents (see "Grounding recommendations in code" below) so a recommendation points at the actual file and change rather than saying "audit X".
  9. Diff against the previous report (do this last, if there is one). If the sibling query-performance-analysis repo is not present, skip this step entirely. Otherwise, only now, after the independent pass above, read the most recent dated report in its analysis/ folder (sort by filename date). Add a short delta section to the new report covering: what moved since last time (new incidents, findings that grew or resolved, headline numbers up or down), and a follow-up check on anything the previous report flagged as needing action (a materialization that was recommended, a team to watch, a pipeline to make incremental). For each prior follow-up, state whether it is resolved, still open, or regressed, with the current numbers as evidence. Doing this last is deliberate: it keeps the fresh analysis unbiased while still closing the loop on history. Make the windows comparable before quoting a delta: confirm the previous report used the same window length (both reports here use a trailing now() - INTERVAL N DAY, so equal length but with overlapping and partial edge days). Headline totals between two trailing windows are usually dominated by whichever one-off incident sits inside one window and not the other, so a large drop is rarely a structural improvement. Always also compare an incident-excluded baseline (e.g. OOMs/day with the spike days removed) so the delta is not misread, and say explicitly when a total moved because an incident aged into or out of the window. Remember the summed metrics (bytes read, cluster-hours) cover the slow set only, not total cluster I/O, so they also move when a heavy background job's runs cross or stop crossing the 30s threshold; attribute a big bytes/hours swing to specific categories (it is usually one or two background pipelines) rather than reporting it as a cluster-wide change.

Grounding recommendations in code

A recommendation like "audit pipeline X" or "materialize property Y" is far more useful when it points at the actual code. For each recommendation that maps to a concrete place in the PostHog codebase, spawn a background research agent (the Agent tool, run_in_background: true, subagent_type: general-purpose or Explore) to read the source and return: how the relevant code works today, the specific file / function to change, any constraints, and whether a better mechanism already exists. Spawn one agent per researchable recommendation, all in a single message so they run in parallel, as soon as the recommendations are drafted. Let them run while you do the delta (step 9) and finalize the write-up, then fold each finding into its recommendation: replace "audit X" with "X is implemented in <file> as <current behavior>; the change is <specific>", and cite the file paths so the human can jump straight in. The agents research and report only; they do not change code.

Not every recommendation is researchable this way. Spawn an agent only where source code is the source of truth; skip operational / infra items:

Recommendation shapeResearchable?What the agent reads
Rewrite a slow insight / query shapeyesthe query runner under posthog/hogql_queries/, the HogQL it emits
Materialize property Xyesthe materialized-column registry (ee/clickhouse/materialized_columns/)
Make pipeline Y incrementalyesthe dagster / temporal job that builds it
Cap memory / add a query guard per keyyeswhere ClickHouse SETTINGS and per-key throttling are applied
Add a breakdown cardinality guardyesthe trends / breakdown query runner
Investigate an infra incident windownon/a (deploys, node health, cluster state)
Watch / confirm a tenant's intended loadnon/a (a judgement call for a human)

Give each agent a focused prompt: the recommendation, the specific question, and an instruction to return file paths + current behavior + the precise change point and to change nothing. The agents read the posthog repo (where this skill lives); the report itself is written to the separate query-performance-analysis repo.

Interpreting the results

  • Two populations live in "slow queries." Tight-timeout API noise (queries erroring at ~10s against a low max_execution_time, usually personal_api_key) inflates the raw count without representing real compute. Genuinely expensive work is better measured by total cluster-hours and OOM count. Always call this distinction out; do not let timeout volume masquerade as slowness.
  • Bytes read is the truest cost signal, more than duration (which varies with cache and cluster load). High bytes against low rows means heavy columns, almost always JSONExtract over a properties blob. For root-causing individual queries, see the optimizing-clickhouse-and-hogql-queries skill.
  • Background pipelines usually dominate raw cluster-time (data-modeling DAGs, web-analytics pre-aggregation). That is expected; weigh them by whether their scan volume is necessary, separately from user-facing latency.

Структура отчёта

Отчёт должен содержать, по порядку:

  1. Однострочный охват: регион, окно и используемое определение медленного запроса / исключения.
  2. Таблица ключевых цифр + таблица суммарных значений по кластеру (все запросы) (всего query-секунд, CPU-секунд, прочитанных байт, OOM) + оговорка о двух популяциях.
  3. Таблица суточного распределения (отметьте любое окно инцидента).
  4. Находки, начиная с худшей. Каждая находка требует как минимум одного конкретного query_id + event_date, связанного через shareable query_link URL (см. references/query-patterns.md) чтобы читатель мог кликнуть сразу к точному запросу, плюс гипотеза о том, почему он медленный (из optimizing-clickhouse-and-hogql-queries playbook по расследованию из skill). Группируйте находки по их сути: инцидент по конкретному тенанту, самые тяжёлые потребители времени кластера, медленность user-facing инсайтов и шум API с жёсткими таймаутами.
  5. A раздел top-consumers-by-resource (все запросы, не только медленные): топ команд, топ API-ключей и топ инструментов (lc_product) с ранжированием по байтам / CPU / wall-time (references/query-patterns.md §4c), с выделением потребителей, которые никогда не превышают порог медленного запроса, и разбивкой compute-bound vs wait-bound.
  6. A Таблица свойств, извлечённых из JSON: имена топ-свойств событий и person, вытащенные из JSON-блобов в медленном наборе, с командами, использующими каждое (references/query-patterns.md §7). Это кандидаты на материализацию.
  7. Конкретные рекомендации, привязанные к каждой находке (материализовать свойство X, ограничить память на API-ключ, сделать пайплайн Y инкрементальным, ...). Обоснуйте исследуемые из них кодом (см. "Grounding recommendations in code"): укажите файл / функцию и конкретное изменение, а не просто "audit X".
  8. A delta относительно предыдущего отчёта (шаг 9): что изменилось с прошлого раза, плюс проверка-продолжение по каждому действию, рекомендованному предыдущим отчётом (решено / всё ещё открыто / регресс, с цифрами). Опустите этот раздел, если предыдущего отчёта нет.

Сохраните готовый отчёт как analysis/<YYYY-MM-DD>-<topic>.md в соседнем query-performance-analysis репозитории, никогда в публичном репозитории posthog; если этого репозитория нет, сохраните во временную папку (например, /tmp/<YYYY-MM-DD>-<topic>.md) и сообщите пользователю путь.

Ссылки

  • references/query-patterns.md: готовый к запуску SQL для каждого шага выше, против query_log_archive.
  • references/materialization-analysis.md: поиск свойств для материализации и столбцов для удаления, запускать и в US, и в EU.
  • references/hogql-deep-dive.md: анализ HogQLQuery (произвольный пользовательский/AI SQL) конкретно, включая то, как выявлять написанный ИИ HogQL (lc_product/lc_feature, а не ai_query_source) и причины, из-за которых ad-hoc и AI-запросы медленные.

Связанные skills

Этот skill работает на уровне флота: он находит и ранжирует медленные запросы по всем командам и пишет отчёт. Как только находка указывает на один запрос, который вы хотите объяснить или исправить, переключитесь на optimizing-clickhouse-and-hogql-queries — он отвечает за поиск корневой причины отдельного запроса (его references/investigation-playbook.md) и применение исправления на правильном слое (printer, query runner или миграция ClickHouse).

Вставить в README

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

[DarkPlay: generating-clickhouse-query-performance-reports](https://darkplay.ru/ai/skills/posthog-posthog-generating-clickhouse-query-performance-reports)

Из того же репозитория

creating-an-endpoint Создаёт эндпоинт PostHog правильной формы с первого раза: выбор типа запроса, соглашения о ★40,9K diagnosing-endpoint-performance Диагностирует, почему эндпоинт PostHog медленный или дорогой, и предлагает конкретное испр ★40,9K diagnosing-ci-and-merge-bottlenecks Диагностирует здоровье CI и пайплайна pull-request в GitHub-репозитории через MCP-инструме ★40,9K debugging-surveys Отладка, поддержка и разработка PostHog Surveys на бэкенде и во всех пяти SDK (web/posthog ★40,9K creating-replay-vision-scanners Помогает создавать и безопасно масштабировать сканер Replay Vision: выбор типа (monitor/cl ★40,9K creating-online-evaluations Создаёт постоянно работающие онлайн-оценки в PostHog AI observability на основе реального ★40,9K consuming-endpoints-from-client-code Подключает эндпоинт PostHog к клиентскому приложению или SDK: получение OpenAPI-спеки, ген ★40,9K checking-deploy-timing Определяет, когда изменение кода PostHog попало в окружение, читая скрытые GIT-аннотации д ★40,9K

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

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

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

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 устан.
Похожее в других разделах каталога

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

Database Revieweraffaan-m · Специалист PostgreSQL: оптимизация запросов, схемы, безопасность, Supabase.
225 587 ★
E2e Runneraffaan-m · Специалист по E2E-тестам на Vercel Agent Browser и Playwright: генерация, запуск и…
225 587 ★
apolloanthropics · Поиск клиентов, обогащение лидов, загрузка цепочек аутрича и аналитика продаж с Apollo.io…
100 комп.
apollo-skillsanthropics · Навыки агентов Apollo GraphQL для Claude Code — Apollo Client, Server, Federation…
100 комп.
azure-cosmos-db-assistantanthropics · Экспертный помощник по Azure Cosmos DB — моделирование данных, оптимизация запросов…
100 комп.
bigquery-data-analyticsanthropics · Подключение, запросы и генерация аналитики по наборам данных и данным BigQuery.
100 комп.
carta-cap-tableanthropics · Плагин Carta Cap Table — навыки и хуки для запросов к cap table, грантам, SAFE, оценкам…
100 комп.
carta-investorsanthropics · Плагин Carta Investors — навыки для запросов данных об инвесторах, бенчмарков…
100 комп.
clickhouseanthropics · Подключение Claude к базам данных ClickHouse Cloud. Просмотр организаций, сервисов, баз…
100 комп.
clickhouse-best-practicesanthropics · 28 правил лучших практик для проектирования схем ClickHouse, оптимизации запросов и…
100 комп.

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

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

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