Building Web Analytics with ClickHouse: Schema, Queries, Integration

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.

Development and maintenance of all types of websites:

Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Showing 1 of 1All 2062 services
Building Web Analytics with ClickHouse: Schema, Queries, Integration
Complex
~2-3 days
Frequently Asked Questions

Our competencies:

Development stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1358
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1250
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    956
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1188
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    929
  • image_bitrix-bitrix-24-1c_fixper_448_0.webp
    Website development for FIXPER company
    947

This guide covers the complete ClickHouse setup for web application analytics. When your web application generates over 100 million events, PostgreSQL starts returning results in minutes. We've seen this many times: a client requests a DAU report over 90 days broken down by sources, and the query hangs for 40 seconds. ClickHouse is a powerful OLAP database designed for real-time analytics. It processes billions of rows in seconds. Our experience implementing ClickHouse in 10+ projects over 5 years shows a consistent 10–100x speedup. For top-tier analytical queries like DAU, ClickHouse is 100 times faster than PostgreSQL. ClickHouse doesn't replace transactional databases—it complements them: PostgreSQL for operational data, ClickHouse for analytics. For a typical mid-size project, switching to ClickHouse can save $30,000–$50,000 annually on infrastructure costs. We guarantee: after tuning, you'll forget about timeouts.

ClickHouse saves 5–10x on server costs; for example, one client saved $50,000 per year.

This guide covers ClickHouse setup, web application analytics, ClickHouse table schema design, the MergeTree engine, analytical queries in ClickHouse, materialized views, Laravel ClickHouse integration, Node.js ClickHouse client, OLAP database capabilities, query acceleration, data aggregation, and ClickHouse replication.

What Makes ClickHouse Ideal for Web Application Analytics?

ClickHouse uses columnar storage: each column's data lies separately—the query reads only the needed columns. Vectorized processing allows the CPU to operate on batches of values rather than individual rows. Similar data compresses 5–10 times more efficiently than in PostgreSQL. ClickHouse offers specialized table engines like MergeTree that optimize storage and queries for analytical scenarios.

MergeTree: Structure and Optimization

MergeTree is the primary ClickHouse engine. It sorts data by the ORDER BY key and splits into granules of 8192 rows. On query, ClickHouse prunes entire granules based on the primary index and additional indexes like bloom_filter. This provides block-level pruning, significantly reducing the amount of scanned data.

How to Design an Efficient Table Schema for ClickHouse?

CREATE TABLE events (
    event_date   Date,
    event_time   DateTime,
    event_type   LowCardinality(String),
    user_id      UInt64,
    session_id   String,
    tenant_id    UInt32,
    page_url     String,
    referrer     String,
    country      LowCardinality(String),
    device_type  LowCardinality(String),
    properties   String
) ENGINE = MergeTree()
ORDER BY (tenant_id, event_date, event_type, user_id)
PARTITION BY toYYYYMM(event_date);

ALTER TABLE events ADD INDEX idx_session session_id TYPE bloom_filter(0.01) GRANULARITY 4;

ORDER BY is the sort key by which ClickHouse stores data. Queries with filters on tenant_id and event_date use it for pruning. LowCardinality is an optimization for columns with few unique values (~10k)—stored as dictionary encoding.

Efficient Data Insertion in ClickHouse

ClickHouse is optimized for batch inserts. Use buffering as in the example below.

import { createClient } from '@clickhouse/client';

const client = createClient({
  host: process.env.CLICKHOUSE_HOST,
  username: process.env.CLICKHOUSE_USER,
  password: process.env.CLICKHOUSE_PASSWORD,
  database: 'analytics',
});

class EventBuffer {
  private buffer: EventRow[] = [];
  private flushTimer: NodeJS.Timeout;

  async push(event: EventRow) {
    this.buffer.push(event);
    if (this.buffer.length >= 1000) await this.flush();
  }

  async flush() {
    if (!this.buffer.length) return;
    const rows = [...this.buffer];
    this.buffer = [];
    await client.insert({
      table: 'events',
      values: rows,
      format: 'JSONEachRow',
    });
  }
}

Never insert row by row—for high loads, use Kafka Engine.

Speeding Up Queries

Here are example analytical queries that execute in seconds on 100M rows.

-- DAU over 90 days
SELECT event_date, uniqExact(user_id) AS dau
FROM events
WHERE tenant_id = 42 AND event_date >= today() - 90 AND event_type = 'pageview'
GROUP BY event_date
ORDER BY event_date;

-- Conversion funnel
SELECT
    countIf(event_type = 'product_view') AS views,
    countIf(event_type = 'add_to_cart') AS cart,
    countIf(event_type = 'checkout_start') AS checkout,
    countIf(event_type = 'purchase') AS purchases,
    round(100.0 * purchases / views, 2) AS conversion_pct
