Metrics standard¶
This page sets the rules for custom metrics in ConnectSoft services and libraries. It is written for engineers who add or review meters and instruments. How the OpenTelemetry metrics pipeline, exporters and automatic instrumentation are wired is explained in Metrics; this page covers only what a meter, an instrument and a tag must look like.
Names in existing code¶
Services generated from the templates today use a meter name that starts with the service name in PascalCase, for example Company.Orders, followed by lowercase segments, and a tenant_id tag. Those names stay as they are; see CS-MET-006. The naming rules below apply to new meters and instruments. Changing the template default is tracked in the findings register.
Rules¶
CS-MET-001: Create meters through IMeterFactory in a metrics class¶
Severity: minor · Applies to: service, library, template · Enforced by: manual · Status: active
Why¶
A meter created through IMeterFactory is owned by the dependency injection container, is disposed with it and can be replaced in tests. A metrics class per service or feature keeps instrument names and tags in one place, so domain services call methods such as AddOrder(...) and never build an instrument themselves.
Do¶
- Create one metrics class per service, and one per feature where a feature has its own meter, in the
*.Metricsproject. - Create the meter in the constructor with
meterFactory.Create(<MeterName>), where the meter name is apublic const string. Declare each instrument name as apublic const stringtoo, so tests and queries use one spelling (CS-MET-007). - Create every instrument in that constructor and expose one method per measurement.
- Register the meter name with the OpenTelemetry metrics builder (
AddMeter).
Don't¶
- Create a meter with
new Meter(...)in service or library code. - Create instruments in domain services, controllers or handlers.
Example¶
public sealed class OrdersMetrics
{
public const string OrdersMetricsMeterName = "company.orders";
public const string OrderAddedCounterName = "company.orders.order.added";
private readonly Counter<long> ordersAdded;
public OrdersMetrics(IMeterFactory meterFactory)
{
ArgumentNullException.ThrowIfNull(meterFactory);
Meter meter = meterFactory.Create(OrdersMetricsMeterName);
this.ordersAdded = meter.CreateCounter<long>(name: OrderAddedCounterName, unit: "1", description: "Orders added");
}
}
How to check¶
- Search the change for
new Meter(outside test code. - Every
Create(Counter|Histogram|UpDownCounter|ObservableGauge)call is in a class in the*.Metricsproject. - Every new meter name constant is passed to
AddMeterin the host's OpenTelemetry metrics setup.
CS-MET-002: Name new meters and instruments in lowercase OpenTelemetry style¶
Severity: minor · Applies to: service, library, template · Enforced by: manual (target: ENF-036) · Status: active
Why¶
OpenTelemetry back-ends and the semantic conventions expect lowercase, dot-separated names. Mixed casing splits the same metric into several series in back-ends that are case sensitive, and makes queries depend on how each service spelled its own name.
Do¶
- Name a new meter
<company>.<service>, all lowercase, for examplecompany.orders. - Name a new instrument
<meter>.<entity>.<event>, for examplecompany.orders.order.added. - Use dots between segments, and an underscore inside a segment of several words, for example
company.orders.line_item.added. - Use the past tense for counted events (
added,deleted),.failedfor failures and.durationfor durations, as CS-MET-004 lists.
Don't¶
- Use uppercase letters or hyphens in a new name.
- Put the unit in the name; see CS-MET-003.
- Rename an existing meter or instrument to follow this rule; see CS-MET-006.
How to check¶
New MeterName constants and instrument names match ^[a-z0-9_]+(\.[a-z0-9_]+)+$.
CS-MET-003: Record durations as Histogram<double> in seconds¶
Severity: minor · Applies to: service, library, template · Enforced by: manual (target: ENF-037) · Status: active
Why¶
OpenTelemetry records durations in seconds as floating-point values, and its histogram buckets and dashboards assume that. A mix of milliseconds and seconds across services makes every latency query wrong for half of them. The unit belongs in the unit argument, where exporters read it, not in the name.
Do¶
- Create duration instruments with
CreateHistogram<double>andunit: "s". - Record
elapsed.TotalSeconds. - End the instrument name with
.duration.
Don't¶
- Record milliseconds, or use
Histogram<long>for durations. - Add
.seconds,.msor.bytesto an instrument name.
Example¶
this.orderAddDuration = meter.CreateHistogram<double>(
name: "company.orders.order.add.duration",
unit: "s",
description: "Duration of adding an order");
this.orderAddDuration.Record(elapsed.TotalSeconds, tags);
How to check¶
- New duration instruments are
Histogram<double>withunit: "s". Recordcalls on them passTotalSeconds.- New names do not end in a unit.
CS-MET-004: Record a success counter, a failure counter and a duration for every operation¶
Severity: major · Applies to: service, template · Enforced by: manual · Status: active
Why¶
Rate, errors and duration are the three signals an operator alerts on. When every domain operation records all three with matching names, an error-rate or latency alert can be written once and applied to every service.
Do¶
- For each public domain operation, create a success counter (for example
company.orders.order.added), a failure counter ending in.failed(for examplecompany.orders.order.add.failed) and a duration histogram ending in.duration. - Record them from the domain service as CS-SVC-001 and CS-SVC-002 describe.
- Use an
UpDownCounterfor a running total, such as the number of active orders, and keep it in step on create and delete.
Don't¶
- Count failures only in logs.
- Record a failure in the success counter with a status tag in place of the
.failedcounter.
How to check¶
For each public method of a domain service, the metrics class has the three instruments, and the method records them on the matching paths.
CS-MET-005: Keep tag values few and safe¶
Severity: major · Applies to: service, library, template · Enforced by: manual (target: ENF-036) · Status: active
Why¶
Each distinct combination of tag values is a separate time series. An identifier or free text as a tag value creates one series per value, which slows or breaks the metrics back-end and raises its cost. Tag values are also exported to systems with wider access than the service's data, so they must never carry personal data.
Do¶
- Use tags whose values come from a small, known set: the tenant, the aggregate type, an enumeration value or an outcome.
- Name the tenant tag
tenant.idin new metrics. - Build tags in one private method of the metrics class, and leave out a tag whose value is empty.
Don't¶
- Use an entity id, a user id, an e-mail address, a URL with ids, an exception message or other free text as a tag value.
- Put personal data or secrets in a tag; CS-LOG-005 applies to tags as it applies to logs.
How to check¶
- Read every tag added in the change and ask how many distinct values it can take in production. Anything that grows with the number of records or users is rejected.
- A new tenant tag uses the key
tenant.id, and a tag whose value is empty is left out.
CS-MET-006: Treat existing metric names as behaviour¶
Severity: minor · Applies to: service, library, template · Enforced by: manual · Status: active
Why¶
Dashboards, alerts and service-level objectives match on meter names, instrument names and tag keys. A rename silently breaks them, in the same way that CS-LOG-006 describes for log text.
Do¶
- Keep the names, units and tag keys of existing meters and instruments when refactoring or upgrading.
- When a rename is needed, state it in the pull request description so dashboards and alerts can be updated.
Don't¶
- Rename existing meters, instruments or tag keys to follow CS-MET-002 or CS-MET-005.
How to check¶
Compare the instrument names, units and tag keys in the diff. Any changed name is listed in the pull request description.
CS-MET-007: Test every metrics class and the metrics of every domain operation with MetricCollector<T>¶
Severity: major · Applies to: service, library, template · Enforced by: manual · Status: active
Why¶
A metric that is never recorded, records milliseconds into a seconds histogram, or loses its tenant tag raises no error. The dashboard goes flat and the alert never fires, and nobody notices until an incident. A test of the metrics class proves what each method records. A test of the domain operation proves that the operation calls it on the right path, which CS-MET-004 requires and a review alone cannot confirm.
Do¶
- Expose the meter name and every instrument name of a metrics class as
public const stringfields, and refer to those constants in tests. - Give every metrics class a dedicated test class named
<MetricsClass>UnitTests, for exampleOrdersMetricsUnitTests. - In that class, test every public recording method and assert, for each instrument it records:
- the value:
1for a counter, the elapsed time in seconds for a duration histogram; - each tag key and value;
- that a tag whose value is empty is left out (CS-MET-005).
- the value:
- For every public domain-service operation, add two tests that use the real metrics class:
- the success path records the success counter and the duration, and no
.failedmeasurement; - a failure path records the
.failedcounter and no success measurement.
- the success path records the success counter and the duration, and no
- Assert that a cancelled operation records no
.failedmeasurement (CS-LOG-004). - Capture measurements with
MetricCollector<T>from the built-inMicrosoft.Extensions.Diagnostics.Testingpackage (namespaceMicrosoft.Extensions.Diagnostics.Metrics.Testing). Create it with theIMeterFactoryof a realServiceProviderbuilt withAddMetrics(), and dispose it withusing. - Use
MeterListeneronly for an instrument that no metrics class owns, such as a helper that records into a meter it is given.
Don't¶
- Replace the metrics class with a fake or a stub in domain-service tests; the test then proves only that a method was called, not what was recorded.
- Create a
new Meter(...)in a test to stand in for the one the metrics class creates. - Mock
IMeterFactory, or take it in a new test from a hand-written factory such asTestMeterFactoryinConnectSoft.Extensions.Testing. Move an existing test toAddMetrics()when you change it. - Assert only that a collector has some measurement, without the value and the tags.
Example¶
A test of the metrics class:
[TestMethod]
public void AddOrderShouldCountTheOrderAndRecordItsDurationInSeconds()
{
// Arrange
using ServiceProvider services = new ServiceCollection()
.AddMetrics()
.AddSingleton<OrdersMetrics>()
.BuildServiceProvider();
IMeterFactory meterFactory = services.GetRequiredService<IMeterFactory>();
OrdersMetrics metrics = services.GetRequiredService<OrdersMetrics>();
using var added = new MetricCollector<long>(meterFactory, OrdersMetrics.OrdersMetricsMeterName, OrdersMetrics.OrderAddedCounterName);
using var duration = new MetricCollector<double>(meterFactory, OrdersMetrics.OrdersMetricsMeterName, OrdersMetrics.OrderAddDurationHistogramName);
// Act
metrics.AddOrder(TimeSpan.FromMilliseconds(1500), tenantId: "tenant-a");
// Assert
Assert.AreEqual(1L, added.LastMeasurement?.Value);
CollectedMeasurement<double>? recorded = duration.LastMeasurement;
Assert.IsNotNull(recorded);
Assert.AreEqual(1.5, recorded.Value, 1e-9);
Assert.AreEqual("tenant-a", recorded.Tags["tenant.id"]);
}
A failure-path test of the domain operation, with the processor built from the same service provider:
[TestMethod]
public async Task CreateOrderShouldCountAFailureAndNoSuccessWhenTheInputIsInvalid()
{
// Arrange
using var added = new MetricCollector<long>(this.meterFactory, OrdersMetrics.OrdersMetricsMeterName, OrdersMetrics.OrderAddedCounterName);
using var failed = new MetricCollector<long>(this.meterFactory, OrdersMetrics.OrdersMetricsMeterName, OrdersMetrics.OrderAddFailedCounterName);
CreateOrderInput input = new() { CustomerId = Guid.Empty };
// Act
await Assert.ThrowsExactlyAsync<ValidationException>(() => this.processor.CreateOrder(input));
// Assert
Assert.AreEqual(1L, failed.LastMeasurement?.Value);
Assert.IsEmpty(added.GetMeasurementSnapshot());
}
How to check¶
- Every metrics class in the change has a
<MetricsClass>UnitTestsclass, and every public recording method has a test that asserts its value and tags. - Every new or changed public domain-service operation has a success-path and a failure-path test that use
MetricCollector<T>on the real metrics class. - Tests do not register a fake metrics class or create their own
Meter. - Every new or changed public domain-service operation has a test that cancels it and asserts no
.failedmeasurement. - New tests take
IMeterFactoryfrom aServiceProviderbuilt withAddMetrics(), not from a mock or a hand-written factory such asTestMeterFactory.
CS-MET-008: Make health checks cover hosted services and the schema, not only connectivity¶
Severity: major · Applies to: service, template · Enforced by: manual · Status: active
Why¶
A health check that only proves the process runs and the database accepts connections reports Healthy while a hosted service fails on every cycle, or while the database has no tables. Monitoring and deployment checks then accept a broken service.
Do¶
- Add a health check for each hosted service that reports the time and result of its last cycle, and degrades when the cycle fails or stops.
- Add a health check that a table the service needs exists, for each database the service owns.
- Keep connectivity checks as well.
Don't¶
- Treat a connectivity check as proof that the service works.
How to check¶
A health test drops a required table, or makes a hosted service fail, and asserts that the health status degrades.
CS-MET-009: Configure health dashboard endpoints with absolute URIs¶
Severity: minor · Applies to: service, template · Enforced by: manual · Status: active
Why¶
The health dashboard collector turns a relative endpoint into an absolute URI with the first server address. Behind a web server binding without a host name, that address is https://*:port/, which is not a valid URI, and the collector fails on every poll while the health endpoint itself works.
Do¶
- Configure each health dashboard endpoint with an absolute URI, set per environment in the deployment.
Don't¶
- Configure a relative health dashboard endpoint in a service that runs behind a binding without a host name.
How to check¶
The health dashboard endpoints in deployed settings are absolute URIs.
Related¶
- Metrics explains the metrics pipeline.
- Domain service shape standard
- Logging standard
- Testing standard
- Engineering standards