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, or establishing team coding standards. Trigger: "clickhouse SDK patterns", "clickhouse client patterns", "clickhouse best practices", "clickhouse streaming insert".
Best use case
clickhouse-sdk-patterns is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
Production-ready patterns for @clickhouse/client — streaming inserts, typed queries, error handling, and connection management. Use when building robust ClickHouse integrations, implementing streaming, or establishing team coding standards. Trigger: "clickhouse SDK patterns", "clickhouse client patterns", "clickhouse best practices", "clickhouse streaming insert".
Teams using clickhouse-sdk-patterns should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/clickhouse-sdk-patterns/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How clickhouse-sdk-patterns Compares
| Feature / Agent | clickhouse-sdk-patterns | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
Production-ready patterns for @clickhouse/client — streaming inserts, typed queries, error handling, and connection management. Use when building robust ClickHouse integrations, implementing streaming, or establishing team coding standards. Trigger: "clickhouse SDK patterns", "clickhouse client patterns", "clickhouse best practices", "clickhouse streaming insert".
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
Related Guides
AI Agents for Coding
Browse AI agent skills for coding, debugging, testing, refactoring, code review, and developer workflows across Claude, Cursor, and Codex.
Best AI Skills for Claude
Explore the best AI skills for Claude and Claude Code across coding, research, workflow automation, documentation, and agent operations.
ChatGPT vs Claude for Agent Skills
Compare ChatGPT and Claude for AI agent skills across coding, writing, research, and reusable workflow execution.
SKILL.md Source
# ClickHouse SDK Patterns
## Overview
Production patterns for `@clickhouse/client` — typed queries, streaming inserts,
error handling, and connection lifecycle management.
## Prerequisites
- `@clickhouse/client` installed (see `clickhouse-install-auth`)
- Familiarity with async/await and Node.js streams
## Instructions
### Pattern 1: 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>();
}
// Usage
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 }
);
```
**Note on parameterized queries:** ClickHouse uses `{name:Type}` syntax for parameters,
not `$1` or `?`. Always use typed parameters to prevent SQL injection.
### Pattern 2: Streaming Insert (Backpressure-Safe)
```typescript
import { createClient } from '@clickhouse/client';
import { Readable } from 'stream';
// For large inserts, stream data instead of buffering in memory
async function streamInsert(rows: AsyncIterable<Record<string, unknown>>) {
const stream = new Readable({
objectMode: true,
read() {}, // push-based
});
const insertPromise = client.insert({
table: 'events',
values: stream,
format: 'JSONEachRow',
});
for await (const row of rows) {
// Backpressure: if push returns false, wait for drain
if (!stream.push(row)) {
await new Promise<void>((resolve) => stream.once('drain', resolve));
}
}
stream.push(null); // Signal end of stream
await insertPromise;
}
```
### Pattern 3: Batch Insert with Retry
```typescript
async function batchInsert<T extends Record<string, unknown>>(
table: string,
rows: T[],
batchSize = 10_000,
maxRetries = 3,
): Promise<{ inserted: number; errors: Error[] }> {
let inserted = 0;
const errors: Error[] = [];
for (let i = 0; i < rows.length; i += batchSize) {
const batch = rows.slice(i, i + batchSize);
let attempt = 0;
while (attempt < maxRetries) {
try {
await client.insert({
table,
values: batch,
format: 'JSONEachRow',
});
inserted += batch.length;
break;
} catch (err) {
attempt++;
if (attempt === maxRetries) {
errors.push(err as Error);
} else {
await new Promise((r) => setTimeout(r, 1000 * Math.pow(2, attempt)));
}
}
}
}
return { inserted, errors };
}
```
### Pattern 4: Streaming SELECT (Low Memory)
```typescript
// For large result sets, stream rows instead of loading all into memory
async function* streamQuery<T>(sql: string): AsyncGenerator<T> {
const rs = await client.query({ query: sql, format: 'JSONEachRow' });
const stream = rs.stream();
for await (const rows of stream) {
// Each chunk is an array of rows (typically ~8KB worth)
for (const row of rows) {
yield (row as { json: () => T }).json();
}
}
}
// Usage
for await (const event of streamQuery<{ event_type: string }>('SELECT * FROM events')) {
process.stdout.write(`${event.event_type}\n`);
}
```
### Pattern 5: Error Handling
```typescript
import { ClickHouseError } from '@clickhouse/client';
async function safeQuery<T>(sql: string): Promise<{ data: T[] | null; error: string | null }> {
try {
const rs = await client.query({ query: sql, format: 'JSONEachRow' });
return { data: await rs.json<T>(), error: null };
} catch (err) {
if (err instanceof ClickHouseError) {
// ClickHouse server-side error (syntax, permissions, etc.)
console.error(`ClickHouse error ${err.code}: ${err.message}`);
return { data: null, error: `CH-${err.code}: ${err.message}` };
}
// Network or client-side error
console.error('Client error:', (err as Error).message);
return { data: null, error: (err as Error).message };
}
}
```
### Pattern 6: Connection Lifecycle
```typescript
// Graceful shutdown — important for flush of pending inserts
process.on('SIGTERM', async () => {
console.log('Closing ClickHouse connection...');
await client.close();
process.exit(0);
});
// Health check
async function isHealthy(): Promise<boolean> {
try {
const { success } = await client.ping();
return success;
} catch {
return false;
}
}
```
### Pattern 7: ClickHouse Settings Per Query
```typescript
// Override server settings for specific queries
const rs = await client.query({
query: 'SELECT * FROM huge_table',
format: 'JSONEachRow',
clickhouse_settings: {
max_threads: 4, // Limit parallelism
max_memory_usage: 1_000_000_000, // 1GB memory limit
max_execution_time: 30, // 30s timeout
max_result_rows: 100_000, // Cap result size
},
});
```
## Format Reference
| Format | Use Case | Streaming |
|--------|----------|-----------|
| `JSONEachRow` | Standard JSON rows (NDJSON) | Yes |
| `JSONCompactEachRow` | Arrays instead of objects (smaller) | Yes |
| `CSV` | Export/import | Yes |
| `TabSeparated` | CLI-compatible output | Yes |
| `Parquet` | Analytics interchange | Yes |
| `Native` | Fastest binary format | Yes |
## Error Handling
| 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 |
## Resources
- [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.Related Skills
workhuman-sdk-patterns
Workhuman sdk patterns for employee recognition and rewards API. Use when integrating Workhuman Social Recognition, or building recognition workflows with HRIS systems. Trigger: "workhuman sdk patterns".
wispr-sdk-patterns
Wispr Flow sdk patterns for voice-to-text API integration. Use when integrating Wispr Flow dictation, WebSocket streaming, or building voice-powered applications. Trigger: "wispr sdk patterns".
windsurf-sdk-patterns
Apply production-ready Windsurf workspace configuration and Cascade interaction patterns. Use when configuring .windsurfrules, workspace rules, MCP servers, or establishing team coding standards for Windsurf AI. Trigger with phrases like "windsurf patterns", "windsurf best practices", "windsurf config patterns", "windsurfrules", "windsurf workspace".
windsurf-reliability-patterns
Implement reliable Cascade workflows with checkpoints, rollback, and incremental editing. Use when building fault-tolerant AI coding workflows, preventing Cascade from breaking builds, or establishing safe practices for multi-file AI edits. Trigger with phrases like "windsurf reliability", "cascade safety", "windsurf rollback", "cascade checkpoint", "safe cascade workflow".
webflow-sdk-patterns
Apply production-ready Webflow SDK patterns — singleton client, typed error handling, pagination helpers, and raw response access for the webflow-api package. Use when implementing Webflow integrations, refactoring SDK usage, or establishing team coding standards. Trigger with phrases like "webflow SDK patterns", "webflow best practices", "webflow code patterns", "idiomatic webflow", "webflow typescript".
vercel-sdk-patterns
Production-ready Vercel REST API patterns with typed fetch wrappers and error handling. Use when integrating with the Vercel API programmatically, building deployment tools, or establishing team coding standards for Vercel API calls. Trigger with phrases like "vercel SDK patterns", "vercel API wrapper", "vercel REST API client", "vercel best practices", "idiomatic vercel API".
vercel-reliability-patterns
Implement reliability patterns for Vercel deployments including circuit breakers, retry logic, and graceful degradation. Use when building fault-tolerant serverless functions, implementing retry strategies, or adding resilience to production Vercel services. Trigger with phrases like "vercel reliability", "vercel circuit breaker", "vercel resilience", "vercel fallback", "vercel graceful degradation".
veeva-sdk-patterns
Veeva Vault sdk patterns for REST API and clinical operations. Use when working with Veeva Vault document management and CRM. Trigger: "veeva sdk patterns".
vastai-sdk-patterns
Apply production-ready Vast.ai SDK patterns for Python and REST API. Use when implementing Vast.ai integrations, refactoring SDK usage, or establishing coding standards for GPU cloud operations. Trigger with phrases like "vastai SDK patterns", "vastai best practices", "vastai code patterns", "idiomatic vastai".
twinmind-sdk-patterns
Apply production-ready TwinMind SDK patterns for TypeScript and Python. Use when implementing TwinMind integrations, refactoring API usage, or establishing team coding standards for meeting AI integration. Trigger with phrases like "twinmind SDK patterns", "twinmind best practices", "twinmind code patterns", "idiomatic twinmind".
together-sdk-patterns
Together AI sdk patterns for inference, fine-tuning, and model deployment. Use when working with Together AI's OpenAI-compatible API. Trigger: "together sdk patterns".
techsmith-sdk-patterns
TechSmith sdk patterns for Snagit COM API and Camtasia automation. Use when working with TechSmith screen capture and video editing automation. Trigger: "techsmith sdk patterns".