The Span: Every Field, and Which Three Are Load-Bearing

Identity: Three IDs and Nothing Else

FieldSizeRule
trace_id16 bytes / 128 bitsRequired. Identical on every span of the trace. All-zeroes is invalid — in OTLP and in W3C traceparent alike.
span_id8 bytes / 64 bitsRequired. Assigned at span creation. All-zeroes is invalid.
parent_span_id8 bytesThe parent's span_id. Empty on a root span — the OTLP proto says "if this is a root span, then this field must be empty."

Why 128 bits for the trace id and only 64 for the span id? Because they have different uniqueness requirements. A span_id only needs to be unique within one trace — tens to thousands of spans — where the birthday-collision probability at 1000 spans is about 1000²/2⁶⁵ ≈ 3×10⁻¹⁴. A trace_id needs to be unique across every trace in your retention window, and randomly generated ids collide by the birthday bound n²/2^(b+1). At a billion traces a day:

64-bit: 10¹⁸ / 2⁶⁵ ≈ 2.7% chance of a collision per day  ·  128-bit: 10¹⁸ / 2¹²⁹ ≈ 1.5×10⁻²¹

A 2.7% daily collision rate means two unrelated requests merge into one nonsense trace roughly every five weeks — rare enough that nobody catches it, common enough to be real. Dapper used 64-bit ids for both; Zipkin and early Jaeger inherited that. W3C Trace Context standardized on 128 bits and specified the migration rule: a system with a shorter id "SHOULD" incorporate it "at the rightmost part of a trace-id" and left-pad the original identifier with zeroes.

name — the Most-Violated Rule in the Spec

The span name is the operation, and the OTel API spec is explicit that it "MUST be the most general string that identifies a (statistically) interesting class of Spans, rather than individual Span instances," explicitly prioritizing generality over human-readability. The spec's own examples:

Span nameVerdict
getToo general — every operation collapses into one bucket
get_account/42Too specific — one distinct name per account
get_accountGood — put account_id=42 in an attribute
get_account/{accountId}Good — the route template, not the URL

The HTTP semantic conventions make this concrete: a server span is named {method} {http.route} — GET /users/:userID — and the route "MUST be low-cardinality and include all static path segments, with dynamic path segments represented with placeholders." If no route is available, the name is just the method. Never the URL.

Why this is not pedantry: span name is the primary aggregation dimension in every tracing backend, and it is almost always an indexed, per-value keyspace. Putting /user/12345 in the name turns one index entry into one per user, and the index — not the span data — is what makes trace storage expensive (see Trace Storage).

SpanKind — the Field Everyone Ignores and the Backend Depends On

In one line: SpanKind tells the backend what role this span played in a conversation between two parties — so it knows which spans to glue together into a service map, and which ones were actually waiting on something.

Which gives five values — one decision rule each, and one consequence each:

KindSet it whenWhat the backend does with it
SERVERYou are receiving a remote requestMarks a service entry point — the nodes on the dependency graph, and the spans backends count as "a request arrived here."
CLIENTYou are making one and waiting for the answerMarks a service exit. Pairs with the remote SERVER span to form one edge.
PRODUCERYou are dropping a message on a queue or topicSuppresses critical-path reasoning: the proto notes "there is often no direct critical path latency relationship between producer and consumer spans."
CONSUMERYou are picking one upSame — must not be drawn as blocking the producer.
INTERNALNone of the above. The default.Not a hop. Excluded from the dependency graph; contributes to the parent's gap analysis (see Reading a Trace).

When you set it: kind is an argument to Tracer.Start() — there is no span.setKind() in any SDK. It is fixed before the span runs a single line, which is why the sampler can see it at root-span time (see Head-Based Sampling), and why getting it wrong is an edit to the creation site plus a redeploy. Omitting it is a decision, not an omission: that span is INTERNAL, permanently.

Where you set it: only at the two points where bytes cross a socket — SERVER on the span that begins when the framework hands your process a decoded request, CLIENT on the span that wraps handing a request to a transport and blocking on the reply. Everything strictly between those two points is INTERNAL, however important the function is. In practice you will rarely type either one: middleware and the HTTP/gRPC/DB/Redis client libraries set them. The spans you hand-write are almost always the INTERNAL ones — and that is correct.

