posthog-performance-tuning

0
0
Source

Optimize PostHog API performance with caching, batching, and connection pooling. Use when experiencing slow API responses, implementing caching strategies, or optimizing request throughput for PostHog integrations. Trigger with phrases like "posthog performance", "optimize posthog", "posthog latency", "posthog caching", "posthog slow", "posthog batch".

Install

mkdir -p .claude/skills/posthog-performance-tuning && curl -L -o skill.zip "https://mcp.directory/api/skills/download/7844" && unzip -o skill.zip -d .claude/skills/posthog-performance-tuning && rm skill.zip

Installs to .claude/skills/posthog-performance-tuning

About this skill

PostHog Performance Tuning

Overview

Optimize PostHog for production workloads. The biggest performance wins are: local feature flag evaluation (eliminates network calls), proper batching configuration, event sampling for high-volume apps, and efficient HogQL queries with date filters.

Prerequisites

  • posthog-node and/or posthog-js installed
  • Personal API key (phx_...) for local flag evaluation
  • Feature flags configured (if applicable)

Instructions

Step 1: Enable Local Feature Flag Evaluation

The single biggest performance improvement. Without local evaluation, every getFeatureFlag() call makes a network request (~50-200ms). With local evaluation, flag definitions are cached and evaluation is instant (~0.1ms).

import { PostHog } from 'posthog-node';

const posthog = new PostHog(process.env.NEXT_PUBLIC_POSTHOG_KEY!, {
  host: 'https://us.i.posthog.com',
  // This is the key: personal API key enables local flag evaluation
  personalApiKey: process.env.POSTHOG_PERSONAL_API_KEY,
  // Flag definitions are polled every 30 seconds by default
  // Adjust if you need faster flag updates:
  // featureFlagsPollingInterval: 10000, // 10 seconds
});

// With personalApiKey set, this evaluates locally (no network call)
const variant = await posthog.getFeatureFlag('pricing-experiment', 'user-123', {
  personProperties: { plan: 'pro', country: 'US' },
});

// Get all flags at once (still local, still fast)
const allFlags = await posthog.getAllFlags('user-123', {
  personProperties: { plan: 'pro' },
  groupProperties: { company: { industry: 'SaaS' } },
});

Step 2: Optimize Client Batching

// Production: batch events for network efficiency
const posthog = new PostHog(process.env.NEXT_PUBLIC_POSTHOG_KEY!, {
  host: 'https://us.i.posthog.com',
  flushAt: 20,           // Send batch when 20 events accumulated (default)
  flushInterval: 10000,  // Or flush every 10 seconds (default)
  requestTimeout: 10000, // 10 second timeout per request
  maxRetries: 3,         // Retry failed sends
});

// Serverless: flush immediately (function may exit)
const serverless = new PostHog(process.env.NEXT_PUBLIC_POSTHOG_KEY!, {
  host: 'https://us.i.posthog.com',
  flushAt: 1,       // Send every event immediately
  flushInterval: 0, // Don't wait
});

// CRITICAL: Always shutdown before process exits
process.on('SIGTERM', async () => {
  await posthog.shutdown();
  process.exit(0);
});

Step 3: Event Sampling (Browser)

import posthog from 'posthog-js';

posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY!, {
  api_host: 'https://us.i.posthog.com',
  before_send: (event) => {
    // Always capture business-critical events
    const alwaysCapture = ['purchase', 'signup', 'subscription_started', 'subscription_canceled'];
    if (alwaysCapture.includes(event.event)) return event;

    // Sample high-volume events
    const sampleRates: Record<string, number> = {
      '$pageview': 1.0,        // Keep all pageviews
      '$pageleave': 0.5,       // Sample 50%
      '$autocapture': 0.1,     // Sample 10% of autocapture
      'scroll_depth': 0.05,    // Sample 5%
    };

    const rate = sampleRates[event.event] ?? 0.5;
    if (Math.random() >= rate) return null; // Drop event

    // Tag sampled events so you can adjust in analysis
    event.properties = { ...event.properties, $sample_rate: rate };
    return event;
  },
});

Step 4: Efficient HogQL Queries

async function queryPostHog(hogql: string) {
  const response = await fetch(
    `https://app.posthog.com/api/projects/${process.env.POSTHOG_PROJECT_ID}/query/`,
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${process.env.POSTHOG_PERSONAL_API_KEY}`,
      },
      body: JSON.stringify({
        query: { kind: 'HogQLQuery', query: hogql },
      }),
    }
  );
  return response.json();
}

// FAST: Filtered by time, limited results
const fast = await queryPostHog(`
  SELECT
    properties.$current_url AS url,
    count() AS views,
    uniq(distinct_id) AS visitors
  FROM events
  WHERE event = '$pageview'
    AND timestamp > now() - interval 7 day
  GROUP BY url
  ORDER BY views DESC
  LIMIT 50
`);

// SLOW (avoid): No time filter, scans entire table
// SELECT * FROM events WHERE event = '$pageview'

// OPTIMIZED: Use subqueries for complex analysis
const retention = await queryPostHog(`
  SELECT
    dateTrunc('week', first_seen) AS cohort_week,
    dateTrunc('week', timestamp) AS activity_week,
    uniq(distinct_id) AS users
  FROM events
  INNER JOIN (
    SELECT distinct_id, min(timestamp) AS first_seen
    FROM events
    WHERE event = 'user_signed_up'
      AND timestamp > now() - interval 90 day
    GROUP BY distinct_id
  ) AS cohorts ON events.distinct_id = cohorts.distinct_id
  WHERE timestamp > now() - interval 90 day
  GROUP BY cohort_week, activity_week
  ORDER BY cohort_week, activity_week
`);

Step 5: Session Recording Performance

// Limit session recording to reduce data volume and cost
posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY!, {
  api_host: 'https://us.i.posthog.com',
  session_recording: {
    // Only record 10% of sessions
    sampleRate: 0.1,
    // Minimum session duration to record (skip quick bounces)
    minimumDurationMilliseconds: 5000,
    // Mask all text inputs by default
    maskAllInputs: true,
    // Mask specific CSS selectors
    maskTextSelector: '.sensitive-data',
  },
});

Performance Benchmarks

OperationWithout OptimizationWith Optimization
Feature flag evaluation50-200ms (network)<1ms (local eval)
Event captureIndividual sendsBatched (20 events/req)
HogQL query (7d)2-5s<1s (with filters)
HogQL query (no filter)30-60s (timeout risk)N/A (always filter)

Error Handling

IssueCauseSolution
Events dropped on exitNo shutdown hookAdd posthog.shutdown() to SIGTERM handler
Flag evaluation slowNo personalApiKeyAdd personal API key for local evaluation
High event costCapturing everythingImplement before_send sampling
HogQL timeoutNo date filterAlways include timestamp > now() - interval N day
Session recordings largeRecording all sessionsSet sampleRate to 0.1-0.25

Output

  • Local feature flag evaluation (<1ms per check)
  • Optimized batching configuration
  • Event sampling with before_send
  • Efficient HogQL query patterns
  • Session recording sampling

Resources

svg-icon-generator

jeremylongshore

Svg Icon Generator - Auto-activating skill for Visual Content. Triggers on: svg icon generator, svg icon generator Part of the Visual Content skill category.

7824

automating-mobile-app-testing

jeremylongshore

This skill enables automated testing of mobile applications on iOS and Android platforms using frameworks like Appium, Detox, XCUITest, and Espresso. It generates end-to-end tests, sets up page object models, and handles platform-specific elements. Use this skill when the user requests mobile app testing, test automation for iOS or Android, or needs assistance with setting up device farms and simulators. The skill is triggered by terms like "mobile testing", "appium", "detox", "xcuitest", "espresso", "android test", "ios test".

13615

d2-diagram-creator

jeremylongshore

D2 Diagram Creator - Auto-activating skill for Visual Content. Triggers on: d2 diagram creator, d2 diagram creator Part of the Visual Content skill category.

3114

performing-penetration-testing

jeremylongshore

This skill enables automated penetration testing of web applications. It uses the penetration-tester plugin to identify vulnerabilities, including OWASP Top 10 threats, and suggests exploitation techniques. Use this skill when the user requests a "penetration test", "pentest", "vulnerability assessment", or asks to "exploit" a web application. It provides comprehensive reporting on identified security flaws.

4311

performing-security-audits

jeremylongshore

This skill allows Claude to conduct comprehensive security audits of code, infrastructure, and configurations. It leverages various tools within the security-pro-pack plugin, including vulnerability scanning, compliance checking, cryptography review, and infrastructure security analysis. Use this skill when a user requests a "security audit," "vulnerability assessment," "compliance review," or any task involving identifying and mitigating security risks. It helps to ensure code and systems adhere to security best practices and compliance standards.

109

designing-database-schemas

jeremylongshore

Design and visualize efficient database schemas, normalize data, map relationships, and generate ERD diagrams and SQL statements.

1128

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

9521,094

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

846846

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

571699

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

548492

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

673466

fastapi-templates

wshobson

Create production-ready FastAPI projects with async patterns, dependency injection, and comprehensive error handling. Use when building new FastAPI applications or setting up backend API projects.

514280

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.