Streamed SpansNEW
Learn how to use stream mode to send spans to Sentry as they finish, removing the 1,000-span limit and making trace data visible sooner.
By default, the Sentry SDK collects all spans in memory and sends them to Sentry as a single transaction once the root span ends. This is called transaction mode. Stream mode changes this by sending spans to Sentry in batches as they finish, instead of waiting for the whole transaction to complete.
You can find the following span types mentioned throughout this page:
- Root span: The topmost span in a trace. It has no parent span, and sampling decisions are made here.
- Service span: The top-level span within a service boundary. It has no local parent, but it can have a remote parent in another service. Pass
parentSpan: nullto create one. It's the stream mode equivalent of a transaction. The first service span in a trace is also its root span. - Child span: Any span nested under a parent span within the same trace.
This graph shows how these span types relate to each other within a trace:
Trace
│
└── Root span [service A]
├── Child span
│ └── Child span
└── Service span [service B]
├── Child span
└── Child span
Trace
│
└── Root span [service A]
├── Child span
│ └── Child span
└── Service span [service B]
├── Child span
└── Child span
You need:
- Tracing configured in your app
- Sentry SDK
>=9.23.0
For most apps, switching to stream mode requires no code changes beyond the initial opt-in. Automatic instrumentation switches to the streaming span APIs for you.
If you use custom instrumentation or transaction-specific configuration, follow these steps:
- Enable stream mode.
- Replace
Sentry.startTransactionandISentrySpan.startChildwith the streaming span APIs. - Replace span data and tags with attributes.
- Replace
beforeSendTransactionandignoreTransactionswithbeforeSendSpanandignoreSpans. - Verify the migration.
See the Migration Guide for complete before-and-after examples.
Copy the following prompt and paste it into your AI agent:
Follow ___CURRENT_URL___ to enable and migrate to span streaming in the Sentry SDK.
Follow ___CURRENT_URL___ to enable and migrate to span streaming in the Sentry SDK.
Opt in by setting traceLifecycle to SentryTraceLifecycle.stream when initializing the SDK. This is the only required config change:
import 'package:flutter/widgets.dart';
import 'package:sentry_flutter/sentry_flutter.dart';
Future<void> main() async {
await SentryFlutter.init(
(options) {
options.dsn = '___PUBLIC_DSN___';
options.tracesSampleRate = 1.0;
// Enables stream mode
options.traceLifecycle = SentryTraceLifecycle.stream;
},
appRunner: () => runApp(const MyApp()),
);
}
import 'package:flutter/widgets.dart';
import 'package:sentry_flutter/sentry_flutter.dart';
Future<void> main() async {
await SentryFlutter.init(
(options) {
options.dsn = '___PUBLIC_DSN___';
options.tracesSampleRate = 1.0;
// Enables stream mode
options.traceLifecycle = SentryTraceLifecycle.stream;
},
appRunner: () => runApp(const MyApp()),
);
}
To revert to transaction mode, remove the option or set traceLifecycle to SentryTraceLifecycle.static (the default).
Use only the APIs for the tracing mode you choose. Calls to APIs from the other mode are ignored:
- In
streammode, transaction APIs (Sentry.startTransaction,ISentrySpan.startChild) are ignored. - In
staticmode, the new span APIs (Sentry.startSpan,Sentry.startSpanSync, andSentry.startInactiveSpan) are ignored.
Auto-instrumentations switch to the correct API automatically based on this setting. This includes Flutter's frames tracking, app start, TTID/TTFD, navigation, user interaction, HTTP, database, and GraphQL instrumentations.
The SDK instruments common operations for you, but you can wrap your own code in spans to measure anything that matters to your app.
Use Sentry.startSpan to create a span that ends automatically when the callback completes:
final result = await Sentry.startSpan(
'my-operation',
(_) async {
// Your code here
return await doWork();
},
attributes: {
'my.attribute': SentryAttribute.string('value'),
},
);
final result = await Sentry.startSpan(
'my-operation',
(_) async {
// Your code here
return await doWork();
},
attributes: {
'my.attribute': SentryAttribute.string('value'),
},
);
Child spans created inside the callback are automatically associated with the parent through zones:
await Sentry.startSpan('parent-operation', (_) async {
await Sentry.startSpan('child-step-1', (_) async {
await stepOne();
});
await Sentry.startSpan('child-step-2', (_) async {
await stepTwo();
});
});
await Sentry.startSpan('parent-operation', (_) async {
await Sentry.startSpan('child-step-1', (_) async {
await stepOne();
});
await Sentry.startSpan('child-step-2', (_) async {
await stepTwo();
});
});
By default, a span inherits the currently active span as its parent. To change this, pass parentSpan:
parentSpan: nullforces a service span with no local parent.parentSpan: someSpanparents the new span under a specific span.
// force a new service span
await Sentry.startSpan(
'checkout-flow',
(span) async {
await runCheckout();
},
parentSpan: null,
);
// start a child span with a specific parent
final parent = Sentry.startInactiveSpan(
'background-sync',
parentSpan: null,
);
try {
await someOtherAsyncBoundary();
await Sentry.startSpan(
'fetch-page',
(child) async {
await api.fetchPage();
},
parentSpan: parent,
);
} finally {
parent.end();
}
// force a new service span
await Sentry.startSpan(
'checkout-flow',
(span) async {
await runCheckout();
},
parentSpan: null,
);
// start a child span with a specific parent
final parent = Sentry.startInactiveSpan(
'background-sync',
parentSpan: null,
);
try {
await someOtherAsyncBoundary();
await Sentry.startSpan(
'fetch-page',
(child) async {
await api.fetchPage();
},
parentSpan: parent,
);
} finally {
parent.end();
}
Sentry.startSpan takes an asynchronous callback (returning Future<T>). For synchronous work, use Sentry.startSpanSync, which takes a synchronous callback (returning T). Both variants can be freely nested, and parent-child relationships resolve correctly across sync and async boundaries:
final config = Sentry.startSpanSync('parse-config', (_) {
return Config.parse(raw);
});
final config = Sentry.startSpanSync('parse-config', (_) {
return Config.parse(raw);
});
If a span isn't sampled, the callback still runs and receives a no-op span, so all span operations remain safe to call.
Use Sentry.startInactiveSpan when the work can't be wrapped in a single callback — widget lifecycles, stream subscriptions, or platform channel round-trips. You have to call end() manually, and other spans do not automatically become its children — to nest a span under it, pass it explicitly via parentSpan when starting the child.
final paymentSpan = Sentry.startInactiveSpan(
'payment',
attributes: {'payment.provider': SentryAttribute.string('stripe')},
);
// ...later, from a different entry point
void onPaymentComplete() {
paymentSpan.end();
}
final paymentSpan = Sentry.startInactiveSpan(
'payment',
attributes: {'payment.provider': SentryAttribute.string('stripe')},
);
// ...later, from a different entry point
void onPaymentComplete() {
paymentSpan.end();
}
When the real start or end of the work happened before you could create or end the span (for example, a duration measured by a platform channel) pass startTimestamp or an explicit end time:
// startTimestamp is available on the callback variants
Sentry.startSpanSync('replay-import', (_) => importRows(),
startTimestamp: measuredStart);
final paymentSpan = Sentry.startInactiveSpan('payment');
// ...native reports the work ended at `nativeEnd`
paymentSpan.end(endTimestamp: nativeEnd);
// startTimestamp is available on the callback variants
Sentry.startSpanSync('replay-import', (_) => importRows(),
startTimestamp: measuredStart);
final paymentSpan = Sentry.startInactiveSpan('payment');
// ...native reports the work ended at `nativeEnd`
paymentSpan.end(endTimestamp: nativeEnd);
Attach structured metadata to spans using typed SentryAttribute values.
You can set attributes when starting a span:
Sentry automatically sets several standard attributes on spans. To avoid accidentally overwriting these, refer to our Sentry Attribute Conventions.
await Sentry.startSpan(
'process-order',
(_) async {
await processOrder();
},
attributes: {
'sentry.op': SentryAttribute.string('queue.process'),
'order.id': SentryAttribute.string('abc-123'),
'order.item_count': SentryAttribute.int(5),
'order.priority': SentryAttribute.bool(true),
},
);
await Sentry.startSpan(
'process-order',
(_) async {
await processOrder();
},
attributes: {
'sentry.op': SentryAttribute.string('queue.process'),
'order.id': SentryAttribute.string('abc-123'),
'order.item_count': SentryAttribute.int(5),
'order.priority': SentryAttribute.bool(true),
},
);
Or add them to an already running span with setAttribute or setAttributes. Use removeAttribute to remove an attribute:
await Sentry.startSpan('handle-request', (span) async {
span.setAttribute(
'http.response.status_code',
SentryAttribute.int(200),
);
span.setAttributes({
'http.route': SentryAttribute.string('/api/users'),
'user.id': SentryAttribute.string('user-42'),
});
await handleRequest();
});
await Sentry.startSpan('handle-request', (span) async {
span.setAttribute(
'http.response.status_code',
SentryAttribute.int(200),
);
span.setAttributes({
'http.route': SentryAttribute.string('/api/users'),
'user.id': SentryAttribute.string('user-42'),
});
await handleRequest();
});
In transaction mode, tags set on the scope are applied to the transaction. In stream mode, tags aren't applied to spans. You don't need to remove existing tags because they still apply to error events, but you should add attributes for data that's also relevant to spans.
Use Sentry.setAttributes to attach attributes to the current scope. The SDK automatically includes them on spans created from that scope:
Sentry.setAttributes({
'org_id': SentryAttribute.string(user.orgId),
'user_tier': SentryAttribute.string(user.tier),
'service': SentryAttribute.string('checkout'),
});
Sentry.setAttributes({
'org_id': SentryAttribute.string(user.orgId),
'user_tier': SentryAttribute.string(user.tier),
'service': SentryAttribute.string('checkout'),
});
Error handling is automatic: if the callback throws (or its future errors), the span status is set to error before the span ends and the error is rethrown. Otherwise the status defaults to ok.
Status can only be SentrySpanStatusV2.ok or SentrySpanStatusV2.error:
await Sentry.startSpan('sync', (span) async {
if (!await isReachable()) {
span.status = SentrySpanStatusV2.error;
return;
}
await sync();
});
await Sentry.startSpan('sync', (span) async {
if (!await isReachable()) {
span.status = SentrySpanStatusV2.error;
return;
}
await sync();
});
In stream mode, breadcrumbs are no longer sent with spans. They remain attached to errors, so you don't need to change how you record them.
You can shape what ends up in Sentry by filtering span data or dropping spans entirely.
To modify or redact span data before it's sent, use beforeSendSpan:
options.beforeSendSpan = (span) {
span.removeAttribute('http.request.body');
};
options.beforeSendSpan = (span) {
span.removeAttribute('http.request.body');
};
To prevent specific spans from being sent, use ignoreSpans. Rules are evaluated at span start and match against the span name. Attribute-based matching is not yet supported.
options.ignoreSpans = [
IgnoreSpanRule.nameEquals('health-check'),
IgnoreSpanRule.nameStartsWith('internal.'),
IgnoreSpanRule.nameContains('metrics'),
IgnoreSpanRule.nameEndsWith('.bg'),
];
options.ignoreSpans = [
IgnoreSpanRule.nameEquals('health-check'),
IgnoreSpanRule.nameStartsWith('internal.'),
IgnoreSpanRule.nameContains('metrics'),
IgnoreSpanRule.nameEndsWith('.bg'),
];
When an ignored span has children, the children are re-parented to the nearest recording ancestor rather than dropped.
If you use tracesSampleRate, no changes are needed — it works the same way in stream mode.
If you use a custom tracesSampler, the shape of the sampling context is different in stream mode. Instead of a transaction context, read the span's name and attributes from samplingContext.spanContext:
options.tracesSampler = (samplingContext) {
final spanContext = samplingContext.spanContext;
if (spanContext.name == 'health-check') {
return 0.0;
}
return 0.2;
};
options.tracesSampler = (samplingContext) {
final spanContext = samplingContext.spanContext;
if (spanContext.name == 'health-check') {
return 0.0;
}
return 0.2;
};
Only service spans are sampled and child spans inherit the service span's decision. When a service span isn't sampled, its callback still executes with a no-op span, so all span operations remain safe to call.
Automatic trace propagation for outgoing requests continues to work in stream mode.
See Trace Propagation for configuration and supported integrations.
To make sure you've enabled stream mode successfully:
- Check the Sentry dashboard: Spans should appear in the Traces view shortly after they complete. Traces look similar to transaction mode, but contain spans instead of transactions. Spans are buffered briefly and flushed in batches, so expect a short delay before they appear.
- Check your logs: If the SDK logs warnings about unsupported span operations, you may still be using the legacy Span API somewhere in your code. See the Migration Guide to update it.
Our documentation is open source and available on GitHub. Your contributions are welcome, whether fixing a typo (drat!) or suggesting an update ("yeah, this would be better").