PostHog Setup & Implementation | OpsBlu Docs

PostHog Setup & Implementation

Deploy PostHog with self-hosted or cloud setup, SDK installation, event taxonomy design, and data governance configuration.

Overview

PostHog implementation follows a deliberate path: choose your deployment model, install the SDK, define your event taxonomy, instrument tracking, and validate data quality. Unlike rigid analytics platforms that force you into specific workflows, PostHog adapts to your tech stack and organizational needs.

The key decisions happen upfront: Cloud versus self-hosted, client-side versus server-side tracking, autocapture versus custom events, and how to structure user identity. Get these foundational choices right, and everything else flows smoothly.

Implementation Phases

Discovery & Planning

Determine deployment model:

  • PostHog Cloud: Managed infrastructure, fastest setup, usage-based pricing
  • Self-Hosted: Full data ownership, one-time infrastructure cost, requires DevOps

Choose data hosting region (Cloud only):

  • US: https://app.posthog.com
  • EU: https://eu.posthog.com (GDPR-optimized)

Define identity strategy:

  • How will you identify users? (User ID from database, email hash, UUID?)
  • When will anonymous users become identified? (Login, signup, both?)
  • How will you handle logout and session resets?

Plan event taxonomy:

  • Core business events (purchases, signups, subscriptions)
  • Product engagement events (feature usage, page views)
  • Funnel milestones (onboarding steps, checkout flow)
  • Error and diagnostic events

Decide tracking approach:

  • Autocapture: Fast setup, captures everything, good for exploration
  • Custom events: Precise tracking, business-focused, requires instrumentation
  • Hybrid: Autocapture for general behavior, custom events for conversions

Infrastructure Setup

For Cloud deployment:

  1. Sign up at app.posthog.com (or eu.posthog.com)
  2. Create organization and project
  3. Note your project API key
  4. Configure project settings (timezone, data retention, autocapture)

For self-hosted deployment:

  1. Choose infrastructure (AWS, GCP, DigitalOcean, on-premises)
  2. Deploy using Docker Compose (dev) or Kubernetes (production)
  3. Configure DNS, SSL certificates, and ingress
  4. Set environment variables (secret keys, email, etc.)
  5. Run database migrations
  6. Create initial admin user

Configure data governance:

  • Set event retention policy (default: unlimited for Cloud free tier)
  • Enable session recording (if desired)
  • Configure autocapture rules (what to capture, what to ignore)
  • Set up data sampling if high-volume

Set up integrations (optional but recommended):

SDK Installation

Web applications:

  • Install via npm/yarn or use CDN snippet
  • Initialize with API key and host
  • Configure autocapture, recordings, and feature flags
  • Set up reverse proxy to avoid ad blockers (optional but recommended)

Mobile applications:

  • Add SDK via package manager (CocoaPods, Gradle)
  • Initialize in app delegate/main activity
  • Request tracking permissions (iOS 14.5+)
  • Configure background tracking

Server-side applications:

  • Install SDK for your language (Node, Python, Ruby, Go, etc.)
  • Initialize with API key
  • Track backend events (subscriptions, API usage, cron jobs)
  • Ensure distinct_id consistency with client-side

Event Instrumentation

Enable autocapture (web only):

posthog.init('YOUR_API_KEY', {
  autocapture: true,  // Tracks clicks, form submissions, pageviews
  capture_pageview: true,
  capture_pageleave: true
});

Implement custom events:

// Business-critical events
posthog.capture('subscription_created', {
  plan: 'Pro Annual',
  price: 299.99,
  billing_cycle: 'yearly'
});

// Feature usage
posthog.capture('report_generated', {
  report_type: 'analytics_dashboard',
  date_range: '30_days',
  format: 'pdf'
});

// Errors
posthog.capture('api_error', {
  endpoint: '/api/users',
  status_code: 500,
  error_message: 'Database timeout'
});

Implement user identification:

// On signup/login
posthog.identify('user_123', {
  email: 'user@example.com',
  name: 'Jane Doe',
  plan: 'Pro',
  signup_date: '2024-01-15'
});

// On logout
posthog.reset();

Set up feature flags (if using):

// Check flag state
posthog.onFeatureFlags(() => {
  if (posthog.isFeatureEnabled('new-dashboard')) {
    // Show new UI
  }
});

Quality Assurance

Validate event ingestion:

  • Use PostHog debug mode: posthog.debug = true
  • Check browser console for event confirmations
  • Verify events appear in PostHog Activity within 30 seconds
  • Inspect network requests to ensure proper payload structure

Test user identification:

  • Track anonymous events, then identify user
  • Verify events merge into single user profile
  • Test logout and verify reset creates new anonymous ID
  • Confirm server-side and client-side distinct_ids match

Verify session recordings:

  • Start recording, interact with app, check if recording appears
  • Test sensitive data masking (passwords, credit cards)
  • Ensure recordings work across SPA route changes
  • Check recording quality and performance impact

Test feature flags:

  • Create test flag with targeting rules
  • Verify flag evaluates correctly for different users
  • Test flag override functionality
  • Confirm flag states persist across sessions

Cross-browser and device testing:

  • Test on Chrome, Firefox, Safari, Edge
  • Test on mobile (iOS Safari, Android Chrome)
  • Verify ad blocker scenarios (or implement reverse proxy)
  • Check cookie/localStorage persistence

