What it does
- Counter, sharded counter, gauge, histogram and summary
- Spans with sampling decided at the root
- Propagation through <code>rpc</code>, HTTP headers and fibers
- Exporter with backoff and a bounded queue
- Cardinality limit, sensitive fields kept out of every output
- Instrumentation through macros, with no thread, socket or address of its own
Measured
- i7-6700, Release, GCC 15.2 / MSVC 19.51. Counter increment: 4.94 to 4.98 ns and 4.88 to 4.94 ns, on par with a <code>fetch_add</code> (target 5 ns)
- Histogram record: 12.9 to 13.1 ns. Unsampled span: 7.9 to 8.2 ns
- Checked against real Prometheus 3.15.0 and OpenTelemetry Collector 0.161.0
- Scales to 64 threads, verified only up to 4 cores (3.2x on 4 threads)
Ethereal::Telemetry · Tier 2
Instrumentation that can stay in hot code: **an Inc is an atomic add and nothing more**, the bucket index of a histogram comes from the bits of the double, and an unsampled span neither records nor allocates. The trace context is W3C Trace Context (traceparent), it crosses RPC and Coroutine fibers, and export comes out in formats the customer's tools already read: Prometheus, OTLP (protobuf and JSON), StatsD and JSON lines.
No thread, no socket, no embedded address. Export runs when the integrator calls CExporter::Tick, and sending goes through an ITransport the integrator provides. Nothing is sent to us, ever.
Disabled means absent. With ETHEREAL_TELEMETRY=OFF (the default) no source of the module is compiled, the ETL_TELEMETRY_* macros expand to nothing, and the module headers keep only forward declarations (code that holds a CCounter* compiles the same) and no standard header. The object file of the instrumented code comes out identical to that of the same code without the instrumentation (the telemetry.disabled test checks this). The last point is not a detail: MSVC records in the object file the standard library headers that were included (/FAILIFMISMATCH, /DEFAULTLIB:msvcprt), and the first version, which always included them, came out different on MSVC because of that. The test caught it.
#include <ethereal/cpp/telemetry/telemetry_inc.hpp>
namespace T = Ethereal::Telemetry;
T::CRegistry R;
R.Init( T::SRegistryParams{} ); // fixed capacity: nothing grows afterwards
const std::string_view aNames[] = { "method", "code" };
T::CCounter * Requests = R.Counter( "http_requests_total", "Requests served.", aNames );
const std::string_view aGet[] = { "GET", "200" };
T::CCounter * Get200 = Requests->WithLabels( aGet ); // resolves once. Keep the pointer
T::CHistogram * Lat = R.Histogram( "latency_seconds", "", T::SHistogramSpec{ 1e-4, 10.0, 2 } );
ETL_TELEMETRY_INC( Get200 ); // lock add. Without ETL_TELEMETRY: nothing
ETL_TELEMETRY_RECORD( Lat, 0.0123 );
T::CTracer Tr;
Tr.Init( T::STracerParams{} );
{
T::CSpan S = Tr.StartSpan( "process" ); // child of the current context
auto Scope = S.Activate(); // now it is the current one (this thread / fiber)
S.SetAttribute( "items", std::int64_t( 42 ) );
} // the destructor ends it
T::CPrometheusSink Prom; // the text, for your own HTTP handler
T::ISink * aSinks[] = { &Prom };
T::CExporter X;
X.Init( T::SExporterParams{ .pRegistry = &R, .pTracer = &Tr, .apSinks = aSinks, .nSinks = 1 } );
X.Tick(); // in the main loop, or in a dispatcher of yours---
The hot path, and what it costs
Intel i7-6700 (Skylake, 4 physical cores, 8 logical), Release. GCC 15.2 on WSL2 and MSVC 19.51. Everything comes from the telemetry.measurements test (the best of seven repetitions of one million operations).
| Operation | What it does | GCC | MSVC |
|---|---|---|---|
CCounter::Inc | mov + lock add + ret, checked in the disassembly by telemetry.asm | 4.94 to 4.98 ns (raw fetch_add: 4.90 to 4.98) | 4.88 to 4.94 ns (raw: 4.88 to 4.89) |
| with resolved labels | the same instruction, in another cell | 4.92 to 4.94 ns | 4.89 ns |
CShardedCounter::Inc | the same add, in this thread's cell (index in a thread_local) | 5.5 to 6.1 ns alone | 6.0 to 6.8 ns |
CHistogram::Record | index from the bits (exponent + top of the mantissa), add to the bucket, CAS on the sum | 12.9 to 13.1 ns | 12.9 ns |
CGauge::Set | one atomic write | 0.54 ns | 0.54 ns |
| unsampled span | new ids (wyrand, per-thread prefix), no clock, no allocation | 7.9 to 8.2 ns | 8.0 ns |
sampled span (with Drain) | slot in the pool, two clock reads, queue | ~103 ns | ~132 ns (no ceiling in the spec) |
**Inc is at the machine's floor.** On a Skylake, a lock add followed by another one on the same address costs ~18 cycles (~5 ns). Inc cannot go below that, and it does not go above it. The telemetry.measurements test measures both side by side (alternating, so turbo does not skew the result) and accepts "< 5 ns, or at most +5% over the raw fetch_add", because it is the same instruction, and telemetry.asm proves that it is only that instruction.
The 8 ns of the unsampled span came down from 16 ns: IsValid did a vector reduction over bytes (now it is three 64-bit reads), the per-thread state became a single TLS access, and the ids moved from splitmix64 (two multiplications in series) to wyrand (one 64×64→128), with the upper half of the trace id drawn once per thread.
Contention (the sharded counter)
Millions of operations per second summed over all threads, by the wall-clock time of the whole batch.
| threads | sharded, GCC | sharded, MSVC | a single cell (both) |
|---|---|---|---|
| 1 | 145 to 146 | 146 | 194 to 204 |
| 2 | 288 to 293 | 278 to 290 | 94 to 150 |
| 4 | 410 to 476 | 449 to 556 | 52 to 64 |
| 8 | 508 to 608 | 568 to 609 | 51 to 58 |
| 16 | 371 to 404 | 496 to 561 | 51 to 57 |
| 64 | 266 to 289 | 503 to 521 | 50 to 57 |
The machine has 4 physical cores with hyperthreading (8 logical). Up to 4 threads the sharded counter scales almost linearly (2.8 to 3.8× at 4, because turbo drops with more active cores). The hyperthreads still add. With more threads than logical cores the throughput falls due to context switching (more on WSL2 Linux than on Windows), but it does not collapse. A single cell falls to a quarter already at 4 threads: that is the fight over the cache line the spec describes. "Almost linear up to 64 threads" requires a 64-core machine, which is not available here: the test asserts what this one can show (≥ 60% of linear at 4 threads, no drop when the hyperthreads join, and the sharded counter ≥ 4× the single cell).
---
The decisions, and the declared deviations from the spec
- The histogram is exponential, without arbitrary boundaries. The spec shows
Histogram(..., SSpan<const double> Buckets), but it also forbids searching for the bucket on the hot path, and with arbitrary boundaries there is no other way. Here: from 2^⌊log₂ dMin⌋ to 2^⌈log₂ dMax⌉, each power of 2 divided into 2^s equal buckets (s=2: width ≤ 25%, s=3: ≤ 12.5%), plus "up to the minimum" and "+Inf". The buckets are (from, to], like the Prometheusle: a value equal to a bound counts in that bound (the index comes from the bits of the double immediately below). - Stats has no histogram and no quantiles (it has
CRunningStatsandCSampleWindow). The spec says "the Telemetry histogram is the Stats one with a name and labels". Since Stats has none, Telemetry has its own, and the summary (CSummary) is a fine histogram (64 buckets per power of 2, from 2⁻²⁰ to 2⁴⁰) that gives each quantile with relative error ≤ 0.8% (worst measured: 0.5%), over everything since the start (no sliding window). - Two counter types:
CCounter(one cell) andCShardedCounter(one per thread, up to 64). A sharded counter costs more alone (the thread index) and wins under contention. The choice belongs to whoever instruments. - The context is 25 bytes, not 29 (16 + 8 + 1).
tracestateis read and checked (ParseTracestate: simple keys andtenant@system, up to 32 members and 512 bytes, no duplicates), but it does not travel in the context: the RPC glue carries onlytraceparent. - Sampling is decided at the root: a child of the current context always inherits. The sampler only decides roots and children of a supplied parent (one that came from outside).
eRatiodecides by the last 8 bytes of the trace id, and so two services with the same ratio agree. - The registry never returns null: an error (a repeated name with another type, capacity, cardinality) gives an inert instrument that records into a place that is never exported. The error stays in
LastErrorand theTry*variants return it. - Process metrics (
RegisterProcessMetrics, disabled by default): CPU time, resident memory, threads, and the time since the registry'sInit. There are no "open handles" and no process lifetime: the platform layer does not provide them, and they were not invented. - HTTP: propagation is done through headers, without an HTTP client (since 2026-09-28).
InjectHttpHeaders( Ctx, pState, Set )writestraceparent(andtracestate) through a caller'sSet( name, value )function.ExtractHttpHeaders( Get, &Ctx, &State )reads through aGet( name )function, and there is a ready-made form for a list ofSHttpHeader. It is what any HTTP library allows, and it follows the W3C rules: an invalidtraceparent(or two of them) starts a new trace and takestracestatewith it. An invalidtracestateis dropped on its own. Names are compared case-insensitively, surrounding whitespace is removed, and multipletracestateheaders are joined with commas. The Ethereal Http module remains disabled: it is code inherited from another project (it includes files that do not exist here, OpenSSL through fixed paths, and Windows only), and the owner decided not to port it now. Tested intelemetry.http. - Meta names:
RegisterStructuses the name Meta gives the field (iConnections→connections, without the Hungarian prefix, in snake_case), which is what Prometheus wants.
---
Export
| Destination | What comes out | Notes | |||
|---|---|---|---|---|---|
CPrometheusSink / RenderPrometheus | exposition text 0.0.4 | HELP/TYPE, escaped labels, cumulative buckets, _sum/_count, {quantile=…} | |||
COtlpHttpSink / EncodeOtlpMetrics, EncodeOtlpTraces | ExportMetricsServiceRequest / ExportTraceServiceRequest (opentelemetry-proto v1), protobuf or JSON | POST to <base>/v1/metrics and /v1/traces. Retries 429/502/503/504 (the retryable ones in the OTLP/HTTP specification), discards and counts the other 4xx/5xx | |||
CStatsdSink | `name:value\ | c/\ | g, DogStatsD tags \ | #k:v` | counters as deltas (a delta only counts as sent together with the datagram). Histograms and summaries as .count/.sum: StatsD wants samples and here there are aggregates |
CJsonLinesSink | one JSON line per series, per span, per log record | for installations without a network |
- The exporter: the first collection lands at a random point in the interval. A retryable failure waits base·2^(k−1) (up to the maximum) times a factor in [1 − jitter, 1]. Spans are retried only for the destinations that failed. Bounded span queue with
eDropOldest,eDropNewestoreBlock(the latter only makes sense with a dispatcher on another thread). - OTLP JSON follows the OTLP deviations from proto3: names in lowerCamelCase, enums as integers, (s)fixed64/int64 as strings, ids in hex (and not base64).
---
The glue targets (each one is the only place that connects the two modules)
| Target | What it does | |
|---|---|---|
Ethereal::TelemetryRpcGlue | StartClientSpan puts traceparent in the call metadata. CServerTracing (an interceptor) opens the eServer span as a child of the incoming one, makes it current while the method runs, and ends it with an error if the method failed | |
Ethereal::TelemetryCoroutineGlue | CFiberContextStorage: the current context in a per-fiber slot. A fiber that resumes on another thread keeps its own context. Without allocating memory: the storage only keeps a pointer into the SScope (on the fiber's stack) | |
Ethereal::TelemetryLogGlue | CLogBridge, on the new Log hook (Logging::LogSetHook): `trace=… span=… \ | on each line, and the line through CJsonLinesSink` with the ids in fields |
**Sensitive: a marked field is not registered** (RegisterStruct), and so there is no format through which it could leak. The test checks all five. In the log, RedactedText( obj ) writes <sensitive> in its place (the same rule as the Testing failure messages). Text that reaches the log already formatted cannot be undone by the bridge, and that is recorded here.
The Log hook is new and generic (ILogHook: Decorate and OnRecord, on the thread of whoever logs). With no hook attached, the log writes exactly what it used to write. If the marked line does not fit in the log buffer, it goes out without the mark instead of being lost.
---
The C layer
ethereal/c/telemetry/telemetry.h. The ETLC_Counter * are the C++ instruments: ETLC_CounterInc is one call and the same lock add. Spans and scopes live in ETLC_Span / ETLC_Scope, which the caller allocates (on the stack): starting a span in C does not allocate memory. ETLC_TracerDrainOtlp returns the spans in OTLP and, when out of space, says how much it needs and keeps the request for the next call (nothing is lost).
---
Status (spec §9)
| Criterion | Status |
|---|---|
| Disabled build identical byte for byte | ✅ GCC: the whole object file, byte for byte. MSVC: code and symbols (the MSVC .obj carries its own path in .debug$S, and so two .obj files are never identical byte for byte). telemetry.disabled also checks that with ETL_TELEMETRY the object file changes |
| Inc < 5 ns, one atomic add in the disassembly | ✅ 4.88 to 4.98 ns = the machine's raw lock add. telemetry.asm: mov + lock addq + ret on GCC, mov + lock inc + ret on MSVC |
| Record < 20 ns, no search | ✅ 12.9 to 13.1 ns. Index from the bits, checked against the bounds of each bucket (including values exactly on the bounds) |
| With labels = without labels | ✅ the same instruction. 4.89 to 4.94 vs 4.88 to 4.98 ns, 12.7 to 13.0 vs 12.9 to 13.1 ns |
| Zero allocations on the recording path | ✅ ETL_EXPECT_NO_ALLOC over counters, sharded counters, gauges, histograms, summaries, and sampled and unsampled spans |
| Almost linear scaling up to 64 threads | ⚠️ up to the 4 physical cores of this machine (3.2× at 4 threads). 64 threads require a 64-core machine. See above |
| Unsampled span < 10 ns, no allocations | ✅ 7.9 to 8.2 ns (GCC and MSVC) |
| W3C propagation through RPC, correct parents, end to end | ✅ client → server → method in a real CRpcServer on another thread: the same trace, each one a child of the previous. Without a context, the server starts a trace. An unsampled one propagates the decision |
| Propagation through HTTP | ✅ through headers, with any HTTP library (InjectHttpHeaders / ExtractHttpHeaders, telemetry.http) · ⚠️ the Ethereal Http module remains disabled (inherited code, by the owner's decision) |
| Cardinality limit | ✅ clear error (eCardinality), inert instrument, counted, no growth |
| Prometheus output valid per the standard, scraped by a real Prometheus | ✅ a reader of the standard in the tests (which rejects what the standard rejects) validates the text. And Prometheus 3.15.0 scraped it: target up with no error, all 35 samples, the correct values through its API (the label with quotes, backslash and newline comes back unchanged), and histogram_quantile runs over our buckets |
| OTLP accepted by a real collector | ✅ the OpenTelemetry Collector 0.161.0 (core) received metrics and traces, in protobuf and in JSON: 200 on all four, zero rejected. And through its debug exporter: monotonic cumulative Sum with the integers 12 and 3, Histogram with count 6 and sum 2.8045, Summary, the resource, the error span, the Server, and the child's Parent ID equal to the parent's ID. In the tests, the protobuf is also read field by field by a generic reader |
| Bounded queue, policy honored | ✅ all three policies. eBlock with and without a dispatcher |
| No background work | ✅ zero threads (counted by the platform before and after), zero sockets, and Tick with no work calls no destination |
Sensitive absent from every format | ✅ Prometheus, OTLP protobuf (also the 8 bytes of the value), OTLP JSON, StatsD, JSON lines. And <sensitive> in the log text |
| Sanitizers | ✅ ASan+UBSan: zero reports (telemetry, telemetry.propagation, the C layer). TSan: zero reports, with concurrent recording and collection and RPC on two threads · ⚠️ the fiber test is skipped under TSan, because the Coroutine fiber switches do not have the TSan annotations (noted in the Coroutine README) and TSan breaks when it sees the stack change |
| C layer | ✅ C11 and C17 without extensions |
| The tests catch defects | ✅ 18 planted defects (tools/telemetry_check/mutants_telemetry.py), 18 caught. See below |
| Full test suite after this | ✅ full ctest with ETHEREAL_TELEMETRY=ON: GCC 131/131, MSVC 135/135. Zero warnings in the new files on both |
The real tools, again
tools/telemetry_check/real_tools.sh (on Linux/WSL) redoes the end-to-end verification: etl_telemetria_amostras (with ETHEREAL_BUILD_TOOLS=ON) writes the Prometheus text and the OTLP requests. The script serves the text to a Prometheus, sends the requests to a Collector and checks on the other side. The two executables are not kept in the repository: they are downloaded from the official releases (checked against the published SHA-256 hashes) and passed in ETL_PROMETHEUS and ETL_OTELCOL.
How the tests were checked
Each defect below was planted in the code, rebuilt and run. All of them made a test fail.
| Planted defect | Caught by |
|---|---|
bucket from the bits of the value itself (without le) · the maximum goes to +Inf | TheBucketComesFromTheBitsWithPrometheusLe |
| Prometheus buckets not cumulative | PrometheusValidBySpec |
OTLP explicit_bounds carries +Inf | OtlpProtobufByGrammarAndFields |
| cardinality: one series too many | CardinalityLimitedWithClearError |
| sharded counter: collection sums only one cell | ContendedCountersSumCorrectly |
| the child of the current context decides sampling again | SamplingDecidedAtTheRoot |
eDropOldest discards the new one | BoundedQueueHonorsThePolicy |
| ending a scope clears instead of restoring the previous one | CurrentContextChildrenAndScopes |
traceparent accepts uppercase hex · tracestate accepts repeated keys | the two W3C tests |
| no exponential backoff · no jitter · spans retried for destinations that already accepted | the two exporter tests |
| StatsD: the delta counts as sent without the datagram | StatsdDeltasTagsAndDatagrams |
| RPC: the server ignores the incoming context | the two propagation tests |
Meta: Sensitive is registered · appears in the log text | the Sensitive test and the Log bridge test |
Two of these are only caught because, while writing the campaign, it became clear that checks were missing: an unsampled child of the current context under an eAlways tracer, and that the retry jitter actually exists (all waits at the ceiling would pass). Both were added.