Observability and telemetry
Reflex provides an optional OpenTelemetry path that links browser activity, backend requests, event handlers, compile work, and socket health. Framework hooks stay inactive until an instrumentor enables them. The OtelPlugin adds browser spans and trace context to the generated frontend. Reflex also has a separate opt-in path for anonymous product usage events. See Backend services, Data models and persistence, and Uploads and middleware for the server, state, request, and upload paths that can carry a trace.
Telemetry model
The telemetry system has two cooperating parts. The backend instrumentor turns on framework trace points and wraps the ASGI application. The frontend plugin adds a browser module that exports user-facing signals and links supported browser actions to backend work.
The system aims to answer three broad questions:
- What happened in the browser before a backend event or upload?
- How did the backend process the request, event, state access, or compile?
- Where did time, message size, connection count, or an error affect the user flow?
The OpenTelemetry path does not record event payloads or application state as trace data. It uses a pseudonymous session value instead of the client token, and it removes the token from recorded request URLs.
Anonymous usage telemetry
Anonymous usage telemetry is separate from OpenTelemetry tracing. When telemetry is enabled, Reflex collects product events with coarse environment and version data, then sends them through a single background worker so collection and delivery do not block the app or its event loop. Delivery is best effort. Failures are suppressed and do not change application behavior.
The usage path identifies an installation and, when available, a project with UUID-form values. It keeps the same underlying identifiers when it moves from the older numeric form, which lets historical usage remain linked without exposing a client token. The configuration flag controls whether the path collects and sends these events. The worker carries the caller's registration context so it uses the app's loaded configuration rather than loading a separate one.
References: reflex/…/telemetry.py• L196-214 reflex/…/telemetry.py• L276-365 reflex/…/telemetry.py• L438-475 reflex/…/telemetry.py• L481-501 reflex/…/telemetry.py• L544-617 reflex/…/telemetry.py• L648-753
OpenTelemetry integration
Backend instrumentation
The reflex-otel package exposes ReflexInstrumentor as the backend entry point. An engineer can call instrument() from the application process or let the standard OpenTelemetry launcher discover it through the opentelemetry_instrumentor entry point. The instrumentor enables the framework hooks and adds OpenTelemetry ASGI middleware around the application so HTTP routes and the websocket connection use the same telemetry system.
The instrumentor uses explicit OpenTelemetry providers when the application supplies them. If the application has not set providers and the standard OTEL_* exporter settings request one, it can configure the SDK from the environment. A repeated instrument() call has no effect, which makes activation safe when the application module loads more than once.
References: packages/…/instrumentor.py• L130-169 packages/…/instrumentor.py• L171-241 packages/…/pyproject.toml• L10-21
Browser instrumentation
The OtelPlugin adds the browser part of the integration during a frontend compile. It supplies a browser telemetry module, its frontend packages, and an OTEL configuration block in the generated environment data. The browser module can export event and upload producer spans, web-vital spans, socket connect and disconnect spans, and optional React render spans.
The browser endpoint is a public OTLP/HTTP destination that must allow browser requests through CORS. No endpoint means that the browser module stays present but does not export spans. Headers are part of the public bundle, so they are not a safe place for secrets.
References: packages/…/plugin.py• L18-29 packages/…/plugin.py• L98-125 packages/…/otel.js• L38-64 packages/…/otel.js• L115-145
Instrumentor lifecycle
Activation and provider selection
Instrumentation starts when ReflexInstrumentor.instrument() calls the framework telemetry boundary. That boundary binds the OpenTelemetry tracer and meter, creates the framework metrics, and stores the ASGI wrapper for later application assembly. Before this point, framework calls perform only an enabled check and produce no spans or metrics.
The activation boundary also installs a W3C trace-context reader for frontend events. It reads only the trace fields needed to link an event. This keeps untrusted event data from adding unrelated context to downstream work.
References: packages/…/otel.py• L1-14 packages/…/otel.py• L95-98 packages/…/otel.py• L165-208 packages/…/otel.py• L277-298
Deactivation and reactivation
ReflexInstrumentor.uninstrument() disables framework trace points and removes the ASGI wrapper. The framework resets its metric instruments to no-op objects, so later runtime calls do not emit data. A later activation can bind providers again and restore the hooks.
The instrumentor also honors OTEL_SDK_DISABLED=true. In that state it leaves the framework trace points off. URL filtering excludes health polling by default and can also exclude compiled frontend assets when the backend serves them.
References: packages/…/instrumentor.py• L187-189 packages/…/instrumentor.py• L200-233 packages/…/instrumentor.py• L235-241 packages/…/otel.py• L211-227
Plugin registration
Compile-time plugin hooks
The plugin follows the framework Plugin contract rather than changing the runtime directly. During compilation it registers a static browser asset and asks the compiler to modify the client entry. When render timing is enabled, it also requests the profiling React build. This lets the normal compiler own file output while the plugin contributes only the browser telemetry pieces.
The plugin is configured in the app's plugin list. The compiler calls each configured plugin's pre-compile hook and later applies its asset and file-change contributions. This makes the browser integration part of the same build lifecycle as other frontend extensions.
References: packages/…/base.py• L121-168 packages/…/base.py• L197-250 packages/…/plugin.py• L137-171 reflex/…/compiler.py• L1371-1388 reflex/…/compiler.py• L1469-1489
Runtime configuration
The plugin merges its browser settings into the generated env.json. The browser reads this configuration at startup to choose its OTLP endpoint, service name, headers, web-vital setting, render-timing setting, and sample rate. Browser traces are roots, so a sampled browser trace can make the backend event its child. An unsampled browser send does not force the backend event to remain unsampled.
References: reflex/…/build.py• L19-34 packages/…/plugin.py• L173-193 packages/…/otel.js• L38-64
Framework-level hooks
Application assembly
The application builds its API, mounted routes, custom API transforms, CORS layer, and Reflex context layer before it exposes the final ASGI application. If instrumentation is active, App.__call__ applies the stored OpenTelemetry middleware to that complete outer application. This places HTTP routes, upload requests, websocket traffic, transformer-added routes, and outer error responses inside the same server telemetry boundary.
The telemetry wrapper is therefore a framework-level hook rather than a route-specific feature. It is applied after the app has assembled the layers that can change request handling, so telemetry follows the application that users actually reach.
References: reflex/app.py• L1279-1381
Request and socket hooks
The ASGI wrapper exposes server spans and HTTP metrics for requests that reach the application. Reflex records socket message size when it serializes outgoing packets or reads incoming packets. It records an open connection when a socket connects and removes it when the socket disconnects. These measurements stay behind the enabled check, so the transport works without telemetry.
The socket event boundary also accepts bounded frontend error reports and routes valid reports through the app's frontend exception handler. Reports must come from a known session and pass both per-session and process-wide limits. This exposes client-side failures to backend logs and custom error trackers without allowing unknown or excessive socket reports to flood them.
References: reflex/app.py• L2588-2618 reflex/app.py• L2717-2749 reflex/app.py• L2835-2863 reflex/app.py• L3033-3111 packages/…/state.js• L669-709 packages/…/upload.js• L155-170
Event trace context
An event sent by the browser may carry W3C traceparent and tracestate fields. The event boundary extracts those fields before it places the event in the backend queue. The event processor then creates one handler span for the event. An event produced by another handler becomes an internal child, while a browser event is treated as an inbound consumer operation.
The event context preserves the active OpenTelemetry context when a handler forks or enqueues more work. This keeps a chain of related events connected without placing application payloads into the trace.
The following flow shows how browser context reaches event handling and related state work.
flowchart LR
B[Browser event or upload] --> P[Producer span and W3C context]
P --> R[Backend request or event boundary]
R --> H[Event handler span]
H --> S[State access and handler work]
H --> C[Chained event spans]
References: packages/…/otel.js• L100-123 reflex/app.py• L2910-2989 packages/…/context.py• L77-129 packages/…/event_processor.py• L625-652 packages/…/otel.py• L374-435
Compile and runtime signals
The framework exposes fixed trace points for the parts of its work that help explain system behavior. Event handler duration, state acquisition time, websocket message size, and open websocket count are metrics. App compilation has a parent span with child spans for major phases such as page evaluation, asset copying, package installation, and file writing.
The app records compile telemetry around the single compile boundary used by normal builds, dry runs, command-line paths, and export paths. The outer compile span covers each attempt, while completion accounting records real builds and marks failures in the active compile context. It then clears compile caches after success or failure. Socket serialization and deserialization also record wire size. These hooks help find slow handlers, state contention, large socket messages, connection churn, and slow builds without collecting the full application data that passes through the framework.
References: packages/…/otel.py• L40-61 packages/…/otel.py• L133-163 packages/…/otel.py• L437-465 reflex/app.py• L2224-2259 reflex/app.py• L2588-2618 reflex/…/compiler.py• L1207-1218 reflex/…/compiler.py• L1354-1360 reflex/…/compiler.py• L1438-1495
Trace and metric boundaries
The integration keeps browser and backend signals separate when no browser endpoint is configured. When the browser exports a sampled producer span, W3C context joins the browser action to the backend request or event. The backend can still create its own trace for an unsampled browser send.
The main telemetry boundaries are:
| Boundary | Signal | Product question |
|---|---|---|
| Browser event and upload | Producer span | Which user action sent work to the backend? |
| HTTP and websocket server | Server spans and HTTP metrics | How did the application receive the work? |
| Event processor | Handler span and duration metric | Which event handler ran and how long did it take? |
| State manager boundary | State acquisition metric | Did session state delay the handler? |
| Socket transport | Message size metric and connection count | Is transport load or reconnect churn affecting the app? |
| Frontend error boundary | Routed client error report | Which client failure reached the backend error path? |
| Compiler | Compile parent and phase spans | Which build phase makes compilation slow? |
Change checklist
When these files or sections are changed, remember to consider these:
- When event or upload payload fields change, preserve the W3C trace field contract between the browser bridge and backend extraction.
- When the generated client entry or React root changes, keep the plugin's browser load point and optional profiling wrapper valid.
- When ASGI assembly, custom API transforms, or middleware order changes, keep the telemetry wrapper around the final outer application so routes, uploads, and websocket traffic remain visible.
- When socket serialization or connection callbacks change, keep message-size and active-connection measurements tied to the enabled telemetry boundary.
- When frontend error report fields, socket event names, or session validation changes, preserve the bounded handoff to
frontend_exception_handler. - When plugin environment merging changes, keep the
OTELconfiguration shape aligned with the browser module and avoid exposing private collector settings. - When event context forking changes, preserve the captured context needed for chained event parentage.
- When metric names or attributes change, update the exporter and dashboards that rely on the stable framework telemetry contract.
- When anonymous usage event fields or identifier encoding changes, preserve the opt-in boundary, the background delivery behavior, the registration context, and the link to prior installation history.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| The browser plugin has no endpoint | Browser spans are dropped and no browser trace context reaches backend events. | Configure a browser-reachable OTLP/HTTP endpoint when browser telemetry is required. |
| The browser collector rejects cross-origin requests | Export fails in the browser and the first failure is reported as OtelExportError through the frontend error path. | Allow the app origin with collector CORS settings. |
| A browser header contains a secret | The secret is shipped in the public frontend bundle. | Use only public headers in OtelPlugin.headers. |
OTEL_SDK_DISABLED=true is set | Framework spans and metrics remain off even when the instrumentor is called. | Check the process environment when telemetry is unexpectedly absent. |
| A configured provider is replaced by repeated manual setup | OpenTelemetry may warn about provider overrides and telemetry can use an unintended provider. | Activate the instrumentor once and pass providers from one process-level setup. |
| The compiler no longer exposes the expected entry or Vite alias shape | The plugin cannot attach browser startup or render timing and compilation can fail when render timing is enabled. | Keep compiler output anchors compatible with the plugin hooks before changing frontend templates. |
| The telemetry wrapper is applied before later API transforms or is not applied to the final ASGI app | Routes, uploads, or websocket traffic can be missing from server telemetry. | Keep otel.asgi_middleware around the assembled outer app in App.__call__. |
| A client error report comes from an unknown socket or exceeds the rate limit | The report is ignored, so a real client failure may not reach the backend error path. | Keep the client connected to a valid session and inspect the bounded report path when diagnosing errors. |
| Anonymous usage telemetry runs with a blocking send on the app thread | Event handling or the server loop can pause during local data collection or network delivery. | Keep usage collection on the single-worker executor and treat delivery as best effort. |
| A telemetry job runs without the app's registration context | The worker may load a separate configuration context and collect data under the wrong app settings. | Preserve context capture when submitting background telemetry work. |
Key files
| File | Why to read it |
|---|---|
| packages/…/instrumentor.py | Defines activation, provider selection, ASGI wrapping, URL filtering, and shutdown behavior. |
| packages/…/plugin.py | Defines compile-time browser registration and the public browser configuration contract. |
| packages/…/otel.js | Shows the browser signals and how browser spans inject trace context. |
| packages/…/otel.py | Defines the framework telemetry boundary, metrics, trace context rules, and event spans. |
| packages/…/context.py | Shows how event work preserves telemetry context across chained events. |
| packages/…/event_processor.py | Shows where handler spans surround event execution. |
| reflex/app.py | Shows final ASGI assembly, compile spans, socket metrics, frontend error reporting, and inbound event context handling. |
| reflex/…/compiler.py | Shows where plugin contributions and compile phase spans enter the frontend build. |
| packages/…/state.js | Shows the client hooks for events and socket lifecycle signals. |
| packages/…/upload.js | Shows how uploads receive browser trace headers. |
| reflex/…/telemetry.py | Defines the separate opt-in path for anonymous usage events, identifier continuity, context propagation, and non-blocking delivery. |