FROM events
WHERE tenant_id = 42 AND event_date BETWEEN '2024-01-01' AND '2024-01-31';

uniqExact gives exact unique count. uniq is approximate (~2% error) but an order of magnitude faster.

Performance Comparison: PostgreSQL vs ClickHouse

ClickHouse vs PostgreSQL Performance
Query PostgreSQL (100M rows) ClickHouse (100M rows) Speedup
DAU over 90 days 42 sec 0.4 sec ~100x
Conversion funnel over a quarter 18 sec 0.2 sec ~90x
Cohort analysis 35 sec 0.6 sec ~58x

Materialized Views: Automatic Pre-aggregation

CREATE MATERIALIZED VIEW daily_metrics
ENGINE = SummingMergeTree()
ORDER BY (tenant_id, event_date, country, device_type)
AS SELECT
    tenant_id,
    event_date,
    country,
    device_type,
    count() AS events_count,
    uniqState(user_id) AS unique_users_state,
    uniqState(session_id) AS unique_sessions_state
FROM events
GROUP BY tenant_id, event_date, country, device_type;

SELECT
    event_date,
    sum(events_count) AS total_events,
    uniqMerge(unique_users_state) AS unique_users
FROM daily_metrics
WHERE tenant_id = 42 AND event_date >= today() - 7
GROUP BY event_date;

Materialized views automatically update on insert and store pre-aggregated metrics. This accelerates typical reports by tens of times.

Integration and Operation

Integration with Laravel and Node.js

For Laravel ClickHouse integration, use the package sanchov/laravel-clickhouse. Add a clickhouse connection in config/database.php and query like: DB::connection('clickhouse')->select(..., [$tenantId]). The official Node.js ClickHouse client is @clickhouse/client, which we used in the example above.

Replication and TTL

CREATE TABLE events ON CLUSTER analytics_cluster (
    ...
) ENGINE = ReplicatedMergeTree('/clickhouse/tables/{shard}/events', '{replica}')
ORDER BY (tenant_id, event_date, event_type, user_id)
PARTITION BY toYYYYMM(event_date)
TTL event_date + INTERVAL 2 YEAR DELETE;

TTL automatically deletes data older than two years. For compliance, you can configure moving to cold storage.

Common Mistakes and Our Process

Common Mistakes

The most frequent mistake is trying to insert data row by row. ClickHouse is not designed for transactional inserts. The second is choosing the wrong ORDER BY sort key. If you filter by user_id and event_date, the ORDER BY order should match the filter frequency. The third is forgetting Materialized Views for typical reports, leading to full table scans.

What's Included in Our Work

  1. Analysis of current data model and metrics
  2. Designing events schema + Materialized Views
  3. Configuring replication and TTL
  4. Integration code for Laravel or Node.js
  5. Documentation of schema and queries
  6. Team training (1–2 hours)
  7. 1 month support after implementation

Stages and Timelines

Stage Timeline Cost
Schema events + Materialized Views + Laravel integration 1–2 weeks individually
Cohort analysis, retention, replication, Kafka Engine 2–4 weeks individually

Order a free audit of your current analytics schema—our engineer with 10 years of experience will analyze bottlenecks. To discuss details, contact us via the website form. Project payback is 3–6 months due to infrastructure cost savings.

Official ClickHouse documentation

Setup Web Analytics: GA4, GTM, Yandex.Metrica, and Amplitude

We often see: conversion rate 1.2%, traffic grows, but conversion stays flat. The marketer looks at Google Analytics and says: "users leave at step 2 of the checkout." The developer opens the same step — no errors, Sentry is silent. So it's not a JS bug, but a UX issue or skewed data from analytics. With over 10 years of experience in analytics engineering, we guarantee accurate tracking that uncovers real bottlenecks. Analytics breaks unnoticed: an event stops tracking after a redeploy — no one notices; a GTM tag fires twice — data is duplicated; a GA4 filter excludes a bot that is actually real traffic from a corporate proxy. An audit of your current tags will find the cause within a week.

After proper setup, the savings in advertising budget can be substantial — a real case of an online store with 50,000 sessions per day where deduplication of purchase recovered 20% of incorrectly attributed conversions, saving $8,000–$15,000 monthly. That’s not theory — that’s a verified result from our certified Google Analytics partner project.

Why do GA4 events duplicate and how to fix it?

Universal Analytics is gone, replaced by GA4's event-based model. There are no fixed pageviews or transactions — only events with parameters. This is more flexible but requires proper event design. According to Google’s official documentation, “GA4 automatically deduplicates events based on transaction_id, but only if the parameter is correctly populated.” Many implementations miss this.

