Skip to content
Skills Library
Programming · Building & coding

clickhouse-sdk-patterns

/clickhouse-sdk-patterns

Production-ready patterns for @clickhouse/client — streaming inserts, typed queries, error handling, and connection management. Use when building robust ClickHouse integrations, implementing streaming inserts or low-memory streaming reads, or establishing team coding standards. Trigger with "clickhouse SDK patterns", "clickhouse client patterns", "clickhouse best practices", "clickhouse streaming insert".

Licence
MIT
Last repository change
26.10.2026

Assessment and security

100/ 100Class: good
Format25 / 25
Frontmatter with name and description, valid name, description up to 1,024 characters, name matching the folder.
Discoverability25 / 25
Description explains when to use the skill, has a reasonable length and uses third person.
Content35 / 35
At least 150 words and at most 500 lines, headings, step lists, examples or code.
Hygiene15 / 15
No placeholders such as TODO, no Windows paths, with a licence.
Riskno signals detected in the scan
Files in this package
3
Scripts
0
HTML comments
0
URLs in SKILL.md
3
Deprecation

No signals detected. Repository changed on 26.10.2026, without references to retired models or APIs.

Licence

MIT, open: use and modify while retaining author attribution.

What it does and when to use it

Production-ready patterns for @clickhouse/client — streaming inserts, typed queries, error handling, and connection management. Use when building robust ClickHouse integrations, implementing streaming inserts or low-memory streaming reads, or establishing team coding standards. Trigger with "clickhouse SDK patterns", "clickhouse client patterns", "clickhouse best practices", "clickhouse streaming insert".

Triggers from the description

clickhouse SDK patternsclickhouse client patternsclickhouse best practicesclickhouse streaming insert
Original author description

Production-ready patterns for @clickhouse/client — streaming inserts, typed queries, error handling, and connection management. Use when building robust ClickHouse integrations, implementing streaming inserts or low-memory streaming reads, or establishing team coding standards. Trigger with "clickhouse SDK patterns", "clickhouse client patterns", "clickhouse best practices", "clickhouse streaming insert".

How it works

  1. Overview
  2. Prerequisites
  3. Instructions
  4. Output
  5. Error Handling
  6. Examples
  7. Resources
  8. Next Steps
Original SKILL.md headings · 124 lines, 605 words
SKILL.md preview
---
name: clickhouse-sdk-patterns
description: |
  Production-ready patterns for @clickhouse/client — streaming inserts, typed
  queries, error handling, and connection management.
  Use when building robust ClickHouse integrations, implementing streaming
  inserts or low-memory streaming reads, or establishing team coding standards.
  Trigger with "clickhouse SDK patterns", "clickhouse client patterns",
  "clickhouse best practices", "clickhouse streaming insert".
allowed-tools: Read
version: 1.7.0
license: MIT
author: Jeremy Longshore <jeremy@intentsolutions.io>
tags:
- saas
- database
- analytics
- clickhouse
- olap
compatibility: Designed for Claude Code
---
# ClickHouse SDK Patterns

## Overview

Production patterns for `@clickhouse/client` — typed queries, streaming inserts,
error handling, and connection lifecycle management. Start from the typed query
helper below, then drill into `references/implementation.md` for the streaming,
batching, and lifecycle patterns.

## Prerequisites

- `@clickhouse/client` installed and authenticated (see `clickhouse-install-auth`)
- Node.js 18+ with a `CLICKHOUSE_HOST` / `CLICKHOUSE_USER` / `CLICKHOUSE_PASSWORD` env set
- Familiarity with async/await and Node.js streams (backpressure, `drain`, `Readable`)

## Instructions

Apply the pattern that fits your workload. Steps 2–7 live in
[references/implementation.md](references/implementation.md) with full,
copy-pasteable code; the core typed-query skeleton stays here.

1. **Typed query helper** — the foundation every other pattern builds on. Define
   a generic `query<T>` wrapper that returns parsed rows (skeleton below).
2. **Streaming insert (backpressure-safe)** — stream large inserts through a
   `Readable` instead of buffering in memory; honor `drain`.
3. **Batch insert with retry** — chunk rows (default 10k) with exponential-backoff
   retries, returning `{ inserted, errors }`.
4. **Streaming SELECT (low memory)** — consume large result sets as an
   `AsyncGenerator` so you never load the full set into RAM.
5. **Error handling** — distinguish server-side `ClickHouseError` (code + message)
   from network/client errors and normalize into a structured result.
6. **Connection lifecycle** — flush pending inserts on `SIGTERM` via
   `client.close()`; expose a `ping()`-based health check.
7. **Per-query settings** — override `max_threads`, `max_memory_usage`,
   `max_execution_time`, and `max_result_rows` for heavy queries.

### Skeleton: Typed Query Helper

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

const client = createClient({
  url: process.env.CLICKHOUSE_HOST!,
  username: process.env.CLICKHOUSE_USER ?? 'default',
  password: process.env.CLICKHOUSE_PASSWORD ?? '',
});

