sentry-cost-tuning

7
1
Source

Optimize Sentry costs and event volume. Use when managing Sentry billing, reducing event volume, or optimizing quota usage. Trigger with phrases like "reduce sentry costs", "sentry billing", "sentry quota", "optimize sentry spend".

Install

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

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

About this skill

Sentry Cost Tuning

Reduce Sentry spend by 60-95% through SDK-level sampling, server-side inbound filters, beforeSend event dropping, and quota management — without losing visibility into production errors that matter.

Prerequisites

  • Active Sentry account with org:read and project:read scopes on an auth token
  • Access to the project's Sentry.init() configuration (typically sentry.client.config.ts or instrument.ts)
  • Current plan tier identified: Developer (free, 5K errors/mo), Team ($26/mo, 50K errors + 100K transactions), or Business ($80/mo, 100K errors + 500K transactions)
  • SENTRY_AUTH_TOKEN and SENTRY_ORG environment variables set for API calls
  • @sentry/node >= 8.0 or @sentry/browser >= 8.0 installed

Instructions

Step 1 — Audit Current Usage via the Stats API

Query the Sentry Usage Stats API to understand where volume comes from before making changes. This endpoint returns event counts grouped by category over any time period.

# Pull 30-day usage breakdown by category
curl -s -H "Authorization: Bearer $SENTRY_AUTH_TOKEN" \
  "https://sentry.io/api/0/organizations/$SENTRY_ORG/stats/usage/?statsPeriod=30d&groupBy=category&field=sum(quantity)&interval=1d" \
  | python3 -c "
import json, sys
data = json.load(sys.stdin)
print('=== 30-Day Usage by Category ===')
for group in data.get('groups', []):
    cat = group['by']['category']
    total = sum(interval[1] for interval in group.get('series', {}).get('sum(quantity)', []))
    print(f'  {cat}: {total:,} events')
"
# Identify top error-producing projects
curl -s -H "Authorization: Bearer $SENTRY_AUTH_TOKEN" \
  "https://sentry.io/api/0/organizations/$SENTRY_ORG/stats/usage/?statsPeriod=30d&groupBy=project&category=error&field=sum(quantity)" \
  | python3 -c "
import json, sys
data = json.load(sys.stdin)
projects = []
for group in data.get('groups', []):
    proj = group['by']['project']
    total = sum(interval[1] for interval in group.get('series', {}).get('sum(quantity)', []))
    projects.append((proj, total))
projects.sort(key=lambda x: -x[1])
print('=== Top Error-Producing Projects ===')
for name, count in projects[:10]:
    print(f'  {name}: {count:,}')
"

Record the baseline numbers. You need these to measure savings after optimization.

Step 2 — Configure Error Sampling with sampleRate

The sampleRate option in Sentry.init() controls the percentage of error events sent to Sentry. Setting it to 0.1 means only 10% of errors are sent, yielding a 90% cost reduction on the error category.

import * as Sentry from '@sentry/node';

Sentry.init({
  dsn: process.env.SENTRY_DSN,

  // 10% of errors sent = 90% cost reduction
  // Sentry extrapolates counts in the Issues dashboard
  sampleRate: 0.1,
});

Trade-off: Low-frequency errors (< 10 occurrences/day) may be missed entirely. Mitigate this by using beforeSend to always send errors with specific severity or tags rather than relying on blanket sampling.

Step 3 — Configure Performance Sampling with tracesSampleRate and tracesSampler

Performance monitoring (transactions/spans) is typically the largest cost driver. A tracesSampleRate of 0.05 sends only 5% of traces, cutting performance costs by 95%.

import * as Sentry from '@sentry/node';

Sentry.init({
  dsn: process.env.SENTRY_DSN,

  // Static: 5% of all traces (95% cost reduction)
  tracesSampleRate: 0.05,

  // Dynamic: per-endpoint sampling for fine-grained control
  // When tracesSampler is defined, it overrides tracesSampleRate
  tracesSampler: (samplingContext) => {
    const { name, attributes } = samplingContext;

    // Never trace health checks, readiness probes, static assets
    if (name?.match(/\/(health|healthz|ready|livez|ping|robots\.txt|favicon)/)) {
      return 0;
    }
    if (name?.match(/\.(js|css|png|jpg|svg|woff2?|ico)$/)) {
      return 0;
    }

    // High-value: payment and auth flows get 50% sampling
    if (name?.includes('/checkout') || name?.includes('/payment')) {
      return 0.5;
    }
    if (name?.includes('/auth') || name?.includes('/login')) {
      return 0.25;
    }

    // API routes: 5%
    if (name?.includes('/api/')) {
      return 0.05;
    }

    // Everything else: 1%
    return 0.01;
  },
});

The tracesSampler function receives a samplingContext with the transaction name (usually the route) and attributes. Return a number between 0 (drop) and 1 (always send), or true/false.

Step 4 — Drop Noisy Events with beforeSend

The beforeSend hook fires for every error event before it is sent to Sentry. Returning null drops the event entirely — it never counts against quota.

import * as Sentry from '@sentry/node';

