Articles · Production Operations
Telemetry Segmentation: Per-Tenant & Per-Dimension Metrics
Try out the running example
Sample:
samples/038-telemetry-segmentationPrerequisites: Observability, Multi-tenancy
Overview
Relay’s command/query metrics are tagged by message type out of the box — relay.commands.executed
and relay.queries.executed carry a command/query name plus success, and a matching duration
histogram. That answers “how is PlaceOrder doing?” but not “how is PlaceOrder doing for the
eu-west region, or for tenant X?” This article covers the opt-in seam that adds caller-defined
dimensions to those same instruments and to the trace span — without forking the framework’s
instrumentation.
Two mechanisms, both off by default so existing dashboards are untouched until you ask:
| Mechanism | What it tags | Default |
|---|---|---|
[MetricTag("name")] on a message property |
counter + histogram + span | on for messages that carry it |
RelayTelemetryOptions.TagTenant |
ambient tenant (from IRelayTenantAccessor) |
off (opt-in) |
Why this exists
Read this first — cardinality is the whole game. Every distinct tag value creates a new time series, and tags multiply:
query × success × region × tenant. A bounded dimension (a handful of regions) is cheap; an unbounded one (order id, user id, or a 50,000-tenant fleet) will blow up your metrics backend and your bill. Tag only bounded, categorical fields as metrics. High-cardinality values belong on spans and logs, where they’re searchable attributes, not series multipliers. This reinforces the “don’t export high-cardinality tags” rule from Observability.
With that guardrail stated: operators routinely need to slice the golden signals by a business
dimension — latency per region, error rate per plan tier, throughput per (small set of) tenant. Before
this seam you’d have to stand up a parallel Meter and re-instrument the bus by hand. Now the dimension
rides Relay’s existing instruments, so one dashboard built for a Relay service keeps working and simply
gains a region/tenant breakdown.
When to use this
- Slicing command/query throughput, latency, or success rate by a bounded dimension: region, plan tier, channel, message source.
- Per-tenant metrics when the tenant set is small and known (turn on
TagTenant). - Always-safe per-tenant / per-anything tracing — spans tolerate high cardinality, so the span enrichment is applied regardless of the metric toggle.
When not to use this
- Do not tag metrics with per-entity ids or large/unbounded tenant fleets. Leave
TagTenantoff and rely on the span tag (and your log scope) for those — drill down in traces, not in the TSDB. - Do not add a new
Meterto duplicate this — annotate the message instead.
Concepts
[MetricTag] is a property attribute. It marks which message properties are telemetry dimensions.
On positional records use the property: target:
public sealed record GetOrders(Guid TenantId, [property: MetricTag("region")] string Region)
: IQuery<IReadOnlyList<Order>>;
The bus owns the tags, not the pipeline. Relay records the counter/histogram in the bus finally,
outside the behavior pipeline — so a pipeline behavior could enrich the span but never the metric.
That’s why segmentation lives in the bus: CommandBus/QueryBus read the message’s [MetricTag]
properties and the ambient tenant and apply them to the metrics and the span together.
Reflection happens once. RelayTelemetryTagBuilder reflects a message type’s [MetricTag]
properties a single time and caches compiled getter delegates (keyed by type in a
ConcurrentDictionary). Each dispatch is a delegate call — no per-call reflection, mirroring how the
caching behavior caches its attribute lookup.
Tenant is opt-in and bounded. TagTenant reads IRelayTenantAccessor.CurrentTenantId — the same
ambient accessor the outbox and inbox use — and is the one knob you flip per service.
Architecture
%% image: /diagrams/telemetry-segmentation.png
%% caption: Tags without cardinality accidents — [MetricTag] properties and the tenant flow through cached compiled getters onto every counter, histogram and span.
flowchart LR
Msg["Command/Query<br/>[MetricTag] props"] --> Bus[Command/Query Bus]
Tenant["IRelayTenantAccessor<br/>(if TagTenant=on)"] --> Bus
Bus -->|base + dynamic tags| TB[RelayTelemetryTagBuilder<br/>cached compiled getters]
TB --> Counter["relay.*.executed (counter)"]
TB --> Hist["relay.*.duration (histogram)"]
TB --> Span["trace span"]
Counter & Hist & Span --> T[RelayTelemetry<br/>Meter + ActivitySource]
Building it step by step
1. Annotate the dimension
public sealed record GetOrders(Guid TenantId, [property: MetricTag("region")] string Region)
: IQuery<IReadOnlyList<Order>>;
Dispatching this now emits relay.queries.executed{query=GetOrders, success=true, region=eu-west}, the
matching relay.query.duration histogram with region, and a query GetOrders span tagged region.
2. Opt into tenant tagging (only where it’s bounded)
// region/tier/channel via [MetricTag] need no configuration; tenant is the one opt-in:
services.Configure<RelayTelemetryOptions>(o => o.TagTenant = true);
With tenancy wired (AddRelayTenancy(), see Multi-tenancy) the ambient tenant is added
as a tenant tag. Leave it off (the default) for large fleets and lean on the span tag instead.
3. Asserting it without a backend
Same in-process listener pattern as Observability — attach a MeterListener, dispatch
through the real bus, and read the tags off the measurement:
meterListener.SetMeasurementEventCallback<long>((_, value, tags, _) => { /* capture tags */ });
await queryBus.Execute<GetOrders, IReadOnlyList<Order>>(new GetOrders(tenant, "eu-west"), default);
// → relay.queries.executed {query: "GetOrders", success: true, region: "eu-west"}
// → span "query GetOrders" with tag region=eu-west
Complete source code
| File | Shows |
|---|---|
SegmentationTests.cs |
[MetricTag] on counter/histogram/span; tenant tag only when opted in |
MetricTagAttribute |
the property attribute |
RelayTelemetryOptions |
the TagTenant opt-in |
RelayTelemetryTagBuilder |
cached compiled-getter tag extraction |
Running the example
dotnet test samples/038-telemetry-segmentation/TelemetrySegmentation.Sample.Tests
Testing
The framework’s TelemetrySegmentationTests (in Nuvora.Nexus.Relay.Tests.Unit.Core) assert the
dimensions land on counter, histogram, and span; that the tenant tag is absent by default and present
when enabled; and — as a regression guard — that a message with no [MetricTag] and tenant tagging off
emits byte-for-byte the original tag set. Tags are a public contract dashboards bind to, so this is
worth a test.
Production considerations
- Cardinality budget. Decide the dimension’s value set up front. Regions/tiers/channels are safe; ids and big tenant fleets are not — those go on spans/logs.
- Tenant tag is per-service. Flip
TagTenanton only for services whose tenant count is small; prefer span-level tenant context everywhere else (always emitted). - Naming. Pick stable, lowercase tag keys (
region,plan_tier) — renaming a tag breaks every dashboard and alert bound to it. - Backward compatible. No annotation and
TagTenantoff ⇒ identical to pre-feature behaviour, so rolling this out is safe and incremental.