sentry-performance-tracing

0
0
Source

Execute set up performance monitoring and distributed tracing with Sentry. Use when implementing performance tracking, tracing requests, or monitoring application performance. Trigger with phrases like "sentry performance", "sentry tracing", "sentry APM", "monitor performance sentry".

Install

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

Installs to .claude/skills/sentry-performance-tracing

About this skill

Sentry Performance Tracing

Overview

Sentry performance monitoring captures distributed traces across your application stack, measuring latency, identifying bottlenecks, and tracking Web Vitals. The v8 SDK uses a span-based API where Sentry.startSpan() replaces the deprecated startTransaction(). Auto-instrumentation covers HTTP, database queries, and framework routes out of the box. Manual spans let you measure business-critical operations. Combined with profiling (profilesSampleRate), you get function-level flamegraphs attached to traces.

Prerequisites

  • Sentry SDK v8+ installed (@sentry/node >= 8.0.0 or sentry-sdk >= 2.0.0)
  • tracesSampleRate > 0 set in Sentry.init() — performance data is not collected at zero
  • Performance monitoring enabled in your Sentry project settings (Settings > Performance)
  • For distributed tracing: all participating services must have Sentry SDK initialized

Instructions

Step 1 — Configure Tracing and Profiling in SDK Init

Set tracesSampleRate to control what percentage of requests generate traces. Use tracesSampler for dynamic, per-endpoint sampling. Add profilesSampleRate to attach function-level flamegraphs to sampled transactions.

TypeScript (@sentry/node):

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

Sentry.init({
  dsn: process.env.SENTRY_DSN,
  tracesSampleRate: 0.2, // 20% of transactions in production

  // Profiling — profiles 10% of sampled transactions
  profilesSampleRate: 0.1,

  // Dynamic sampling overrides tracesSampleRate when defined
  tracesSampler: (samplingContext) => {
    const { name, attributes } = samplingContext;

    // Drop health checks entirely — no trace data
    if (name === 'GET /health') return 0;

    // Always trace payment flows
    if (name?.includes('/api/payment')) return 1.0;

    // Higher sampling for API routes
    if (name?.startsWith('GET /api/') || name?.startsWith('POST /api/')) return 0.2;

    // Default: 5% for everything else
    return 0.05;
  },
});

Python (sentry-sdk):

import os
import sentry_sdk

sentry_sdk.init(
    dsn=os.environ["SENTRY_DSN"],
    traces_sample_rate=0.2,       # 20% of transactions
    profiles_sample_rate=0.1,     # 10% of sampled transactions get profiled

    # Dynamic sampling via traces_sampler (overrides traces_sample_rate)
    traces_sampler=lambda ctx: (
        0.0 if ctx.get("transaction_context", {}).get("name") == "GET /health"
        else 1.0 if "/api/payment" in ctx.get("transaction_context", {}).get("name", "")
        else 0.2
    ),
)

Key decisions:

  • Start at tracesSampleRate: 0.2 and adjust based on volume and budget
  • tracesSampler takes priority when defined — tracesSampleRate becomes the fallback
  • profilesSampleRate is relative to sampled transactions (0.1 means 10% of the 20% that are sampled)
  • Return 0 from tracesSampler to explicitly drop a transaction, not false

Step 2 — Create Custom Spans for Business Logic

Auto-instrumentation covers HTTP and database calls, but business-critical operations need manual spans. The v8 API provides three span creation methods for different use cases.

Sentry.startSpan() — auto-ending spans (most common):

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

const result = await Sentry.startSpan(
  {
    name: 'order.process',
    op: 'task',
    attributes: {
      'order.id': orderId,
      'order.items': items.length,
    },
  },
  async (span) => {
    // Nested spans automatically become children of the parent
    const validated = await Sentry.startSpan(
      { name: 'order.validate', op: 'validation' },
      async () => validateOrder(order)
    );

    const charged = await Sentry.startSpan(
      { name: 'payment.charge', op: 'http.client' },
      async () => chargePayment(order.total)
    );

    // Set span status based on outcome
    if (!charged.success) {
      span.setStatus({ code: 2, message: 'payment_failed' });
    }

    // Add custom measurements visible in Performance dashboard
    Sentry.setMeasurement('order.item_count', items.length, 'none');
    Sentry.setMeasurement('order.total_cents', order.total, 'none');

    return { validated, charged };
  }
);
// Span automatically ends when callback resolves or rejects

Sentry.startSpanManual() — for spans that cross callback boundaries:

Sentry.startSpanManual(
  { name: 'queue.process', op: 'queue.task' },
  (span) => {
    queue.on('message', async (msg) => {
      try {
        await processMessage(msg);
        span.setStatus({ code: 1 }); // OK
      } catch (error) {
        span.setStatus({ code: 2, message: 'processing_failed' });
        Sentry.captureException(error);
      } finally {
        span.end(); // REQUIRED — must call end() manually
      }
    });
  }
);

Sentry.startInactiveSpan() — background work without changing active context:

const span = Sentry.startInactiveSpan({
  name: 'cache.warmup',
  op: 'cache',
});

await warmCache(); // Other spans created here won't be children of this span

span.end();

Span attributes and measurements:

await Sentry.startSpan(
  { name: 'search.query', op: 'db.query' },
  async (span) => {
    const start = Date.now();
    const results = await searchIndex(query);

    // Attributes — appear in span details, filterable in Sentry UI
    span.setAttribute('search.query', query);
    span.setAttribute('search.results_count', results.length);
    span.setAttribute('search.index', indexName);

    // Measurements — appear in Performance dashboard charts
    Sentry.setMeasurement('search.duration_ms', Date.now() - start, 'millisecond');
    Sentry.setMeasurement('search.result_count', results.length, 'none');

    return results;
  }
);

Python equivalent:

import sentry_sdk

with sentry_sdk.start_span(op="task", name="process_order") as span:
    span.set_data("order_id", order_id)
    span.set_data("item_count", len(items))

    with sentry_sdk.start_span(op="validation", name="validate_input"):
        validate(input_data)

    with sentry_sdk.start_span(op="http.client", name="charge_payment"):
        result = charge(payment)

    if not result.success:
        span.set_status("internal_error")

Step 3 — Enable Auto-Instrumentation and Distributed Tracing

SDK v8 auto-instruments most I/O without configuration. For distributed tracing across services, Sentry propagates sentry-trace and baggage headers automatically on HTTP calls. Custom propagation is needed only for non-HTTP transports (message queues, gRPC, etc.).

Auto-instrumented integrations (Node.js v8):

IntegrationWhat it tracesEnabled by
httpIntegration()All outbound HTTP/HTTPS requestsDefault
expressIntegration()Express route handlers and middlewareDefault with Express
fastifyIntegration()Fastify routesDefault with Fastify
graphqlIntegration()GraphQL resolversDefault with graphql
mongoIntegration()MongoDB queriesDefault with mongodb driver
postgresIntegration()PostgreSQL queries (pg driver)Default with pg
mysqlIntegration()MySQL queriesDefault with mysql2
redisIntegration()Redis commandsDefault with ioredis/redis
prismaIntegration()Prisma ORM queriesDefault with @prisma/client

Express with custom middleware spans:

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

const app = express();

// Sentry auto-instruments all Express routes
// Add custom spans for specific middleware:
app.use('/api', async (req, res, next) => {
  await Sentry.startSpan(
    { name: 'middleware.auth', op: 'middleware' },
    async () => {
      req.user = await authenticateRequest(req);
    }
  );
  next();
});

// Parameterized route names prevent cardinality explosion
// Sentry automatically uses '/api/users/:id' not '/api/users/12345'
app.get('/api/users/:id', async (req, res) => {
  const user = await Sentry.startSpan(
    { name: 'db.getUser', op: 'db.query' },
    () => db.users.findById(req.params.id)
  );
  res.json(user);
});

// Must be after all routes
Sentry.setupExpressErrorHandler(app);

Django/Flask auto-instrumentation (Python):

import sentry_sdk
from sentry_sdk.integrations.django import DjangoIntegration

sentry_sdk.init(
    dsn=os.environ["SENTRY_DSN"],
    integrations=[DjangoIntegration()],
    traces_sample_rate=0.2,
    profiles_sample_rate=0.1,
)
# All Django views, middleware, and template rendering are traced automatically
# Flask equivalent
from sentry_sdk.integrations.flask import FlaskIntegration

sentry_sdk.init(
    dsn=os.environ["SENTRY_DSN"],
    integrations=[FlaskIntegration()],
    traces_sample_rate=0.2,
)
# FastAPI equivalent
from sentry_sdk.integrations.fastapi import FastApiIntegration
from sentry_sdk.integrations.starlette import StarletteIntegration

sentry_sdk.init(
    dsn=os.environ["SENTRY_DSN"],
    integrations=[FastApiIntegration(), StarletteIntegration()],
    traces_sample_rate=0.2,
)

Distributed tracing — custom header propagation:

When Sentry cannot automatically propagate headers (non-HTTP transports, custom fetch wrappers), extract and inject manually:

// Service A: Extract trace headers from the active span
const activeSpan = Sentry.getActiveSpan();
const traceHeaders = {
  'sentry-trace': Sentry.spanToTraceHeader(activeSpan),
  'baggage': Sentry.spanToBaggageHeader(activeSpan),
};

// Pass headers to downstream service via HTTP, message queue, etc.
await fetch('https://service-b.internal/api/process', {
  headers: { ...traceHeaders, 'Content-Type': 'application/json' },
  body: JSON.stringify(payload),
});

// Service B: Sentry SDK automatically reads sentry-trace and baggage
// from incoming request headers and continues the same tr

---

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

7824

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

13615

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.

3114

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.

4311

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.

109

designing-database-schemas

jeremylongshore

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

1128

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.

9521,094

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.

846846

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

571699

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.

548492

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.

673466

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.

514280

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.