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".
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.
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.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();
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):
Integration
What it traces
Enabled by
httpIntegration()
All outbound HTTP/HTTPS requests
Default
expressIntegration()
Express route handlers and middleware
Default with Express
fastifyIntegration()
Fastify routes
Default with Fastify
graphqlIntegration()
GraphQL resolvers
Default with graphql
mongoIntegration()
MongoDB queries
Default with mongodb driver
postgresIntegration()
PostgreSQL queries (pg driver)
Default with pg
mysqlIntegration()
MySQL queries
Default with mysql2
redisIntegration()
Redis commands
Default with ioredis/redis
prismaIntegration()
Prisma ORM queries
Default 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
# 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 trace
Browser Web Vitals (@sentry/browser):
The browser SDK automatically captures Core Web Vitals when tracing is enabled: