home / skills / jeremylongshore / claude-code-plugins-plus-skills / posthog-reference-architecture

This skill helps design and validate PostHog reference architectures by outlining layered project structure, services, and health checks for reliable

npx playbooks add skill jeremylongshore/claude-code-plugins-plus-skills --skill posthog-reference-architecture

Review the files below or copy the command above to add this skill to your agents.

Files (1)
SKILL.md
7.0 KB
---
name: posthog-reference-architecture
description: |
  Implement PostHog reference architecture with best-practice project layout.
  Use when designing new PostHog integrations, reviewing project structure,
  or establishing architecture standards for PostHog applications.
  Trigger with phrases like "posthog architecture", "posthog best practices",
  "posthog project structure", "how to organize posthog", "posthog layout".
allowed-tools: Read, Grep
version: 1.0.0
license: MIT
author: Jeremy Longshore <[email protected]>
---

# PostHog Reference Architecture

## Overview
Production-ready architecture patterns for PostHog integrations.

## Prerequisites
- Understanding of layered architecture
- PostHog SDK knowledge
- TypeScript project setup
- Testing framework configured

## Project Structure

```
my-posthog-project/
├── src/
│   ├── posthog/
│   │   ├── client.ts           # Singleton client wrapper
│   │   ├── config.ts           # Environment configuration
│   │   ├── types.ts            # TypeScript types
│   │   ├── errors.ts           # Custom error classes
│   │   └── handlers/
│   │       ├── webhooks.ts     # Webhook handlers
│   │       └── events.ts       # Event processing
│   ├── services/
│   │   └── posthog/
│   │       ├── index.ts        # Service facade
│   │       ├── sync.ts         # Data synchronization
│   │       └── cache.ts        # Caching layer
│   ├── api/
│   │   └── posthog/
│   │       └── webhook.ts      # Webhook endpoint
│   └── jobs/
│       └── posthog/
│           └── sync.ts         # Background sync job
├── tests/
│   ├── unit/
│   │   └── posthog/
│   └── integration/
│       └── posthog/
├── config/
│   ├── posthog.development.json
│   ├── posthog.staging.json
│   └── posthog.production.json
└── docs/
    └── posthog/
        ├── SETUP.md
        └── RUNBOOK.md
```

## Layer Architecture

```
┌─────────────────────────────────────────┐
│             API Layer                    │
│   (Controllers, Routes, Webhooks)        │
├─────────────────────────────────────────┤
│           Service Layer                  │
│  (Business Logic, Orchestration)         │
├─────────────────────────────────────────┤
│          PostHog Layer        │
│   (Client, Types, Error Handling)        │
├─────────────────────────────────────────┤
│         Infrastructure Layer             │
│    (Cache, Queue, Monitoring)            │
└─────────────────────────────────────────┘
```

## Key Components

### Step 1: Client Wrapper
```typescript
// src/posthog/client.ts
export class PostHogService {
  private client: PostHogClient;
  private cache: Cache;
  private monitor: Monitor;

  constructor(config: PostHogConfig) {
    this.client = new PostHogClient(config);
    this.cache = new Cache(config.cacheOptions);
    this.monitor = new Monitor('posthog');
  }

  async get(id: string): Promise<Resource> {
    return this.cache.getOrFetch(id, () =>
      this.monitor.track('get', () => this.client.get(id))
    );
  }
}
```

### Step 2: Error Boundary
```typescript
// src/posthog/errors.ts
export class PostHogServiceError extends Error {
  constructor(
    message: string,
    public readonly code: string,
    public readonly retryable: boolean,
    public readonly originalError?: Error
  ) {
    super(message);
    this.name = 'PostHogServiceError';
  }
}

export function wrapPostHogError(error: unknown): PostHogServiceError {
  // Transform SDK errors to application errors
}
```

### Step 3: Health Check
```typescript
// src/posthog/health.ts
export async function checkPostHogHealth(): Promise<HealthStatus> {
  try {
    const start = Date.now();
    await posthogClient.ping();
    return {
      status: 'healthy',
      latencyMs: Date.now() - start,
    };
  } catch (error) {
    return { status: 'unhealthy', error: error.message };
  }
}
```

## Data Flow Diagram