Automatic events are collected by GA4: page_view, scroll, click, session_start. Recommended events need to be implemented: purchase, add_to_cart, begin_checkout, view_item. Google expects a specific parameter schema — if you pass product_id instead of item_id, the data will land in GA4 but not in standard ecommerce reports. Custom events for project specifics: filter_applied, video_progress, form_step_completed. Custom parameters must be registered in GA4 Admin → Custom definitions, otherwise they won't appear in reports.

A common mistake is the purchase event being duplicated. Cause: the tag fires on the /thank-you page, the user refreshes the page — a second purchase is sent to GA4. Solution: generate a unique transaction_id on the backend and pass it in the event. In our experience, 80% of e-commerce stores have this issue. GA4 deduplicates based on it (in theory — verify with DebugView). Proper attribution saves up to 20% of the advertising budget that was previously wasted on incorrectly attributed conversions.

How to set up the data layer to avoid data loss?

GTM is a tool for managing tags without code deployment. But "no code" doesn't mean "no architecture." The data layer is the foundation. We pass data from the application to GTM via dataLayer.push(). Structure: event + contextual data. For e-commerce: before opening a product page — push with product data. GTM tag reads from the data layer, not from the DOM.

window.dataLayer = window.dataLayer || [];
dataLayer.push({
  event: 'view_item',
  ecommerce: {
    items: [{
      item_id: 'SKU-12345',
      item_name: 'Product name',
      price: 1990.00,
      currency: 'USD'
    }]
  }
});

Bad practice: GTM tag parses the DOM — looks for the price in span.price, the name in h1. This breaks with any layout change. Good practice: always use the data layer. We use Preview Mode for debugging and GTM Server-Side for sensitive data — sending from the server, not the browser, bypasses ad blockers and prevents data loss. A properly implemented data layer reduces tracking errors by 95%.

How does Yandex.Metrica complement web analytics?

For a Russian audience, Metrica is a must — especially Webvisor. Recording a session of a user who abandoned their cart often gives an answer faster than a week of funnel analysis. Goals in Metrica: event-based (via ym(COUNTER_ID, 'reachGoal', 'GOAL_NAME')) or automatic (button click, page visit). Integration with CRM via Metrica Plus — passing offline conversions. Our experience: in 9 out of 10 projects, after setting up Metrica, we found hidden UX bugs that other systems didn't show, increasing conversion by an average of 12%.

What does product analytics give in Amplitude?

Amplitude is a product tool, unlike marketing-oriented GA4 and Metrica. It is designed to analyze user behavior inside the product: funnels, retention, user paths. Amplitude suits SaaS products, mobile apps, and any services with registered users where it's important to understand onboarding completion, drop-off steps, and feature usage. Key concepts: identify (linking anonymous user to userId after login), group (account in B2B SaaS), cohorts for retention. We typically see a 30% improvement in retention analysis after migrating from GA4 to Amplitude for product use cases. Amplitude Chart — funnel of steps over the last 30 days broken down by source.

Monitoring Data Quality

Analytics without monitoring is a black box. We set up:

  • GA4 Realtime — check after every deploy that key events are coming in
  • Alerting in GA4 — anomaly in the number of purchase events (sharp drop = something broke)
  • GTM Preview in staging before production
  • Manual funnel tests once a week — simply go through the buyer journey and verify everything is tracked
What we check after each deploy
  • All recommended events present in DebugView
  • No duplicates (count purchase per 100 sessions)
  • Data layer structure unchanged after frontend update

What the work includes

Component Description
Audit of existing tags Check current GTM tags, data layer, duplicates, and errors
Event schema design Documentation: event list, parameters, triggers
GA4 + GTM setup Create configuration, tags, custom definitions
Yandex.Metrica Install counter, create goals, set up Webvisor
Amplitude (optional) Set up client and server SDK, cohorts
QA and monitoring Testing in Preview Mode, alerting
Training and handover Access, instructions for adding new events, console

Process and timeline

  1. Audit of existing tags and data (2 days)
  2. Event schema design (2 days)
  3. Data layer development and tag setup (3–5 days)
  4. QA in Preview Mode and staging (2 days)
  5. Deploy and dashboard setup (1 day)
Scenario Timeline
Basic GA4 + GTM setup 1 week
Full e-commerce tracking + Metrica 2–3 weeks
Server-side GTM + Amplitude 3–5 weeks

Cost is calculated individually. Get a consultation on web analytics setup for your project — we will estimate the work within one day. Contact us to get started with a free audit of your current tracking.