Sentry.init({
  dsn: process.env.SENTRY_DSN,

  beforeSend(event, hint) {
    const error = hint?.originalException;
    const message = typeof error === 'string' ? error : error?.message || '';

    // Drop ResizeObserver noise (Chrome fires this constantly, never actionable)
    if (message.includes('ResizeObserver loop')) return null;

    // Drop network errors from flaky client connections
    if (/^(Failed to fetch|NetworkError|Load failed|AbortError)$/i.test(message)) {
      return null;
    }

    // Drop cancelled navigation (user clicked away)
    if (message.includes('cancelled') || message.includes('AbortError')) {
      return null;
    }

    // Drop browser extension errors by checking stack frames
    const frames = event.exception?.values?.[0]?.stacktrace?.frames || [];
    if (frames.some(f => f.filename?.match(/extensions?\//i) || f.filename?.match(/^(chrome|moz)-extension:\/\//))) {
      return null;
    }

    // Always send critical errors regardless of sampleRate
    // Re-enable any that were sampled out
    if (event.level === 'fatal' || event.tags?.critical === 'true') {
      return event;
    }

    return event;
  },

  // Complementary: block errors from known noisy patterns
  ignoreErrors: [
    'ResizeObserver loop completed with undelivered notifications',
    'ResizeObserver loop limit exceeded',
    'Non-Error promise rejection captured',
    /Loading chunk \d+ failed/,
    /Unexpected token '<'/,       // HTML returned instead of JS (CDN issue)
    /^Script error\.?$/,          // Cross-origin script with no details
  ],

  // Block events from third-party scripts
  denyUrls: [
    /extensions\//i,
    /^chrome:\/\//i,
    /^chrome-extension:\/\//i,
    /^moz-extension:\/\//i,
    /hotjar\.com/,
    /intercom\.io/,
    /google-analytics\.com/,
    /googletagmanager\.com/,
    /cdn\.segment\.com/,
  ],
});

Step 5 — Enable Server-Side Inbound Data Filters (Free)

Inbound data filters drop events at Sentry's edge before they are ingested and counted against quota. They cost nothing to enable.

Navigate to Project Settings > Inbound Filters (or use the API) and enable:

FilterWhat it dropsImpact
Browser ExtensionsErrors from Chrome/Firefox extensions5-15% of frontend errors
Legacy BrowsersIE 11, old Safari/Chrome versions2-10% depending on audience
Localhost EventsErrors from localhost and 127.0.0.1Dev noise (variable)
Web CrawlersBot-triggered errors (Googlebot, Bingbot)1-5% of frontend errors
Filtered TransactionsHealth checks, static asset requests10-40% of transactions
# Enable inbound filters via API
for filter in browser-extensions legacy-browsers localhost-events web-crawlers; do
  curl -s -X PUT \
    -H "Authorization: Bearer $SENTRY_AUTH_TOKEN" \
    -H "Content-Type: application/json" \
    -d '{"active": true}' \
    "https://sentry.io/api/0/projects/$SENTRY_ORG/$SENTRY_PROJECT/filters/$filter/"
  echo " -> Enabled: $filter"
done

Add custom error message filters for project-specific noise:

# Add custom inbound filter for error messages
curl -s -X PUT \
  -H "Authorization: Bearer $SENTRY_AUTH_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"active": true, "subfilters": ["ResizeObserver", "ChunkLoadError", "Script error"]}' \
  "https://sentry.io/api/0/projects/$SENTRY_ORG/$SENTRY_PROJECT/filters/custom-error-messages/"

Step 6 — Configure Spike Protection and Per-Key Rate Limits

Spike protection is auto-enabled on all Sentry plans and caps burst events during sudden spikes (deploy bugs, infinite loops). Verify it is active under Organization Settings > Spike Protection.

Per-key rate limits restrict events per DSN key per time window. Set these in Project Settings > Client Keys (DSN) > Rate Limiting or via the API:

# Set rate limit: 1000 errors per hour per DSN key
curl -s -X PUT \
  -H "Authorization: Bearer $SENTRY_AUTH_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"rateLimit": {"window": 3600, "count": 1000}}' \
  "https://sentry.io/api/0/projects/$SENTRY_ORG/$SENTRY_PROJECT/keys/$KEY_ID/"

Spend allocations (Team and Business plans): Set per-category budgets under Settings > Subscription > Spend Allocations to cap on-demand spending per billing period.

Step 7 — Optimize Reserved vs On-Demand Volume

Sentry offers two pricing models for volume above the plan's included quota:

ModelRate (errors)Best for
Reserved volume~$0.000180/event (pre-paid blocks)Predictable workloads
On-demand volume~$0.000290/event (pay-as-you-go)Spiky/seasonal traffic

Reserved volume is approximately 38% cheaper per event than on-demand. If your 30-day audit shows consistent volume, purchase reserved blocks to match the P90 usage. Let spikes overflow into on-demand.

Example calculation:
  Average monthly errors:  120,000
  Plan included:            50,000  (Team plan)
  Overage:                  70,000

  On-demand cost:  70,000 x $0.000290 = $20.30/month
  Reserved cost:   70,000 x $0.000180 = $12.60/month
  Monthly savings: $7.70 ($92.40/year)

---

*Content truncated.*

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.

10735

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.

9033

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

18728

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.

5519

designing-database-schemas

jeremylongshore

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

12516

optimizing-sql-queries

jeremylongshore

This skill analyzes and optimizes SQL queries for improved performance. It identifies potential bottlenecks, suggests optimal indexes, and proposes query rewrites. Use this when the user mentions "optimize SQL query", "improve SQL performance", "SQL query optimization", "slow SQL query", or asks for help with "SQL indexing". The skill helps enhance database efficiency by analyzing query structure, recommending indexes, and reviewing execution plans.

5513

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.

1,6811,428

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

1,2591,318

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.

1,5271,144

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.

1,347807

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.

1,261727

pdf-to-markdown

aliceisjustplaying

Convert entire PDF documents to clean, structured Markdown for full context loading. Use this skill when the user wants to extract ALL text from a PDF into context (not grep/search), when discussing or analyzing PDF content in full, when the user mentions "load the whole PDF", "bring the PDF into context", "read the entire PDF", or when partial extraction/grepping would miss important context. This is the preferred method for PDF text extraction over page-by-page or grep approaches.

1,466674