Skip to content

Commit 91abaad

Browse files
committed
Adding sampling docs to tracing section
1 parent 3c4795b commit 91abaad

File tree

1 file changed

+227
-0
lines changed
  • docs/platforms/javascript/common/tracing/configure-sampling

1 file changed

+227
-0
lines changed
Lines changed: 227 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,227 @@
1+
---
2+
title: Configure Sampling
3+
description: "Learn how to configure sampling in your app."
4+
sidebar_order: 30
5+
---
6+
7+
Sentry's tracing functionality helps you monitor application performance by capturing distributed traces, attaching attributes, and span performance across your application. However, Capturing traces for every transaction can generate significant volumes of data. Sampling allows you to control the amount of spans that are sent to Sentry from your application.
8+
9+
## Sampling Configuration Options
10+
11+
The JavaScript SDK provides two main options for controlling the sampling rate:
12+
13+
1. Uniform Sample Rate (`tracesSampleRate`)
14+
This option sets a fixed percentage of transactions to be captured:
15+
16+
```javascript
17+
Sentry.init({
18+
dsn: "https://[email protected]/0",
19+
integrations: [Sentry.browserTracingIntegration()],
20+
// Capture 25% of all transactions
21+
tracesSampleRate: 0.25
22+
});
23+
```
24+
25+
With `tracesSampleRate` set to `0.25`, approximately 25% of transactions will be recorded and sent to Sentry. This provides an even cross-section of transactions regardless of where in your app they occur.
26+
27+
2. Sampling Function (`tracesSampler`)
28+
29+
For more granular control, you can use the `tracesSampler` function. This approach allows you to:
30+
31+
- Apply different sampling rates to different types of transactions
32+
- Filter out specific transactions entirely
33+
- Make sampling decisions based on transaction data
34+
- Control the inheritance of sampling decisions in distributed traces
35+
36+
```javascript
37+
Sentry.init({
38+
dsn: "https://[email protected]/0",
39+
integrations: [Sentry.browserTracingIntegration()],
40+
tracesSampler: (samplingContext) => {
41+
// Access transaction details from the sampling context
42+
const { name, attributes, inheritOrSampleWith } = samplingContext;
43+
44+
// Skip health checks entirely
45+
if (name.includes('healthcheck')) {
46+
return 0;
47+
}
48+
49+
// Capture all auth-related transactions
50+
if (name.includes('auth')) {
51+
return 1;
52+
}
53+
54+
// Sample only 1% of comment-related transactions
55+
if (name.includes('comment')) {
56+
return 0.01;
57+
}
58+
59+
// For everything else, inherit parent sampling decision or use 0.5
60+
return inheritOrSampleWith(0.5);
61+
}
62+
});
63+
```
64+
65+
## The Sampling Context Object
66+
67+
When the `tracesSampler` function is called, it receives a `samplingContext` object with valuable information to help make sampling decisions:
68+
69+
```typescript
70+
typescriptCopyinterface SamplingContext {
71+
// Name of the span/transaction
72+
name: string;
73+
74+
// Initial attributes of the span/transaction
75+
attributes: SpanAttributes | undefined;
76+
77+
// Whether the parent span was sampled (undefined if no incoming trace)
78+
parentSampled: boolean | undefined;
79+
80+
// Sample rate from incoming trace (undefined if no incoming trace)
81+
parentSampleRate: number | undefined;
82+
83+
// Utility function to inherit parent decision or fallback
84+
inheritOrSampleWith: (fallbackRate: number) => number;
85+
}
86+
```
87+
88+
The sampling context contains:
89+
90+
- `name`: The name of the transaction/span
91+
- `attributes`: Initial tags and attributes set on the transaction
92+
- `parentSampled`: Whether the parent transaction was sampled (for distributed tracing)
93+
- `parentSampleRate`: The sample rate used in the parent transaction
94+
- `inheritOrSampleWith`: A utility function to handle inheritance logic (recommended)
95+
96+
## Inheritance in Distributed Tracing
97+
98+
In distributed systems, trace information is propagated between services. The inheritOrSampleWith function simplifies handling parent sampling decisions:
99+
100+
```javascript
101+
tracesSampler: (samplingContext) => {
102+
const { name, inheritOrSampleWith } = samplingContext;
103+
104+
// Apply specific rules first
105+
if (name.includes('critical-path')) {
106+
return 1.0; // Always sample
107+
}
108+
109+
// Otherwise inherit parent sampling decision or fall back to 0.1
110+
return inheritOrSampleWith(0.1);
111+
}
112+
```
113+
This approach ensures consistent sampling decisions across your entire distributed trace. All transactions in a given trace will share the same sampling decision, preventing broken or incomplete traces.
114+
115+
**Note:** The `inheritOrSampleWith` helper was introduced in version 9 of the SDK. For earlier versions, you can implement similar logic manually using the `parentSampled` property.
116+
117+
## Sampling Decision Precedence
118+
119+
When multiple sampling mechanisms could apply, Sentry follows this order of precedence:
120+
121+
- If `tracesSampler` is defined, its decision is used (can consider parent sampling)
122+
- If no `tracesSampler` but parent sampling is available, parent decision is used
123+
- If neither of the above, `tracesSampleRate` is used
124+
- If none of the above are set, no transactions are sampled (0%)
125+
126+
## How Sampling Propagates in Distributed Traces
127+
128+
Sentry uses a "head-based" sampling approach:
129+
130+
- A sampling decision is made in the originating service (the "head")
131+
- This decision is propagated to all downstream services via HTTP headers
132+
133+
The two key headers are:
134+
- `sentry-trace`: Contains trace ID, span ID, and sampling decision
135+
- `baggage`: Contains additional trace metadata including sample rate
136+
137+
Sentry automatically attaches these headers to outgoing HTTP requests when using the `browserTracingIntegration`. For other communication channels like WebSockets, you can manually propagate trace information:
138+
139+
```javascript
140+
// Extract trace data from the current scope
141+
const traceData = Sentry.getTraceData();
142+
const sentryTraceHeader = traceData["sentry-trace"];
143+
const sentryBaggageHeader = traceData["baggage"];
144+
145+
// Add to your custom request (example using WebSocket)
146+
webSocket.send(JSON.stringify({
147+
message: "Your data here",
148+
metadata: {
149+
sentryTrace: sentryTraceHeader,
150+
baggage: sentryBaggageHeader
151+
}
152+
}));
153+
```
154+
155+
## Real-world Use Cases for Trace Samplers
156+
157+
1. Prioritizing Critical User Flows
158+
159+
```javascript
160+
tracesSampler: (samplingContext) => {
161+
const { name, attributes } = samplingContext;
162+
163+
// Sample all checkout transactions
164+
if (name.includes('/checkout') || attributes?.flow === 'checkout') {
165+
return 1.0;
166+
}
167+
168+
// Sample 50% of login transactions
169+
if (name.includes('/login') || attributes?.flow === 'login') {
170+
return 0.5;
171+
}
172+
173+
// Sample 10% of everything else
174+
return 0.1;
175+
}
176+
```
177+
178+
2. Handling Different Environments
179+
180+
```javascript
181+
tracesSampler: (samplingContext) => {
182+
// Sample all transactions in development
183+
if (process.env.NODE_ENV === 'development') {
184+
return 1.0;
185+
}
186+
187+
// Sample 5% in production
188+
if (process.env.NODE_ENV === 'production') {
189+
return 0.05;
190+
}
191+
192+
// Sample 20% in staging
193+
return 0.2;
194+
}
195+
```
196+
197+
3. Controlling Sampling Based on User or Transaction Properties
198+
199+
```javascript
200+
tracesSampler: (samplingContext) => {
201+
const { attributes, inheritOrSampleWith } = samplingContext;
202+
203+
// Always sample for premium users
204+
if (attributes?.userTier === 'premium') {
205+
return 1.0;
206+
}
207+
208+
// Sample more transactions for users experiencing errors
209+
if (attributes?.hasRecentErrors === true) {
210+
return 0.8;
211+
}
212+
213+
// Sample less for high-volume, low-value paths
214+
if (attributes?.path?.includes('/api/metrics')) {
215+
return 0.01;
216+
}
217+
218+
// Default sampling rate
219+
return inheritOrSampleWith(0.2);
220+
}
221+
```
222+
223+
## Conclusion
224+
225+
Effective sampling is key to getting the most value from Sentry's performance monitoring while minimizing overhead. The `tracesSampler` function gives you precise control over which transactions to record, allowing you to focus on the most important parts of your application.
226+
227+
By implementing a thoughtful sampling strategy, you'll get the performance insights you need without overwhelming your systems or your Sentry quota.

0 commit comments

Comments
 (0)