Soklet Logo

Core Concepts

Metrics Collection

Soklet provides a MetricsCollector hook for capturing operational metrics without tying you to a specific observability stack. It is invoked for HTTP requests, Model Context Protocol (MCP) activity, and Server-Sent Event (SSE) activity, and is designed to be lightweight and safe to call on hot paths.

At a high level:

  • It is a separate hook from LifecycleObserver - use metrics collectors for low-cardinality counters, gauges, and histograms; use lifecycle observers for traces, audit, logging, and cleanup hooks
  • Implementations must be thread-safe, non-blocking, and avoid I/O
  • Exceptions are caught and logged - they will not break request handling

Configuration

By default, Soklet ships with an in-memory MetricsCollector, an instance of which can be acquired by calling MetricsCollector::defaultInstance.

Soklet's default covers basic workflows, but you can also plug in the official OpenTelemetry integration (soklet-otel) or your own custom implementation.

HttpServer httpServer = HttpServer.fromPort(8080);
SokletConfig config = SokletConfig.withHttpServer(httpServer)
  // This is already the default; specifying it here is optional
  .metricsCollector(MetricsCollector.defaultInstance())
  .build();

To disable metrics collection entirely, specify Soklet's no-op implementation, MetricsCollector::disabledInstance:

HttpServer httpServer = HttpServer.fromPort(8080);
SokletConfig config = SokletConfig.withHttpServer(httpServer)
  // Use this instead of null to disable metrics collection
  .metricsCollector(MetricsCollector.disabledInstance())
  .build();

Accessing Metrics

Collectors that support snapshots expose them via MetricsCollector::snapshot. The default collector returns a MetricsCollector.Snapshot containing histogram data and gauges. If a collector does not support snapshots, it returns Optional::empty.

