Skip to content
STACK IT FAST

PostHog

Curated OSSHybridProduct Analytics Platform20+ people

Audited from github.com/PostHog/posthog

PostHog is an open-source product engineering platform combining web analytics, session replay, feature flags, A/B testing, and AI observability.

Language
Python
Database
ClickHouse
Hosting
Docker
Running for
4 years 10 months
Team
20+ people

Why this architecture

Pairing Apache Kafka with ClickHouse columnar storage enables PostHog to ingest billions of monthly events while maintaining sub-second query response times.

Tech stack by layer

11 technologies · audited Sep 17, 2026
Frontend & UI
  • ReactPowers the analytics dashboards, session replay player, and experimentation UI.
  • TypeScriptEnsures strict type-checking across frontend apps, plugins, and shared schema contracts.
  • KeaRedux-based state management framework developed by PostHog for orchestrating complex UI logic.
Backend & APIs
  • DjangoPython REST API framework handling authentication, organization management, and billing.
  • PythonPrimary language for the core API, background workers, and analytical query compilers.
  • RustHigh-throughput event ingestion pipelines and parsing services compiled in rust/Cargo.toml.
  • TemporalCoordinates long-running background tasks, data warehouse syncing, and migration jobs.
Data & Persistence
  • ClickHouseColumnar database storing billions of events, session recordings, and HogQL telemetry.
  • PostgreSQLRelational database storing teams, feature flag configurations, user roles, and dashboard metadata.
  • KafkaDistributed messaging log buffering incoming event streams before batching into ClickHouse.
  • RedisIn-memory caching layer, rate limiter, and Celery task broker.
Infrastructure & Deploy
  • DockerMulti-stage Dockerfile packaging the web application, workers, and background processors.

PostHog architecture diagram

Open SVG
PostHog architecture diagramWeb app → Django API (REST); SDKs → Capture (events); Capture → Kafka (produce); Kafka → Ingestion consumers (consume); Ingestion consumers → ClickHouse (batch writes); Django API → PostgreSQL (metadata); Django API → ClickHouse (HogQL queries); Django API → Redis (tasks); Redis → Celery workers (broker); Temporal workflows → ClickHouse (warehouse sync)CLIENTSSERVICESWORKERS & JOBSDATA & STORAGEWeb appReact · KeaSDKscapture clientsDjango APIPython · DRFCaptureRustCelery workersPythonTemporal workflowsPythonIngestion consumersRustRediscache · brokerPostgreSQLteams · flagsClickHouseevents · HogQLKafkaevent topicsRESTeventsconsumebatch writesbrokerwarehouse syncproducemetadataHogQL queriestasks
How the main components of PostHog connect, drawn from the audited repository.
Diagram as text
  • Web app (React · Kea) → Django API (Python · DRF): REST
  • SDKs (capture clients) → Capture (Rust): events
  • Capture (Rust) → Kafka (event topics): produce
  • Kafka (event topics) → Ingestion consumers (Rust): consume
  • Ingestion consumers (Rust) → ClickHouse (events · HogQL): batch writes
  • Django API (Python · DRF) → PostgreSQL (teams · flags): metadata
  • Django API (Python · DRF) → ClickHouse (events · HogQL): HogQL queries
  • Django API (Python · DRF) → Redis (cache · broker): tasks
  • Redis (cache · broker) → Celery workers (Python): broker
  • Temporal workflows (Python) → ClickHouse (events · HogQL): warehouse sync

Key architectural decisions

5 decisions
  1. 01

    Ingestion decoupled from persistence via Kafka and Rust capture workers

    Incoming event batches are captured by high-throughput Rust services and pushed to Apache Kafka topics, isolating web-tier ingestion spikes from database write pressure.

  2. 02

    Bifurcated storage model: ClickHouse for telemetry, PostgreSQL for metadata

    PostgreSQL manages tenant accounts, feature flag toggles, team memberships, and dashboard layouts, while ClickHouse executes columnar aggregations over billions of events.

  3. 03

    Custom SQL dialect (HogQL) compiled directly to ClickHouse SQL

    PostHog created HogQL (common/hogql_parser/), a domain-specific SQL dialect with AST validation that translates safe user-defined queries directly into optimized ClickHouse SQL.

  4. 04

    Temporal workflow engine for complex multi-step background orchestration

    Long-running batch workflows, data warehouse synchronization, and cohort recalculations are orchestrated via Temporal rather than unbounded Celery worker chains.

  5. 05

    Kea state management for declarative Redux architecture

    The frontend in frontend/ uses Kea to organize business logic into typed state "logics" that encapsulate actions, reducers, and side effects without boilerplate Redux plumbing.

How PostHog is built

How PostHog is structured

PostHog is structured as a polyglot monorepo that spans Python, TypeScript, and Rust. The repository is coordinated to deliver an end-to-end product engineering platform covering event analytics, session recording, feature flags, experimentation, and error tracking:

  • posthog/: The core Python Django web application (posthog/api/, posthog/models/, posthog/hogql/), housing REST API endpoints, business logic, authorization rules, and the HogQL query engine.
  • frontend/: A TypeScript single-page application built on React (frontend/package.json), containing the interactive analytics explorer, insight visualizers, and session replay players.
  • rust/: Performance-critical event ingestion pipelines, Kafka consumer groups, and replay transformation services (rust/Cargo.toml).
  • common/: Shared cross-language libraries, including the HogQL parser (common/hogql_parser/), plugin transpilers, and headless replay tools.
  • livestream/: Real-time streaming services implemented in Go (livestream/go.mod) for live telemetry delivery.

Frontend

The user interface in frontend/ is a TypeScript application driven by React (react, react-dom in frontend/package.json). PostHog employs an in-house design system known as Lemon UI (packages/lemon-ui), delivering standardized buttons, navigation drawers, form controls, and theme toggles.

State management relies on Kea, an open-source architecture built on top of Redux and Redux-Saga. Kea structures frontend state into modular "logics" that pair actions, reducers, selectors, and asynchronous listeners into strongly typed units. For complex analytical visualizations, PostHog integrates D3, Chart.js, and custom canvas-based heatmaps. Session recordings are rendered using rrweb (rrweb, rrweb-player), allowing developers to inspect pixel-accurate client-side DOM mutations and network requests captured by the PostHog browser SDK.

Backend & APIs

The primary application server runs on Python 3.11+ using the Django and Django REST Framework stack (pyproject.toml). Django handles authentication, organization and project hierarchies, role-based permissions (RBAC), billing integrations with Stripe, and REST endpoints consumed by the frontend application and public SDKs.

Asynchronous tasks and recurring batch jobs are divided between Celery and Temporal:

  • Celery with Redis: Executes quick, asynchronous tasks such as sending alert notifications, firing webhooks, and computing lightweight statistics.
  • Temporal Workflow Engine: Coordinates complex, fault-tolerant batch operations—including external data warehouse extraction, full database cohort synchronizations, and schema migrations.

High-throughput event capture is offloaded to Rust microservices located in rust/. These services accept incoming HTTP payloads from client libraries, perform schema validation and IP anonymization, and push sanitized events directly into Kafka topics at wire speed.

Data & persistence

PostHog's data layer is split into specialized datastores:

  1. ClickHouse: Serves as the primary analytics engine. Raw events, session recordings, and user actions are written into partitioned ClickHouse tables. ClickHouse's columnar layout and vector compression enable sub-second aggregation across billions of event records.
  2. PostgreSQL: Houses transactional application metadata, including user credentials, team memberships, saved dashboards, insight queries, and feature flag rules.
  3. Apache Kafka: Acts as the central event bus. Incoming events from ingestion proxies are committed to Kafka topics before asynchronous ingestion workers flush them to ClickHouse in micro-batches.
  4. Redis: Provides low-latency caching, session state management, distributed locks, and Celery job queue storage.

Analytical queries authored by users in the dashboard or via API are processed through HogQL (common/hogql_parser/). The HogQL compiler parses SQL-like expressions into a safe AST, injects tenant boundaries (team_id = ...), validates field references against the project's data taxonomy, and produces an optimized ClickHouse SQL query.

Build, test & deploy

The development and delivery pipelines incorporate strict automated guardrails:

  • Linting & Formatting: PostHog uses Ruff for rapid Python linting and formatting, Biome and ESLint for JavaScript/TypeScript, and Cargo Clippy for Rust.
  • Testing: Python tests execute via Pytest against local PostgreSQL and ClickHouse containers. Frontend tests run with Jest and Playwright (playwright/package.json) for end-to-end browser journeys.
  • Docker: The production Dockerfile builds a consolidated container image with Python dependencies and pre-compiled frontend assets, while separate Dockerfiles (rust/Dockerfile, livestream/Dockerfile) package standalone microservices.

Self-hosting notes

Self-hosting PostHog requires container orchestration (typically Kubernetes using Helm or Docker Compose for evaluation). A self-hosted production cluster requires:

  • An ingress load balancer for HTTP traffic.
  • PostHog web and worker containers running the Django application.
  • High-throughput Kafka brokers and Zookeeper/KRaft nodes.
  • A ClickHouse cluster with dedicated persistent SSD storage.
  • A PostgreSQL 15+ database instance.
  • A Redis instance configured for persistent caching and queueing.

For cloud deployments, PostHog provides managed Cloud infrastructure across the US and EU, compliant with GDPR and HIPAA regulations.

