posthog-cost-tuning

0
0
Source

Optimize PostHog costs through tier selection, sampling, and usage monitoring. Use when analyzing PostHog billing, reducing API costs, or implementing usage monitoring and budget alerts. Trigger with phrases like "posthog cost", "posthog billing", "reduce posthog costs", "posthog pricing", "posthog expensive", "posthog budget".

Install

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

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

About this skill

PostHog Cost Tuning

Overview

PostHog Cloud pricing is event-based: 1M events/month free, then usage-based pricing beyond that. Session recordings, feature flag evaluations, and surveys each have their own free tiers. The biggest cost drivers are typically $autocapture events, $pageview on high-traffic pages, and bot traffic. This skill covers specific techniques to reduce event volume without losing analytical value.

Prerequisites

  • PostHog Cloud account with billing access
  • Application instrumented with posthog-js
  • Understanding of which events drive your analytics

PostHog Cloud Free Tiers (2025)

ProductFree TierOverage
Product analytics1M events/month~$0.00031/event
Session recordings5K sessions/month~$0.04/session
Feature flags1M API requests/month~$0.0001/request
Surveys250 responses/month~$0.10/response

Instructions

Step 1: Audit Current Event Volume

set -euo pipefail
# See which events consume the most quota (last 30 days)
curl "https://app.posthog.com/api/projects/$POSTHOG_PROJECT_ID/query/" \
  -H "Authorization: Bearer $POSTHOG_PERSONAL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "query": {
      "kind": "HogQLQuery",
      "query": "SELECT event, count() AS total FROM events WHERE timestamp > now() - interval 30 day GROUP BY event ORDER BY total DESC LIMIT 20"
    }
  }' | jq '.results[] | {event: .[0], count: .[1]}'

Step 2: Tune Autocapture

$autocapture is often the largest event volume. Restrict it to only useful interactions.

import posthog from 'posthog-js';

posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY!, {
  api_host: 'https://us.i.posthog.com',
  autocapture: {
    // Only capture click and submit events (skip change, scroll, etc.)
    dom_event_allowlist: ['click', 'submit'],
    // Only capture meaningful elements
    element_allowlist: ['a', 'button', 'form', 'input[type=submit]'],
    // Only capture elements with this CSS class
    css_selector_allowlist: ['.track-click', '[data-track]'],
    // Skip internal/admin pages entirely
    url_ignorelist: ['/admin', '/health', '/api/internal', '/_next'],
  },
});

Step 3: Event Sampling with before_send

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

    // 2. Drop bot traffic entirely
    const ua = navigator?.userAgent?.toLowerCase() || '';
    if (/bot|crawler|spider|scrapy|headless|phantom|puppeteer/i.test(ua)) {
      return null;
    }

    // 3. Sample pageviews to 25% on high-traffic pages
    if (event.event === '$pageview') {
      const highTraffic = ['/', '/pricing', '/blog'];
      const url = event.properties?.$current_url || '';
      if (highTraffic.some(p => url.endsWith(p))) {
        return Math.random() < 0.25 ? event : null;
      }
      return event; // Keep other pageviews at 100%
    }

    // 4. Sample autocapture to 20%
    if (event.event === '$autocapture') {
      return Math.random() < 0.2 ? event : null;
    }

    // 5. Sample pageleave to 50%
    if (event.event === '$pageleave') {
      return Math.random() < 0.5 ? event : null;
    }

    return event; // Keep all other events
  },
});

Step 4: Optimize Session Recording Costs

posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY!, {
  api_host: 'https://us.i.posthog.com',
  session_recording: {
    // Record only 10% of sessions (saves 90% on recording costs)
    sampleRate: 0.1,
    // Don't record sessions shorter than 5 seconds (bounces)
    minimumDurationMilliseconds: 5000,
    // Record 100% of sessions with errors (most valuable for debugging)
    // This is configured in PostHog dashboard under Session Replay settings
  },
});

// Alternatively: disable recording for non-paying users
posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY!, {
  api_host: 'https://us.i.posthog.com',
  disable_session_recording: true, // Start disabled
});

// Enable only for paying users
if (user.plan !== 'free') {
  posthog.startSessionRecording();
}

Step 5: Monitor Usage and Set Alerts

set -euo pipefail
# Check current month's event usage
curl "https://app.posthog.com/api/projects/$POSTHOG_PROJECT_ID/query/" \
  -H "Authorization: Bearer $POSTHOG_PERSONAL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "query": {
      "kind": "HogQLQuery",
      "query": "SELECT count() AS total_events, uniq(distinct_id) AS unique_users, count() / dateDiff('"'"'day'"'"', toStartOfMonth(now()), now()) AS events_per_day FROM events WHERE timestamp > toStartOfMonth(now())"
    }
  }' | jq '.results[0] | {
    total_events: .[0],
    unique_users: .[1],
    avg_events_per_day: .[2],
    projected_monthly: (.[2] * 30),
    over_free_tier: (.[2] * 30 > 1000000)
  }'
// Automated cost monitoring
async function checkPostHogBudget() {
  const result = await queryPostHog(`
    SELECT count() AS events_this_month
    FROM events
    WHERE timestamp > toStartOfMonth(now())
  `);

  const eventsThisMonth = result.results[0][0];
  const FREE_TIER = 1_000_000;
  const projectedMonthly = eventsThisMonth / (new Date().getDate() / 30);

  if (projectedMonthly > FREE_TIER * 0.8) {
    // Alert: approaching free tier limit
    await sendSlackAlert(`PostHog usage alert: ${Math.round(projectedMonthly / 1000)}K events projected this month (free tier: 1M)`);
  }
}

Cost Reduction Estimates

TechniqueTypical ReductionImpact on Analytics
Restrict autocapture elements40-60%Low (keep meaningful clicks)
Filter bot traffic10-30%None (bots are noise)
Sample $pageview on high-traffic20-40%Low (trends still accurate)
Session recording at 10%90% on recordingsMedium (fewer sessions to review)
Disable $pageleave15-20%Low (rarely analyzed)

Error Handling

IssueCauseSolution
Event volume spikeNew feature without volume estimateForecast events before launch
Bill higher than expectedBot trafficAdd bot filtering in before_send
Missing critical eventsSampling too aggressiveExclude revenue events from sampling
Free tier exceeded mid-monthAutocapture too broadRestrict to .track-click elements only

Output

  • Autocapture restricted to meaningful interactions
  • Event sampling reducing volume by 30-50%
  • Bot traffic filtered
  • Session recording sampled to 10%
  • Budget monitoring with alerting

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.

6814

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.

2412

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.

379

designing-database-schemas

jeremylongshore

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

978

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.

86

django-view-generator

jeremylongshore

Generate django view generator operations. Auto-activating skill for Backend Development. Triggers on: django view generator, django view generator Part of the Backend Development skill category. Use when working with django view generator functionality. Trigger with phrases like "django view generator", "django generator", "django".

15

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.

643969

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.

591705

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."

318398

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.

339397

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.

451339

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.

304231

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.