Worked Example — A calls B, B calls C

checkout-api (A) receives POST /checkout, does real work in-process, and calls pricing-svc (B) over HTTP; B reads Postgres and calls inventory-svc (C) over gRPC; C reads Redis. Back in A, a payment is charged and an event published. Kinds in the left gutter, who sets each one on the right:

KIND        SPAN                                       SET BY
─────────── ────────────────────────────────────────── ────────────────────
checkout-api  (A)
SERVER      POST /checkout                             framework middleware
INTERNAL     ├─ validateCart                           you
INTERNAL     ├─ computeCartTotal                       you
INTERNAL     │   └─ applyPromotions                    you
CLIENT       ├─ GET /price/{sku} ───────────┐          http client lib
                                            │ edge A → B
pricing-svc   (B)                             │
SERVER       │  └─ GET /price/{sku} ◄───────┘          framework middleware
INTERNAL     │     ├─ loadPricingRules                 you
CLIENT       │     ├─ SELECT FROM price_table          postgres driver
INTERNAL     │     ├─ applyPricingRules                you
CLIENT       │     └─ inventory.Stock/Get ──┐          grpc client interceptor
                                            │ edge B → C
inventory-svc (C)                             │
SERVER       │        └─ Stock/Get ◄────────┘          grpc server interceptor
INTERNAL     │           ├─ reserveFromWarehouse       you
CLIENT       │           └─ HGET stock:{sku}           redis client lib

back in checkout-api (A), once B has answered
CLIENT       ├─ POST /charge ───────────────┐          http client lib
                                            │ edge A → payments
payments-svc                                  │
SERVER       │  └─ POST /charge ◄───────────┘          framework middleware
INTERNAL     ├─ persistOrder                           you
PRODUCER     └─ order.placed publish                   kafka producer lib
                  ... A's trace is done; nobody is waiting ...
email-svc, 40 seconds later
CONSUMER        order.placed receive                   kafka consumer lib
INTERNAL         └─ renderAndSendEmail                 you
  1. Every span you wrote is INTERNAL. Seven hand-written application spans — validateCart, computeCartTotal, applyPromotions, loadPricingRules, applyPricingRules, reserveFromWarehouse, persistOrder — and not one is a hop. They exist to answer "where did the 200ms inside this handler go." That is their whole job.

  2. CLIENT means "a socket is involved," not "another team owns it." The Postgres query and the Redis HGET are CLIENT spans exactly like the gRPC call, and both databases become nodes on the service map. The field encodes the process boundary, not the microservice boundary.

  3. A countable invariant. Each network hop contributes exactly two non-INTERNAL spans, one per side. Five hops here — A→B, B→pg, B→C, C→redis, A→payments — so ten, plus the producer/consumer pair. More CLIENT+SERVER spans than 2× your hops means someone labelled business logic as a hop.

Pairing those two spans per hop is not bookkeeping — the difference between them is the only measurement you will ever get of what happened outside both processes:

                  0ms       15ms      30ms      45ms      60ms
                  |---------|---------|---------|---------|--
checkout-api
  c3  CLIENT      [========================================]  62.9ms
pricing-svc
  c5  SERVER             [============================]       44.2ms
                  <----->                             <--->
                  request                             response
                  in flight                           in flight

    62.9 - 44.2 = 18.7ms  DNS, TCP, TLS, the wire, LB queue,
                          connection-pool wait, (de)serialization

The TOTAL is derivable from two numbers the backend already has, using
only each machine's own clock. The SPLIT is not: deciding how much was
the request leg vs the response leg means comparing a clock on one
machine against a clock on another (see: The Trace). The 18.7ms is measured; the
two arrows above are drawn.

Where the kind appears in code — and where it conspicuously doesn't:

✓ pricing-svc — the kinds you don't type

# SERVER: created by the middleware when the
# request lands. It extracts traceparent, sets
# kind=SERVER, names it "GET /price/{sku}".
FastAPIInstrumentor.instrument_app(app)

# CLIENT (x2): set by the library, not by you.
Psycopg2Instrumentor().instrument()
GrpcInstrumentorClient().instrument()

