К основному содержанию
скилл CX Codex

posthog-cost-tuning — скилл для Claude Code

Скилл posthog-cost-tuning считает, за что PostHog выставляет счёт, и режет шум в захвате событий, не теряя данные, нужные для решений.

MIT 1 установок ★ 2 935 обновлён 2026-10-29

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add jeremylongshore/tons-of-skills-marketplace --skill posthog-cost-tuning -a claude-code
Открыть на GitHub

Что делает posthog-cost-tuning

Скилл идёт по включённым продуктам PostHog и меряет биллинговый объём: HogQL-запросы к /api/projects/$POSTHOG_PROJECT_ID/query/ показывают, какие события съедают квоту. Дальше он ищет релиз инструментации, после которого трафик вырос, и режет только то, что владелец продукта уже признал шумом или безопасным для сэмплирования.

Внутри — порядок шагов: аудит событий за 30 дней, настройка autocapture с allowlist по DOM-событиям, элементам и CSS-селекторам, хук before_send, который сохраняет покупки и регистрации, сэмплирует просмотры страниц и отбрасывает ботов по user-agent. Запись сессий получает минимум 5000 мс и отключается для бесплатных аккаунтов, а в конце считается прогноз на месяц с алертом на 0.8 от согласованного лимита. Из инструментов доступны Read, Grep и curl.

Нужен аккаунт PostHog Cloud с доступом к биллингу и приложение, уже размеченное posthog-js. Приватные запросы к биллингу идут с personal API key или OAuth-токеном с минимальными правами: без такого ключа шаг с HogQL не выполнится. В браузер при этом уходит только публичный project token, а хост выбирается под проект, US или EU.

Какие задачи решает

  • найти события, которые съедают месячную квоту
  • урезать $autocapture без потери кликов и отправок форм
  • отсечь ботов и headless-браузеры в before_send
  • посчитать прогноз расходов до конца месяца
  • поставить алерт при подходе к лимиту событий

Примеры запросов агенту

  • Посчитай биллинговый объём PostHog по проекту $POSTHOG_PROJECT_ID и покажи топ событий за 30 дней.
  • Настрой autocapture в posthog.init: только клики и submit, страницы /admin и /_next не трогай.
  • Сделай прогноз событий до конца месяца и поставь алерт на 0.8 от лимита.

Как установить posthog-cost-tuning

1Через Skills CLI (Vercel)

npx skills add jeremylongshore/tons-of-skills-marketplace --skill posthog-cost-tuning -a claude-code

2Вручную: положить файлы

~/.claude/skills/posthog-cost-tuning/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/posthog-cost-tuning/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о posthog-cost-tuning

Как установить posthog-cost-tuning в Claude Code?

Запустите npx skills add jeremylongshore/tons-of-skills-marketplace --skill posthog-cost-tuning -a claude-code. После установки файл скилла лежит в ~/.claude/skills/posthog-cost-tuning/SKILL.md.

Что делает posthog-cost-tuning?

Меряет биллинговый объём по каждому продукту PostHog, связывает рост трафика с релизом инструментации и сокращает захват там, где данные признаны шумом или безопасны для сэмплирования.

Что нужно для запросов к PostHog?

Аккаунт PostHog Cloud с доступом к биллингу и personal API key или OAuth-токен с минимальными правами, который читается из секрет-менеджера. В браузере остаётся только публичный project token.

Исходный текст

SKILL.md · MIT
---
name: posthog-cost-tuning
description: |
  Reduce PostHog usage cost without silently losing decision-critical data by measuring billable volume, applying product limits, and filtering noise. Use when forecasting spend or responding to a usage spike. Trigger with "PostHog cost", "PostHog billing", or "reduce PostHog usage".
argument-hint: "[project-path] [product-or-budget]"
allowed-tools: Read, Grep, Bash(curl:*)
version: 1.14.0
license: MIT
author: Jeremy Longshore <[email protected]>
tags:
- saas
- posthog
- api
- monitoring
- cost-optimization
compatibility: Designed for Claude Code
---
# 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

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

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

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

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

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

