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:
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),Quantilereturns0.1for p50,0.75for p95,0.95for p99 and1for p100. - For buckets
(0.2, 10)and(+Inf, 10),Quantile(0.5, buckets)returns0.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)returns1, the previous finite upper bound. - A quantile below zero returns negative infinity, and a quantile above one returns positive infinity. For example,
q=-0.1returns-Infandq=1.1returns+Inf. - An empty bucket slice and a histogram with zero total observations return NaN.
- Parsing
http_request_duration_secondswithmatchset 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_secondswith a nil match map merges every matching series. The resulting+Infbucket has a count of125. - Parsing
other_metricreturns one bucket with a count of7. Ignore unrelated metrics and_sumand_countsamples. - 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_secondsforroute="/a"and calculating p99 returns the interpolated result0.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:
cd backend
make test W=6O2
go test -race -tags w6o2 ./internal/slo/
curl -s localhost:8080/metrics | grep http_request_duration_seconds_bucket | headInspect 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.
The reference solution passes every check for this exercise. Try the hints first; reading the answer before you have struggled with the problem teaches much less.
Implementation
Run locally
Write the code in your editor inside zomato-prep, then work through this list.
- Implement the exported
Buckettype andErrNoSerieserror. - Calculate quantiles using cumulative bucket counts.
- Parse Prometheus histogram bucket samples.
- Filter and merge matching series by
leboundary. - Handle empty histograms, invalid quantiles and missing series.
- Pass all 10 tests and the race-detector run.
Commands
cd backend && make test W=6O2cd backend && go test -race -tags w6o2 ./internal/slo/Tests
TestW6O2_QuantileInterpolatesInsideTheBucketinbackend/internal/slo/slo_test.goTestW6O2_FirstBucketStartsAtZeroinbackend/internal/slo/slo_test.goTestW6O2_QuantileInTheInfBucketReturnsTheLastFiniteBoundinbackend/internal/slo/slo_test.goTestW6O2_QuantileOutsideZeroToOneIsInfiniteinbackend/internal/slo/slo_test.goTestW6O2_NoObservationsIsNaNinbackend/internal/slo/slo_test.goTestW6O2_ParseBucketsSumsSeriesThatMatchTheLabelsinbackend/internal/slo/slo_test.goTestW6O2_ParseBucketsWithoutLabelsMergesEverySeriesinbackend/internal/slo/slo_test.goTestW6O2_ParseBucketsIgnoresOtherMetricsinbackend/internal/slo/slo_test.goTestW6O2_ParseBucketsReportsAMissingMetricinbackend/internal/slo/slo_test.goTestW6O2_P99OfTheRouteinbackend/internal/slo/slo_test.go