// Generic typed query — returns parsed JSON rows
async function query<T>(sql: string, params?: Record<string, unknown>): Promise<T[]> {
  const rs = await client.query({
    query: sql,
    query_params: params,
    format: 'JSONEachRow',
  });
  return rs.json<T>();
}
```

**Note on parameterized queries:** ClickHouse uses `{name:Type}` syntax for
parameters, not `$1` or `?`. Always use typed parameters to prevent SQL injection.

## Output

Applying these patterns produces:

- A single reusable `client` instance plus a generic `query<T>` helper that
  returns typed, parsed rows.
- Streaming insert/read paths that keep memory flat regardless of dataset size.
- A batch-insert result object `{ inserted: number; errors: Error[] }` you can act
  on programmatically.
- Normalized error results (`CH-<code>: <message>` for server-side failures) rather
  than raw thrown exceptions.
- Graceful shutdown that flushes pending inserts before the process exits.

## Error Handling

Map common ClickHouse server error codes to a corrective action:

| Error Code | Meaning | Action |
|------------|---------|--------|
| `SYNTAX_ERROR (62)` | Bad SQL | Fix query syntax |
| `UNKNOWN_TABLE (60)` | Table doesn't exist | Check table name, database |
| `TOO_MANY_SIMULTANEOUS_QUERIES (202)` | Connection overload | Reduce concurrency or pool |
| `MEMORY_LIMIT_EXCEEDED (241)` | Query uses too much RAM | Add filters, use streaming |
| `TIMEOUT_EXCEEDED (159)` | Query too slow | Optimize ORDER BY, add indexes |

Full `safeQuery` wrapper (server-vs-client error discrimination) is in
[references/implementation.md](references/implementation.md) under Pattern 5.

## Examples

Worked, runnable usage of each helper is in
[references/examples.md](references/examples.md). Quick look — a typed aggregation
query with named parameters:

```typescript
interface EventCount {
  event_type: string;
  cnt: string;  // ClickHouse JSON returns numbers as strings
}

const rows = await query<EventCount>(
  'SELECT event_type, count() AS cnt FROM events WHERE user_id = {user_id:UInt64} GROUP BY event_type',
  { user_id: 42 }
);
```

See [references/examples.md](references/examples.md) for streaming reads and
structured error-result usage.

## Resources

- [references/implementation.md](references/implementation.md) — full code for patterns 2–7 + format table
- [references/examples.md](references/examples.md) — worked, runnable usage examples
- [Node.js Client Docs](https://clickhouse.com/docs/integrations/javascript)
- [Client Examples (GitHub)](https://github.com/ClickHouse/clickhouse-js/tree/main/examples)
- [Query Settings Reference](https://clickhouse.com/docs/operations/settings/settings)

## Next Steps

Apply these patterns in `clickhouse-core-workflow-a` for real data modeling, then
tune query cost and concurrency with `clickhouse-cost-tuning` and
`clickhouse-performance-tuning`.
Files in this package (3)
  • SKILL.md 6 KB
  • references/examples.md 2 KB
  • references/implementation.md 5 KB

Versions

The database has no other skills named clickhouse-sdk-patterns.

Identical content appears in 1 other GitHub folders. We show one copy with the highest score.

Database snapshot: 13.11.2026 · package version 1c0cf3a50949 (SHA-256 digest of the entire package)

Downloads in the last 30 days: 2 · ranking

Report a problem with this skill: harmful content, incorrect descriptions or an author’s removal request.

Similar skills

  • 100clickhouse-common-errors
    Diagnose and fix the top 15 ClickHouse errors — query failures, insert problems, memory limits, and merge issues. Use when a ClickHouse query or insert throws an exception, a server-side error appears in logs, or a failed query needs root-cause analysis. Trigger with "clickhouse…
  • 100clickhouse-pr-description
    Generate PR descriptions for ClickHouse/ClickHouse that match maintainer expectations. Use when creating or updating PR descriptions.
  • 100clickhouse-install-auth
    Install @clickhouse/client and configure authentication to ClickHouse Cloud or self-hosted. Use when setting up a new ClickHouse project, configuring connection strings, or initializing the official Node.js or Python client. Trigger with "install clickhouse", "setup clickhouse…
  • 100clickhouse-migrations
    ClickHouse migration patterns and rules. Use when creating or modifying ClickHouse migrations.
  • 100clickhouse-js-node-coding
    Write idiomatic application code with the ClickHouse Node.js client (`@clickhouse/client`). Use this skill whenever a user is *building* against the Node.js client — configuring the client, pinging, inserting rows in JSON or raw formats, selecting and parsing results, binding…
  • 100apollo-sdk-patterns
    Apply production-ready Apollo.io SDK patterns. Use when implementing Apollo integrations, refactoring API usage, or establishing team coding standards. Trigger with phrases like "apollo sdk patterns", "apollo best practices", "apollo code patterns", "idiomatic apollo", "apollo client wrapper".

Feedback and reports

Your message goes to Bartosz Sokoliński. An email address is needed only for a reply. See the privacy policy.