Skip to content

feat(middleware): record HTTP server request duration metrics#13

Open
gandalf-at-lerian wants to merge 2 commits into
developfrom
feat/http-server-request-metrics
Open

feat(middleware): record HTTP server request duration metrics#13
gandalf-at-lerian wants to merge 2 commits into
developfrom
feat/http-server-request-metrics

Conversation

@gandalf-at-lerian
Copy link
Copy Markdown
Contributor

Summary

  • Adds native OpenTelemetry http.server.request.duration metrics to the Fiber WithTelemetry middleware.
  • Records a Float64 histogram in seconds with http.request.method, http.route, http.response.status_code, and error.type for handler errors / 5xx responses.
  • Keeps excluded routes and nil telemetry / meter / metrics factory paths as no-op paths.

Context

Originally requested through LerianStudio/lib-commons#462, but the middleware now lives in lib-observability after the lib-commons v5 split, so the implementation lands here.

Tests

  • go test -tags=unit ./middleware/ -count=1
  • go test -tags=unit ./...
  • golangci-lint run ./...

Requested by: @gauchito91

Implement the OpenTelemetry HTTP semantic-convention server metric
http.server.request.duration as a Float64 seconds histogram on the Fiber
WithTelemetry middleware. The instrument is created lazily at handler-
construction time from the configured MeterProvider and is gated on the
presence of a non-nil MetricsFactory so callers without a metrics pipeline
are unaffected.

Recording happens for every non-excluded request alongside the existing
span behavior, attaching low-cardinality OTel attributes derived from the
captured Fiber context: http.request.method (heap-copied before c.Next to
survive fasthttp buffer recycling), http.route from c.Route().Path (route
template, never the raw path), http.response.status_code, and error.type
when the handler returns an error or the response is 5xx. Nil telemetry,
nil MeterProvider, nil MetricsFactory, excluded routes, and instrument
creation errors all silently skip the metric without affecting the request
path. Existing span attributes and EndTracingSpans behavior are unchanged.

Originally tracked as LerianStudio/lib-commons#462; the middleware now
lives in lib-observability after the v5 split, so the change lands here.

Tests cover success (200), client error (404), server status (503),
handler-returned error, excluded route, nil telemetry, nil MeterProvider,
and nil MetricsFactory paths using a real OTel SDK ManualReader.

Requested-by: @gauchito91
X-Lerian-Ref: 0x1
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 26, 2026

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 30e493f7-1d10-42ec-aec8-3545f7db64b5

📥 Commits

Reviewing files that changed from the base of the PR and between 972c752 and b57e0cf.

📒 Files selected for processing (2)
  • middleware/telemetry.go
  • middleware/telemetry_metrics_test.go

Walkthrough

The PR adds OpenTelemetry HTTP server request duration metrics to the telemetry middleware. A Float64 histogram named http.server.request.duration (in seconds) is precomputed when telemetry provides both a MeterProvider and MetricsFactory. For each request, the middleware captures the start time before execution and records the duration upon completion, including HTTP semantic attributes and error type classification from handler errors or status codes.

Changes

HTTP Request Duration Metrics

Layer / File(s) Summary
Histogram metric definition and initialization
middleware/telemetry.go
Imports time and strconv; adds a histogram construction helper with explicit second-based bucket boundaries; precomputes the http.server.request.duration histogram at handler construction time when effective telemetry has both MeterProvider and MetricsFactory.
Request timing and duration recording
middleware/telemetry.go
Captures request start time before handler execution; records duration histogram upon completion with HTTP semantic attributes (http.request.method, http.route, http.response.status_code) and conditional error.type; includes helpers recordHTTPServerDuration and classifyHTTPErrorType that handle typed-nil checks and derive error type from handler errors or server status codes.
Metric recording test suite
middleware/telemetry_metrics_test.go
Adds an OTel ManualReader-based test harness and tests asserting histogram recording and attributes for success (2xx), 4xx, 5xx (status-derived error.type), handler errors (Go concrete type), Fiber errors, excluded routes (no recording), and no-op behavior when telemetry, MeterProvider, or MetricsFactory are absent.

