PO

posthog-cost-tuning

Reduce PostHog event volume and costs by tuning autocapture, implementing event sampling, and monitoring usage metrics.

Install

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

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

Activation

This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.

Optimize PostHog costs: autocapture tuning, event sampling with before_send,
76 charsno explicit “when” trigger
Intermediate

Key capabilities

  • →Audit event volume by event type
  • →Tune autocapture to reduce noise
  • →Filter bot traffic from analytics
  • →Monitor usage and set budget alerts

How it works

The skill uses HogQL queries to identify high-volume events and provides configuration patterns to filter, sample, or restrict data capture to stay within budget.

Inputs & outputs

You give it
Current PostHog event usage data
You get back
Optimized configuration for reduced event volume

When to use posthog-cost-tuning

  • →Optimizing PostHog billing
  • →Reducing event volume
  • →Implementing event sampling
  • →Monitoring analytics budget

About this skill

PostHog Cost Tuning

Overview

Measure the live billable volume for each enabled PostHog product, trace changes to instrumentation releases, and reduce only traffic that the product owner has classified as noise or safely sampleable. Pricing, free allowances, and product entitlements are live facts; read them from the billing dashboard, pricing calculator, and approved product limits at execution time.

Prerequisites

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

Authentication

  • Usage inspection through private query and billing APIs requires a least-privilege personal API key or OAuth token on a trusted machine.
  • Event capture and browser-side filtering use only the public project token; never ship a personal or secure key to the browser.
  • Read private credentials from a secret manager, redact command output before sharing it, and select the private US or EU API host that matches the project.

Live Pricing Boundary

Do not copy prices or free allowances into implementation code. Record the billing-dashboard timestamp, current product limit, projected usage, unit price from the live calculator, and the owner who approved any data-loss tradeoff. Recheck those values before applying a change.

Instructions

Tool discipline

Use Read to inspect the relevant configuration and implementation before proposing changes. Use Grep to locate initialization, capture, flag, and credential boundaries.

Step 1: Audit Current Event Volume

set -euo pipefail
# See which events consume the most quota (last 30 days)
curl "https://us.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. Apply only the sample rate approved for this event class.
    if (event.event === '$pageview') {
      const highTraffic = ['/', '/pricing', '/blog'];
      const url = event.properties?.$current_url || '';
      if (highTraffic.some(p => url.endsWith(p))) {
        return Math.random() < approvedPageviewSampleRate ? event : null;
      }
      return event;
    }

    // 4. Use a separately approved rate for autocapture.
    if (event.event === '$autocapture') {
      return Math.random() < approvedAutocaptureSampleRate ? 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: {
    // Load the reviewed rate from configuration; document analysis impact.
    sampleRate: approvedSessionRecordingSampleRate,
    // 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://us.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)
  }'
// 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 approvedMonthlyLimit = Number(process.env.POSTHOG_MONTHLY_EVENT_LIMIT);
  if (!Number.isFinite(approvedMonthlyLimit)) {
    throw new Error('Set POSTHOG_MONTHLY_EVENT_LIMIT from the current billing configuration');
  }
  const projectedMonthly = eventsThisMonth / (new Date().getDate() / 30);

  if (projectedMonthly > approvedMonthlyLimit * 0.8) {
    await sendSlackAlert(`PostHog usage alert: ${Math.round(projectedMonthly)} events projected against reviewed limit ${approvedMonthlyLimit}`);
  }
}

Decision Record

For each proposed filter or sample, record the baseline count, affected event or product, chosen rate, expected analytical limitation, rollback trigger, and measured result after one full review window. Never report generic savings estimates as if they were measured for the target project.

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
Approved product limit reached mid-monthVolume exceeds the reviewed budgetApply the least destructive approved control and preserve conversion events

Output

  • Autocapture restricted to meaningful interactions
  • Reviewed event-sampling policy with its analytical limitations recorded
  • Bot traffic filtered
  • Session-recording control derived from the live billing configuration
  • Budget monitoring against the approved product limit

Examples

For an autocapture spike, compare billing-dashboard volume with the release timeline, preserve named conversion events, narrow noisy autocapture, and set a reviewed product limit. Report expected data loss explicitly; do not invent savings percentages.

Resources

See official PostHog references for current authority and verification boundaries.

When not to use it

  • →When event volume is already within the free tier
  • →When all events are required for business-critical reporting

Prerequisites

PostHog Cloud account with billing accessApplication instrumented with posthog-js

Limitations

  • →Sampling may reduce the granularity of analytics data
  • →Requires ongoing monitoring to ensure budget compliance

How it compares

It offers programmatic control over event volume through SDK configuration, unlike manual dashboard-based adjustments.

Compared to similar skills

posthog-cost-tuning side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
posthog-cost-tuning (this skill)12moCautionIntermediate
korean-public-data-api511moNo flagsIntermediate
apollo-data-handling12moCautionIntermediate
azure-ai-contentunderstanding-py12moReviewIntermediate

Try saying

Example prompts that trigger this skill in your AI assistant.

More by jeremylongshore

View all by jeremylongshore →

analyzing-logs

jeremylongshore

Analyze application logs to detect performance issues, identify error patterns, and improve stability by extracting key insights.

14123

ollama-setup

jeremylongshore

Configure auto-configure Ollama when user needs local LLM deployment, free AI alternatives, or wants to eliminate hosted API costs. Trigger phrases: "install ollama", "local AI", "free LLM", "self-hosted AI", "replace OpenAI", "no API costs". Use when appropriate context detected. Trigger with relevant phrases based on skill purpose.

1167

backtesting-trading-strategies

jeremylongshore

Backtest crypto and traditional trading strategies against historical data. Calculates performance metrics (Sharpe, Sortino, max drawdown), generates equity curves, and optimizes strategy parameters. Use when user wants to test a trading strategy, validate signals, or compare approaches. Trigger with phrases like "backtest strategy", "test trading strategy", "historical performance", "simulate trades", "optimize parameters", or "validate signals".

1071

generating-database-seed-data

jeremylongshore

Process this skill enables AI assistant to generate realistic test data and database seed scripts for development and testing environments. it uses faker libraries to create realistic data, maintains relational integrity, and allows configurable data volumes. u... Use when working with databases or data models. Trigger with phrases like 'database', 'query', or 'schema'.

1033

cursor-codebase-indexing

jeremylongshore

Execute set up and optimize Cursor codebase indexing. Triggers on "cursor index setup", "codebase indexing", "index codebase", "cursor semantic search". Use when working with cursor codebase indexing functionality. Trigger with phrases like "cursor codebase indexing", "cursor indexing", "cursor".

885

testing-mobile-apps

jeremylongshore

Execute mobile app testing on iOS and Android devices/simulators. Use when performing specialized testing. Trigger with phrases like "test mobile app", "run iOS tests", or "validate Android functionality".

810

You might also like

korean-public-data-api

swszz

Extract API request/response schema from Korean Public Data Portal (data.go.kr) documentation pages and generate structured JSON representation

596

apollo-data-handling

jeremylongshore

Apollo.io data management and compliance. Use when handling contact data, implementing GDPR compliance, or managing data exports and retention. Trigger with phrases like "apollo data", "apollo gdpr", "apollo compliance", "apollo data export", "apollo data retention", "apollo pii".

12

azure-ai-contentunderstanding-py

microsoft

Azure AI Content Understanding SDK for Python. Use for multimodal content extraction from documents, images, audio, and video. Triggers: "azure-ai-contentunderstanding", "ContentUnderstandingClient", "multimodal analysis", "document extraction", "video analysis", "audio transcription".

12

azure-ai-document-intelligence-dotnet

microsoft

Azure AI Document Intelligence SDK for .NET. Extract text, tables, and structured data from documents using prebuilt and custom models. Use for invoice processing, receipt extraction, ID document analysis, and custom document models. Triggers: "Document Intelligence", "DocumentIntelligenceClient", "form recognizer", "invoice extraction", "receipt OCR", "document analysis .NET".

03

fireflies-core-workflow-a

jeremylongshore

Execute Fireflies.ai primary workflow: Core Workflow A. Use when implementing primary use case, building main features, or core integration tasks. Trigger with phrases like "fireflies main workflow", "primary task with fireflies".

12

fireflies-cost-tuning

jeremylongshore

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

12

Search skills

Search the agent skills registry