```
User Request
     │
     ▼
┌─────────────┐
│   API       │
│   Gateway   │
└──────┬──────┘
       │
       ▼
┌─────────────┐    ┌─────────────┐
│   Service   │───▶│   Cache     │
│   Layer     │    │   (Redis)   │
└──────┬──────┘    └─────────────┘
       │
       ▼
┌─────────────┐
│ PostHog    │
│   Client    │
└──────┬──────┘
       │
       ▼
┌─────────────┐
│ PostHog    │
│   API       │
└─────────────┘
```

## Configuration Management

```typescript
// config/posthog.ts
export interface PostHogConfig {
  apiKey: string;
  environment: 'development' | 'staging' | 'production';
  timeout: number;
  retries: number;
  cache: {
    enabled: boolean;
    ttlSeconds: number;
  };
}

export function loadPostHogConfig(): PostHogConfig {
  const env = process.env.NODE_ENV || 'development';
  return require(`./posthog.${env}.json`);
}
```

## Instructions

### Step 1: Create Directory Structure
Set up the project layout following the reference structure above.

### Step 2: Implement Client Wrapper
Create the singleton client with caching and monitoring.

### Step 3: Add Error Handling
Implement custom error classes for PostHog operations.

### Step 4: Configure Health Checks
Add health check endpoint for PostHog connectivity.

## Output
- Structured project layout
- Client wrapper with caching
- Error boundary implemented
- Health checks configured

## Error Handling
| Issue | Cause | Solution |
|-------|-------|----------|
| Circular dependencies | Wrong layering | Separate concerns by layer |
| Config not loading | Wrong paths | Verify config file locations |
| Type errors | Missing types | Add PostHog types |
| Test isolation | Shared state | Use dependency injection |

## Examples

### Quick Setup Script
```bash
# Create reference structure
mkdir -p src/posthog/{handlers} src/services/posthog src/api/posthog
touch src/posthog/{client,config,types,errors}.ts
touch src/services/posthog/{index,sync,cache}.ts
```

## Resources
- [PostHog SDK Documentation](https://docs.posthog.com/sdk)
- [PostHog Best Practices](https://docs.posthog.com/best-practices)

## Flagship Skills
For multi-environment setup, see `posthog-multi-env-setup`.

Overview

This skill implements a production-ready PostHog reference architecture and a best-practice project layout for building PostHog integrations. It provides a clear layered structure, reusable client wrapper patterns, error handling, health checks, and configuration guidance to accelerate consistent implementations. Use it to standardize new integrations and speed up code reviews and onboarding.

How this skill works

The skill prescribes a layered layout: API, Service, PostHog, and Infrastructure layers. It defines a singleton client wrapper with caching and monitoring, custom error types and an error wrapper, health check probes, and environment-based configuration loading. The patterns are language-agnostic but include TypeScript examples, plus recommended directories for tests, jobs, and docs.

When to use it

  • Designing a new PostHog integration or plugin
  • Reviewing project structure and architecture for PostHog apps
  • Establishing standards for multi-environment deployments
  • Implementing resilient PostHog client usage with caching and monitoring
  • Creating maintainable webhooks, background jobs, or sync processes

Best practices

  • Keep concerns separated by layer: API -> Service -> PostHog -> Infrastructure
  • Use a singleton client wrapper that adds caching, monitoring, and retries
  • Map SDK errors to application-specific error types with retry metadata
  • Load config per environment and avoid hardcoded secrets in code
  • Add health checks and latency metrics for PostHog connectivity
  • Isolate tests (unit vs integration) and inject dependencies for testability

Example use cases

  • A webhook endpoint that validates, enriches, and forwards events to PostHog using the service facade
  • A background job that synchronizes user properties between your database and PostHog with cache-backed reads
  • A new PostHog integration scaffolded with environment configs, health endpoint, and runbook
  • Refactoring an existing codebase to remove circular dependencies by applying the layered layout
  • Automating multi-environment deployments with separate config files per stage

FAQ

How do I handle transient PostHog API failures?

Wrap SDK errors in a PostHogServiceError and mark retryable cases; implement retries with backoff in the client wrapper and surface safe failure modes to callers.

Where should caching live in the architecture?

Place cache access inside the PostHog client wrapper or service layer so business logic uses cached reads and the cache implementation can be swapped without affecting controllers.