Sequence Diagram

sequenceDiagram
    participant Request
    participant Middleware
    participant Handler
    participant OTelMeter
    Request->>Middleware: HTTP request arrives
    Middleware->>Middleware: requestStart ← current time
    Middleware->>Handler: c.Next()
    Handler-->>Middleware: status code + optional error
    Middleware->>OTelMeter: recordHTTPServerDuration(duration, attributes)
    OTelMeter->>OTelMeter: record histogram sample
    OTelMeter->>OTelMeter: attach http.request.method
    OTelMeter->>OTelMeter: attach http.route
    OTelMeter->>OTelMeter: attach http.response.status_code
    OTelMeter->>OTelMeter: conditionally attach error.type
    OTelMeter-->>Request: response sent
Loading

Possibly related issues


Comment @coderabbitai help to get the list of available commands and usage tips.

@lerian-studio
Copy link
Copy Markdown
Contributor

⚠️ Invalid Source Branch

Pull requests to main can only come from:

  • develop
  • release-candidate
  • hotfix/*

Your source branch: feat/http-server-request-metrics

Please change the base branch or create a PR from an allowed branch.

@lerian-studio
Copy link
Copy Markdown
Contributor

lerian-studio commented May 26, 2026

🔍 PR Validation Summary

✅ PR Mergeable — no blocking failures

Check Status Blocking
Source Branch ✅ success yes
PR Title ✅ success yes
PR Description ✅ success yes
PR Size ✅ success no
Auto Labels ✅ success no
PR Metadata ✅ success no

🔍 View workflow run

@lerian-studio
Copy link
Copy Markdown
Contributor

lerian-studio commented May 26, 2026

🔒 Security Scan Results — lib-observability

✅ PR Mergeable — no blocking findings

Stage Status Blocking?
Filesystem Scan ✅ Clean
Docker Image Scan ➖ Skipped
Docker Hub Health Score ➖ Skipped
Pre-release Version Check ✅ Clean

Trivy

Filesystem Scan

✅ No vulnerabilities or secrets found.


Pre-release Version Check

✅ No unstable version pins found.


🔍 View full scan logs

@lerian-studio
Copy link
Copy Markdown
Contributor

📊 Unit Test Coverage Report: lib-observability

Metric Value
Overall Coverage 84.5% ✅ PASS
Threshold 80%

Coverage by Package

Package Coverage
github.com/LerianStudio/lib-observability/assert 97.9%
github.com/LerianStudio/lib-observability/constants 83.3%
github.com/LerianStudio/lib-observability/log 94.9%
github.com/LerianStudio/lib-observability/metrics 91.4%
github.com/LerianStudio/lib-observability/middleware 68.6%
github.com/LerianStudio/lib-observability/redaction 95.8%
github.com/LerianStudio/lib-observability/runtime 80.4%
github.com/LerianStudio/lib-observability/tracing 84.9%
github.com/LerianStudio/lib-observability/zap 96.0%
github.com/LerianStudio/lib-observability 91.1%

Generated by Go PR Analysis workflow

@gandalf-at-lerian gandalf-at-lerian changed the base branch from main to develop May 26, 2026 22:22
@lerian-studio lerian-studio added size/M PR changes 200–499 lines middleware HTTP/gRPC observability middleware tests Unit, integration and end-to-end tests labels May 26, 2026
@lerian-studio lerian-studio added size/L PR changes 500–999 lines and removed size/M PR changes 200–499 lines labels May 27, 2026
@blacksmith-sh
Copy link
Copy Markdown

blacksmith-sh Bot commented May 27, 2026

Found 1 test failure on Blacksmith runners:

Failure

Test View Logs
github.com/LerianStudio/lib-observability/middleware/
TestWithTelemetry_RecordsDurationOnSuccess
View Logs

Fix in Cursor

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

middleware HTTP/gRPC observability middleware size/L PR changes 500–999 lines tests Unit, integration and end-to-end tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants