Skip to main content

[JavaScript] How can I ensure my custom span is sampled when the parent span is sampled out?

Issue

I create custom spans (for example queue work) that I want Sentry to capture even when the parent span is sampled out by tracesSampleRate.

Applies To

  • All SaaS Customers and Self-Hosted Users

  • JavaScript SDK

  • Performance Monitoring

Resolution

By default, child spans inherit the parent sampling decision. If the parent span is not sampled, those children are not sent.

To always sample specific custom spans, use a tracesSampler and return 1 for those spans. This can override a parent’s negative sampling decision. Overriding parent sampling can break distributed-trace continuity, so limit it to spans you intentionally want as their own sampled roots.

Sentry.init({
  tracesSampler: ({ name, attributes, inheritOrSampleWith }) => {
    if (name === "queue.process" || attributes?.["messaging.system"]) {
      return 1;
    }
    return inheritOrSampleWith(0.1);
  },
});Sentry.startSpan({ name: "queue.process", op: "queue.process" }, () => {
  // your work
});

If you also need the custom span to appear as its own transaction in the Sentry UI, pass forceTransaction: true to startSpan, startSpanManual, or startInactiveSpan:

Sentry.startSpan(
  {
    name: "queue.process",
    op: "queue.process",
    forceTransaction: true,
  },
  () => {
    // your work
  },
);

forceTransaction does not replace tracesSampler when you only use tracesSampleRate. Under tracesSampleRate, an unsampled parent still causes the forced transaction to inherit that negative decision. forceTransaction is not available in stream mode. Use parentSpan: null there if you need a service-entry span.

Did this answer your question?