What to copy (and what not to)

Key architecture patterns to learn from PostHog:

  • Decoupled ingestion with message buffering: Placing Kafka in front of analytical databases absorbs sudden traffic surges and protects columnar datastores from unbuffered per-request write locks.
  • Domain-specific query compilation (HogQL): Creating an intermediate AST compiler allows end users to execute flexible SQL expressions without exposing raw database tables or allowing arbitrary SQL injection.
  • Polyglot division of labor: Utilizing Python for rapid business logic iteration, Rust for CPU-intensive ingestion pipelines, and React for complex client applications leverages each language's greatest strength.

Avoid replicating PostHog's complex infrastructure stack (Kafka + ClickHouse + PostgreSQL + Redis + Temporal) for small or medium applications where a single managed relational database (such as PostgreSQL with TimescaleDB or DuckDB) can adequately satisfy telemetry needs without substantial DevOps overhead.

Sources & repo audit

Audited
Sep 17, 2026
Commit
ceedeea
License
NOASSERTION

Independent analysis of repository at github.com/PostHog/posthog. Spotted an inaccuracy? Use the claim form to request a correction.

Show this stack on your README or website
Tech stack of PostHog
[![Tech stack of PostHog on STACK IT FAST](https://stackitfast.com/badge/posthog.svg)](https://stackitfast.com/project/posthog)

Paste it into your README. It shows your current stack and links to this page.

Use this stack

Scaffold it with your agent

Paste this prompt into Claude Code, Cursor, Windsurf or AGY to start a project with PostHog's architecture.

  1. 1Copy the promptThe full markdown spec, with every layer and decision.
  2. 2Open your AI toolClaude Code, Cursor, Windsurf or Copilot, in a new repo.
  3. 3Paste and scaffoldUse it as the first instruction; review before you ship.
use-this-stack.md · 59 lines · 6.4 KB
# MISSION: Scaffold "PostHog" Production Architecture
You are an expert Senior Staff Software Architect and Full-Stack Engineer. Your mission is to scaffold and implement a production-grade, highly reliable, and modular codebase following the proven architecture of **PostHog**.
---
## 1. PROJECT SPECIFICATIONS & BENCHMARK
- **Reference Architecture**: PostHog
- **What It Does**: PostHog is an open-source product engineering platform combining web analytics, session replay, feature flags, A/B testing, and AI observability.
- **Domain & Category**: Product Analytics Platform
- **Production Scale**: 20+ people
- **Development Mode**: HYBRID
- **Architectural Rationale**: Pairing Apache Kafka with ClickHouse columnar storage enables PostHog to ingest billions of monthly events while maintaining sub-second query response times.
- **Live Website Reference**: https://posthog.com
- **Source Repository**: https://github.com/PostHog/posthog
---
## 2. PRODUCTION TECH STACK
- **Full Stack Array**: Django, Python, React, TypeScript, ClickHouse, PostgreSQL, Kafka, Redis, Docker, Rust, Temporal
- **Primary Language(s)**: Python, TypeScript, Rust
- **License of the reference repo**: NOASSERTION
- **Frontend**: React — Powers the analytics dashboards, session replay player, and experimentation UI.; TypeScript — Ensures strict type-checking across frontend apps, plugins, and shared schema contracts.; Kea — Redux-based state management framework developed by PostHog for orchestrating complex UI logic.
- **Backend & APIs**: Django — Python REST API framework handling authentication, organization management, and billing.; Python — Primary language for the core API, background workers, and analytical query compilers.; Rust — High-throughput event ingestion pipelines and parsing services compiled in rust/Cargo.toml.; Temporal — Coordinates long-running background tasks, data warehouse syncing, and migration jobs.
- **Data & persistence**: ClickHouse — Columnar database storing billions of events, session recordings, and HogQL telemetry.; PostgreSQL — Relational database storing teams, feature flag configurations, user roles, and dashboard metadata.; Kafka — Distributed messaging log buffering incoming event streams before batching into ClickHouse.; Redis — In-memory caching layer, rate limiter, and Celery task broker.
- **Infrastructure & deploy**: Docker — Multi-stage Dockerfile packaging the web application, workers, and background processors.
---
## 3. KEY ARCHITECTURAL DECISIONS (audited from https://github.com/PostHog/posthog @ ceedeea)
1. **Ingestion decoupled from persistence via Kafka and Rust capture workers**: Incoming event batches are captured by high-throughput Rust services and pushed to Apache Kafka topics, isolating web-tier ingestion spikes from database write pressure.
2. **Bifurcated storage model: ClickHouse for telemetry, PostgreSQL for metadata**: PostgreSQL manages tenant accounts, feature flag toggles, team memberships, and dashboard layouts, while ClickHouse executes columnar aggregations over billions of events.
3. **Custom SQL dialect (HogQL) compiled directly to ClickHouse SQL**: PostHog created HogQL (common/hogql_parser/), a domain-specific SQL dialect with AST validation that translates safe user-defined queries directly into optimized ClickHouse SQL.
4. **Temporal workflow engine for complex multi-step background orchestration**: Long-running batch workflows, data warehouse synchronization, and cohort recalculations are orchestrated via Temporal rather than unbounded Celery worker chains.
5. **Kea state management for declarative Redux architecture**: The frontend in frontend/ uses Kea to organize business logic into typed state "logics" that encapsulate actions, reducers, and side effects without boilerplate Redux plumbing.
---
## 4. NON-NEGOTIABLE ARCHITECTURAL GUARDRAILS
1. **Monorepo & Modular Separation**:
   - Structure as a Turborepo monorepo with strict package boundaries:
     - `apps/web`: Application UI, routing, layouts, and server endpoints.
     - `packages/ui`: Shared design tokens, CSS variables, and Radix UI primitive components.
     - `packages/db`: Database schemas, client singleton, declarative migrations, and seed scripts.
     - `packages/config`: Shared TypeScript, ESLint, and build configurations.
2. **Strict Type Safety & Zero `any` Policy**:
   - Enable `strict: true`, `noImplicitAny: true`, and `strictNullChecks: true`.
   - Validate ALL external inputs, API request bodies, and query parameters with **Zod** schemas before execution.
3. **Frontend & Rendering Guidelines**:
   - Isolate interactive UI state to leaf components. Keep core pages lightweight and performant.
4. **Design System & Aesthetics**:
   - Keep every color, radius, shadow and font in a single token file (CSS variables) and consume tokens everywhere; never hardcode hex values in components.
   - Prefer crisp 1px borders and one subtle shadow scale over blurry default shadows. Pair one sans-serif for body/headings with one monospace for tags, badges, metrics, and code.
5. **Data Layer & Reliability**:
   - Write declarative schema definitions with foreign keys, composite indexes on queried filters, and automated timestamp triggers.
   - Use connection pooling and prepared statements for serverless database execution.
---
## 5. STEP-BY-STEP SCAFFOLDING ROADMAP
- **Phase 1: Workspace & Root Config**: Initialize package manager, monorepo configuration (`turbo.json`, `tsconfig.base.json`, `package.json`).
- **Phase 2: Database Schema & Client**: Set up the data layer (ClickHouse, PostgreSQL, Kafka, Redis): client, connection pool, models, and migration scripts.
- **Phase 3: Design Tokens & UI Primitives**: Build accessible `Button`, `Input`, `Card`, `Badge`, and layout wrappers inside `packages/ui`.
- **Phase 4: Core Application Routes & Handlers**: Implement primary authentication, user session handling, and application routes.
- **Phase 5: Quality Assurance & Build Verification**: Run `tsc --noEmit`, ESLint, Prettier, and smoke test suites to ensure zero compilation or runtime errors.
---
## 6. EXECUTION INSTRUCTIONS
1. Review all specifications, architectural guardrails, and stack choices above.
2. Present the full monorepo directory tree structure.
3. Systematically generate the complete, production-ready codebase according to the 5-phase roadmap above — starting with the root workspace setup, followed by the database schema, UI design system package, and full-stack application routes until the repository is fully scaffolded and ready to run.
Scaffolded something with this prompt?
Would you pick this stack for a product analytics platform project?

Frequently asked about PostHog

What is PostHog built with?

PostHog combines a Python Django API, Rust event ingestion services, a React frontend, Apache Kafka for streaming, and ClickHouse for columnar analytics storage.

Why does PostHog use both PostgreSQL and ClickHouse?

PostgreSQL provides ACID relational consistency for team accounts and feature flag states, while ClickHouse handles high-speed analytical queries over massive event volumes.

What is HogQL in PostHog?

HogQL is PostHog custom SQL-like query language that safely compiles user analytical queries into optimized ClickHouse SQL with built-in tenant isolation.

How does PostHog handle high-velocity event ingestion?

Events are ingested by specialized Rust services, queued in Apache Kafka topics, and written in micro-batches to ClickHouse, preventing database overload.

Is PostHog built with Django?

Yes. The main application server is Python 3.11+ on Django and Django REST Framework (posthog/api, posthog/models); high-volume event capture runs in separate Rust services instead.

What is PostHog?

PostHog is an open-source product analytics platform: a Django API and React app on top of Kafka-fed ClickHouse for event analytics, with PostgreSQL holding accounts, projects and settings.

One email a month: new deep dives and stack trends

New source-audited architectures, head-to-head comparisons and the monthly stack report. No spam, unsubscribe anytime.

use-this-stack.md