Watching everything is watching nothing: Sampling strategy for Sentry
TL;DR: You don’t need every trace, replay, and log from every page of your app. With
tracesSampler, per-page replay policies, and log filters, you can keep more of what you care about and send less of everything else.
A blanket sample rate treats a routine page load on a stable legacy route the same as your checkout flow or a feature you shipped yesterday. Sample 5% of everything, and you get 5% of your checkout traces, while spending the same share of your quota on a page that hasn’t changed in a year.
Every Span, Trace, Log, and Replay you send to Sentry shows you what’s actually happening in production. But once you’re at scale, you have to choose what to keep.
So we want to move past “blanket sampling,” keeping high-resolution data where things are critical or changing fast, and turning it down where the system is stable.
Why not sample 100% of everything?
You can!
And if your app is small or brand new, that might actually be the right plan. But as you scale, “100% of everything” usually stops being a practical option, for a couple reasons:
- Signal-to-Noise: Telemetry data is more useful when you know what happened at a glance. Needing to parse through 1 million “user clicked button” spans to discover the 100 times users experienced issues during checkout isn’t efficient for you, for queries, or any LLMs that might be consuming the same information as us.
- The Network Footprint: While the SDK is highly optimized, every interaction, every function call, it starts to add up. By sampling only what you need, performance stays high while still collecting valuable information.
The basic dials: Static sample rates
When you initialize Sentry, you get four main options for adjusting how much data you send. Understanding how these interact is the first step:
// instrumentation-client.ts
import * as Sentry from "@sentry/nextjs";
Sentry.init({
dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
// Replay needs its integration; the replay rates below do nothing without it.
integrations: [Sentry.replayIntegration()],
// 1. Errors: We want to capture 100% of errors.
// 1.0 is the default, and this is usually omitted.
sampleRate: 1.0,
// 2. Tracing: A uniform slice of your traffic.
tracesSampleRate: process.env.NODE_ENV === "development" ? 1.0 : 0.05,
// 3. Full Replays: Great for UX audits.
replaysSessionSampleRate: 0.01,
// 4. Error Replays: The "Flight Recorder" that triggers on crashes.
replaysOnErrorSampleRate: 1.0,
});sampleRate: This is for errors. We almost always leave this at 1.0 because if something breaks, we want to know every single time.tracesSampleRate: This provides a cross-section of your traffic. It’s your primary lever for managing the volume of performance data.replaysSessionSampleRate: This records the whole session from the start. It’s high-fidelity, so you usually only need a small percentage to see how the “average” user navigates.replaysOnErrorSampleRate: This is a buffer. It only sends the replay if an error occurs, capturing the 60 seconds of activity leading up to the error.
Precision control: The tracesSampler
Traces connect your errors, performance data, and logs, so you’ll want to keep as many as your traffic and quota allow. But in very high-traffic applications, you don’t need every trace if you sample strategically.
Instead of a blanket percentage, Sentry lets you pass a tracesSampler function in place of tracesSampleRate. That way you can decide in real time, based on the context of the request.
What’s in the sampling context?
When a span starts, the sampler receives a samplingContext object. You’ll have this data automatically and can use it, along with anything else you may pass in, to decide if you should sample.
interface SamplingContext {
name: string; // e.g. "GET /api/v1/checkout"
attributes: SpanAttributes | undefined; // feature flags, user tiers, etc.
parentSampled: boolean | undefined; // Did the upstream service sample this?
parentSampleRate: number | undefined; // Sample rate from incoming trace
inheritOrSampleWith: (fallbackRate: number) => number; // Inherit parent decision or fallback
}In your tracesSampler function, read values from the context object, or destructure the ones you need, and provide a return value ranging from 0 to 1.
Sentry.init({
dsn: process.env.SENTRY_DSN,
tracesSampler: ({ name, attributes }) => {
// Sample 50% of login transactions
if (name.includes("/login") || attributes?.flow === "login") {
return 0.5;
}
// Everything else: 5%
return 0.05;
},
});You can find a few useful example sampling functions in our docs.
Staying in sync with inheritOrSampleWith
If the backend has already decided to sample a trace, the frontend should usually follow suit. You can use the inheritOrSampleWith utility to handle this. Destructure it from the samplingContext and call it to inherit the backend sample, or fall back to another value.
Sentry.init({
tracesSampler: ({ name, attributes, inheritOrSampleWith }) => {
// New features: Keep 100% of the data for a new UI launch.
if (attributes?.['feature_flag.new_v2_ui'] === true) {
return 1.0;
}
// Fallback: Respect the backend's choice, or default to 5%.
return inheritOrSampleWith(0.05);
},
});Smart sampling with Session Replay
A trace can tell you a database query was slow, but a replay shows you the user giving up and leaving the page while it loaded.
By default, Session Replay is configured to record a percentage of all user sessions, based on replaysSessionSampleRate.
Replay can also buffer sessions in memory and only send them if the user hits an error, with its own sample rate, replaysOnErrorSampleRate. We usually set that one higher, since what it sends tends to be more valuable.
Sentry.init({
dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
integrations: [Sentry.replayIntegration()],
// Define how likely Replay events are sampled.
replaysSessionSampleRate: 0.1,
// Define how likely Replay events are sampled when an error occurs.
replaysOnErrorSampleRate: 1.0,
});All Sentry plans, including the free “Developer” tier, start with 50 Session Replays, though you can always add more. We want to be intentional about how we spend our Session Replay quota. There’s no point in recording some static page that hasn’t changed in months if nothing ever goes wrong there. Not recording unnecessary replays also spares our users a small but measurable performance overhead.
So, rather than setting some global sample rates using the default Sentry config, we can use the Sentry SDK directly to implement our own per-page sampling strategy.
Per-page replay policies with a React provider and hook
There’s no replaysSampler option (yet), but the Replay integration gives us everything we need to build one ourselves: replay.start(), replay.startBuffering(), and replay.stop().
So we wrapped those in a small custom hook, useSessionReplay, and a SessionReplayProvider component that calls it for you.
You drop the provider into a layout (or call the hook from a component), tell it how you want that part of the app recorded, and it makes the Replay calls when users enter and leave that section.
We call each of those rules a replay policy, and it replaces the built-in global sampling for that part of the app. A policy is made of four settings:
name: Set on every replay as thereplay.policytag, so you can filter replays by the policy that captured them.mode: What Replay does in that section.sessionrecords the visit in full,bufferkeeps the last ~60 seconds in memory and only sends it if something breaks, andoffdoesn’t record at all.sampleRate: The share of users who get thatmode. Everyone else getsoff. Each policy is rolled once per page load, so navigating back isn’t a second chance to be sampled.sendOnLeave: Forbufferpolicies, also send the buffer when the user navigates away from the section. That’s how you catch users who abandon a funnel.
Follow the full guide in the cookbook, Control Session Replay sampling per page with a React hook. It has the full code for the hook and provider, plus the small policy controller behind them that you can copy as is.
First, set both replay sample rates to 0. The replayIntegration() stays installed, but it sits idle until a policy tells it what to do. Any non-zero rate lets the SDK start recording or buffering on its own, which would fight with our policies.
Sentry.init({
dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
integrations: [Sentry.replayIntegration()],
// Both at 0: nothing records until a <SessionReplayProvider> says so.
replaysSessionSampleRate: 0,
replaysOnErrorSampleRate: 0,
});Then set an app-wide default in your root layout. Layouts in Next.js are usually Server Components, which can’t call hooks, so the provider is a "use client" component that calls the hook for you.
// app/layout.tsx
import { SessionReplayProvider } from "@/components/session-replay-provider";
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>
{/* The app-wide default: 10% of sessions. Sections override it in their own layouts. */}
<SessionReplayProvider name="app" mode="session" sampleRate={0.1}>
{children}
</SessionReplayProvider>
</body>
</html>
);
}Now override that default wherever you need to. The most deeply nested policy wins, and only its sample rate counts, so each section can make its own call.
// app/(browse)/layout.tsx
// Landing page + event list. High traffic, low insight: never record.
<SessionReplayProvider name="browse" mode="off">
{children}
</SessionReplayProvider>
// app/(event)/layout.tsx
// Stable pages we only care about when something breaks:
// buffer the last ~60s for everyone, send it only if an error happens.
<SessionReplayProvider name="event" mode="buffer">
{children}
</SessionReplayProvider>
// app/(submit)/layout.tsx
// A mature funnel: we only want to watch the people who give up.
// Send the buffer if they navigate away before finishing.
<SessionReplayProvider name="submit" mode="buffer" sendOnLeave>
{children}
</SessionReplayProvider>When one component matters more than the page it’s on, like a new checkout form behind a feature flag, call the hook directly from a Client Component. Its policy applies while it’s mounted, and the surrounding policy takes over again when it unmounts.
"use client";
import { useSessionReplay } from "@/components/session-replay-provider";
export function CheckoutForm() {
// Record this form in full for everyone who reaches it,
// overriding whatever the surrounding layout asked for.
useSessionReplay({ name: "checkout", mode: "session" });
return <form>{/* ... */}</form>;
}This lets you decide what you want to record, and how often, on a per-component basis.
The name you give to a replay in this hook becomes the value of the replay.policy tag, making it easy to identify which policy captured it.
There are a couple of gotchas I’d read up on before shipping this, like how buffered replays still get sent on errors with replaysOnErrorSampleRate at 0, and why a funnel’s success screen should turn Replay off. The cookbook recipe covers those, along with the full controller code and a checklist for verifying each policy in Sentry.
One catch: a policy only takes effect once its component mounts, so you may miss hydration issues that happen in the earliest part of the render. Though we may not see that in a replay, we will capture it in Web Vitals.
What about Logs?
Logs are on by default.
Initialize Sentry and you can start sending logs, either with Sentry.logger from the SDK, or an integration like the Console Integration.
Sentry receives 100% of the logs you send.
However, if you have a lot of traffic or just different log sources, you may want to filter the logs before they are sent using Sentry’s beforeSendLog. Many other logging libraries, like LogTape, also have their own filtering and redaction mechanisms.
I recently mentioned using LogTape with the Sentry sink, which happens to be one of my favorite structured logging libraries.
import { configure, getConsoleSink } from "@logtape/logtape";
import { getSentrySink } from "@logtape/sentry";
await configure({
sinks: {
console: getConsoleSink(),
sentry: getSentrySink()
},
loggers: [
{ category: "app", lowestLevel: "debug", sinks: ["console", "sentry"] }
],
});At the most basic level, we can limit what logs are sent, per sink, based on the “severity” level.
You might have a lot of debug logs that you consume locally but don’t want to send to Sentry.
Instead, we can decide to filter out the lowest levels of logs by configuring lowestLevel.
If we carefully plan our structured logs with useful attributes, we’ll be able to use them for filtering and querying later.
import { getLogger } from "@logtape/logtape";
const logger = getLogger(["app", "api"]);
// Routine UI noise: stays local (low signal)
logger.debug("menu.opened", { "menu.name": "account" });
// Sent to Sentry: payments are a critical domain
logger.info("payment.processed", {
"payment.amount": 50,
"payment.currency": "USD",
result: "success",
});
// Sent to Sentry: it failed
logger.error("db.connect", { "db.host": "primary", result: "failure" });Using LogTape filters we can instrument our own filtering logic, including even our own built-in sampling logic if we wished.
import {
configure,
getConsoleSink,
withFilter,
type LogRecord,
} from "@logtape/logtape";
import { getSentrySink } from "@logtape/sentry";
// 1. High Signal: Always send failures, and every event in a critical domain
const CRITICAL_DOMAINS = ["payment.", "checkout."];
const isHighSignal = (record: LogRecord) => {
const event = typeof record.rawMessage === "string" ? record.rawMessage : "";
return (
record.level === "error" ||
record.level === "fatal" ||
record.properties.result === "failure" ||
CRITICAL_DOMAINS.some((domain) => event.startsWith(domain))
);
};
// 2. Random Sampling: Keep a 5% slice of regular traffic for context.
// Debug and trace logs never leave the console.
const SAMPLE_RATE = 0.05;
const isSampled = (record: LogRecord) =>
record.level !== "debug" &&
record.level !== "trace" &&
Math.random() < SAMPLE_RATE;
// 3. Env Guard: Only send to Sentry from production
const isProduction = () => process.env.NODE_ENV === "production";
await configure({
sinks: {
// The console still gets everything.
console: getConsoleSink(),
// Sentry only gets (high signal OR sampled) AND production.
sentry: withFilter(
getSentrySink(),
(record) => (isHighSignal(record) || isSampled(record)) && isProduction(),
),
},
loggers: [
{
category: ["app", "api"],
lowestLevel: "debug",
sinks: ["console", "sentry"],
},
],
});Read more about filtering and querying logs using LogTape.
Start with your most critical flow
Sampling 100% of everything is the right call when you first set up Sentry. Once traffic picks up, don’t try to tune it all at once. Pick the flow you’d be most upset to lose data on, like checkout or the feature you just shipped, and give it its own rules first. Everything else can sit on a low static rate until it gives you a reason not to.
New to Sentry? Sign up to get started, or check out our quickstart guides for Logs and Session Replay.
FAQs
Why shouldn't I just sample 100% of everything?
You can, especially if your app is small or brand new. But as you scale, capturing everything gets wasteful and noisy. Parsing through a million routine "button clicked" spans to find the 100 that actually matter isn't efficient. Plus, every interaction adds up on the network. Sampling lets you focus on high-signal data where things are critical or changing fast, while keeping stable parts of your system at lower rates.
What's the difference between tracesSampleRate and tracesSampler?
tracesSampleRate is a flat percentage applied to all traces, simple but blunt. tracesSampler is a function that lets you decide in real-time whether to sample a trace based on context like the route, user attributes, or whether the backend already made a sampling decision. If you need more control than "sample 5% of everything," use tracesSampler.
How do I make sure my frontend and backend sampling decisions stay in sync?
Use inheritOrSampleWith in your tracesSampler function. It checks if the backend already decided to sample a trace, and if so, the frontend follows that decision. If there's no upstream decision, it falls back to whatever rate you specify. This prevents "orphaned spans" where part of a trace gets sampled and part doesn't.
Can I control Session Replay sampling the same way I control trace sampling?
Not exactly. There's no replaysSampler function (yet). You can set static sample rates with replaysSessionSampleRate and replaysOnErrorSampleRate, or you can manually trigger replays using replay.start() in your code. To control replays per page, set both rates to 0 and use a React provider and useSessionReplay hook that give each section of your app its own policy: record in full, buffer and send only on errors, or skip entirely. The full code is in the Session Replay sampling cookbook recipe.
How do I sample logs without flooding Sentry?
Use beforeSendLog to filter logs by severity or custom metadata before they're sent. Better yet, adopt structured logging with a tool like LogTape so you can filter at the source based on attributes like severity level, the event name, or whether the operation failed. This way, only high-signal logs make it to Sentry.
If I sample at 5%, does that mean I'm only seeing 5% of my issues?
Not necessarily. Sampling affects volume, not visibility. Errors are usually sampled at 100% (sampleRate: 1.0), so you see every failure. For performance data, 5% gives you a representative slice of traffic. If checkout is slow, a 5% sample will still show you it's slow. You just have fewer individual spans to sift through. You just want your sample to be representative, and tracesSampler helps there by prioritizing high-impact routes.