services
Get a key

library / Integrations / I0050

OpenTelemetry RPC latency tracing

A Node script wraps the Solana RPC transport so each call becomes an OpenTelemetry span with method, status and duration, keeps a rolling p95 per method, and prints a switch or stay decision before a slow endpoint turns into timeouts at a drop.

By Carbium · Search and time series · I0050 · updated 2026-11-22

01

What each span records

A span is the record of one call: when it started, how long it took, what it was and how it ended. The OpenTelemetry conventions for JSON-RPC name three attributes that carry the failover decision, and the span's own status and duration complete it. The code adds one more attribute, rpc.duration_ms, which holds the same duration as a plain number.

AttributeExampleWhy it is kept
rpc.systemjsonrpcSeparates RPC spans from database and HTTP spans in the same trace store.
rpc.methodgetLatestBlockhashMethods do different work, so one p95 across all of them lets a fast method hide a slow one.
server.addressthe endpoint hostTells primary spans from second-endpoint spans after a switch.
span statusOK or ERRORA node that answers every call with a JSON-RPC error body is still a failing node, however fast it replies.
durationend minus startThe number the rolling window stores.

The duration comes from performance.now, a monotonic clock, while the start and end stamps come from the wall clock. A clock adjustment on the host can shift a stamp but never produces a negative duration. The span holds no request params and no key. Params can contain addresses, and the key travels in a header that the wrapper never reads.

02

Where the wrapper sits

@solana/kit builds its RPC client from a transport: a function that takes the JSON payload and returns the parsed response. The wrapper is a second function with the same signature placed around the HTTP transport. It reads the method from the payload, starts the clock, awaits the real call and records the span in a finally block, so a thrown error is timed too.

Every method the client exposes goes through that one function. A call added next month is traced the day it is written, and no call site needs an edit. Timing in each handler would also include your own code, such as a database write between two RPC calls, and the p95 would then describe your handler more than the endpoint.

Failures show up in two forms. An HTTP status such as a 401 or a 429 makes the transport throw. A JSON-RPC error arrives as a normal response body with an error field, so the wrapper checks for that field and marks the span ERROR. Without the check, an endpoint that rejects every call would produce a tidy run of fast green spans.

03

The rolling window and its threshold

The decision reads the last 20 durations for each method and drops the oldest as new ones arrive. One slow call is noise, and a mean hides the tail. A p95 says that one call in twenty took at least this long, which is the number a user at a drop feels as a hang.

The code uses the nearest-rank rule: sort the window and take the value at position ceil(0.95 * n). With 100 samples, five calls sit above it. With 20, one does. With the ten samples this script collects per method, the p95 is the slowest call, so treat the demo output as a shape and size the window for production at 100 or more.

  • Switch when any method has at least ten samples and a p95 above P95_LIMIT_MS.
  • Switch when three calls have failed, whatever the durations say.
  • Failed calls stay out of the window, so a burst of fast errors cannot pull the p95 down.

The default limit of 750 ms is a placeholder. Run the script during a quiet hour, read the p95 per method, and set the limit at a few times that figure. In the live service, require the condition to hold for two windows in a row before flipping, so a single stalled connection does not move traffic.

The probe asks for getSlot, getHealth and getLatestBlockhash ten times each. getSlot and getHealth are cheap cached reads that cost 1 cell, at 5 req/s on Free. The script waits 200 ms after each call, so one call every 200 ms plus its own duration stays under that rate.

04

The tracer

Install the one dependency with npm install @solana/[email protected] and set "type": "module" in package.json. Node 24 strips the types on load. CARBIUM_KEY is required. CARBIUM_RPC_URL defaults to the RPC endpoint, and P95_LIMIT_MS is optional.

main.ts
// I0050 · OpenTelemetry RPC latency tracing// https://carbium.sh/library/integrate/opentelemetry-rpc-latency-tracing// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { createDefaultRpcTransport, createSolanaRpcFromTransport } from "@solana/kit";const key = process.env.CARBIUM_KEY;if (!key) {  console.error("Set CARBIUM_KEY first: CARBIUM_KEY=<key> node main.ts");  process.exit(1);}const url = process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh";const limitMs = Number(process.env.P95_LIMIT_MS ?? 750);const rounds = 10;const windowSize = 20;const attr = (k: string, v: string | number) => ({ key: k, value: typeof v === "number" ? { doubleValue: v } : { stringValue: v } });const nanos = (ms: number) => `${Math.round(ms)}000000`;const spans: object[] = [];const windows = new Map<string, number[]>();let failures = 0;const base = createDefaultRpcTransport({ url, headers: { "x-api-key": key } });// One wrapper around the transport: every call kit makes passes through it.const traced = async <T>(config: Parameters<typeof base>[0]): Promise<T> => {  const method = (config.payload as { method: string }).method;  const startMs = Date.now();  const t0 = performance.now();  let failed = true;  try {    const res = await base<T>(config);    failed = typeof res === "object" && res !== null && "error" in res; // JSON-RPC errors arrive as a normal body    return res;  } finally {    const ms = performance.now() - t0;    if (failed) failures++;    else windows.set(method, [...(windows.get(method) ?? []), ms].slice(-windowSize));    const traceId = crypto.randomUUID().replace(/-/g, "");    spans.push({      traceId,      spanId: traceId.slice(0, 16),      name: `solana.rpc ${method}`,      kind: 3,      startTimeUnixNano: nanos(startMs),      endTimeUnixNano: nanos(startMs + ms),      attributes: [attr("rpc.system", "jsonrpc"), attr("rpc.method", method), attr("server.address", new URL(url).hostname), attr("rpc.duration_ms", ms)],      status: { code: failed ? 2 : 1 },    });  }};const rpc = createSolanaRpcFromTransport(traced);const calls: Record<string, () => Promise<unknown>> = {  getSlot: () => rpc.getSlot().send(),  getHealth: () => rpc.getHealth().send(),  getLatestBlockhash: () => rpc.getLatestBlockhash().send(),};const pct = (xs: number[], p: number) => [...xs].sort((a, b) => a - b)[Math.ceil(p * xs.length) - 1];async function main() {  await createSolanaRpcFromTransport(base).getHealth().send().catch(() => {}); // untimed: opens the connection  for (let i = 0; i < rounds; i++) {    for (const [name, call] of Object.entries(calls)) {      try {        await call();      } catch (e) {        console.error(`${name} failed: ${e instanceof Error ? e.message : String(e)}`);      }      await new Promise((r) => setTimeout(r, 200));    }  }  const resource = { attributes: [attr("service.name", "mint-backend")] };  console.log(JSON.stringify({ resourceSpans: [{ resource, scopeSpans: [{ scope: { name: "rpc-latency" }, spans }] }] }));  let slow = failures >= 3;  for (const [method, xs] of windows) {    const p95 = pct(xs, 0.95);    slow = slow || (xs.length >= rounds && p95 > limitMs);    console.log(`${method}: n=${xs.length} p50=${pct(xs, 0.5).toFixed(1)} ms p95=${p95.toFixed(1)} ms`);  }  console.log(`decision: ${slow ? "switch to the second endpoint" : "stay on the primary"} (p95 limit ${limitMs} ms, ${failures} failed calls)`);}main();

