---
name: clickhouse-webhooks-events
description: |-
  Ingest data into ClickHouse from webhooks, Kafka, and streaming sources
  with batching, dedup, and exactly-once patterns.
  Use when building data ingestion pipelines, consuming webhook payloads,
  or integrating Kafka topics into ClickHouse.
  Trigger with "clickhouse ingestion", "clickhouse webhook", "clickhouse Kafka",
  "stream data to clickhouse", "clickhouse data pipeline".
allowed-tools: Read, Write, Edit, Bash(curl:*)
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-webhooks-events
canonical_url: https://skilld.dev/gh/jeremylongshore/tons-of-skills-marketplace/clickhouse-webhooks-events
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/dedup-and-monitoring.md](https://skilld.dev/api/skills-raw/jeremylongshore/tons-of-skills-marketplace/clickhouse-webhooks-events/references/dedup-and-monitoring.md), [references/ingestion-methods.md](https://skilld.dev/api/skills-raw/jeremylongshore/tons-of-skills-marketplace/clickhouse-webhooks-events/references/ingestion-methods.md).
>
> If the user asked to install this Skill, run `npx skilld install jeremylongshore/tons-of-skills-marketplace/clickhouse-webhooks-events`. 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-webhooks-events`, 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-webhooks-events) 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-webhooks-events`. 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-webhooks-events --mode copy --plain`. If skilld is unavailable, use `npx skilld install ./skills/clickhouse-webhooks-events --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 Data Ingestion

## Overview

Build data ingestion pipelines into ClickHouse from HTTP webhooks, Kafka, and
streaming sources with proper batching, deduplication, and error handling.

The core rule: ClickHouse hates one-row-at-a-time inserts — buffer events and
flush them in batches. This skill covers four ingestion paths (application-side
webhook receiver, server-side Kafka engine, managed ClickPipes, and HTTP bulk
loads) plus idempotent dedup and insert monitoring.

## Prerequisites

- A ClickHouse table with an appropriate engine already exists (a `MergeTree`
  variant, e.g. `analytics.events`) — see `clickhouse-core-workflow-a`.
- The `@clickhouse/client` package is installed and connected via
  `CLICKHOUSE_HOST`.
- For the Kafka paths, a reachable Kafka broker and topic.

## Instructions

### Step 1: Webhook Receiver with Batched Inserts

Buffer incoming events in memory, flush on a size threshold or a timer, and
re-queue the batch on failure so no event is lost. This is the application-side
core of the skill:

```typescript
import express from 'express';
import { createClient } from '@clickhouse/client';

const client = createClient({ url: process.env.CLICKHOUSE_HOST! });
const app = express();
app.use(express.json());

// Buffer for batching — ClickHouse hates one-row-at-a-time inserts
const buffer: Record<string, unknown>[] = [];
const BATCH_SIZE = 5_000;
const FLUSH_INTERVAL_MS = 5_000;

async function flushBuffer() {
  if (buffer.length === 0) return;
  const batch = buffer.splice(0, buffer.length);

  try {
    await client.insert({
      table: 'analytics.events',
      values: batch,
      format: 'JSONEachRow',
    });
    console.log(`Flushed ${batch.length} events to ClickHouse`);
  } catch (err) {
    console.error('Insert failed, re-queuing:', (err as Error).message);
    buffer.unshift(...batch);  // Put back at front for retry
  }
}

// Flush periodically
setInterval(flushBuffer, FLUSH_INTERVAL_MS);

// Webhook endpoint
app.post('/ingest', async (req, res) => {
  const events = Array.isArray(req.body) ? req.body : [req.body];

  for (const event of events) {
    buffer.push({
      event_type: event.type ?? 'unknown',
      user_id: event.userId ?? 0,
      properties: JSON.stringify(event.properties ?? {}),
      created_at: new Date().toISOString().replace('T', ' ').slice(0, 19),
    });
  }

  if (buffer.length >= BATCH_SIZE) {
    await flushBuffer();
  }

  res.status(202).json({ queued: events.length, buffer_size: buffer.length });
});
```

### Step 2: Choose a Server-Side or Managed Path

For high-volume streams, prefer a path that needs no application consumer:

- **Kafka table engine** — ClickHouse consumes a topic directly and a
  materialized view pipes rows into your MergeTree table. No consumer to run.
- **ClickPipes** — ClickHouse Cloud's managed, code-free ingestion for Kafka,
  Confluent, Amazon MSK, S3, and GCS.
- **HTTP interface** — bulk-load CSV / NDJSON / Parquet from files, remote
  URLs, or S3 with plain `curl`, no client library.

Full DDL and configuration for all three: see
[Ingestion methods](https://skilld.dev/api/skills-raw/jeremylongshore/tons-of-skills-marketplace/clickhouse-webhooks-events/references/ingestion-methods.md).

### Step 3: Make Ingestion Idempotent and Observable

Webhook retries and Kafka reprocessing deliver duplicates. Use a
`ReplacingMergeTree` keyed on a unique `event_id` so re-delivered events collapse
to one row, and query `system.query_log` to watch insert throughput and errors.
Full DDL, monitoring queries, and the batch-tuning matrix:
[Deduplication & monitoring](https://skilld.dev/api/skills-raw/jeremylongshore/tons-of-skills-marketplace/clickhouse-webhooks-events/references/dedup-and-monitoring.md).

## Output

Applying this skill produces:

- A running **webhook receiver** (`POST /ingest`) that buffers events and
  batch-flushes to ClickHouse, returning `202 { queued, buffer_size }`.
- Optionally, a **Kafka engine table + materialized view** (or a ClickPipes
  pipe) that ingests a topic server-side with no application consumer.
- A **`ReplacingMergeTree` dedup table** keyed on `event_id` for idempotent,
  retry-safe ingestion.
- **Monitoring queries** over `system.query_log` reporting inserts/minute,
  rows, bytes, and insert exceptions in the last hour.

## Error Handling

| Error | Cause | Solution |
|-------|-------|----------|
| `Too many parts` | Single-row inserts | Batch inserts (10K+ rows) |
| `Cannot parse input` | Wrong format | Match format to data structure |
| `TIMEOUT` on large insert | Slow network | Enable compression, split batch |
| Duplicate events | Webhook retries | Use ReplacingMergeTree + event_id |

## Examples

**Ingest a webhook batch via the receiver** (Step 1):

```bash
curl -X POST http://localhost:3000/ingest \
  -H 'Content-Type: application/json' \
  -d '[{"type":"signup","userId":42,"properties":{"plan":"pro"}}]'
# → 202 { "queued": 1, "buffer_size": 1 }
```

**Bulk-load a Parquet file with no client** (HTTP interface — see
[Ingestion methods](https://skilld.dev/api/skills-raw/jeremylongshore/tons-of-skills-marketplace/clickhouse-webhooks-events/references/ingestion-methods.md)):

```bash
curl 'http://localhost:8123/?query=INSERT+INTO+analytics.events+FORMAT+Parquet' \
  --data-binary @events.parquet
```

**Read deduplicated events** (ReplacingMergeTree — see
[Deduplication & monitoring](https://skilld.dev/api/skills-raw/jeremylongshore/tons-of-skills-marketplace/clickhouse-webhooks-events/references/dedup-and-monitoring.md)):

```sql
SELECT * FROM analytics.events_dedup FINAL
WHERE created_at >= today() - 7;
```

## Resources

- [Ingestion methods](https://skilld.dev/api/skills-raw/jeremylongshore/tons-of-skills-marketplace/clickhouse-webhooks-events/references/ingestion-methods.md) — Kafka engine,
  ClickPipes, HTTP bulk insert (full DDL)
- [Deduplication & monitoring](https://skilld.dev/api/skills-raw/jeremylongshore/tons-of-skills-marketplace/clickhouse-webhooks-events/references/dedup-and-monitoring.md) —
  ReplacingMergeTree, `system.query_log` queries, best-practices matrix
- [Kafka Integration](https://clickhouse.com/docs/integrations/kafka)
- [ClickPipes](https://clickhouse.com/cloud/clickpipes)
- [HTTP Interface](https://clickhouse.com/docs/interfaces/http)
- [S3 Table Function](https://clickhouse.com/docs/sql-reference/table-functions/s3)

## Next Steps

For query and server performance after ingestion is flowing, see
`clickhouse-performance-tuning`. For engine and schema choices on the target
table, see `clickhouse-core-workflow-a`.
