Files
supabase/apps/docs/content/guides/observability/client-side-tracing.mdx
Guillaume Faas 411e81bbd6 docs(csharp): update Client-Side Tracing guide for C# (#53928)
This PR updates the Client-Tracing Guide for C#, with the latest updates
from the tracing initiative.
2026-11-24 11:22:11 +02:00

438 lines
27 KiB
Plaintext
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
id: 'client-side-tracing'
title: 'Client-side tracing'
description: 'Propagate W3C trace context from the Supabase JS, Swift, Dart, Python, and C# SDKs through Supabase services'
---
The [Supabase JS](/docs/reference/javascript/introduction), Swift, Dart, Python, and C# SDKs can attach [W3C Trace Context](https://www.w3.org/TR/trace-context/) headers (`traceparent`, `tracestate`, `baggage`) to outgoing requests. The resulting `trace_id` flows through Supabase services and appears in API Gateway and [Edge Function](/docs/guides/functions) logs, so you can correlate client-side spans with the server-side logs they produced — end-to-end, across the network boundary.
Because the headers follow the W3C standard, any compliant tracing SDK (such as OpenTelemetry, Sentry, Datadog, or Honeycomb) can pick up the trace on the server side, including in self-hosted collectors. The C# SDK also emits its own spans and metrics, described in the C# tab. On the client side, some vendor SDKs need a small configuration change before they emit the standard headers — see [Using a vendor tracing SDK](#using-a-vendor-tracing-sdk) in the JavaScript tab.
<Tabs
scrollable
size="small"
type="underlined"
defaultActiveId="js"
queryGroup="language"
>
<TabPanel id="js" label="JavaScript">
## Requirements
- `@supabase/supabase-js` version `2.106.0` or later
- `@opentelemetry/api` available at runtime — either installed directly or pulled in as a transitive dependency of your tracing SDK
- A tracing SDK that registers a W3C-compliant propagator with the OpenTelemetry API
<Admonition type="caution">
As of `@supabase/supabase-js` version `2.112.0`, the OpenTelemetry integration lives in an opt-in subpath that you load once at your application entry point:
```ts
import '@supabase/supabase-js/tracing'
```
The main bundle contains no OpenTelemetry code — this import is what wires it up. The subpath imports `@opentelemetry/api` directly, so your bundler includes it and module resolution fails loudly if it isn't installed. If `tracePropagation` is enabled without this import, the SDK logs a one-time warning and sends requests without trace headers.
On versions `2.106.0`–`2.111.x`, the subpath doesn't exist — don't add the import there. Those versions load `@opentelemetry/api` dynamically and silently no-op when it's missing.
</Admonition>
Trace propagation isn't available through the CDN (UMD) build — there's no way to load the tracing runtime there.
## Set up OpenTelemetry first
The SDK reads from whatever `TracerProvider` you register globally — it doesn't configure one for you. If you haven't instrumented your app yet, follow the [OpenTelemetry JavaScript getting started guide](https://opentelemetry.io/docs/languages/js/getting-started/) to install an SDK (`@opentelemetry/sdk-trace-node` for Node, `@opentelemetry/sdk-trace-web` for browsers) and an exporter for your backend (OTLP, Jaeger, Zipkin, or a vendor-specific one).
The Supabase SDK only propagates the trace context that's already active when a request is made.
## Enable trace propagation
Trace propagation is opt-in and takes two steps: load the tracing runtime at your entry point (version `2.112.0` and later), and pass `tracePropagation: true` when creating the client:
```ts
import '@supabase/supabase-js/tracing'
import { trace } from '@opentelemetry/api'
import { createClient } from '@supabase/supabase-js'
const supabase = createClient(SUPABASE_URL, SUPABASE_KEY, {
tracePropagation: true,
})
const tracer = trace.getTracer('my-app')
await tracer.startActiveSpan('fetch-users', async (span) => {
// Outgoing request carries the active trace context.
const { data, error } = await supabase.from('users').select('*')
span.end()
})
```
For security, trace headers are only attached to requests targeting Supabase domains (`*.supabase.co`, `*.supabase.in`, and `localhost` for local development). Third-party hosts called through a custom `fetch` are never tagged.
<Admonition type="note">
Calling Edge Functions from the browser with trace propagation enabled requires the function's CORS allow-list to include the trace headers. In the function, import `corsHeaders` from `npm:@supabase/supabase-js@^2.112.3/cors` or add `traceparent`, `tracestate`, and `baggage` to your own allow-list, then redeploy the function. See [CORS support for Edge Functions](/docs/guides/functions/cors).
</Admonition>
## Advanced configuration
Pass an object instead of `true` for fine-grained control:
```ts
import '@supabase/supabase-js/tracing'
const supabase = createClient(SUPABASE_URL, SUPABASE_KEY, {
tracePropagation: {
enabled: true,
// Default: true. Non-sampled requests carry only `traceparent` (with the
// sampled flag preserved, so nothing is recorded downstream) — log
// correlation keeps working while `tracestate` and `baggage` are withheld.
// Set to false to always send the full trace context regardless of sampling.
respectSamplingDecision: false,
},
})
```
| Option | Type | Default | Description |
| ------------------------- | --------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `enabled` | `boolean` | `false` | Enable trace propagation. |
| `respectSamplingDecision` | `boolean` | `true` | When `true`, non-sampled requests send only `traceparent` (sampled flag preserved) and omit `tracestate` and `baggage`; `false` always sends the full trace context. On versions before `2.112.3`, `true` skipped all trace headers for non-sampled requests. |
## Using a vendor tracing SDK
Many tracing SDKs are built on top of OpenTelemetry, but they differ in whether their propagator emits the standard `traceparent` header by default:
| Vendor setup | Works with `tracePropagation`? | Required configuration |
| --------------------------------------------------------------- | -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| OpenTelemetry SDK (also Honeycomb, Grafana, New Relic via OTLP) | Yes | None — the W3C propagator is the default |
| Sentry (Node.js, including Next.js server-side) | Yes, with one flag | Set `propagateTraceparent: true` in `Sentry.init()` — Sentry's propagator omits `traceparent` by default |
| Sentry (browser) | Via Sentry's own instrumentation | Set `propagateTraceparent: true` and add your project URL (`https://<ref>.supabase.co`) to `tracePropagationTargets` — Sentry's browser SDK only attaches headers cross-origin for listed targets. For Edge Functions, also add `sentry-trace` to the function's CORS allow-list: Sentry always sends its own header, and it isn't part of `corsHeaders` |
| Datadog `dd-trace` (Node.js) | Out of the box | None — `dd-trace` injects W3C headers at the HTTP layer itself, even without `tracePropagation` |
| Datadog Browser RUM | Yes, with configuration | Add your project URL to `allowedTracingUrls` with the `tracecontext` propagator type |
If a propagator is active but doesn't emit `traceparent`, the SDK logs a one-time console warning naming the headers the propagator wrote (version `2.112.3` and later).
## Troubleshooting
The SDK never throws when it can't propagate, which keeps it safe to enable but can mask configuration issues. If `trace_id` is missing from your Supabase logs, check these in order:
- **The tracing runtime isn't loaded** (version `2.112.0` and later). `tracePropagation` is enabled but your entry point never imports `@supabase/supabase-js/tracing`. The SDK logs a one-time console warning and sends requests without trace headers — look for that warning in your console.
- **No active span at request time.** The SDK reads the _current_ context. If `supabase.from(...)` is called outside `tracer.startActiveSpan(...)` (or equivalent), there's nothing to propagate. Wrap the call in a span or use OpenTelemetry's automatic instrumentation.
- **`@opentelemetry/api` is not installed** in the app making the request. On `2.112.0` and later the tracing subpath imports it directly, so a missing package surfaces as a module resolution error. On `2.106.0`–`2.111.x` it's loaded dynamically and the SDK silently no-ops.
- **No `TracerProvider` registered.** `@opentelemetry/api` defaults to a noop provider that produces non-recorded spans. Ensure your app calls `provider.register()` (or your vendor SDK's equivalent) before making requests.
- **Your tracing SDK's propagator doesn't emit W3C `traceparent`.** Sentry's propagator, for example, only emits it when `propagateTraceparent: true` is set. From version `2.112.3` the SDK logs a one-time warning naming the headers the propagator wrote — see [Using a vendor tracing SDK](#using-a-vendor-tracing-sdk).
- **The upstream trace is not sampled** (versions before `2.112.3`). Older versions skip all trace headers when the upstream trace is not sampled. From `2.112.3`, non-sampled requests still carry `traceparent`, so log correlation keeps working by default. Set `respectSamplingDecision: false` to always send the full trace context.
- **You're calling a non-Supabase host through a custom `fetch`.** Trace headers are only attached to Supabase domains (`*.supabase.co`, `*.supabase.in`, `localhost`).
- **You're using the CDN (UMD) build.** Trace propagation isn't available there — the tracing runtime can't be loaded from a script tag.
</TabPanel>
<TabPanel id="swift" label="Swift">
Requires `supabase-swift` `2.51.0` or later and `swift-tools-version: 6.1` or later (SwiftPM trait support).
1. **Add the `OpenTelemetry` trait** to your dependency declaration in `Package.swift`:
```swift
// Package.swift
.package(
url: "https://github.com/supabase/supabase-swift.git",
from: "2.51.0",
traits: ["OpenTelemetry"]
)
```
No changes to `SupabaseClient` are required. After enabling the trait, the active OpenTelemetry span's trace context is automatically injected as a `traceparent` header on every outgoing request across PostgREST, Storage, Auth, Functions, and Realtime. When there is no active span, the header is not added.
2. **Register a `TracerProvider`** at app start. The SDK reads from whatever provider you register globally:
```swift
import Supabase
import OpenTelemetryApi
import OpenTelemetrySdk
let exporter = /* your OTLP / Jaeger / Zipkin exporter */
let spanProcessor = SimpleSpanProcessor(spanExporter: exporter)
let provider = TracerProviderBuilder()
.add(spanProcessor: spanProcessor)
.build()
OpenTelemetry.registerTracerProvider(tracerProvider: provider)
```
3. **Create your `SupabaseClient`**. Any active span is now propagated automatically:
```swift
let supabase = SupabaseClient(
supabaseURL: URL(string: "https://xyzcompany.supabase.co")!,
supabaseKey: "your-publishable-key"
)
```
</TabPanel>
<TabPanel id="dart" label="Dart">
Requires `supabase` `2.x` or later (Flutter or Dart-only).
1. **Implement a `traceContextProvider`** that returns the current `TraceContext` from your tracing library. Return `null` when there is no active span.
2. **Pass `TracePropagationOptions`** when creating the client:
```dart
import 'package:supabase/supabase.dart';
final supabase = SupabaseClient(
'https://xyzcompany.supabase.co',
'your-publishable-key',
tracePropagationOptions: TracePropagationOptions(
enabled: true,
traceContextProvider: () {
final span = YourTracer.activeSpan;
if (span == null) return null;
return TraceContext(
traceparent: span.traceparent,
tracestate: span.tracestate,
);
},
),
);
```
For `supabase_flutter`, pass the same option through `Supabase.initialize`:
```dart
await Supabase.initialize(
url: 'https://xyzcompany.supabase.co',
anonKey: 'your-publishable-key',
tracePropagationOptions: TracePropagationOptions(
enabled: true,
traceContextProvider: () => yourTraceContextProvider(),
),
);
```
## Options
| Option | Type | Default | Description |
| ------------------------- | ----------------------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `enabled` | `bool` | `false` | Enable trace propagation. |
| `respectSamplingDecision` | `bool` | `true` | When `true`, skips propagation if the upstream trace is not sampled. Set to `false` to always attach a `trace_id` — useful for log correlation even when traces are not exported. |
| `traceContextProvider` | `TraceContextProvider?` | `null` | Callback returning the current `TraceContext`. Return `null` when there is no active span. |
Headers are only injected on requests targeting Supabase hosts (`*.supabase.co`, `*.supabase.in`, your project host, and loopback addresses for local development). Third-party hosts never receive trace headers.
</TabPanel>
<TabPanel id="python" label="Python">
The Python `opentelemetry` propagation is handled entirely through the `opentelemetry-instrumentation-httpx` package.
1. **Add** the `opentelemetry-sdk` and `opentelemetry-instrumentation-httpx` package:
```sh
uv add opentelemetry-sdk opentelemetry-instrumentation-httpx
```
2. **Instrument** the `httpx` client using the `HTTPXClientInstrumentor`:
```python
from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor
HTTPXClientInstrumentor().instrument()
```
<Admonition type="note">
This will instrument all `httpx` clients in your process. If you want to instrument only the Supabase client, you can use `HTTPXClientInstrumentor.instrument_client` in the specific sub-package client you want to trace.
</Admonition>
3. **Create** your `SupabaseClient`. Any active span is now propagated automatically:
```python
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from supabase import AsyncClient
trace.set_tracer_provider(TracerProvider())
tracer = trace.get_tracer(__name__)
async def query(client: AsyncClient):
with tracer.start_as_current_span("orchestral_query") as span:
await client.table("orchestral_sections") \
.select("name, instruments(name)") \
.order("name", desc=True, foreign_table="instruments") \
.execute()
```
</TabPanel>
<TabPanel id="csharp" label="C#">
Requires `supabase-csharp` `8.15.0` or later. The Auth, Database, Storage, and Edge Functions clients propagate trace context. Realtime does not.
The C# SDK has no dependency on OpenTelemetry. It reads `Activity.Current` from `System.Diagnostics`, so any OpenTelemetry setup, or a plain `ActivityListener`, can supply the trace.
1. **Add** the OpenTelemetry packages to your app:
```sh
dotnet add package OpenTelemetry.Extensions.Hosting
dotnet add package OpenTelemetry.Exporter.OpenTelemetryProtocol
```
2. **Register the Supabase sources** with your tracer provider. `SupabaseDiagnostics.SourceNames` lists the sources of all four clients:
```csharp
using System.Linq;
using OpenTelemetry.Trace;
using Supabase;
builder.Services.AddOpenTelemetry()
.WithTracing(tracing => tracing
.AddSource(SupabaseDiagnostics.SourceNames.ToArray())
.AddOtlpExporter());
```
The OTLP exporter reads its endpoint and headers from the standard `OTEL_EXPORTER_OTLP_*` environment variables.
3. **Create your `SupabaseClient`**. When there is an active `Activity`, the SDK sets the `traceparent`, `tracestate`, and `baggage` headers on each request. It never overwrites a header you already set.
```csharp
var supabase = new Supabase.Client(url, key);
await supabase.InitializeAsync();
using var activity = MyActivitySource.StartActivity("load-messages");
var response = await supabase.From<Message>().Get();
```
To stop the SDK from adding these headers, set `SupabaseOptions.TracePropagation`:
```csharp
var options = new Supabase.SupabaseOptions
{
TracePropagation = Supabase.Core.Http.TracePropagation.Disabled
};
var supabase = new Supabase.Client(url, key, options);
```
This option controls only what the SDK injects. The .NET runtime has its own injection for `HttpClient`, which you control through `DistributedContextPropagator.Current`.
## SDK spans and metrics
Unlike the other SDKs, the C# SDK also records its own spans and metrics. Nothing is recorded until something subscribes, so without a listener the instrumentation does no work.
Each client exposes one `ActivitySource` and one `Meter` that share a name. Register the name for tracing, for metrics, or for both. Names are case-sensitive, so use the constants.
| Client | Constant | Name |
| --------- | --------------------------------- | -------------------- |
| Auth | `GotrueDiagnostics.SourceName` | `supabase.gotrue` |
| Database | `PostgrestDiagnostics.SourceName` | `supabase.postgrest` |
| Storage | `StorageDiagnostics.SourceName` | `supabase.storage` |
| Functions | `FunctionsDiagnostics.SourceName` | `supabase.functions` |
To export metrics as well as traces, add the meters to the provider from step 2:
```csharp
builder.Services.AddOpenTelemetry()
.WithTracing(tracing => tracing
.AddSource(SupabaseDiagnostics.SourceNames.ToArray())
.AddOtlpExporter())
.WithMetrics(metrics => metrics
.AddMeter(SupabaseDiagnostics.SourceNames.ToArray())
.AddOtlpExporter());
```
### Spans
Every HTTP request the SDK sends produces a client span named `{METHOD} {path}`, for example `POST /auth/v1/token`. A 4xx or 5xx response, or an exception, sets the span status to `Error`.
| Tag | Value |
| --------------------------- | ------------------------------------------------------------------------------ |
| `http.request.method` | The HTTP method |
| `server.address` | The host |
| `server.port` | The port, only when it is not the default for the scheme |
| `url.full` | `scheme://host[:port]/path`, never with the fragment or user info |
| `http.response.status_code` | The response status code |
| `error.type` | The status code for a 4xx or 5xx response, or the exception type for a failure |
Each client adds its own tags and spans:
- **Database:** spans carry these tags:
- `supabase.postgrest.operation` holds the logical operation (`select`, `insert`, `update`, `upsert`, `delete`, or `rpc`). Several operations share an HTTP method, so use this tag to tell them apart. A count is reported as `select`.
- `supabase.postgrest.table` holds the table name, on table calls.
- `supabase.postgrest.function` holds the function name, on RPC calls.
The `url.full` tag includes the query string with its values redacted. Keys are kept and every value becomes `REDACTED`, except the values of `select`, `order`, `limit`, and `offset`. For example, `?select=id,email&email=eq.john@doe.com&order=created_at.desc&limit=10` is recorded as `?select=id,email&email=REDACTED&order=created_at.desc&limit=10`. The client percent-encodes the query it sends, so a comma appears as `%2c`. For Auth, Storage, and Functions, the query string is not yet recorded.
- **Storage:** upload and download spans carry `storage.transfer.direction` (`upload` or `download`). A resumable (TUS) upload is one span for the whole transfer, not one per chunk.
- **Functions:** the `faas.invoked_name` tag holds the name of the invoked function. A relay error is a failed span even when the HTTP status is a success.
- **Auth:** each public operation produces a span of its own, named `gotrue.*` (for example `gotrue.sign_in`, `gotrue.refresh_session`, or `gotrue.verify_otp`), with the HTTP span as its child. These spans can carry `gotrue.provider`, `gotrue.otp.channel`, `gotrue.sign_out.scope`, and similar tags. Each value is a category such as a provider name, never a credential or a user identifier.
### Metrics
All metrics are histograms.
| Metric | Unit | Measures |
| ---------------------------------------- | ---- | ------------------------------------------------------ |
| `supabase.gotrue.http.request.duration` | `s` | Duration of Auth HTTP requests |
| `http.client.request.duration` | `s` | Duration of Database HTTP requests |
| `supabase.storage.http.request.duration` | `s` | Duration of Storage requests other than file transfers |
| `supabase.storage.transfer.duration` | `s` | Duration of file uploads and downloads |
| `supabase.storage.transfer.size` | `By` | Bytes moved by file uploads and downloads |
| `supabase.functions.invoke.duration` | `s` | Duration of function invocations |
The Database metric `http.client.request.duration` is on the `supabase.postgrest` meter. Its attributes are `http.request.method`, `server.address`, `server.port`, `url.scheme`, `supabase.postgrest.operation`, and `supabase.postgrest.table` or `supabase.postgrest.function`. It also carries `http.response.status_code` when the request got a response, and `error.type` when it failed. It has no `url.path` and never carries a URL.
Every measurement from the other clients carries `http.request.method`, `server.address`, and `url.path`. It also carries `http.response.status_code` when the request got a response, and `error.type` when it failed. Storage transfers add `storage.transfer.direction`, and Functions measurements add `faas.invoked_name`.
### Without the OpenTelemetry SDK
The same sources work with the listeners in `System.Diagnostics`, with no extra package:
```csharp
using System;
using System.Diagnostics;
using System.Linq;
using Supabase;
using var activityListener = new ActivityListener
{
ShouldListenTo = source => SupabaseDiagnostics.SourceNames.Contains(source.Name),
Sample = (ref ActivityCreationOptions<ActivityContext> _) => ActivitySamplingResult.AllData,
ActivityStopped = activity => Console.WriteLine(
$"{activity.OperationName} {activity.Duration.TotalMilliseconds}ms {activity.Status}")
};
ActivitySource.AddActivityListener(activityListener);
```
Use a `MeterListener` the same way for metrics. The duration histograms record `double` values, and `supabase.storage.transfer.size` records `long` values, so register a callback for each type.
### Privacy
- URLs are recorded as `scheme://host[:port]/path`. The fragment and user info are never recorded. For Database, the query string is redacted: keys are kept and values are replaced with `REDACTED`, except for `select`, `order`, `limit`, and `offset`. For Auth, Storage, and Functions, the query string is never recorded, because query strings can hold grant types, API keys, and signed URL tokens.
- No tag ever holds an access token, refresh token, API key, request body, response body, row data, or file contents.
- Function names and Storage object paths are recorded because they are part of the URL path. Payloads and file contents are not.
- The SDK doesn't send telemetry anywhere. It goes only to the listeners and exporters that you register.
### Realtime
The Realtime client emits no spans or metrics and doesn't propagate trace context. To observe a connection, use `supabase.Realtime.AddStateChangedHandler`, `supabase.Realtime.AddHeartbeatHandler`, or pass an `ILoggerFactory` as `SupabaseOptions.LoggerFactory`. Realtime logs lifecycle events such as connect, disconnect, reconnect, heartbeat timeout, and channel state changes. It never logs credentials, tokens, payloads, or the query string of the endpoint.
</TabPanel>
</Tabs>
## Correlating with Supabase logs
After trace context is flowing through, the `trace_id` appears in:
- **API Gateway logs** — every request to PostgREST, Auth, Storage, and Realtime
- **Edge Function logs** — invocations and any structured logs emitted from within the function
If you forward Supabase logs to a third-party backend via [Log Drains](/docs/guides/observability/log-drains), you can join Supabase logs to your own client and server traces using the shared `trace_id`. This is especially useful for self-hosted setups where you already operate your own OpenTelemetry collector — Supabase logs become first-class citizens in your existing tracing UI.