sentry-performance-tuning
Optimize Sentry performance monitoring for lower overhead and higher signal. Use when tuning tracesSampleRate vs tracesSampler, configuring continuous profiling, fixing high-cardinality transaction names, adding custom span measurements, reducing SDK overhead, or setting Web Vitals thresholds. Trigger: "sentry performance optimize", "tune sentry sampling", "reduce sentry overhead", "sentry web vitals", "sentry profiling setup".
What this skill does
# Sentry Performance Tuning
## Overview
Optimize Sentry's performance monitoring pipeline to maximize signal quality while minimizing SDK overhead and event volume costs. Covers the v8 SDK API for `@sentry/node`, `@sentry/browser`, and `sentry-sdk` (Python), targeting `sentry.io` or self-hosted Sentry 24.1+.
## Prerequisites
- Sentry SDK v8+ installed (`@sentry/node` >= 8.0.0 or `sentry-sdk` >= 2.0.0)
- `Sentry.init()` called with a valid DSN before any application code runs
- Performance monitoring enabled (`tracesSampleRate > 0` or a `tracesSampler` function)
- Access to the Sentry Performance dashboard to verify changes
## Instructions
### Step 1 — Replace Static `tracesSampleRate` with Dynamic `tracesSampler`
A flat `tracesSampleRate: 0.1` samples all routes equally. The `tracesSampler` callback makes per-transaction decisions based on route, operation type, and upstream trace context.
```typescript
import * as Sentry from '@sentry/node';
Sentry.init({
dsn: process.env.SENTRY_DSN,
// tracesSampler replaces tracesSampleRate — do not set both
tracesSampler: (samplingContext) => {
const { name, attributes, parentSampled } = samplingContext;
// Honor parent sampling for distributed trace consistency
if (parentSampled !== undefined) return parentSampled ? 1.0 : 0;
// Drop noise — health probes, static assets
if (name?.match(/\/(health|ready|alive|ping|metrics)$/)) return 0;
if (name?.match(/\.(js|css|png|jpg|svg|woff2?|ico)$/)) return 0;
// Always sample business-critical paths
if (name?.includes('/checkout') || name?.includes('/payment')) return 1.0;
// Higher sampling for write operations (mutations are riskier)
if (name?.startsWith('POST ') || name?.startsWith('PUT ')) return 0.25;
// Moderate sampling for read APIs
if (name?.startsWith('GET /api/')) return 0.1;
// Low sampling for background work
if (name?.startsWith('job:') || name?.startsWith('queue:')) return 0.05;
// User-tier sampling (via custom attributes from middleware)
if (attributes?.['user.plan'] === 'enterprise') return 0.5;
return 0.05; // Default: 5%
},
});
```
### Step 2 — Configure Profiling with `profilesSampleRate`
The `profilesSampleRate` controls what fraction of *traced* transactions get profiled. Setting it to 1.0 with a 5% `tracesSampler` means 5% of traffic is profiled.
```typescript
import { nodeProfilingIntegration } from '@sentry/profiling-node';
Sentry.init({
dsn: process.env.SENTRY_DSN,
integrations: [nodeProfilingIntegration()],
tracesSampler: (ctx) => { /* ... from Step 1 ... */ },
// Effective rate = tracesSampler rate * profilesSampleRate
profilesSampleRate: 1.0,
// Alternative: Continuous profiling (v8.7.0+) — profiles the entire process
// profileSessionSampleRate: 0.1, // 10% of server instances
});
```
**Tuning:** Start at `profilesSampleRate: 0.1` in production. Profiling adds ~3-5% CPU overhead per profiled transaction. Continuous profiling (`profileSessionSampleRate`) has lower per-transaction cost but runs on sampled instances continuously.
### Step 3 — Fix Transaction Naming (Prevent Cardinality Explosion)
Names with dynamic IDs (`/api/users/12345`) create thousands of unique entries, degrading dashboard performance and inflating quota. **Route templates go in the name, dynamic values go in attributes.**
```typescript
// BAD — creates thousands of unique transaction entries
// GET /api/users/12345, GET /api/users/67890, ...
// GOOD — Sentry auto-parameterizes Express/Koa/Fastify routes
// GET /api/users/:userId
// For custom spans, always parameterize:
Sentry.startSpan(
{
name: 'order.process', // No dynamic IDs in name
op: 'task',
attributes: {
'order.id': orderId, // Filterable in Discover queries
'order.total_cents': totalCents,
'customer.tier': customerTier,
},
},
async (span) => {
const result = await processOrder(orderId);
span.setAttribute('order.status', result.status);
return result;
}
);
```
**Detect cardinality issues** with a Discover query:
```
SELECT count(), transaction FROM transactions GROUP BY transaction ORDER BY count() DESC
```
### Step 4 — Add Custom Measurements
Custom measurements appear in the Performance dashboard and can be charted, alerted on, and queried in Discover. Unit types: `'millisecond'`, `'byte'`, `'none'` (count), `'percent'`.
```typescript
await Sentry.startSpan(
{ name: 'search.execute', op: 'function' },
async (span) => {
const start = performance.now();
const results = await searchService.query(term);
Sentry.setMeasurement('search.latency', performance.now() - start, 'millisecond');
Sentry.setMeasurement('search.result_count', results.length, 'none');
Sentry.setMeasurement('search.memory_delta',
process.memoryUsage().heapUsed - memBefore, 'byte');
span.setAttribute('search.cache_hit', results.fromCache);
return results;
}
);
```
| Measurement | Unit | Use case |
|-------------|------|----------|
| `cart.total_cents` | `none` | Revenue correlation with latency |
| `query.rows_scanned` | `none` | Database query efficiency |
| `cache.hit_rate` | `percent` | Cache performance per route |
| `upload.file_size` | `byte` | File upload impact on response time |
### Step 5 — Reduce SDK Overhead
For high-throughput services (>1000 req/s), every integration and breadcrumb counts.
```typescript
Sentry.init({
dsn: process.env.SENTRY_DSN,
maxBreadcrumbs: 20, // Default: 100. Each ~0.5-2KB.
maxValueLength: 500, // Truncate long string values
maxAttachmentSize: 5_242_880, // 5MB (default: 20MB)
// Remove noisy integrations
integrations: (defaults) => defaults.filter(
(i) => i.name !== 'Console'
),
// Trim oversized stack traces
beforeSend: (event) => {
if (event.exception?.values) {
for (const exc of event.exception.values) {
if (exc.stacktrace?.frames && exc.stacktrace.frames.length > 30) {
exc.stacktrace.frames = [
...exc.stacktrace.frames.slice(0, 10),
...exc.stacktrace.frames.slice(-20),
];
}
}
}
return event;
},
// Drop internal/noise spans
beforeSendSpan: (span) => {
if (span.description?.startsWith('internal.')) return null;
return span;
},
});
```
**Browser SDK lazy loading** (saves ~30KB gzipped from critical path):
```typescript
async function initSentry() {
const Sentry = await import('@sentry/browser');
Sentry.init({
dsn: process.env.SENTRY_DSN,
integrations: [Sentry.browserTracingIntegration()],
tracesSampleRate: 0.1,
});
}
window.addEventListener('load', initSentry, { once: true });
```
### Step 6 — Span Best Practices (Avoid Span Explosion)
Only wrap operations with measurable latency (>1ms). Never span synchronous lookups or individual loop iterations.
```typescript
// BAD — sub-microsecond config read; span overhead exceeds operation cost
function getConfig(key: string) {
return Sentry.startSpan({ name: 'config.get', op: 'function' }, () => config[key]);
}
// BAD — N spans per request from loop iterations
for (const item of items) {
await Sentry.startSpan({ name: 'process.item', op: 'function' }, () => processItem(item));
}
// GOOD — span the batch, count in attributes
await Sentry.startSpan(
{ name: 'process.batch', op: 'function', attributes: { 'batch.size': items.length } },
async () => Promise.all(items.map(processItem))
);
// GOOD — span external I/O with real latency
async function fetchUserProfile(userId: string) {
return Sentry.startSpan(
{ name: 'user.fetch_profile', op: 'http.client', attributes: { 'user.id': userId } },
async () => fetch(`${USER_SERVICE_URL}/users/${userId}`).then(r => r.json())
);
}
```
### Step 7 — Web Vitals Monitoring
The Browser SDK auto-captures Core Web Vitals. Filter span creation to avoid noise from third-party scripts.
```typescript
Sentry.init(Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.