posthog-cost-tuning

Optimize PostHog costs: autocapture tuning, event sampling with before_send, bot filtering, session recording sampling, and billing monitoring. Trigger: "posthog cost", "posthog billing", "reduce posthog costs", "posthog pricing", "posthog expensive", "posthog budget", "posthog free tier".

1,868 stars

Best use case

posthog-cost-tuning is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Optimize PostHog costs: autocapture tuning, event sampling with before_send, bot filtering, session recording sampling, and billing monitoring. Trigger: "posthog cost", "posthog billing", "reduce posthog costs", "posthog pricing", "posthog expensive", "posthog budget", "posthog free tier".

Teams using posthog-cost-tuning should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/posthog-cost-tuning/SKILL.md --create-dirs "https://raw.githubusercontent.com/jeremylongshore/claude-code-plugins-plus-skills/main/plugins/saas-packs/posthog-pack/skills/posthog-cost-tuning/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/posthog-cost-tuning/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How posthog-cost-tuning Compares

Feature / Agentposthog-cost-tuningStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Optimize PostHog costs: autocapture tuning, event sampling with before_send, bot filtering, session recording sampling, and billing monitoring. Trigger: "posthog cost", "posthog billing", "reduce posthog costs", "posthog pricing", "posthog expensive", "posthog budget", "posthog free tier".

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

Related Guides

SKILL.md Source

# 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)

| Product | Free Tier | Overage |
|---------|-----------|---------|
| Product analytics | 1M events/month | ~$0.00031/event |
| Session recordings | 5K sessions/month | ~$0.04/session |
| Feature flags | 1M API requests/month | ~$0.0001/request |
| Surveys | 250 responses/month | ~$0.10/response |

## Instructions

### Step 1: Audit Current Event Volume

```bash
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.

```typescript
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

```typescript
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

```typescript
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

```bash
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)
  }'
```

```typescript
// 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

| Technique | Typical Reduction | Impact on Analytics |
|-----------|------------------|-------------------|
| Restrict autocapture elements | 40-60% | Low (keep meaningful clicks) |
| Filter bot traffic | 10-30% | None (bots are noise) |
| Sample $pageview on high-traffic | 20-40% | Low (trends still accurate) |
| Session recording at 10% | 90% on recordings | Medium (fewer sessions to review) |
| Disable $pageleave | 15-20% | Low (rarely analyzed) |

## Error Handling

| Issue | Cause | Solution |
|-------|-------|----------|
| Event volume spike | New feature without volume estimate | Forecast events before launch |
| Bill higher than expected | Bot traffic | Add bot filtering in `before_send` |
| Missing critical events | Sampling too aggressive | Exclude revenue events from sampling |
| Free tier exceeded mid-month | Autocapture too broad | Restrict 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

- [PostHog Pricing](https://posthog.com/pricing)
- [PostHog Autocapture Config](https://posthog.com/docs/product-analytics/autocapture)
- [PostHog before_send](https://posthog.com/docs/libraries/js/config)
- [Session Recording Control](https://posthog.com/docs/session-replay/how-to-control-which-sessions-you-record)

Related Skills

workhuman-performance-tuning

1868
from jeremylongshore/claude-code-plugins-plus-skills

Workhuman performance tuning for employee recognition and rewards API. Use when integrating Workhuman Social Recognition, or building recognition workflows with HRIS systems. Trigger: "workhuman performance tuning".

workhuman-cost-tuning

1868
from jeremylongshore/claude-code-plugins-plus-skills

Workhuman cost tuning for employee recognition and rewards API. Use when integrating Workhuman Social Recognition, or building recognition workflows with HRIS systems. Trigger: "workhuman cost tuning".

wispr-performance-tuning

1868
from jeremylongshore/claude-code-plugins-plus-skills

Wispr Flow performance tuning for voice-to-text API integration. Use when integrating Wispr Flow dictation, WebSocket streaming, or building voice-powered applications. Trigger: "wispr performance tuning".

wispr-cost-tuning

1868
from jeremylongshore/claude-code-plugins-plus-skills

Wispr Flow cost tuning for voice-to-text API integration. Use when integrating Wispr Flow dictation, WebSocket streaming, or building voice-powered applications. Trigger: "wispr cost tuning".

windsurf-performance-tuning

1868
from jeremylongshore/claude-code-plugins-plus-skills

Optimize Windsurf IDE performance: indexing speed, Cascade responsiveness, and memory usage. Use when Windsurf is slow, indexing takes too long, Cascade times out, or the IDE uses too much memory. Trigger with phrases like "windsurf slow", "windsurf performance", "optimize windsurf", "windsurf memory", "cascade slow", "indexing slow".

windsurf-cost-tuning

1868
from jeremylongshore/claude-code-plugins-plus-skills

Optimize Windsurf licensing costs through seat management, tier selection, and credit monitoring. Use when analyzing Windsurf billing, reducing per-seat costs, or implementing usage monitoring and budget controls. Trigger with phrases like "windsurf cost", "windsurf billing", "reduce windsurf costs", "windsurf pricing", "windsurf budget".

webflow-performance-tuning

1868
from jeremylongshore/claude-code-plugins-plus-skills

Optimize Webflow API performance with response caching, bulk endpoint batching, CDN-cached live item reads, pagination optimization, and connection pooling. Use when experiencing slow API responses or optimizing request throughput. Trigger with phrases like "webflow performance", "optimize webflow", "webflow latency", "webflow caching", "webflow slow", "webflow batch".

webflow-cost-tuning

1868
from jeremylongshore/claude-code-plugins-plus-skills

Optimize Webflow costs through plan selection, CDN read optimization, bulk endpoint usage, and API usage monitoring with budget alerts. Use when analyzing Webflow billing, reducing API costs, or implementing usage monitoring for Webflow integrations. Trigger with phrases like "webflow cost", "webflow billing", "reduce webflow costs", "webflow pricing", "webflow budget".

vercel-performance-tuning

1868
from jeremylongshore/claude-code-plugins-plus-skills

Optimize Vercel deployment performance with caching, bundle optimization, and cold start reduction. Use when experiencing slow page loads, optimizing Core Web Vitals, or reducing serverless function cold start times. Trigger with phrases like "vercel performance", "optimize vercel", "vercel latency", "vercel caching", "vercel slow", "vercel cold start".

vercel-cost-tuning

1868
from jeremylongshore/claude-code-plugins-plus-skills

Optimize Vercel costs through plan selection, function efficiency, and usage monitoring. Use when analyzing Vercel billing, reducing function execution costs, or implementing spend management and budget alerts. Trigger with phrases like "vercel cost", "vercel billing", "reduce vercel costs", "vercel pricing", "vercel expensive", "vercel budget".

veeva-performance-tuning

1868
from jeremylongshore/claude-code-plugins-plus-skills

Veeva Vault performance tuning for REST API and clinical operations. Use when working with Veeva Vault document management and CRM. Trigger: "veeva performance tuning".

veeva-cost-tuning

1868
from jeremylongshore/claude-code-plugins-plus-skills

Veeva Vault cost tuning for REST API and clinical operations. Use when working with Veeva Vault document management and CRM. Trigger: "veeva cost tuning".