This section describes snapshot-capable collectors (for example, Soklet's default in-memory collector).

Snapshots from MetricsCollector.Histogram.snapshot() derive the sample count from the final captured cumulative bucket. In the default collector's exported histograms, _count therefore equals the +Inf bucket within the same point, including during concurrent recording or reset. Bucket boundaries and units are unchanged.

These snapshots are concurrent observations. Buckets, sum, minimum and maximum are read independently and do not form an atomic transaction. A record overlapping reset() can be discarded or represented partly across those fields. Coordinate writers with reset if you need an exact observation-window boundary. Quiescent reset clears histogram state; previously returned snapshots remain immutable. Collector reset preserves live gauges and the identity bookkeeping needed to match later lifecycle callbacks.

The MetricsCollector is injectable as a Resource Method parameter, so you can easily expose a GET /metrics endpoint which can be scraped by your telemetry tooling:

@GET("/metrics")
public MarshaledResponse getMetrics(@NonNull MetricsCollector metricsCollector) {
  // Configure export to use Prometheus format
  SnapshotTextOptions options = SnapshotTextOptions
    .fromMetricsFormat(MetricsFormat.PROMETHEUS);

  // Generate our export (if supported by the MetricsCollector)
  String body = metricsCollector.snapshotText(options).orElse(null);

  if (body == null)
    return MarshaledResponse.fromStatusCode(204);

  return MarshaledResponse.withStatusCode(200)
    .headers(Map.of("Content-Type", List.of("text/plain; charset=UTF-8")))
    .body(body.getBytes(StandardCharsets.UTF_8))
    .build();
}

Protect this endpoint with your application's authentication and authorization, or restrict it to an access-controlled monitoring network. The example shows export formatting only; metric snapshots can reveal service activity and endpoint names.

MetricsCollector::snapshotText returns data compatible with the Prometheus (v0.0.4) and OpenMetrics (1.0) text exposition formats with HTTP, MCP, and SSE metrics. MCP and SSE data are only included when the corresponding servers are configured.

For observed GET/DELETE requests on 2025 MCP session endpoints, the default collector uses the selected configured endpoint path as the HTTP route label. Snapshot keys mark it as RouteType.MATCHED. Endpoint-selected rejections, including unknown-session 404s and facility-unavailable 405s, use that same route; ordinary unmatched HTTP requests retain unmatched. Query values, session IDs and arbitrary request targets are never used as route labels.

Custom collectors and lifecycle observers receive the actual HTTP request with ServerType.HTTP and a null ResourceMethod, because the MCP transport handles these operations. Custom collectors own their route classification and export policy. MCP POST requests use the semantic MCP callbacks.

The generic GET/DELETE observation pair reserves bounded capacity before start and holds it through physical finish. GET lifetimes have a separate bucket of twice the global session cap (512 by default); DELETE and other transient controls use worker-plus-handler-queue capacity (132 by default). GET can use transient headroom after its lifetime bucket fills. Saturation or quiescence skips both callbacks. Saturation while accepting emits a fixed non-error configuration diagnostic at most once per minute; quiescence skips silently. Finish callbacks run on dedicated workers. See MCP observability and testing for the worker limits and shutdown implications.

SnapshotTextOptions also lets you filter samples, drop zero-count buckets, or collapse histograms to just count/sum when you want to reduce payload size.

In OpenMetrics 1.0 output, finite histogram le labels use canonical floating-point formatting: for example, 128.0, 1e+06 and 1.048576e+06. Prometheus 0.0.4 output retains integer labels such as 128, 1000000 and 1048576. Both use +Inf for the overflow bucket. The numeric thresholds and units are the same in both formats. If your query or sample filter matches a le string literally, use the spelling for the selected format; the filter receives the exact label string used in the export.

Here's an example that more fully exercises SnapshotTextOptions:

SnapshotTextOptions options = SnapshotTextOptions
  .withMetricsFormat(MetricsFormat.OPEN_METRICS_1_0)
  .histogramFormat(HistogramFormat.COUNT_SUM_ONLY)
  .includeZeroBuckets(false)
  .metricFilter((MetricSample metricSample) -> {
    String name = metricSample.getName();
    Map<String, String> labels = metricSample.getLabels();

    // Keep only HTTP/MCP/SSE metrics
    if (!name.startsWith("soklet_http_")
        && !name.startsWith("soklet_mcp_")
        && !name.startsWith("soklet_sse_"))
      return false;

    // Keep only /toys routes (route label is "unmatched" for unmatched requests)
    String route = labels.get("route");

    if (route != null && !route.startsWith("/toys"))
      return false;

    // Drop 5xx responses when status_class is present
    String statusClass = labels.get("status_class");

    if (statusClass != null && statusClass.startsWith("5"))
      return false;

    return true;
  })
  .build();

String body = metricsCollector.snapshotText(options).orElse(null);

This configuration emits OpenMetrics 1.0, collapses histograms to count/sum, omits empty buckets, and filters the sample stream by name and labels.

Serve OpenMetrics 1.0 with Content-Type: application/openmetrics-text; version=1.0.0; charset=utf-8. The default Prometheus format uses text/plain; version=0.0.4; charset=utf-8. If an endpoint supports both, select the matching snapshot format from Accept and include Vary: Accept.

Sample Names

Regular HTTP uses ServerType.HTTP. Its built-in Prometheus and OpenMetrics transport-failure samples use server_type="HTTP" on soklet_transport_failures_total. OpenTelemetry's separate soklet.server.type vocabulary is lowercase http, sse, and mcp.

All possible sample names emitted by the default collector:

  • soklet_http_response_stream_terminations_total - Counter of HTTP response stream terminations (labels: method, route, status_class, reason).
  • soklet_http_requests_active - Gauge of currently active HTTP requests (no labels).
  • soklet_http_connections_accepted_total - Counter of total accepted HTTP connections (no labels).
  • soklet_http_connections_rejected_total - Counter of total rejected HTTP connections (no labels).
  • soklet_transport_failures_total - Counter of low-level transport failures across HTTP, SSE, and MCP transports (labels: server_type, reason with values such as WRITE_ERROR, WRITE_TIMEOUT, RESPONSE_WRITE_IDLE_TIMEOUT, ACCEPT_LOOP_ERROR, CONNECTION_SETUP_ERROR, TASK_ERROR, SELECTION_KEY_ERROR, or REGISTER_ERROR). Standard HTTP parser-level rejections are recorded here even when overload prevents their detailed didRejectUnparsedRequest observation work from being admitted.
  • soklet_http_request_read_failures_total - Counter of HTTP request read failures reported through didFailToReadRequest (standard HTTP parser-owned 400, 408, 414, and 431 rejections are recorded in soklet_transport_failures_total instead) (labels: reason with values UNPARSEABLE_REQUEST, REQUEST_READ_TIMEOUT, REQUEST_READ_REJECTED, REQUEST_BODY_DECOMPRESSION_FAILED, or INTERNAL_ERROR).
  • soklet_http_requests_rejected_total - Counter of HTTP requests rejected before handling begins (labels: reason with values REQUEST_HANDLER_QUEUE_FULL, REQUEST_HANDLER_EXECUTOR_SHUTDOWN, or INTERNAL_ERROR).
  • soklet_http_request_duration_nanos_bucket - Cumulative histogram bucket counts for HTTP request duration in nanoseconds (labels: method, route, status_class, plus le).
  • soklet_http_request_duration_nanos_count - Histogram sample count for HTTP request duration in nanoseconds (labels: method, route, status_class).
  • soklet_http_request_duration_nanos_sum - Histogram sample sum for HTTP request duration in nanoseconds (labels: method, route, status_class).
  • soklet_http_handler_duration_nanos_bucket - Cumulative histogram bucket counts for HTTP handler duration in nanoseconds (labels: method, route, status_class, plus le).
  • soklet_http_handler_duration_nanos_count - Histogram sample count for HTTP handler duration in nanoseconds (labels: method, route, status_class).
  • soklet_http_handler_duration_nanos_sum - Histogram sample sum for HTTP handler duration in nanoseconds (labels: method, route, status_class).
  • soklet_http_ttfb_nanos_bucket - Cumulative histogram bucket counts for HTTP time-to-first-byte in nanoseconds (labels: method, route, status_class, plus le).
  • soklet_http_ttfb_nanos_count - Histogram sample count for HTTP time-to-first-byte in nanoseconds (labels: method, route, status_class).
  • soklet_http_ttfb_nanos_sum - Histogram sample sum for HTTP time-to-first-byte in nanoseconds (labels: method, route, status_class).
  • soklet_http_request_body_bytes_bucket - Cumulative histogram bucket counts for HTTP request body size in bytes (labels: method, route, plus le).
  • soklet_http_request_body_bytes_count - Histogram sample count for HTTP request body size in bytes (labels: method, route).
  • soklet_http_request_body_bytes_sum - Histogram sample sum for HTTP request body size in bytes (labels: method, route).

Request-body histograms reflect the bytes handlers observe. With transparent request decompression enabled, they therefore measure the decompressed body. Custom collectors can use Request::getEncodedBodySizeInBytes when they need the pre-decompression payload size instead.

  • soklet_http_response_body_bytes_bucket - Cumulative histogram bucket counts for HTTP response body size in bytes (labels: method, route, status_class, plus le).
  • soklet_http_response_body_bytes_count - Histogram sample count for HTTP response body size in bytes (labels: method, route, status_class).
  • soklet_http_response_body_bytes_sum - Histogram sample sum for HTTP response body size in bytes (labels: method, route, status_class).
  • MCP metric families cover accepted/rejected connections, typed transport failures, server starts and shutdown outcomes, pre-admission acceptance/rejection, handler capacity, admitted-request activity/outcomes/duration, request-stream and subscription activity/duration, cooperative cancelation, progress, keep-alives, fixed protocol errors, and unknown mirrored-header occurrences. MCP has no dedicated session-count or session-lifetime instruments; session-related terminal causes appear in stream metrics. See MCP for the exact family names, labels, and bounded vocabularies.
  • soklet_sse_connections_accepted_total - Counter of total accepted SSE TCP connections (no labels).
  • soklet_sse_connections_rejected_total - Counter of total rejected SSE TCP connections (no labels).
  • soklet_sse_request_read_failures_total - Counter of SSE request read failures (labels: reason with values UNPARSEABLE_REQUEST, REQUEST_READ_TIMEOUT, REQUEST_READ_REJECTED, or INTERNAL_ERROR).
  • soklet_sse_requests_rejected_total - Counter of SSE requests rejected before handling begins (labels: reason with values REQUEST_HANDLER_QUEUE_FULL, REQUEST_HANDLER_EXECUTOR_SHUTDOWN, or INTERNAL_ERROR).
  • soklet_sse_streams_active - Gauge of currently active SSE streams (no labels).
  • soklet_sse_handshakes_accepted_total - Counter of total accepted SSE handshakes (labels: route).
  • soklet_sse_handshakes_rejected_total - Counter of total rejected SSE handshakes (labels: route, handshake_failure_reason with values CAPACITY_EXCEEDED, HANDSHAKE_TIMEOUT, HANDSHAKE_REJECTED, or INTERNAL_ERROR).
  • soklet_sse_event_broadcasts_total - Counter of SSE event enqueue outcomes (labels: route, outcome with values ATTEMPTED, ENQUEUED, or DROPPED).
  • soklet_sse_comment_broadcasts_total - Counter of SSE comment enqueue outcomes (labels: route, comment_type, outcome with values ATTEMPTED, ENQUEUED, or DROPPED).
  • soklet_sse_events_dropped_total - Counter of SSE events not enqueued because a connection's write queue was full, after which Soklet closes that connection with BACKPRESSURE (labels: route, drop_reason with value QUEUE_FULL).
  • soklet_sse_comments_dropped_total - Counter of SSE comments dropped before enqueue (labels: route, comment_type, drop_reason with value QUEUE_FULL).
  • soklet_sse_time_to_first_event_nanos_bucket - Cumulative histogram bucket counts for SSE time to first event in nanoseconds (labels: route, plus le).
  • soklet_sse_time_to_first_event_nanos_count - Histogram sample count for SSE time to first event in nanoseconds (labels: route).
  • soklet_sse_time_to_first_event_nanos_sum - Histogram sample sum for SSE time to first event in nanoseconds (labels: route).
  • soklet_sse_event_write_duration_nanos_bucket - Cumulative histogram bucket counts for SSE event write duration in nanoseconds (labels: route, plus le).
  • soklet_sse_event_write_duration_nanos_count - Histogram sample count for SSE event write duration in nanoseconds (labels: route).
  • soklet_sse_event_write_duration_nanos_sum - Histogram sample sum for SSE event write duration in nanoseconds (labels: route).
  • soklet_sse_event_delivery_lag_nanos_bucket - Cumulative histogram bucket counts for SSE event delivery lag in nanoseconds (labels: route, plus le).
  • soklet_sse_event_delivery_lag_nanos_count - Histogram sample count for SSE event delivery lag in nanoseconds (labels: route).
  • soklet_sse_event_delivery_lag_nanos_sum - Histogram sample sum for SSE event delivery lag in nanoseconds (labels: route).
  • soklet_sse_event_size_bytes_bucket - Cumulative histogram bucket counts for SSE event size in bytes (labels: route, plus le).
  • soklet_sse_event_size_bytes_count - Histogram sample count for SSE event size in bytes (labels: route).
  • soklet_sse_event_size_bytes_sum - Histogram sample sum for SSE event size in bytes (labels: route).
  • soklet_sse_queue_depth_bucket - Cumulative histogram bucket counts for SSE per-stream queue depth (events) (labels: route, plus le).
  • soklet_sse_queue_depth_count - Histogram sample count for SSE per-stream queue depth (events) (labels: route).
  • soklet_sse_queue_depth_sum - Histogram sample sum for SSE per-stream queue depth (events) (labels: route).
  • soklet_sse_comment_delivery_lag_nanos_bucket - Cumulative histogram bucket counts for SSE comment delivery lag in nanoseconds (labels: route, comment_type, plus le).
  • soklet_sse_comment_delivery_lag_nanos_count - Histogram sample count for SSE comment delivery lag in nanoseconds (labels: route, comment_type).
  • soklet_sse_comment_delivery_lag_nanos_sum - Histogram sample sum for SSE comment delivery lag in nanoseconds (labels: route, comment_type).
  • soklet_sse_comment_size_bytes_bucket - Cumulative histogram bucket counts for SSE comment size in bytes (labels: route, comment_type, plus le).
  • soklet_sse_comment_size_bytes_count - Histogram sample count for SSE comment size in bytes (labels: route, comment_type).
  • soklet_sse_comment_size_bytes_sum - Histogram sample sum for SSE comment size in bytes (labels: route, comment_type).
  • soklet_sse_comment_queue_depth_bucket - Cumulative histogram bucket counts for SSE comment queue depth (comments) (labels: route, comment_type, plus le).
  • soklet_sse_comment_queue_depth_count - Histogram sample count for SSE comment queue depth (comments) (labels: route, comment_type).
  • soklet_sse_comment_queue_depth_sum - Histogram sample sum for SSE comment queue depth (comments) (labels: route, comment_type).
  • soklet_sse_stream_duration_nanos_bucket - Cumulative histogram bucket counts for SSE stream duration in nanoseconds (labels: route, termination_reason keyed by StreamTerminationReason, plus le).
  • soklet_sse_stream_duration_nanos_count - Histogram sample count for SSE stream duration in nanoseconds (labels: route, termination_reason).
  • soklet_sse_stream_duration_nanos_sum - Histogram sample sum for SSE stream duration in nanoseconds (labels: route, termination_reason).

Histogram samples vary with histogramFormat: COUNT_SUM_ONLY omits finite *_bucket samples (OpenMetrics retains its required le="+Inf" bucket), and NONE omits all histogram samples.


Metrics Collected

Each aggregate map in the default collector retains at most 8,192 keys. Eviction uses approximate least-recently-used order; an evicted key's cumulative counts restart from zero when that key is observed again.

The default collector focuses on high-signal, low-cardinality metrics:

  • HTTP request duration, handler duration, and time-to-first-byte (TTFB), grouped by HttpMethod, ResourcePathDeclaration, and status class (2xx, 3xx, ...)
  • HTTP request/response body sizes, grouped by HttpMethod and ResourcePathDeclaration
  • HTTP, MCP, and SSE connection accept/reject counters (TCP connection attempts, not per-request activity)
  • Low-level transport failures across HTTP, SSE, and MCP transports, including write errors, write timeouts, HTTP read errors with request data in flight, response write-idle timeouts, accept-loop failures, event-loop task failures, selection-key failures, and registration failures

HTTP accept/setup failure observations are emitted at logging milestones during sustained failure. Their counters are sampled diagnostics, not exact totals of every failed accept/setup attempt.

  • HTTP and SSE request read failures delivered through request-read callbacks. Standard HTTP parser-owned malformed-request, read-timeout, target-length, and header-limit rejections use soklet_transport_failures_total; do not infer their counts from soklet_http_request_read_failures_total.
  • HTTP and SSE request rejections (request-handler queue or executor saturation)
  • SSE handshake accept/reject counters (handshake failures are keyed by HandshakeFailureReason)
  • SSE enqueue outcome counters (attempted/enqueued/dropped) and dropped-event counters (when queues are full)
  • SSE stream duration, time to first event, event write duration
  • SSE delivery lag, payload size, and per-stream queue depth for events, plus separate comment metrics split by comment type (SseComment.CommentType.COMMENT vs SseComment.CommentType.HEARTBEAT)
  • MCP handler capacity, admitted-request outcomes/durations, request-stream and subscription lifecycles, subscription-maintenance outcomes, progress/cancelation, protocol errors, and bounded transport/server activity

Routes are keyed on ResourcePathDeclaration (for example, /accounts/{id} as opposed to /accounts/123) to keep label cardinality low.

Metrics callbacks that receive a Request or a request-bearing stream object can read W3C trace data via Request::getTraceContext. Do not put trace IDs in aggregate metric labels: they are high-cardinality values and belong in logs, spans, or exemplars rather than default counters and histograms.

Snapshot histogram durations are in nanoseconds, sizes are in bytes, and queue depths are counts. Callback APIs provide Duration values for write and delivery lag timing.

The default MCP request-duration histogram uses finite boundaries of 0.001, 0.002, 0.005, 0.01, 0.025, 0.05, 0.1, 0.2, 0.4, 0.8, 1.5, 3, 7, 15, 30, 60, 120 and 300 seconds, followed by +Inf. The snapshot and soklet_mcp_request_duration_nanos exports express these values in nanoseconds.

The boundaries above 15 seconds cover the default 60-second request timeout and longer configured deadlines; values above five minutes use +Inf. This layout applies across supported MCP revisions.

soklet-otel advises the same boundaries in seconds for soklet.mcp.request.duration; OpenTelemetry SDK views can override that advice. Recheck dashboards, alerts and filters that assume the previous bucket vector or select an exact le value.

For HTTP response metrics, byte counts refer to the response body only (not headers or transport overhead), so they remain consistent across server implementations.


Snapshot Structure

The MetricsCollector.Snapshot exposes collected HTTP and SSE data as immutable maps keyed by small, final immutable key classes. These classes retain public constructors and structural equality, but expose their dimensions through Soklet-style get... accessors rather than record-component accessors. Route-based keys carry a ResourcePathDeclaration for the templated route and a RouteType that indicates whether the request matched a route. When RouteType is RouteType.UNMATCHED, the route is null. SSE stream duration keys use StreamTerminationReason. Comment metrics also include the comment type (SseComment.CommentType.COMMENT vs SseComment.CommentType.HEARTBEAT) in the key. Handshake failure metrics include the HandshakeFailureReason:

Soklet exposes its independent immutable MCP aggregate through MetricsCollector.Snapshot::getMcpMetrics. McpMetricsSnapshot contains the bounded counters, gauges, histograms, and immutable endpoint/method/termination key classes used by the MCP text exporter. Custom collectors may consume the same semantic transitions through MetricsCollector::didRecordMcpMetricsEvent. See MCP for the current metric API reference.

Route-key getters deliberately return a nullable route rather than an Optional: MATCHED requires a route and UNMATCHED requires null. The established keys retain public constructors; the newer HttpResponseStreamTerminationKey uses fromDimensions(routeStatusKey, reason) to compose an existing key. HTTP status classes are bounded to 1xx through 5xx, plus unknown; constructing a key with another status-class string fails with IllegalArgumentException.

McpMetricsSnapshot.getSubscriptionMaintenance() returns delivered maintenance event counts keyed by SubscriptionMaintenanceKey. Both text formats expose soklet_mcp_subscription_maintenance_total with configured endpoint, fixed lowercase work and fixed lowercase outcome labels. Counts include coalescing and stale-result discards and do not measure unique subscriptions, started attempts, durations or active work. Maintenance-only events are exported without requiring a subscription-open event. The existing 8,192-key retention bound and semantic-delivery overflow policy can omit observations; reset clears these counters while preserving live gauges.

Histogram values are returned as MetricsCollector.HistogramSnapshot instances.

Snapshot scalar values are nonnull: Integer for the bucket count, Double for the sum, and Long for boundaries, cumulative counts, total count, minimum, maximum and percentile results. Indexed accessors accept nonnull Integer; the percentile accessor accepts nonnull Double. A zero value is still present.

The sum uses floating-point accumulation and can grow beyond Long.MAX_VALUE. This applies to duration, byte and queue-depth histograms. Durations remain nanoseconds and other units remain unchanged. Sums are approximate: a small addition to a large total can round away, and concurrent accumulation order can affect the result. Use an application-owned exact total for exact accounting.

For custom collectors constructing snapshots, the constructor accepts List<Long> boundaries and cumulative counts, Long count/min/max, and Double sum. The lists are defensively copied, must have equal sizes, and must contain nonnull elements. All scalar arguments must be nonnull; the sum must be finite and nonnegative. The supplied count is retained independently of the bucket list.


Resetting Metrics

MetricsCollector::reset is supported by the default collector and is useful for tests or ad-hoc sampling. Custom collectors may implement it as a no-op.

metricsCollector.reset();

OpenTelemetry

If you are standardizing on OpenTelemetry, use soklet-otel, which provides:

Metrics answer "how much, how often, how slow" and must keep low-cardinality labels. Traces answer "what happened to this request" and carry trace IDs/span IDs by design. Soklet keeps those concerns separate: configure the metrics collector for aggregate telemetry and the lifecycle observer for spans.

Installation

Maven:

<dependency>
  <groupId>com.soklet</groupId>
  <artifactId>soklet-otel</artifactId>
  <version>2.0.0</version>
</dependency>

Gradle:

repositories {
  mavenCentral()
}

dependencies {
  implementation 'com.soklet:soklet-otel:2.0.0'
}

Configuration

OpenTelemetry integration 2.0.0 targets Soklet 4.0.0. Supply the core dependency and your chosen OpenTelemetry SDK/exporters in the application; upgrading only the integration JAR is not a substitute for the core migration.

Provide your application's OpenTelemetry instance:

// Acquire an OpenTelemetry instance from wherever you'd like...
OpenTelemetry openTelemetry = myOpenTelemetry();

// ...and use it to drive Soklet's OpenTelemetry integrations.
SokletConfig config = SokletConfig.withHttpServer(
  HttpServer.fromPort(8080)
).metricsCollector(
  OpenTelemetryMetricsCollector.withOpenTelemetry(openTelemetry)
    .instrumentationName("com.mycompany.myapp.soklet")
    .instrumentationVersion("1.0.0")
    .build()
).lifecycleObservers(List.of(
  OpenTelemetryLifecycleObserver.withOpenTelemetry(openTelemetry)
    .instrumentationName("com.mycompany.myapp.soklet")
    .instrumentationVersion("1.0.0")
    .build()
)
).build();

The tracing observer neither writes log events to stderr nor exports OpenTelemetry logs. Configuring it replaces Soklet's unconfigured default observer. Add an application logging observer to the same collection, or include LifecycleObserver.defaultInstance() for stderr logging. See Event Logging for application log routing.

If you already have a Meter, you can wire directly via OpenTelemetryMetricsCollector::withMeter.

By default, MetricNamingStrategy.SEMCONV is used:

  • Standard HTTP metrics use OpenTelemetry semantic convention names (for example, http.server.request.duration)
  • http.server.request.body.size records the encoded payload size as transferred, including the compressed size for transparently decompressed gzip requests
  • If an oversized request is rejected before that encoded size is known, the body-size sample is omitted instead of recording an inaccurate zero
  • http.server.response.body.size records the finalized MarshaledResponse size; when the HTTP transport applies dynamic response compression afterward, this remains the pre-compression size
  • Soklet-specific telemetry (especially SSE details) is emitted with soklet.* names
  • For unmatched HTTP requests, http.route is omitted

OpenTelemetryMetricsCollector intentionally does not emit W3C trace IDs, parent IDs, or tracestate values as metric attributes. Use logs, spans, or exemplar-aware tracing integrations for per-trace correlation.

OpenTelemetryLifecycleObserver creates SERVER spans for standard HTTP requests, streaming HTTP responses, SSE connections, and admitted MCP requests. An MCP span is parented only from validated trace context in MCP request _meta; physical HTTP trace headers and ambient context are not fallback parents. The single MCP request span remains open through any request-scoped SSE or subscription lifetime and ends at the corresponding terminal request callback. See MCP for the exact attributes, outcome mapping, and privacy boundary.

For built-in MCP contexts, span timing uses McpRequestContext.getStartedAt() and the semantic finish duration, including start-observer time and excluding asynchronous finish-delivery delay. Custom contexts with an empty start optional retain the callback-time fallback.

Finite HTTP spans measure the tracing observer's start-to-finish callback wall clock. They exclude wrapRequest work before dispatch, earlier start observers in a composed observer, and work after the finish callback. The monotonic duration supplied to metrics measures the core's broader handling interval.

HTTP handler-queue 503 rejection occurs before request handling, so it creates no handler span or http.server.request.duration sample. Observe soklet.server.requests.rejected for it. Parser failures such as 400 or 431 are recorded through soklet.server.transport.failures rather than normal handler metrics.

HTTP/SSE span parenting uses Soklet's validated W3C trace context. It does not consult the SDK's configured B3, Jaeger, X-Ray or other propagators. An SSE connection creates separate handshake and connection SERVER spans; without an inbound trace parent they can belong to separate traces. recordRequestId adds attribute correlation, not a parent-child relationship.

The MCP soklet.mcp.protocol.errors instrument uses the decimal JSON-RPC error code as the string attribute rpc.response.status_code, matching MCP spans. It does not use the deprecated long rpc.jsonrpc.error_code attribute.

Long-lived SSE connection spans and MCP request spans may not appear in some trace backends until the stream or subscription ends. This is normal for exporters/backends that batch or display spans only after completion.

To use Soklet-prefixed HTTP metric names, set MetricNamingStrategy.SOKLET:

// Use Soklet's metric names
OpenTelemetryMetricsCollector.withOpenTelemetry(openTelemetry)
  .metricNamingStrategy(OpenTelemetryMetricsCollector.MetricNamingStrategy.SOKLET)
  .build();

Under this strategy, soklet.server.request.body.size follows Soklet's native handler-visible semantics and records the decompressed size when transparent request decompression is enabled.

The complete HTTP naming-strategy mapping is:

SEMCONVSOKLETKind and unit
http.server.active_requestssoklet.server.requests.activeUp-down counter, {request}
http.server.request.durationsoklet.server.request.durationHistogram, s
http.server.request.body.sizesoklet.server.request.body.sizeHistogram, By
http.server.response.body.sizesoklet.server.response.body.sizeHistogram, By

Both strategies also emit soklet.server.request.throwables, a Counter with unit {throwable}. It counts observed throwables, not requests containing an error: two throwables observed for one request increment it by two. It uses the request-duration attributes: http.request.method, http.response.status_code, and error.type. Under SEMCONV, error.type is the first relevant throwable's class name, omitting expected BadRequestException failures on 4xx responses, or the decimal status for a 5xx response without a throwable. Under SOKLET, it retains the first throwable for compatibility and is absent without one. SEMCONV adds url.scheme=http and http.route only when matched; SOKLET adds soklet.server.type and http.route (including _unmatched). It never exports throwable messages or stack traces.

In 2.0.0, metrics and spans share the soklet.server.type vocabulary: http (including streaming HTTP), sse, and mcp. Update HTTP metric filters, dashboards, and alerts from standard_http to http, and SSE span filters from server_sent_event to sse. HTTP spans retain http; SSE metrics retain sse, and MCP retains mcp across both signals.

For future core enum values, the integration uses bounded fallbacks: ServerType maps to unknown, and shutdown component disposition maps to termination_unknown. Unknown MCP outcomes and stream termination reasons count as errors while still ending spans and retiring active-request gauges.

The HTTP metric-label change affects Soklet connection, request-acceptance, request-read-failure, and transport-failure counters under both naming strategies, including SEMCONV. Request-handling and response-write metrics (including soklet.server.request.throwables) carry soklet.server.type only under SOKLET. Standard HTTP instrument names, semantic-convention attributes, and url.scheme=http are unchanged; this migration adds no attributes to metrics that omit them. MCP stream shutdown uses the termination value server_stopping. MCP request-stream and subscription termination labels also include session_expired and session_closed for 2025 session expiry and closure. Both the default collector's text exports and OpenTelemetry use these lowercase values. There are no dedicated session-count or session-lifetime instruments; session IDs are not labels. See MCP stream termination labels.

Unlike the default in-memory collector, OpenTelemetryMetricsCollector does not implement MetricsCollector::snapshot or MetricsCollector::snapshotText. It emits data through your OpenTelemetry SDK/exporter pipeline instead.

HTTP response stream metrics

For admitted HttpServer response streams, MetricsCollector::didFinishRequestHandling marks application handling and transport handoff. The active HTTP request remains counted until didTerminateResponseStream(StreamingResponseHandle, StreamTermination, Duration, Long) runs. That default callback receives the original dispatch request, the terminal outcome, the full monotonic request duration, and observed payload bytes. It runs once after metrics handling finish and before lifecycle stream observers. Custom collectors overriding handling finish should defer stream duration/body-size samples and their active-request decrement to this callback.

The duration starts at request processing entry and ends at logical transport termination. It excludes observer queue delay and later physical resource cleanup. StreamTermination.getDuration() still describes only the stream lifetime. Socket body-size observations count bytes accepted by socket writes, including partial writes before a later failure; they exclude headers and chunk framing and do not assert client receipt. Simulation counts accepted materialized bytes, including the prefix before a producer failure or simulator limit.

MetricsCollector.Snapshot.getHttpResponseStreamTerminations() returns an immutable Map<HttpResponseStreamTerminationKey, Long>. Its builder setter defensively copies input; null/empty clears, zero is retained, and null keys/values or negative counts are rejected. Keys compose HttpServerRouteStatusKey with StreamTerminationReason; diagnostic rendering redacts application dimensions. The default collector exports soklet_http_response_stream_terminations_total with method, route, status_class, and uppercase reason labels, under the existing 8,192-key capacity. Reset clears cumulative termination counts while preserving live request state.

A producer failure after a committed 200 remains 2xx with PRODUCER_FAILED. Precommit finite replacements (including 505/503), HEAD/bodyless suppression, and unadmitted streams retain finite HTTP accounting and do not invoke the admitted-stream metrics callback. Existing handler-duration and approximate time-to-first-byte scopes remain unchanged. Dedicated SSE-server and semantic MCP metrics retain their existing ownership.

The OpenTelemetry integration defers the existing HTTP duration/body-size instruments and active-request decrement under both SEMCONV and SOKLET. It also emits soklet.http.response.stream.terminations with http.request.method, configured http.route, soklet.http.status_class, and soklet.http.response.stream.termination.reason. Termination counts omit raw paths, request IDs, and exception messages.

SSE request acceptance and rejection counters are not mutually exclusive. A parsed request can be accepted for handling and later rejected at handshake admission; do not add those counters to infer a request total.

Previous
Testing