@app.get("/price/{sku}")
def price(sku: str):
    # INTERNAL -- by saying nothing at all.
    # The default, and it is correct.
    with tracer.start_as_current_span(
            "loadPricingRules") as s:
        s.set_attribute("pricing.tier", tier)
        rules = db.query(...)   # CLIENT child
                                # appears here
    with tracer.start_as_current_span(
            "applyPricingRules"):
        p = evaluate(rules, sku)

    stock = stub.Get(sku)       # CLIENT child

✓ The case where you must type it yourself

# A bespoke protocol, a vendor SDK with no
# instrumentation, a raw socket -- nothing is
# going to set the kind for you.

with tracer.start_as_current_span(
        "inventory.Stock/Get",
        kind=SpanKind.CLIENT,   # <- the one line
        attributes={            #    that draws
          "rpc.system": "grpc", #    the edge
          "rpc.service": "inventory.Stock",
          "server.address": "inventory-svc",
        }) as span:
    inject(carrier)     # traceparent goes on
                        # the wire INSIDE span
    resp = sock.call(carrier, payload)

# Keep the CLIENT span innermost: it wraps the
# injection and the blocking wait, nothing
# else. Retry loops and response parsing go in
# an INTERNAL parent, never in the CLIENT span.

Note server.address on the right. A CLIENT span names the far node, which is what lets the backend draw an edge to an uninstrumented callee — a managed database, a third-party API — where no SERVER span will ever arrive to pair with it. It is also why mislabelling is expensive: kind plus that attribute is enough to invent a node that exists nowhere.

One shape that looks like a violation and isn't: an API gateway or proxy is SERVER and CLIENT in the same process — SERVER for the inbound leg, a CLIENT child for the outbound leg. That is the correct encoding of a pass-through node, and it is how the gateway gets an in-edge and an out-edge instead of being a dead end on the map.

Timing — a Span Stores Two Clock Readings, Not a Duration

A span records when it started and when it ended. It never records how long it took. Duration is arithmetic that the reader does afterwards:

start_time_unix_nano    1757848200123456789
end_time_unix_nano      1757848200167654321
                        ───────────────────
duration  (derived)              44,197,532 ns   =  44.2 ms

both fields are fixed64: 8 bytes each, nanoseconds since
1970, stored at full width rather than varint-compressed

Storing two absolute instants instead of one elapsed time looks like a small encoding choice. It is the single decision that makes a waterfall possible — and it is the reason a waterfall can lie to you. Three consequences, in increasing order of how much trouble they cause:

  1. It buys you a shared time axis. Because every span is stamped in absolute time, spans from 23 different machines can be laid out against one ruler — which is exactly what a waterfall is. An elapsed-time field could tell you a span took 44 ms, but never where those 44 ms sat relative to anything else.

  2. That ruler is only as good as the machines' agreement about the time. The timestamps are read from the wall clock, not a monotonic one. So if the clock jumps mid-span — an NTP correction, a VM live-migration, a leap second — a span can be exported with end < start: a negative duration, on the wire, from working code.

  3. Nothing fixes that across processes. Some SDKs patch it inside one process — Go's time.Time carries a hidden monotonic reading, so a Go span's duration survives a clock step even when its absolute timestamps don't. But two spans on two hosts have no shared reference at all, and OTLP has no field for expressing clock uncertainty. The backend receives two timestamps and must simply trust them. The Trace part is about what goes wrong when it shouldn't have.

Status — Unset Is the Normal Ending

Three values: Unset, Ok, Error. The spec's rules are narrower than most people assume:

RuleSource
Instrumentation libraries "SHOULD leave the status code as Unset unless there is an error," and "SHOULD NOT set the status code to Ok" on their own.OTel trace API spec
Ok is reserved for the application developer or operator, to mean "I explicitly validated this as successful." Once set to Ok, further changes SHOULD be ignored.OTel trace API spec
HTTP 4xx on a SERVER span: status MUST be left unset (absent another error). 5xx on a SERVER span: SHOULD be Error.HTTP semconv
HTTP 4xx and 5xx on a CLIENT span: SHOULD be Error.HTTP semconv
1xx/2xx/3xx: MUST be left unset, in both directions.HTTP semconv

The asymmetry is the interesting part and it is not arbitrary: a 404 is the server doing its job correctly and the caller asking for something that isn't there. So the server's span is Unset and the caller's span is Error, for the same HTTP exchange. Any dashboard that counts "spans with status=Error" without filtering on kind will double-count every client error, and any team that "fixes" their server instrumentation to flag 4xx will light up their own error rate with other people's bad requests.

