Histogram quantile utility

You build a histogram quantile utility that parses Prometheus exposition samples into sorted buckets and calculates a requested latency percentile. Matching series are merged by bucket boundary before quantile calculation.

Ticket

Build a histogram quantile utility in backend/internal/slo. It reads Prometheus text exposition from an io.Reader, filters histogram bucket series by metric name and labels, and calculates a latency percentile from the resulting buckets.

The API already exposes request-duration histograms through /metrics. You can use this utility in a Go-based deploy check to estimate p99 before allowing a deployment. The utility is optional and does not block Week 6.

The tests call these exported declarations directly:

go
import "io"

type Bucket struct {
    UpperBound float64
    Count      float64
}

var ErrNoSeries error

func Quantile(q float64, buckets []Bucket) float64

func ParseBuckets(r io.Reader, metric string, match map[string]string) ([]Bucket, error)

Acceptance criteria

  • For buckets with boundaries and cumulative counts (0.1, 50), (0.5, 90), (1, 100) and (+Inf, 100), Quantile returns 0.1 for p50, 0.75 for p95, 0.95 for p99 and 1 for p100.
  • For buckets (0.2, 10) and (+Inf, 10), Quantile(0.5, buckets) returns 0.1, using zero as the lower bound of the first bucket.
  • For buckets (0.1, 10), (1, 20) and (+Inf, 30), Quantile(0.99, buckets) returns 1, the previous finite upper bound.
  • A quantile below zero returns negative infinity, and a quantile above one returns positive infinity. For example, q=-0.1 returns -Inf and q=1.1 returns +Inf.
  • An empty bucket slice and a histogram with zero total observations return NaN.
  • Parsing http_request_duration_seconds with match set to {"route": "/a"} merges matching status series by bucket boundary. The result contains (0.1, 10), (0.5, 25) and (+Inf, 25).
  • Parsing http_request_duration_seconds with a nil match map merges every matching series. The resulting +Inf bucket has a count of 125.
  • Parsing other_metric returns one bucket with a count of 7. Ignore unrelated metrics and _sum and _count samples.
  • Parsing a missing metric or a metric with no matching label values returns an error for which errors.Is(err, ErrNoSeries) is true.
  • Parsing http_request_duration_seconds for route="/a" and calculating p99 returns the interpolated result 0.1 + 0.4*(0.99*25-10)/(25-10).

Constraints

  • Preserve the exported API names, parameters and return types shown above.
  • Use only the Go standard library. Do not add an external Prometheus client dependency.
  • Do not modify the existing tests.

Design direction

Keep parsing and quantile calculation as separate responsibilities. Let ParseBuckets turn matching exposition samples into sorted cumulative buckets. Let Quantile operate on those buckets independently.

Use a map keyed by the parsed upper bound to aggregate counts from matching series. Apply every entry in match before adding a sample. A nil map should include all matching series. Sort the resulting boundaries before constructing the returned slice.

For label parsing, avoid splitting on commas alone. A quoted label value can contain commas, braces and escaped quotes. Track whether you are inside a quoted value and whether the previous character was an escape character.

For the quantile calculation, use linear interpolation within the selected bucket. This assumes observations are distributed uniformly inside that bucket. The result is an estimate, not the exact percentile of the original requests. Handle +Inf separately because it has no finite upper boundary. Any layout that meets the contract passes.

How to check your work

Run the build-tagged tests, the race-enabled package tests and the manual exposition check:

bash
cd backend
make test W=6O2
go test -race -tags w6o2 ./internal/slo/
curl -s localhost:8080/metrics | grep http_request_duration_seconds_bucket | head

Inspect the /metrics output and confirm that the histogram bucket samples contain le labels. When a test fails, read the first failing assertion to identify whether the problem is in quantile calculation, label filtering or series aggregation before investigating subsequent failures.

Finished Exercise 6.16?

Implementation

Run locally

Write the code in your editor inside zomato-prep, then work through this list.

  1. Implement the exported Bucket type and ErrNoSeries error.
  2. Calculate quantiles using cumulative bucket counts.
  3. Parse Prometheus histogram bucket samples.
  4. Filter and merge matching series by le boundary.
  5. Handle empty histograms, invalid quantiles and missing series.
  6. Pass all 10 tests and the race-detector run.

Commands

terminal
cd backend && make test W=6O2
terminal
cd backend && go test -race -tags w6o2 ./internal/slo/

Tests

  • TestW6O2_QuantileInterpolatesInsideTheBucket in backend/internal/slo/slo_test.go
  • TestW6O2_FirstBucketStartsAtZero in backend/internal/slo/slo_test.go
  • TestW6O2_QuantileInTheInfBucketReturnsTheLastFiniteBound in backend/internal/slo/slo_test.go
  • TestW6O2_QuantileOutsideZeroToOneIsInfinite in backend/internal/slo/slo_test.go
  • TestW6O2_NoObservationsIsNaN in backend/internal/slo/slo_test.go
  • TestW6O2_ParseBucketsSumsSeriesThatMatchTheLabels in backend/internal/slo/slo_test.go
  • TestW6O2_ParseBucketsWithoutLabelsMergesEverySeries in backend/internal/slo/slo_test.go
  • TestW6O2_ParseBucketsIgnoresOtherMetrics in backend/internal/slo/slo_test.go
  • TestW6O2_ParseBucketsReportsAMissingMetric in backend/internal/slo/slo_test.go
  • TestW6O2_P99OfTheRoute in backend/internal/slo/slo_test.go