# Tracing and performance

> Measure page loads, requests, screens and jobs with transactions and spans, follow one request across services with traceparent, and send OpenTelemetry traces.

Source: https://apphelm.dev/docs/tracing

Tracing records how long work takes and where the time goes. A **transaction** is one unit of work: a page load, a navigation, a server request, a mobile screen load or a job. **Spans** are the steps inside it: a database query, an outgoing HTTP call, a cache read. When services pass a `traceparent` header to each other, their transactions join one **trace**, so you can follow a click from the browser through your API to the database.

Every AppHelm SDK has tracing. Each transaction it sends counts as one event against your plan's allowance, so you choose how many to keep with a sample rate.

> **Automatic tracing is off until you set a rate:** In every SDK, the transactions the SDK starts for you (page loads, requests, screen loads, app starts) are not sent until you set `tracesSampleRate` (or a sampler). This keeps your event allowance safe on day one. Errors still carry a trace id without it. Transactions you start yourself are kept at a rate of 1 when no rate is set, except in React Native, where the default rate is 0.

## Turn tracing on

Set the share of new traces to keep, between 0 and 1. Start with `0.1` to `0.2` in production and raise it if you need more samples.

Next.js — app/apphelm-provider.tsx:
```tsx
"use client";
import { ApphelmProvider } from "@sansavision/apphelm/react";
import { ApphelmRouteTracing } from "@sansavision/apphelm/tracing/next";

export function AppHelm({ children }: { children: React.ReactNode }) {
  return (
    <ApphelmProvider options={{ key: process.env.NEXT_PUBLIC_APPHELM_KEY!, workspaceId: "org_…", productId: "prd_…", tracesSampleRate: 0.2 }}>
      <ApphelmRouteTracing /> {/* names navigations /orders/[id] instead of /orders/42 */}
      {children}
    </ApphelmProvider>
  );
}
```

React — src/main.tsx:
```tsx
import { ApphelmProvider } from "@sansavision/apphelm/react";

createRoot(document.getElementById("root")!).render(
  <ApphelmProvider options={{ key: import.meta.env.VITE_APPHELM_KEY, workspaceId: "org_…", productId: "prd_…", tracesSampleRate: 0.2 }}>
    <App />
  </ApphelmProvider>,
);
```

Vue / Nuxt — src/apphelm.ts:
```ts
import { createBrowserSdk } from "@sansavision/apphelm/browser";
import { trackVueRouter } from "@sansavision/apphelm/tracing/vue-router";

export const apphelm = createBrowserSdk({ key: import.meta.env.VITE_APPHELM_KEY, workspaceId: "org_…", productId: "prd_…", tracesSampleRate: 0.2 });
trackVueRouter(router); // names navigations after the route record (/orders/:id)
```

Svelte / SvelteKit — src/lib/apphelm.ts:
```ts
import { createBrowserSdk } from "@sansavision/apphelm/browser";

export const apphelm = createBrowserSdk({ key: import.meta.env.VITE_APPHELM_KEY, workspaceId: "org_…", productId: "prd_…", tracesSampleRate: 0.2 });
// In the root +layout.svelte: trackSvelteKitNavigation(afterNavigate) from "@sansavision/apphelm/tracing/sveltekit"
```

JavaScript (browser):
```js
import { createBrowserSdk } from "https://cdn.jsdelivr.net/npm/@sansavision/apphelm/dist/browser.js";

window.apphelm = createBrowserSdk({ key: "ahl_pub_…", workspaceId: "org_…", productId: "prd_…", tracesSampleRate: 0.2 });
```

React Native / Expo:
```ts
import { createReactNativeSdk } from "@sansavision/apphelm/react-native";

export const apphelm = createReactNativeSdk({
  apiKey: process.env.EXPO_PUBLIC_APPHELM_KEY!, workspaceId: "org_…", productId: "prd_…",
  storage: AsyncStorage, appState: AppState,
  tracesSampleRate: 0.2,      // default 0: no screens and no manual transactions are sent
  instrumentFetch: true,      // http.client spans for fetch (default false)
});
```

iOS (Swift):
```swift
var options = ApphelmOptions(apiKey: "ahl_live_…", workspaceId: "org_…", productId: "prd_…", tracesSampleRate: 0.2)
options.enableAppStartTracking = true          // off by default
options.enableUIViewControllerTracing = true   // off by default: swizzles UIKit
let apphelm = ApphelmClient(options: options)
```