Attributes — and the Three Places a Key/Value Can Live

This is the distinction readers conflate most, and it has real cost consequences:

Resource attributesInstrumentation ScopeSpan attributes
DescribesThe process emitting the telemetryThe library that emitted this spanThis one operation
Examplesservice.name (required; defaults to unknown_service), service.version, host.name, k8s.pod.name, deployment.environment.name, telemetry.sdk.languagename = io.opentelemetry.okhttp-3.0, plus version and its own attributeshttp.route, http.response.status_code, db.query.text, user.id, messaging.message.id
SetOnce, at SDK initBy the instrumentation author, via GetTracer(name, version)Per span, at any time before it ends
On the wireOnce per ResourceSpans group — amortized across the whole batchOnce per ScopeSpans groupOn every span

That last row is the one that decides cost, so it is worth seeing literally. Spans do not go out as a flat list: one export is a three-level tree — one group per distinct Resource, inside it one group per instrumentation Scope, and the spans hang off that. Anything stored above the span level is encoded once and inherited by everything beneath it.

ONE export payload = a batch of 8,192 spans from one pod

resource_spans[0]                         <- encoded ONCE for the whole batch
│   resource.attributes:
│      service.name    = checkout-api
│      service.version = 4.2.1
│      k8s.pod.name    = checkout-api-7d9f-x2k
│      k8s.namespace.name, cloud.region, telemetry.sdk.*, ...
│      ~20 keys, ~700 bytes encoded
│
├── scope_spans[0]                        <- encoded ONCE per library
│   │   scope: io.opentelemetry.okhttp-3.0  v1.32.0
│   ├── span  GET /price/{sku}
│   │      http.request.method, url.path,
│   │      http.response.status_code, user.id   <- per span
│   ├── span  POST /charge
│   │      ... the same key strings, re-encoded in full
│   └── ... ~8,000 more spans, each carrying its own attributes
│
└── scope_spans[1]                        <- encoded ONCE per library
    │   scope: io.opentelemetry.fastapi  v0.44b0
    └── span  POST /checkout
           http.route, http.response.status_code, ...

the whole point, in two lines:
  700 B of resource paid once, covering 8,192 spans  =  0.09 B/span
  700 B of resource copied onto each span            =  5.7 MB/batch

Same key/value, three places to put it, three wildly different prices. (the OpenTelemetry part has the full ExportTraceServiceRequest schema and the case where this dedup stops working; the What It Costs part turns it into a bytes/day figure.)

Two failure modes follow directly. Copying service.version onto every span pays for it on every row instead of once per batch, and makes it un-queryable as a resource dimension. Going the other way — putting a per-request value like user.id on the Resource — is worse than wasteful: the Resource is the batching key, so every distinct value forces its own ResourceSpans group, and your batches degenerate into one span each, destroying both compression and the collector's throughput.

Limits, all from the SDK spec, all overridable by env var: 128 attributes per span (OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT), no value-length limit by default (OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT), 128 events (OTEL_SPAN_EVENT_COUNT_LIMIT), 128 links (OTEL_SPAN_LINK_COUNT_LIMIT), 128 attributes each per event and per link. Anything dropped is counted: OTLP carries dropped_attributes_count (field 10), dropped_events_count (12) and dropped_links_count (14), so a non-zero count in your backend is direct evidence of truncation. The default of no value-length limit is the one to worry about — it is why somebody's serialized request body eventually shows up as a 400 KB span attribute.

Events are timestamped points inside a span: a name, a fixed64 timestamp, attributes. The canonical use is the exception convention — event name exception, attributes exception.type, exception.message, exception.stacktrace — emitted by RecordException(). The trap: RecordException() does not set the span's status. It adds an event and returns. A span that caught, recorded, and re-threw still reads Unset unless you also call SetStatus(Error), so your error-rate query misses it entirely. Know also where this is heading: the exceptions on spans convention is deprecated in favour of exceptions in logs, alongside the deprecation of the Span Events API — opt in with OTEL_SEMCONV_EXCEPTION_SIGNAL_OPT_IN, leave it unset and today's behaviour holds. The attributes themselves stay stable; exception.escaped is deprecated outright.

