← Back to Pull requests

Auto-register client metrics (consumer lag, throughput, broker latency) #261

Closed
unknown closed this pull request without merging on Oct 02, 2026 17:03 UTC
View on GitHub
unknown unknown commented on Sep 22, 2026 19:09 UTC
Author

Summary

  • Replaces the per-gauge KafkaConfiguration.ConsumerMetrics / ProducerMetrics opt-in with an auto-register KafkaMetricsConfig model.

  • Enabled by default (.enabled() — prefix kafka, 5s interval). Tune with .enabled(prefix:updateInterval:); opt out with .disabled (zero overhead: no instruments, no stats polling). An explicit statisticsIntervalMs still wins.

  • Every instrument carries a client_id dimension — the configured client.id, else librdkafka's unique handle name (e.g. rdkafka#consumer-1) — so multiple clients in one process report separate series.

  • When enabled (the default), the client subscribes to librdkafka .statistics events and records the full set below, plus imperative delivery/commit/error hooks.

  • Adds full nested statistics decoding (per-broker / topic / partition / consumer-group) and per-broker latency windows.
  • Enabling

    import Kafka
    import Metrics
    
    // Bootstrap any swift-metrics backend once at startup — the metrics register into it.
    MetricsSystem.bootstrap(/* your MetricsFactory */)
    
    var config = KafkaConsumerConfig()
    config.consumptionStrategy = .group(id: "orders", topics: ["orders"])
    config.clientId = "orders-consumer"   // becomes the client_id dimension
    
    // Metrics are on by default ("kafka" prefix, 5s interval) — nothing to enable.
    let (consumer, messages, events) = try KafkaConsumer.makeConsumer(config: config)
    // Everything under "kafka.consumer.*" auto-registers into the bootstrapped backend.
    
    // Optional: tune the prefix/interval, or opt out entirely.
    // config.metrics = .enabled(prefix: "orders", updateInterval: .seconds(1))
    // config.metrics = .disabled
    

    KafkaProducerConfig.metrics works identically (emits under kafka.producer.).

    Consumer metrics (12)

    All metrics carry client_id; dims listed below are in addition to it. Meters report librdkafka's cumulative totals as-is.

  • kafka.consumer.lag (Gauge, dims: topic, partition) — per-partition lag

  • kafka.consumer.lag.max (Gauge) — max lag across partitions

  • kafka.consumer.queue.operations (Gauge)

  • kafka.consumer.messages.received (Meter)

  • kafka.consumer.bytes.received (Meter)

  • kafka.consumer.errors.total (Counter)

  • kafka.consumer.rebalances (Meter, from cgrp.rebalance_cnt)

  • kafka.consumer.commits.total (Counter) — manual commits

  • kafka.consumer.commits.failed (Counter)

  • kafka.consumer.commit.duration (Timer)

  • kafka.consumer.broker.rtt.{avg,p99,max}.ms (Gauge, dims: broker)

  • kafka.consumer.broker.throttle.{avg,p99,max}.ms (Gauge, dims: broker)
  • Producer metrics (14)


  • kafka.producer.queue.messages (Gauge)

  • kafka.producer.queue.bytes (Gauge)

  • kafka.producer.messages.sent (Meter)

  • kafka.producer.bytes.sent (Meter)

  • kafka.producer.batch.size.avg (Gauge)

  • kafka.producer.delivery.success.total (Counter)

  • kafka.producer.delivery.failure.total (Counter)

  • kafka.producer.send.errors.total (Counter)

  • kafka.producer.send.duration (Timer) — end-to-end acknowledged sendAndAwait

  • kafka.producer.errors.total (Counter)

  • kafka.producer.broker.rtt.{avg,p99,max}.ms (Gauge, dims: broker)

  • kafka.producer.broker.throttle.{avg,p99,max}.ms (Gauge, dims: broker)

  • kafka.producer.broker.queue.latency.{avg,p99,max}.ms (Gauge, dims: broker) — int_latency

  • kafka.producer.broker.request.latency.{avg,p99,max}.ms (Gauge, dims: broker) — outbuf_latency
  • Per-broker latency windows are surfaced as pre-aggregated avg/p99/max gauges dimensioned by broker, normalized to milliseconds (the .ms suffix). librdkafka pre-aggregates them, so a Timer would be incorrect.

    Breaking changes (semver: major)


  • KafkaConfiguration.ConsumerMetrics / ProducerMetrics removed.

  • KafkaConsumerConfig.metrics / KafkaProducerConfig.metrics (and the deprecated Configuration equivalents) change type to KafkaMetricsConfig.

  • Metrics are now on by default; migrate by removing gauge assignments (or set config.metrics = .disabled to opt out).

  • api-breakages.txt updated.
  • Motivation

    The old API required users to construct and assign each Gauge individually, which led to inconsistent naming, incomplete coverage by default, and no Counters/Timers. The auto-register model mirrors the Java client, which records metrics by default; the librdkafka-based Rust/Go/Python clients only expose raw statistics JSON. Consumer lag is the headline signal.

    Test plan


  • Unit: statistics decoding; statistics → instrument mapping (broker-free — covers dimensioned gauges, Meter totals, per-client isolation, window-skip); mock-broker auto-registration incl. the handle-name client_id fallback; default-on and statistics.interval.ms precedence.

  • Integration: real-broker produce → consume → commit asserting delivery, send.duration, commit, stats-sampling, and messages.received Meter metrics. Both metrics suites use withMetricsFactory(_:_:) (task-local) so parallel suites don't clobber the global MetricsSystem.

  • Full suite green on Linux with -Xswiftc -warnings-as-errors (140 tests).
  • Diff: 635 lines (+476 / -159) across 7 files Reviewer: FranzBusch Review duration: 14274m
    All Vouch review confidence checks passed
    Residual risk 0.20 = Change Risk (0.50) × (1 − Review Confidence (0.60)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.50 · 635 lines diff across 7 files
    0.50
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.386
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #261"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 50.4% (MEDIUM) · Higher = larger blast radius
    50.4%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 60.5% · Lower = rushed or shallow review
    60.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 19.9% · Safe to merge
    19.9%