Android (Kotlin):
```kotlin
Apphelm.setup(this, ApphelmConfig(BuildConfig.APPHELM_API_KEY, "org_…", "prd_…").apply {
    tracesSampleRate = 0.2   // screen loads, app starts and frame counts start once this is set
})
```

Flutter:
```dart
await Apphelm.setup(ApphelmConfig(apiKey: '…', workspaceId: 'org_…', productId: 'prd_…', tracesSampleRate: 0.2));
runApp(MaterialApp(navigatorObservers: [ApphelmObserver()], home: const Home()));
```

Node.js:
```ts
import { Apphelm, instrument, httpServerIntegration, httpIntegration, fetchIntegration, pgIntegration, expressRequestHandler } from "@sansavision/apphelm";

const apphelm = new Apphelm({ apiKey: process.env.APPHELM_API_KEY!, workspaceId: "org_…", productId: "prd_…", tracesSampleRate: 0.2 });
instrument(apphelm, { integrations: [httpServerIntegration(), httpIntegration(), fetchIntegration(), pgIntegration()] });
app.use(expressRequestHandler(apphelm)); // Express: first middleware
```

Python:
```python
import os, apphelm

apphelm.init(api_key=os.environ["APPHELM_API_KEY"], workspace_id="org_…", product_id="prd_…",
             traces_sample_rate=0.2)
# Django: add "apphelm_django.ApphelmMiddleware" to MIDDLEWARE. Flask: apphelm_flask.init_app(app).
```

Java / Kotlin (JVM):
```kotlin
val apphelm = ApphelmClient(ApphelmOptions(/* key, workspace, product */, tracesSampleRate = 0.2))
```

Go:
```go
client, err := apphelm.New(apphelm.Config{
	// …
	TracesSampleRate: apphelm.Float(0.2),
})
http.ListenAndServe(":8080", client.Middleware(mux))
```

Ruby:
```ruby
APPHELM = Apphelm::Client.new(api_key: ENV["APPHELM_API_KEY"], workspace_id: "org_…", product_id: "prd_…",
                              traces_sample_rate: 0.2)
# Rails: the Railtie adds the Rack middleware. Other Rack apps: use Apphelm::Rack
```

PHP:
```php
$apphelm = new Client(apiKey: getenv('APPHELM_API_KEY'), workspaceId: 'org_…', productId: 'prd_…',
    tracesSampleRate: 0.2);
```