| 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 |
| Approved product limit reached mid-month | Volume exceeds the reviewed budget | Apply 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](references/official-docs.md) for current authority and verification boundaries.

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

© Jeremy Longshore · MIT · jeremylongshore/tons-of-skills-marketplace

Похожие скиллы

Все скиллы по теме «DevOps и инфраструктура» →
posthog-errors aeonfun Скилл posthog-errors для Claude Code собирает еженедельную сводку ошибок из проектов PostHog. Он ранжирует проблемы по влиянию и отмечает новые. CX Codex +1 ★ 797звёзд репо posthog-automation davepoon Скилл posthog-automation для Claude Code автоматизирует работу с PostHog через Rube MCP: отправляет события и управляет feature-флагами, проектами, профилями пользователей и аннотациями. CX Codex +1 121установок querying-posthog-data PostHog Скилл querying-posthog-data объясняет агенту, как правильно запрашивать данные PostHog: типизированные инструменты для аналитики и HogQL/SQL, когда без него не обойтись. CX Codex +1 890установок posthog-analytics alinaqi Скилл posthog-analytics для Claude Code помогает добавить в продукт аналитику PostHog, события и флаги функций. Подключается при работе с отслеживанием действий пользователей. CX Codex +1 827установок posthog-onboarding PostHog Скилл posthog-onboarding помогает клиенту, у которого PostHog уже стоит, найти дыры в разметке и получить план улучшений: эталонная схема событий, подбор инсайтов, приоритеты. CX Codex +1 223установок seo-posthog AgriciDaniel Скилл seo-posthog для Claude Code выгружает данные органического трафика и посадочных страниц через PostHog MCP. Запускается при запросе аналитики сайта без GA4. CX Codex +1 141установок

Из того же набора139

Весь набор →
deepgram-cost-tuning Скилл deepgram-cost-tuning помогает контролировать расходы на Deepgram: оценивает стоимость транскрибации, учитывает использование API и предлагает сократить оплачиваемую длительность аудио. CX Codex +1 1установок clerk-cost-tuning Скилл clerk-cost-tuning разбирает тарификацию Clerk по MRU и помогает урезать счёт: авторизация только на нужных маршрутах, кеш вокруг Backend API, скрипт поиска неактивных аккаунтов. CX Codex +1 1установок lindy-cost-tuning Скилл lindy-cost-tuning анализирует расход кредитов в Lindy AI, помогает подобрать более дешёвые модели и объединить дублирующих агентов. CX Codex +1 1установок evernote-cost-tuning Скилл evernote-cost-tuning для Claude Code отслеживает квоты загрузки Evernote, оценивает размер вложений и находит крупные заметки. Проверяет лимит до загрузки в интеграциях. CX Codex +1 1установок ideogram-cost-tuning Скилл ideogram-cost-tuning настраивает контроль расходов на генерацию изображений через API Ideogram. Помогает задать лимиты запросов, отсечь дубликаты и учитывать только сохранённые результаты. CX Codex +1 1установок coderabbit-cost-tuning Скилл coderabbit-cost-tuning разбирает тариф, места, лимиты и расход по CodeRabbit на основе актуальных данных. Помогает подготовить варианты экономии до согласования изменений. CX Codex +1 1установок firecrawl-cost-tuning Скилл firecrawl-cost-tuning считает, куда уходят кредиты Firecrawl, и подбирает лимиты, форматы и кеш так, чтобы счёт стал меньше без потери качества данных. CX Codex +1 1установок retellai-cost-tuning Скилл retellai-cost-tuning задаёт сценарии оптимизации затрат на голосовых агентов Retell AI и телефонию. Помогает снизить бюджет на звонки без потери качества диалога с клиентами. CX Codex +1 1установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой