---
name: clickhouse-multi-env-setup
description: |-
  Configure ClickHouse across dev, staging, and production with
  environment-specific settings, secrets management, and infrastructure-as-code
  patterns. Use when setting up per-environment ClickHouse instances, managing
  connection configs, wiring secrets per environment, or deploying to multiple
  environments. Trigger with "clickhouse environments", "clickhouse dev staging
  prod", "clickhouse multi-env", "clickhouse environment config", "clickhouse
  staging setup".
allowed-tools: Read, Write, Edit, Bash(aws:*), Bash(gcloud:*), Bash(vault:*)
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-multi-env-setup
canonical_url: https://skilld.dev/gh/jeremylongshore/tons-of-skills-marketplace/clickhouse-multi-env-setup
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/examples.md](https://skilld.dev/api/skills-raw/jeremylongshore/tons-of-skills-marketplace/clickhouse-multi-env-setup/references/examples.md), [references/implementation.md](https://skilld.dev/api/skills-raw/jeremylongshore/tons-of-skills-marketplace/clickhouse-multi-env-setup/references/implementation.md).
>
> If the user asked to install this Skill, run `npx skilld install jeremylongshore/tons-of-skills-marketplace/clickhouse-multi-env-setup`. 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-multi-env-setup`, 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-multi-env-setup) 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-multi-env-setup`. 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-multi-env-setup --mode copy --plain`. If skilld is unavailable, use `npx skilld install ./skills/clickhouse-multi-env-setup --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 Multi-Environment Setup

## Overview

Configure separate ClickHouse instances for development, staging, and production
with proper secrets management, environment detection, and infrastructure-as-code.
A single typed config module resolves the right instance from `NODE_ENV`, so
application code never branches on environment and destructive operations are
blocked outside dev/staging.

The full code for every step lives in
[references/implementation.md](https://skilld.dev/api/skills-raw/jeremylongshore/tons-of-skills-marketplace/clickhouse-multi-env-setup/references/implementation.md); worked end-to-end
flows are in [references/examples.md](https://skilld.dev/api/skills-raw/jeremylongshore/tons-of-skills-marketplace/clickhouse-multi-env-setup/references/examples.md).

## Prerequisites

- ClickHouse Cloud account or self-hosted instances per environment
- Secret management solution (Vault, AWS Secrets Manager, GCP Secret Manager)
- CI/CD pipeline with environment variables

## Instructions

### Step 1: Choose an environment strategy

Provision one instance per tier, isolated by data sensitivity:

| Environment | Instance | Purpose | Data |
|-------------|----------|---------|------|
| Development | Docker local | Fast iteration | Synthetic seed data |
| Staging | ClickHouse Cloud (Dev tier) | Pre-prod validation | Sampled prod copy |
| Production | ClickHouse Cloud (Prod tier) | Live traffic | Real data |

### Step 2: Build a typed config module

Create `src/config/clickhouse.ts` with one `ClickHouseEnvConfig` per environment,
keyed by `NODE_ENV`. Fail fast in non-dev environments — require a password and
enforce HTTPS at startup:

```typescript
export function getConfig(): ClickHouseEnvConfig {
  const env = process.env.NODE_ENV ?? 'development';
  const config = configs[env];
  if (!config) throw new Error(`Unknown environment: ${env}`);
  if (env !== 'development') {
    if (!config.password) throw new Error(`CLICKHOUSE_PASSWORD not set for ${env}`);
    if (!config.url.startsWith('https://')) {
      throw new Error(`ClickHouse ${env} must use HTTPS`);
    }
  }
  return config;
}
```

Full per-environment config table (pool sizes, timeouts, compression):
[references/implementation.md](https://skilld.dev/api/skills-raw/jeremylongshore/tons-of-skills-marketplace/clickhouse-multi-env-setup/references/implementation.md).

### Step 3: Add a client factory

A lazily-initialized singleton in `src/clickhouse/client.ts` builds the pool once
per process from the resolved config. Full code:
[references/implementation.md](https://skilld.dev/api/skills-raw/jeremylongshore/tons-of-skills-marketplace/clickhouse-multi-env-setup/references/implementation.md).

### Step 4: Wire secrets per environment

Dev uses a git-ignored `.env.local`; every other tier pulls from a secret manager
(AWS Secrets Manager, GCP Secret Manager, or Vault) — never commit credentials.
CLI recipes for all three:
[references/implementation.md](https://skilld.dev/api/skills-raw/jeremylongshore/tons-of-skills-marketplace/clickhouse-multi-env-setup/references/implementation.md).

### Step 5: Apply schema deterministically

Run sorted `.sql` files through a migration runner (`scripts/apply-schema.ts`).
Fail hard in production, log-and-continue in dev/staging:
[references/implementation.md](https://skilld.dev/api/skills-raw/jeremylongshore/tons-of-skills-marketplace/clickhouse-multi-env-setup/references/implementation.md).

### Step 6: Add environment guards

`requireNonProduction` blocks TRUNCATE/reset in prod and `validateDatabaseName`
catches cross-environment queries. Full guards:
[references/implementation.md](https://skilld.dev/api/skills-raw/jeremylongshore/tons-of-skills-marketplace/clickhouse-multi-env-setup/references/implementation.md).

### Step 7: Integrate with CI/CD

Auto-deploy staging; gate production behind `needs: deploy-staging` plus a
manual-approval environment. Full workflow:
[references/examples.md](https://skilld.dev/api/skills-raw/jeremylongshore/tons-of-skills-marketplace/clickhouse-multi-env-setup/references/examples.md).

## Output

Completing this workflow yields:

- `src/config/clickhouse.ts` — typed, per-environment ClickHouse config with
  startup validation (password present, HTTPS enforced outside dev).
- `src/clickhouse/client.ts` — a singleton client factory keyed off `NODE_ENV`.
- `scripts/apply-schema.ts` — a deterministic, sorted migration runner.
- Environment guards preventing destructive operations against production.
- Secrets stored in a secret manager per environment (nothing committed).
- A `.github/workflows/deploy.yml` pipeline that migrates schema and deploys
  staging automatically, production behind manual approval.

Application code then calls `getClient()` with zero environment branching.

## Error Handling

| Issue | Cause | Solution |
|-------|-------|----------|
| Wrong database in prod | Env var not set | Validate config on startup |
| TLS error in staging | Using `http://` for Cloud | Force `https://` in non-dev |
| Schema drift | Applied manually | Use migration runner in CI |
| Secret not found | Missing env var | Check secret manager + CI config |

## Examples

Query from application code with no environment logic — `getConfig()` resolves the
right instance from `NODE_ENV`:

```typescript
import { getClient } from './clickhouse/client';

const rows = await getClient().query({
  query: 'SELECT count() AS c FROM events WHERE date = today()',
  format: 'JSONEachRow',
});
console.log(await rows.json());
```

More worked flows — the environment-strategy layout, the full CI/CD deploy
pipeline, and end-to-end query usage — are in
[references/examples.md](https://skilld.dev/api/skills-raw/jeremylongshore/tons-of-skills-marketplace/clickhouse-multi-env-setup/references/examples.md).

## Resources

- [full implementation walkthrough](https://skilld.dev/api/skills-raw/jeremylongshore/tons-of-skills-marketplace/clickhouse-multi-env-setup/references/implementation.md)
- [worked examples](https://skilld.dev/api/skills-raw/jeremylongshore/tons-of-skills-marketplace/clickhouse-multi-env-setup/references/examples.md)
- [12-Factor App Config](https://12factor.net/config)
- [ClickHouse Cloud Console](https://clickhouse.cloud/)
- [AWS Secrets Manager](https://aws.amazon.com/secrets-manager/)
- [GCP Secret Manager](https://cloud.google.com/secret-manager)

## Next Steps

For monitoring and observability, see the `clickhouse-observability` skill, which
covers query performance dashboards, slow-query logging, and alerting across the
same dev/staging/production tiers you configured here.