Links reference another SpanContext, possibly in a different trace, with optional attributes. A link is not a parent — the spec is explicit, and parents come only from context propagation (see Context Propagation). Links exist for fan-in: a consumer that processes 500 batched messages in one span links to 500 producer contexts. Jaeger maps them onto its FOLLOWS_FROM reference type. The trap: sampling decisions are made per-trace at the root (see Head-Based Sampling), and the default samplers do not consult links — so a link routinely points at a trace that was never kept, and the UI renders a dead reference.

The Lifecycle Rule That Decides Your Debugging

A span is buffered in the emitting process from Start() until End(). Only OnEnd hands it to an exporter — the SDK spec is explicit that the span becomes immutable at that moment. Nothing about an in-flight span is ever visible to anyone outside the process.

  1. A hung request produces no span, not a slow one. The 90-second call that never returns is exactly the one you want, and it is exactly the one that does not exist in your backend. You find it as a hole: a parent span with a child that never appears. Requests that time out and throw do produce spans; requests that block forever do not.

  2. A crash loses every unended span, plus the queue. The BatchSpanProcessor's defaults are OTEL_BSP_MAX_QUEUE_SIZE=2048, OTEL_BSP_MAX_EXPORT_BATCH_SIZE=512, OTEL_BSP_SCHEDULE_DELAY=5000ms, OTEL_BSP_EXPORT_TIMEOUT=30000ms. So a SIGKILL can vaporize up to 2048 already-finished spans and every span still open. The pods that OOM-kill are the ones whose traces you most want, and they are the ones that ship least. Wire SIGTERM to ForceFlush() and set a grace period longer than the 5-second timer.

  3. Spans leave the process in the order they finish, not the order they start. End() is what hands a span to the exporter, and a nested call finishes before its caller does — so the deepest leaf ships first and the root, which cannot end until everything beneath it has, ships last. Export order is roughly the call order reversed. (Roughly: parallel siblings finish in whatever order they finish, and each process's batch timer shuffles arrival further.)

    That makes "the root arrived" look like a trace-complete signal — and it is the single most tempting wrong answer in this whole guide. A root ending does not mean the trace ended. Anything the request started but did not wait for — a PRODUCER span, a detached goroutine, a background flush — ends after the root and carries the same trace_id, so its span arrives after the backend has already decided the trace was whole. The Trace part shows the arrival stream this produces (including a span landing 9 seconds after the root); the Tail-Based Sampling part is where the missing signal turns into a RAM bill.

OTLP protobuf Span — one HTTP server span with ~10 attributes

  field                        proto type    bytes   note
  ------------------------------------------------------------------
  trace_id                     bytes(16)        18   tag + len + 16
  span_id                      bytes(8)         10
  parent_span_id               bytes(8)         10   absent on a root
  flags                        fixed32           6   often omitted
  name  "GET /cart/{id}"       string           17   tag + len + 14
  kind  SPAN_KIND_SERVER       enum              2
  start_time_unix_nano         fixed64           9   NOT a varint
  end_time_unix_nano           fixed64           9
  status {code: ERROR}         message           4
  dropped_attributes_count     uint32          0-2   omitted when 0
  ------------------------------------------------------------------
  fixed overhead                             ~  85
  10 attributes, ~20B key + ~15B value       ~ 450   ~45 B each
  ------------------------------------------------------------------
  ONE SPAN, UNCOMPRESSED                     ~ 535 bytes

  sent ONCE per batch, not per span:
    Resource  service.name, k8s.pod.name, host.name ...   ~200 B
    Scope     io.opentelemetry.http + version              ~40 B

  assumptions: proto3 field tags 1 byte, keys ~20 chars, values ~15
  chars, no events or links. For calibration, Dapper reported an
  average of 426 bytes per span across its whole repository. Treat
  300 B - 1 KB as the working range; §9 builds the bill on it.
  • Guarantees: Every exported span carries a valid 16-byte trace_id, an 8-byte span_id, absolute start and end timestamps, and an honest count of anything the SDK dropped to stay inside its limits.
  • Does not guarantee: That the span is ever exported at all. An unfinished span is invisible, a killed process takes its buffer with it, and the spec puts no upper bound on a span's duration — so the worst request in your system is structurally the least likely to be represented.