.NET (C#):
```csharp
builder.Services.AddApphelm(options => { /* key, workspace, product */ options.TracesSampleRate = 0.2; });
app.UseApphelm(); // one http.server transaction per request
```

Rust:
```rust
let apphelm = Client::new(Options::new(std::env::var("APPHELM_API_KEY")?)
    .workspace_id("org_…").product_id("prd_…")
    .traces_sample_rate(0.2))?;
```

Elixir:
```elixir
config :apphelm,
  traces_sample_rate: 0.2
# Phoenix: `use Apphelm.Plug` in your endpoint
```

**Only for JavaScript (browser), React, Next.js, Vue / Nuxt, Svelte / SvelteKit:**

In the browser, tracing loads with error capture, so it also needs analytics consent (`setConsent({ analytics: true })`) and `errorCapture` left on. The browser has no `tracesSampler`; use `tracesSampleRate` and `ignoreTransactions`.

**Only for iOS (Swift):**

Screen loads and app starts need both their flag and a rate. The flags are off by default because they swizzle UIKit methods. Frame tracking, URLSession spans, file I/O and Core Data spans are on by default and start once a rate is set. SwiftUI screens use `.apphelmTrace("Checkout")` and need only the rate.

### Sample per transaction

A sampler decides per transaction instead of one rate for all. It gets the transaction's name, operation and the caller's decision, and returns a rate or true/false. Use it to drop health checks or keep more of an important route.

Node.js:
```ts
const apphelm = new Apphelm({
  apiKey: process.env.APPHELM_API_KEY!, workspaceId: "org_…", productId: "prd_…",
  tracesSampler: ({ name, parentSampled }) => (name.includes("/health") ? 0 : parentSampled ?? 0.2),
});
```

Python:
```python
apphelm.init(api_key=..., workspace_id="org_…", product_id="prd_…",
             traces_sampler=lambda ctx: 0 if "/health" in ctx["name"] else 0.2)
```

Android (Kotlin):
```kotlin
ApphelmConfig(/* … */).apply {
    tracesSampler = { context -> if (context.op == "ui.load") 0.5 else null } // null: use tracesSampleRate
}
```

Java / Kotlin (JVM):
```kotlin
ApphelmOptions(/* … */, tracesSampler = { context -> if (context.name.startsWith("GET /health")) 0.0 else null })
```

Go:
```go
TracesSampler: func(ctx apphelm.SamplingContext) float64 {
	if ctx.Name == "GET /health" { return 0 }
	return 0.2
},
```

Ruby:
```ruby
traces_sampler: ->(context) { context[:name].include?("/health") ? 0 : 0.2 }
```

PHP:
```php
tracesSampler: fn (array $context) => str_contains($context['name'], '/health') ? 0.0 : 0.2,
```

.NET (C#):
```csharp
options.TracesSampler = context => context.Name.Contains("/health") ? 0.0 : null; // null: use TracesSampleRate
```

Rust:
```rust
Options::new(key).traces_sampler(|ctx| if ctx.name().contains("/health") { 0.0 } else { 0.2 })
```

Elixir:
```elixir
config :apphelm, traces_sampler: fn %{name: name} -> if name =~ "health", do: 0.0, else: 0.2 end
```

The sampler's context fields differ a little by SDK (each README lists them). A sampler that throws drops the transaction in most SDKs. In the browser and React Native there is no sampler: use `ignoreTransactions` to drop by name.

## What is traced automatically

Once a rate is set, these are recorded without more code:

| Platform | Transactions | Spans and measurements |
| --- | --- | --- |
| Browser (all web frameworks) | `pageload` for each page load; `navigation` for each History API change, back/forward and hash route (`#/…`), ending after 1 s idle or 30 s at most | Document request, DOM content loaded and the 30 slowest resources on page load; `http.client` spans for `fetch` and XHR during navigations and your own transactions; TTFB and FCP |
| Node | `http.server` per request with `httpServerIntegration()`, `expressRequestHandler`, `fastifyIntegration`, Next.js `withApphelm`, `registerApphelm` | `http.client` (`httpIntegration`, `fetchIntegration`), `db.query` (`pgIntegration`, `mysql2Integration`, `prismaExtension`), Redis and cache spans (`ioredisIntegration`) |
| Python | Django, Flask, ASGI (FastAPI, Starlette) requests; Celery tasks (`queue.process`) | `requests` and `httpx` (`apphelm_http.instrument()`), SQLAlchemy and Django database spans, Celery `queue.publish` |
| Android | `ui.load` per Activity (with `ttid_ms`), `app.start.cold` and `app.start.warm`, Jetpack Navigation | Fragment loads, OkHttp (`ApphelmOkHttpInterceptor`), Room/SQLite, file I/O; slow and frozen frames on every transaction |
| iOS | UIKit screen loads, SwiftUI `.apphelmTrace`, cold and warm app starts | URLSession, file I/O, Core Data; slow and frozen frames |
| Flutter | `ui.load` per pushed route (`ApphelmObserver`), cold and warm app starts | `ApphelmHttpClient` (package:http), `ApphelmDioInterceptor` (dio); slow and frozen frames |
| React Native | `ui.load` per screen from `screen()` or the navigation tracker; cold start on the first screen when you pass `appStartedAt` | `http.client` with `instrumentFetch` |
| JVM (Kotlin/Java) | your own transactions | `traced(connection)` and `httpCall` for HTTP |
| Go | `client.Middleware` (net/http, named by the ServeMux pattern on Go 1.23+) | `client.Transport(rt)` for HTTP, `WrapSQLDriver` / `WrapSQLConnector` for `database/sql` |
| Ruby | Rack and Rails requests, Sidekiq and Active Job | `instrument_net_http!`, Active Record queries, template renders and cache calls |
| PHP | PSR-15 middleware, Symfony subscriber, Laravel `TraceRequests` | Guzzle middleware, PSR-18 `TracingHttpClient`, `TracedPdo` |
| .NET | ASP.NET Core `UseApphelm()` | `AddApphelmHttpClientInstrumentation()` / `ApphelmHttpMessageHandler`, EF Core and SqlClient with `DatabaseSpans = true` |
| Rust | `ApphelmLayer` (feature `tower`: axum, hyper, tonic) | `ApphelmTracingLayer` (feature `tracing`) turns `tracing` spans into child spans; `start_http_span` |
| Elixir | `Apphelm.Plug`, Phoenix, Oban jobs | Ecto queries, Finch requests (`Apphelm.Telemetry.attach`) |

Web vitals (LCP, INP and CLS) are sent separately from tracing: the browser SDK sends one `$web_vitals` event per page when the page is hidden, with autocapture on (the default) and analytics consent. INP there is the longest event duration seen, an upper bound.

**Only for Android (Kotlin):**

Turn single measurements off with `traceScreenLoads = false`, `traceAppStart = false`, `frameMetrics = false` or `traceFragments = false`. Set `timeToFullDisplay = true` and call `Apphelm.reportFullyDisplayed()` when the screen's content is in, to record `ttfd_ms`. A frame counts as frozen after 700 ms.

**Only for React Native / Expo:**

Call `apphelm.markInitialDisplay()` and `apphelm.markFullDisplay()` on a screen to record `ttid_ms` and `ttfd_ms`. React Native does not count slow or frozen frames on its own.

## Create transactions and spans

Wrap the work you care about. A span started while a transaction is active becomes its child. A transaction keeps at most 50 spans.

JavaScript (browser):
```ts
import { startSpan, startInactiveSpan } from "@sansavision/apphelm/tracing";

const total = await startSpan({ name: "checkout.price", op: "function", attributes: { items: 3 } }, async (span) => price(cart));
const upload = startInactiveSpan({ name: "upload", op: "task" });
/* … */
upload.end();
```

Node.js:
```ts
import { startSpan } from "@sansavision/apphelm";

const tx = apphelm.startTransaction("nightly-import", { op: "queue.process" });
const span = tx.startSpan("db.query", "select * from orders where day = ?", { "db.system": "postgresql" });
await loadOrders();
span.finish("ok");
tx.finish("ok");

// Or, inside a traced request, Sentry-style with nesting through async work:
const rows = await startSpan({ name: "load orders", op: "db.query" }, () => loadOrders());
```

Python:
```python
with apphelm.start_transaction("POST /charges", op="http.server",
                               traceparent=request.headers.get("traceparent")) as tx:
    with apphelm.start_span("db.query", "select * from orders where id = ?", data={"db.system": "postgresql"}):
        ...
    tx.set_http_status(200)
```

React Native / Expo:
```ts
const tx = apphelm.startTransaction("sync orders", { op: "task" }); // null when not sampled
const span = tx?.startSpan("http.client", "GET /api/orders");
await syncOrders();
span?.finish();
tx?.finish();
```

iOS (Swift):
```swift
let tx = apphelm.startTransaction("CheckoutScreen", op: "ui.load")
let cart = try await tx.span("http.client", description: "GET /api/cart") { span in
  var request = URLRequest(url: URL(string: "https://api.example.com/api/cart")!)
  span.propagate(&request)
  return try await URLSession.shared.data(for: request).0
}
await tx.finish()
```

Android (Kotlin):
```kotlin
val tx = Apphelm.client?.startTransaction("CheckoutScreen", op = "ui.load")
val cart = tx?.span("http.client", "GET /api/cart") { span -> loadCart() }
tx?.finish() // blocking: call it off the main thread
```

Flutter:
```dart
final tx = apphelm.startTransaction('sync orders', 'task', bindToScope: true);
final rows = await tx.trace('db.query', (span) async {
  span.setData('db.system', 'sqlite');
  return db.rawQuery('SELECT * FROM orders WHERE updated_at > ?', [since]);
}, description: 'SELECT * FROM orders WHERE updated_at > ?');
tx.finish();
```

Java / Kotlin (JVM):
```kotlin
val tx = apphelm.startTransaction("nightly-report", op = "task")
tx.span("db.sql.query", "SELECT * FROM invoices WHERE due < ?") { loadInvoices() }
tx.finish()
```

Go:
```go
ctx, tx := client.StartTransaction(ctx, "nightly-import", apphelm.WithOp("queue.process"))
defer tx.Finish()

ctx2, span := apphelm.StartSpan(ctx, "cache.get", apphelm.WithDescription("customers:index"))
span.SetData("cache.hit", true)
span.Finish()
```

Ruby:
```ruby
APPHELM.with_transaction("nightly-report", op: "function") do
  APPHELM.with_span("db.query", "SELECT * FROM invoices WHERE due < ?", data: { "db.system" => "postgresql" }) do
    load_invoices
  end
end
```

PHP:
```php
$transaction = $apphelm->startTransaction('import-feed', 'queue.process');
$apphelm->trace('cache.get', 'feed:etag', fn (\Apphelm\Tracing\Span $s) => $s->setData('cache.hit', $cache->has('feed:etag')));
$transaction->finish();
```

.NET (C#):
```csharp
using (var transaction = apphelm.StartTransaction("nightly-report", "queue.task"))
{
    using (apphelm.StartSpan("db.sql.query", "SELECT * FROM orders WHERE day = @day",
        new Dictionary<string, object?> { ["db.system"] = "postgresql" }))
    {
        await LoadOrders();
    }
}
```

Rust:
```rust
let transaction = apphelm.start_transaction(TransactionContext::new("nightly-export", "function"));
let query = transaction.start_child("db.sql.query", "SELECT * FROM orders WHERE day = $1");
query.set_data("db.system", "postgresql");
query.finish();
transaction.finish();
```

Elixir:
```elixir
alias Apphelm.Tracing

Tracing.with_transaction("nightly-report", [op: "function"], fn ->
  Tracing.with_span("db.sql.query", "SELECT * FROM orders WHERE placed_at > $1",
    %{"db.system" => "postgresql"}, fn -> Repo.all(query) end)
end)
```

**Only for JavaScript (browser), React, Next.js, Vue / Nuxt, Svelte / SvelteKit:**

A browser span started during a page load or navigation is its child; otherwise it becomes a transaction of its own. The active span follows only the callback's synchronous part, because browsers have no async context. After an `await`, pass `parentSpan` to nest explicitly. React components can add render spans with `<Profiler name="Checkout">` or `withProfiler(Component)` from `@sansavision/apphelm/react`.

### Name transactions well

- Use the route template, not the URL: `GET /orders/{id}`, not `GET /orders/42`. The router integrations and server middleware do this for you. AppHelm also replaces ids and slugs in names it receives and drops query strings.
- Keep span descriptions free of values: SQL with placeholders (`where id = ?`), `GET https://host/path` without a query. AppHelm replaces SQL literals with `?` and scrubs emails, keys and tokens from the whole description. The trace keeps up to 2,000 characters of each description, so the waterfall shows a long statement in full under **Full statement**. The Trace explorer, Queries and other span pages group and search on the first 200 characters, so put what tells two statements apart near the start. A transaction's spans share 8,000 characters past their first 200 each, slowest span first; past that a description keeps 200.
- A product keeps up to 500 distinct transaction names. Past that, new names are stored as `<other>`.

### Span attributes

Span attributes (`setAttribute`, `set_data`, `SetData`) are checked on the device: keys of letters, digits, `_`, `.` and `-`, string, number or boolean values, and at most 20 per span in the JavaScript SDKs. On the server AppHelm indexes these attributes, which power the Queries, Outbound HTTP, Caches and Queues views:

| Attribute | Used for |
| --- | --- |
| `http.request.method`, `http.response.status_code`, `server.address`, `url.full` | Outbound HTTP by domain and status |
| `db.system` | Queries by database |
| `cache.hit`, `cache.key` | Cache hit rate (the key's prefix is kept) |
| `messaging.destination.name`, `messaging.message.receive.latency` | Queues and their latency |

Other attributes are not stored with the transaction today, so don't rely on them for search. Measurements such as `ttid_ms`, `app_start_cold_ms`, `frames_slow` and the web vitals are stored and shown in the Web vitals and Mobile views.

## Distributed tracing

To follow one request across services, the caller sends its trace id in a header and the receiver continues the trace.

- **Outgoing.** Every SDK sends a W3C `traceparent` header. The browser and Node SDKs also send `baggage` with `sentry-trace_id`, `sentry-sampled`, `sentry-environment` and `sentry-release`, so services on a Sentry SDK or an OpenTelemetry baggage propagator keep the same decision. No SDK sends `sentry-trace`.
- **Incoming.** Server middleware reads `traceparent` and, failing that, Sentry's `sentry-trace`, so a service called by a Sentry-instrumented client joins the trace. The caller's sampling decision is kept.
- **Who receives the header.** The header tells the receiver your trace id, so it is sent only to hosts you list:

| SDK | Option | Default |
| --- | --- | --- |
| Browser (all web frameworks) | `tracePropagationTargets`: URL prefixes (strings) or RegExps | the page's own origin |
| Node | `tracePropagationTargets` on `instrument()`: substrings or RegExps | none |
| React Native | `tracePropagationTargets`: substrings or RegExps | none |
| Python, Ruby, Elixir | `trace_propagation_hosts` | none |
| Android, iOS, Flutter, JVM, PHP | `tracePropagationHosts` | none |
| Go, .NET | `TracePropagationHosts` | none |
| Rust | `.trace_propagation_hosts(…)` | none |

In the host lists, an entry is an exact host, or a leading dot (`.example.com`) for every host under that domain.

JavaScript (browser):
```ts
createBrowserSdk({ key: "ahl_pub_…", workspaceId: "org_…", productId: "prd_…", tracesSampleRate: 0.2,
  tracePropagationTargets: ["https://api.example.com/", /^https:\/\/[a-z]+\.example\.com\//] });
```

Node.js:
```ts
instrument(apphelm, { integrations: [httpServerIntegration(), fetchIntegration()], tracePropagationTargets: ["api.internal.example"] });
```

React Native / Expo:
```ts
createReactNativeSdk({ /* … */ tracesSampleRate: 0.2, instrumentFetch: true, tracePropagationTargets: ["api.example.com"] });
```

iOS (Swift):
```swift
options.tracePropagationHosts = ["api.example.com", ".internal.example.com"]
```

Android (Kotlin):
```kotlin
ApphelmConfig(/* … */).apply { tracePropagationHosts = listOf("api.example.com") }
val http = OkHttpClient.Builder().addInterceptor(ApphelmOkHttpInterceptor()).build()
```

Flutter:
```dart
await Apphelm.setup(ApphelmConfig(/* … */ tracePropagationHosts: ['api.example.com', '.internal.example.com']));
final client = ApphelmHttpClient();
```

Python:
```python
apphelm.init(..., trace_propagation_hosts=["api.example.com", ".internal.example.com"])
import apphelm_http; apphelm_http.instrument()   # requests and httpx carry traceparent
```

Go:
```go
TracePropagationHosts: []string{"api.example.com"},
// then: httpClient := &http.Client{Transport: client.Transport(http.DefaultTransport)}
```

Ruby:
```ruby
APPHELM = Apphelm::Client.new(…, trace_propagation_hosts: ["api.example.com"])
```

PHP:
```php
new Client(/* … */ tracePropagationHosts: ['api.example.com', '.internal.example.com']);
```

.NET (C#):
```csharp
options.TracePropagationHosts.Add("api.example.com");
builder.Services.AddHttpClient("api").AddApphelmHandler();
```

Rust:
```rust
Options::new(key).trace_propagation_hosts(["api.example.com"])
```

Elixir:
```elixir
config :apphelm, trace_propagation_hosts: ["api.example.com"]
```

> **Cross-origin requests need CORS headers:** When the browser sends `traceparent` and `baggage` to another origin, that server's CORS preflight must allow them: `Access-Control-Allow-Headers: traceparent, baggage`. Without it the browser blocks the request. This is why the browser default is your own origin only. Add an origin to `tracePropagationTargets` only after its server allows the headers.

To continue a trace that the server started (so the page load joins the request that rendered it), render a `<meta name="traceparent" content="…">` tag in the page. A sampled one is continued whatever the rate. Sentry's `sentry-trace` and `baggage` meta tags work too.

## Send OpenTelemetry traces

If a service already uses OpenTelemetry, send its traces to AppHelm with the OTLP/HTTP exporter. No AppHelm SDK is needed.

```bash
export OTEL_EXPORTER_OTLP_TRACES_ENDPOINT="https://apphelm.dev/api/v1/traces"
export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer ahl_live_…,x-apphelm-product=prd_…"
export OTEL_SERVICE_NAME="checkout-api"
```

- **Endpoint:** `POST https://apphelm.dev/api/v1/traces`, an `ExportTraceServiceRequest` as protobuf (`application/x-protobuf`) or JSON (`application/json`). An exporter whose base endpoint is `https://apphelm.dev/api` appends `/v1/traces` itself.
- **Key:** a server key with `events:write`.
- **Product:** the `x-apphelm-product` header, `?productId=`, the `apphelm.product_id` resource attribute, or the key's only product.
- **Mapping:** a span with no parent, a parent outside the request, or kind SERVER or CONSUMER becomes a transaction; the others become its spans (50 per transaction). `service.version` becomes the release and `deployment.environment` the environment. Numeric attributes of the entry span named like a measurement (`lcp`, `fcp_ms`, `cls`, `ttfb`, `app_start_cold`, `time_to_initial_display`, `frames_slow` …, in milliseconds) are stored as its measurements. The operation comes from `sentry.op` or from the span's HTTP, database, cache, messaging or RPC attributes.
- **Limits:** 5 MB per request (20 MB unzipped with `Content-Encoding: gzip`), 10,000 spans and 2,000 transactions per request. Each transaction counts as one event.
- **Response:** OTLP's `partialSuccess` with `rejectedSpans` and an `errorMessage` when some spans were not stored.

HTTP (curl):
```bash
curl -X POST https://apphelm.dev/api/v1/traces \
  -H "Authorization: Bearer $APPHELM_API_KEY" \
  -H "x-apphelm-product: prd_…" \
  -H "Content-Type: application/json" \
  --data '{"resourceSpans":[{"resource":{"attributes":[{"key":"service.name","value":{"stringValue":"checkout-api"}}]},"scopeSpans":[{"spans":[{"traceId":"4bf92f3577b34da6a3ce929d0e0e4736","spanId":"00f067aa0ba902b7","name":"GET /orders/{id}","kind":2,"startTimeUnixNano":"1767225600000000000","endTimeUnixNano":"1767225600120000000","attributes":[{"key":"http.request.method","value":{"stringValue":"GET"}},{"key":"http.route","value":{"stringValue":"/orders/{id}"}}]}]}]}]}'
```

Sentry SDKs pointed at an AppHelm DSN also send transactions; [Migrate from Sentry](https://apphelm.dev/docs/migrate-sentry) covers that. AppHelm keeps a Sentry transaction's 50 longest spans.

## See your traces

Open **Performance** in the app. Its tabs:

| Tab | Shows |
| --- | --- |
| Transactions | The 50 busiest transaction names with throughput, p50/p75/p95 duration, failure rate and Apdex, plus the 5 slowest, 5 newest and 5 newest failed samples of each |
| Trace explorer | Every indexed span, searchable, as spans, traces or aggregates |
| Queries | Database spans by statement |
| Outbound HTTP | `http.client` spans by domain |
| Caches | Hit rate and latency of cache spans |
| Queues | Publish and process spans with their latency |
| Web vitals | p75 LCP, INP, CLS, FCP and TTFB per page, rated good (LCP 2.5 s, INP 200 ms, CLS 0.1, FCP 1.8 s, TTFB 800 ms) or poor (4 s, 500 ms, 0.25, 3 s, 1.8 s) |
| Mobile | App starts by release, screen loads with TTID and TTFD, slow and frozen frame rates |

Open a sample to see its waterfall: every transaction in the trace, across services, with errors linked to the span they happened in. If the transaction was [profiled](https://apphelm.dev/docs/profiling), **Show profile** adds its flame graph. The Apdex threshold is 300 ms by default; owners and admins can change it (10 to 60,000 ms). The views cover up to 30 days at a time.

Search spans in the Trace explorer with `key:value` terms joined by spaces: `span.op`, `span.description`, `transaction`, `span.status`, `span.duration`, `span.module`, `span.domain`, `http.status_code`, `http.method`, `db.system`, `cache.hit`, `cache.key`, `messaging.destination`, `release`, `environment` and `trace`. Put `!` or `-` in front of a term to exclude it.

### Read traces through the API

HTTP (curl):
```bash
# One trace, every transaction and up to 1,000 spans
curl https://apphelm.dev/api/v1/traces/4bf92f3577b34da6a3ce929d0e0e4736 \
  -H "Authorization: Bearer $APPHELM_API_KEY"

# Search spans
curl "https://apphelm.dev/api/v1/spans?productId=prd_…&query=span.op:db.query&range=24h&sort=-duration&limit=20" \
  -H "Authorization: Bearer $APPHELM_API_KEY"
```

Both need a server key with `issues:read`. `GET /api/v1/spans` takes `range` (`1h`, `24h`, `7d`, `14d`, `30d`) or `from`/`to`, `sort` (`-timestamp`, `-duration`, `duration`), `limit` (1 to 100, default 50) and `cursor`, and allows 60 searches a minute per key. There is no endpoint that lists traces; search spans and open a trace by its id. See the [API reference](https://apphelm.dev/docs/api).

## Retention and limits

| What | Limit |
| --- | --- |
| Transactions and their duration histograms | Your plan's capture retention: 14 days (Free), 30 (Builder), 90 (Portfolio), 365 (Scale) |
| Span index (Trace explorer, Queries, HTTP, Caches, Queues) | 30 days, or capture retention if shorter; 5,000 indexed spans per product per day (later spans stay in their transaction) |
| Spans per transaction | 50 |
| Distinct transaction names per product | 500, then `<other>` |
| Span description | 2,000 characters in the trace, 200 in the span index; a transaction's spans share 8,000 characters past their first 200, slowest first |
| Transaction duration | up to 1 hour |

## Best practices

- **Sample, don't trace everything.** Each transaction is one event. 10 to 20 percent is usually enough to see p95 latency; use a sampler to keep all of a rare, important route.
- **Propagate only to your own services.** List your API hosts; never `.com` or a third party.
- **Start with the integrations.** The server middleware and HTTP and database integrations cover most of what you want to see. Add manual spans for the parts they can't see: a slow calculation, a queue wait.
- **Use the same release and environment** in every service, so Performance can compare releases. See [Releases and release health](https://apphelm.dev/docs/release-health).
- **Upload source maps and symbols** so profiles and errors linked from a trace show your code. See [Source maps and debug symbols](https://apphelm.dev/docs/source-maps).

## Troubleshooting

| Symptom | Likely cause | What to do |
| --- | --- | --- |
| No transactions at all | No `tracesSampleRate` or sampler is set | Set `tracesSampleRate` (for example `0.2`) where you create the client |
| No page loads in the browser | Analytics consent hasn't been given, or `errorCapture: false` | Call `setConsent({ analytics: true })` from your banner, and leave error capture on |
| No screen loads on iOS | The tracing flags are off by default | Set `enableUIViewControllerTracing` and `enableAppStartTracking`, or use `.apphelmTrace` in SwiftUI |
| React Native sends no manual transactions | The default rate there is 0 | Set `tracesSampleRate`; `startTransaction` returns null for unsampled transactions |
| The backend's transaction is not in the browser's trace | The API's host is not in `tracePropagationTargets`, or its CORS blocks `traceparent` | Add the host, and allow `traceparent, baggage` in `Access-Control-Allow-Headers` |
| A cross-origin request fails after enabling propagation | The server's CORS preflight rejects the new headers | Allow `traceparent` and `baggage` on that server, or remove its origin from `tracePropagationTargets` |
| Thousands of transaction names, or `<other>` | Names contain ids or query strings | Use the route template; add the router integration for your framework |
| OTLP export answers 403 `scope_denied` | The key lacks `events:write` | Use a server key with `events:write` ([Keys, scopes and environments](https://apphelm.dev/docs/keys-and-environments)) |
| OTLP export answers 422 `product_required` | The key covers several products and none was named | Send `x-apphelm-product: prd_…` or set the `apphelm.product_id` resource attribute |
| OTLP export answers 429 | Too many requests for one key (`rate_limited`) or the plan's allowance is used (`event_limit`) | Batch more spans per request (the batch span processor does); lower the sample rate or upgrade |
| A custom attribute is missing in search | Only the indexed attributes above are stored | Put the value in the span's description or operation, or send it as a [log](https://apphelm.dev/docs/logs) line with the trace id |