run: node main.ts

The first line of output is one OTLP JSON body: a resourceSpans envelope holding 30 spans of kind 3 (client), the shape an OTLP/HTTP collector accepts at /v1/traces. Sending it is one fetch POST with content-type: application/json. The script prints its spans and sends nothing to a collector, so the run needs none. Then come the p50 and p95 for each method and the decision line.

One untimed getHealth call opens the connection first, so DNS and TLS setup do not land in a window. getSlot and getLatestBlockhash leave commitment out, so kit sends confirmed. getHealth takes no commitment.

05

What a switch does and what it leaves alone

In the service, the decision flips one value: the URL that the transport factory reads from a small object holding the primary and a second endpoint. New calls follow it. The second endpoint is any RPC URL you already hold access to, and this script never calls it. Give it its own wrapper and its own window, so you can compare the two p95 values before you move.

  • Reads move at once. getLatestBlockhash, getSlot and account reads can be repeated on another endpoint with no harm.
  • A transaction already sent stays tied to its signature. Do not build a second transaction for the same mint because the first send timed out: it may already be in a block. Ask the new endpoint for getSignatureStatuses on the first signature, and rebuild only after that blockhash has expired.
  • A timed-out sendTransaction span records the wait. The send may still land, so check its signature before acting on it.
  • A 429 means the account is over its rate, a Free key is over its network's shared budget, or the endpoint had no free capacity. Honour retry-after before counting it toward a switch. A 401 means the key is unknown: send the whole key, because switching endpoints does not fix it.
  • Switch back only after the primary, probed in the background with the same spans, holds a p95 under the limit for a full window. Add a minimum time on the second endpoint to prevent flapping.
$Probe the primary at the rate of the mint traffic your backend sends during a drop. A switch decided from idle traffic reacts to different conditions than one decided from your real load.

For a sibling of this idea in a build pipeline, see RPC latency CI gate. To serve the same figures to a scrape job, the exporter shape in Prometheus program activity counters applies.

06

Where it ends

  • Ten rounds from one machine measure the path from that machine to the endpoint. A backend in another region sees other numbers, so run the probe where your backend runs.
  • This is a probe, and the wrapper only helps your mint flow once it sits in the process that handles the mints.
  • At a drop, a span per call is a lot of data: sample the spans and keep the window as a metric.
  • The p95 is computed from a small window, so one slow call can trip it on a short run. That is why the live rule asks for two windows in a row.
  • Timing sees the response, and it cannot see a transaction that lands late. Confirmation delay needs its own measure, from signature status.
  • A second endpoint reads the same chain. A congested network slows both of them, and the p95 comparison between the two is what tells the cases apart.
07

When it goes wrong

what goes wrongwhat to do
Every span shows ERROR and the first failure line carries a short message.An unknown key gets 401 at the door: send the whole key in CARBIUM_KEY. A method the endpoint does not serve answers -32601, and retrying it does not help, so check the method name.
The p95 jumps right after the process sat idle.A closed connection pays DNS and TLS again, and that is real latency users would see. With a window this small, one reconnect trips the limit, so use a larger window and require two bad windows before a switch.
The decision says switch, but the second endpoint is just as slow.Probe both with the same spans before flipping. Move only when the second endpoint's p95 sits below the primary's.
A call cancelled by your own timeout shows ERROR with a duration equal to the timeout.That is intended. It counts toward the failure total and stays out of the window, so a run of timeouts trips the switch through the failure count.
After a failover the same mint appears twice.A new transaction was built while the first was still able to land. Check the first signature with getSignatureStatuses on the new endpoint, and rebuild only once its blockhash has expired.
08

Questions

Why time at the transport and not in each handler?

One wrapper sees every call, including ones added later, and its duration excludes your own code. A handler timer mixes the endpoint with whatever else the handler does.

Does the tracing slow the calls down?

The wrapper adds a few clock reads and one small span object per call. Exporting should happen in batches off the request path, never inside the wrapper.

Can the same wrapper time a second endpoint?

Yes. Create a second transport with the other URL and a separate window, then compare the two p95 values before you switch.

How many samples before I trust a p95?

Ten samples make the p95 the slowest call. At 100 samples five calls sit above it, which is a stable enough tail to act on.