Production Launch

Final configuration review:

  • Confirm API keys are correct for production
  • Disable debug mode
  • Set appropriate batch intervals and sizes
  • Configure CSP headers if needed
  • Enable sampling if high-volume (millions of events/day)

Monitoring setup:

  • Create dashboard for key metrics
  • Set up Slack alerts for critical events (errors, churn signals)
  • Configure data quality alerts (event volume drops, property missing)

Documentation:

  • Document event taxonomy (what each event means)
  • List property definitions and data types
  • Record identity strategy and user lifecycle
  • Create runbook for common issues

Team training:

  • Show analysts how to build insights and dashboards
  • Train engineers on instrumentation best practices
  • Demonstrate session recording privacy controls
  • Explain feature flag workflow

Deployment Artifacts

After implementation, maintain these artifacts:

Event taxonomy document:

# Event Taxonomy

## Subscription Events

### subscription_created
Fired when user completes subscription purchase
Properties:
- plan (string): Subscription tier (Basic, Pro, Enterprise)
- price (number): Monthly or annual price
- billing_cycle (string): monthly | yearly
- payment_method (string): credit_card | paypal | invoice

### subscription_cancelled
Fired when user cancels subscription
Properties:
- plan (string): Cancelled subscription tier
- cancellation_reason (string): User-provided reason
- months_subscribed (number): Total months as subscriber
- total_revenue (number): Lifetime revenue from this subscription

User identity documentation:

# Identity Strategy

## Distinct ID
- Anonymous: Auto-generated UUID (stored in cookie)
- Identified: Database user ID (integer)

## Identification Triggers
- User signs up → identify with user ID
- User logs in → identify with user ID
- User logs out → reset to new anonymous ID

## Properties
- email (set on identify)
- name (set on identify)
- plan (updated on subscription changes)
- signup_date (set once on first identify)

SDK initialization reference:

// Production configuration
posthog.init('phc_YOUR_PRODUCTION_API_KEY', {
  api_host: 'https://app.posthog.com',
  autocapture: true,
  capture_pageview: true,
  capture_pageleave: true,
  session_recording: {
    enabled: true,
    maskAllInputs: true,
    maskTextSelector: '.sensitive-data',
    quality: 'medium'
  },
  persistence: 'localStorage+cookie',
  cross_subdomain_cookie: true,
  loaded: (posthog) => {
    if (process.env.NODE_ENV === 'development') {
      posthog.debug();
    }
  }
});

Feature flag registry:

# Feature Flags

## new-dashboard
Purpose: Roll out redesigned analytics dashboard
Rollout: 10% → 50% → 100% over 2 weeks
Targeting: None (random sample)
Metrics: Dashboard engagement, session duration
Owner: Product team

## enterprise-features
Purpose: Gate features for Enterprise plan
Rollout: 100% for users where plan=Enterprise
Targeting: plan property
Metrics: Feature adoption, support tickets
Owner: Engineering team

Linked Runbooks

Detailed guides for specific implementation tasks:

Best Practices

Start simple, iterate later:

  • Begin with autocapture and a handful of critical custom events
  • Add more custom events as you learn what matters
  • Refine taxonomy based on actual usage

Maintain data quality:

  • Use consistent naming conventions (snake_case recommended)
  • Validate event structure in QA
  • Monitor for missing or malformed properties
  • Set up alerts for data anomalies

Respect privacy:

  • Mask sensitive inputs in session recordings
  • Don't track PII without consent
  • Honor opt-out requests immediately
  • Configure data retention policies

Plan for scale:

  • Use sampling for very high-volume events
  • Batch events efficiently (PostHog does this by default)
  • Consider server-side tracking for backend processes
  • Monitor SDK performance impact

Empower your team:

  • Make dashboards accessible to non-technical users
  • Document what each metric means
  • Share insights regularly
  • Encourage experimentation with feature flags

Common Pitfalls

Avoid these mistakes:

  • Tracking too many events early on (causes analysis paralysis)
  • Inconsistent naming (camelCase vs snake_case vs spaces)
  • Not identifying users on login/signup
  • Forgetting to reset on logout (cross-contamination)
  • Skipping QA validation before production launch
  • Using email addresses as distinct_ids (they can change)
  • Autocapturing sensitive forms without masking
  • Not documenting event meanings (future you will be confused)

Success Criteria

You'll know your PostHog implementation is solid when:

  • Events appear in dashboard within 30 seconds
  • User profiles merge correctly on identification
  • Session recordings play back smoothly
  • Feature flags evaluate consistently
  • Team members use PostHog daily for decisions
  • Data quality issues are rare
  • New features ship with tracking from day one
  • Privacy and compliance requirements are met

Change Log & Governance

Track implementation changes:

  • Document SDK version upgrades
  • Log taxonomy changes (new events, deprecated properties)
  • Record feature flag lifecycle (created, rolled out, removed)
  • Note integration additions/removals

Assign ownership:

  • Who approves new events?
  • Who manages feature flags?
  • Who monitors data quality?
  • Who handles privacy requests?

Regular reviews:

  • Quarterly taxonomy audit (remove unused events)
  • Monthly data quality check
  • Bi-weekly team sync on analytics insights