API and worker metrics
You build API and worker metrics that expose request duration, order creation, cache lookups, WebSocket connections, and Kafka consumer lag. Route labels use chi patterns, never raw paths.
Ticket
Build Prometheus instrumentation for the API and worker. The API publishes HTTP request duration, order creation, cache results, and WebSocket connections. The worker publishes Kafka consumer lag. The API and worker also need separate pprof listeners that remain private.
These measurements give you the baseline for load testing and bottleneck analysis in the next module. The worker needs a metrics listener, a private pprof listener, and a lag poller. How you start and coordinate those components is up to you.
The unit tests call these exported declarations directly. Keep their names and signatures unchanged.
func Middleware(next http.Handler) http.Handler
func Handler() http.Handler
func SetConsumerLag(group, topic string, lag int64)
var OrdersPlaced prometheus.Counter
var WSConnections prometheus.Gauge
var CacheRequests *prometheus.CounterVecAcceptance criteria
GET /metricson the API returns HTTP200and includeshttp_request_duration_seconds,orders_placed_total, andws_connections.- Requests to
/w6b2/items/11and/w6b2/items/12produce two observations under the samehttp_request_duration_seconds_countseries withmethod="GET",route="/w6b2/items/{id}", andstatus="200". Neither raw path appears in the exported metrics. - A handler that writes HTTP
418produces an observation withmethod="GET",route="/w6b2/teapot", andstatus="418". - Unmatched requests to
/w6b2/attack-1and/w6b2/attack-2share the route labelunmatchedand record status404. Neither raw path appears in the metrics. - Calling
metrics.OrdersPlaced.Inc()twice increasesorders_placed_totalby exactly2. - Calling
metrics.WSConnections.Inc()twice increasesws_connectionsby2. CallingDec()afterward reduces it to one above its original value. SetConsumerLag("w6b2-group", "w6b2-topic", 42)exportskafka_consumer_lag{group="w6b2-group",topic="w6b2-topic"}with value42. Setting the same series to0makes its value return to0.CacheRequestsmaintains separatecache_requests_totalseries forresult="hit"andresult="miss". One hit increment and two miss increments increase their respective values by exactly1and2.- Requests to the live API produce the route label
/v1/restaurants/{id}/menufor restaurant menu reads. Concrete restaurant IDs and unmatched raw paths never appear as route labels. - Placing one new order increases
orders_placed_totalby exactly1. - Reading a menu that is already cached increases
cache_requests_total{result="hit"}. - The private pprof endpoint at the configured test address, defaulting to
127.0.0.1:6060, returns HTTP200for/debug/pprof/. The same path on the public API port returns HTTP404. - The worker's
/metricsendpoint exposeskafka_consumer_lag.
Constraints
- Use only the labels
method,route, andstatusonhttp_request_duration_seconds. - Use the single route label
unmatchedwhen chi matched no route. - Keep the API pprof listener private, defaulting to
127.0.0.1:6060. The pprof test readsTEST_PPROF_ADDRwhen set, otherwise it uses this default. - The worker serves
/metricson127.0.0.1:8081. - Do not modify the provided tests.
Design direction
Keep metric definitions and request instrumentation together in backend/internal/metrics/metrics.go. This package owns the registry, metric variables, request middleware, and metrics handler.
Put Kafka lag polling in backend/internal/metrics/lag.go. The worker owns the consumer groups, so it is the right place to collect their lag. Keep the pprof and metrics HTTP server lifecycle in backend/internal/metrics/pprof.go.
Update the order handler where a new order is successfully created. Update the cache package where each lookup's outcome becomes known. Neither the metrics package nor the HTTP middleware should need to understand order or cache internals.
Update the Week 5 WebSocket hub too. Increment WSConnections where the hub registers a connection. Decrement it where that connection closes. This keeps the gauge aligned with the number of open connections.
Let cmd/api assemble the API instrumentation and private pprof listener. Let cmd/worker start its own metrics listener, private pprof listener, and lag poller. Use the application's signal context to coordinate their lifecycle and Graceful shutdown. Any layout that meets the contract passes.
Consider these trade-offs:
- Metric updates belong close to the event being measured. This avoids coupling unrelated packages to request handling.
- Histogram bucket boundaries determine the latency detail available when you inspect distributions. Choose boundaries that cover the request durations you need to investigate.
- Polling more frequently makes changes in Consumer lag visible sooner, but increases Kafka admin requests.
- The middleware runs on every request. Keep route lookup and observation work small, and avoid allocations that grow with the number of concrete URLs.
- pprof should have its own mux and private listener. A separate server prevents profiling handlers from becoming reachable through the public API router.
How to check your work
Start from the repository root. Install the Kafka admin dependency and run the unit tests first.
cd backend
go get github.com/twmb/franz-go/pkg/kadm
TEST_REDIS_ADDR=127.0.0.1:6379 make test W=6B2Start the infrastructure in its own terminal.
cd backend
make upRun the migrations in another terminal.
cd backend
make migrateStart the API in another terminal.
cd backend
make runStart the worker in another terminal.
cd backend
make workerWith the API and worker running, execute the end-to-end tests from another terminal.
cd backend
TEST_API_URL=http://localhost:8080 TEST_WORKER_URL=http://localhost:8081 make test W=6B2The end-to-end API tests skip when TEST_API_URL is not set. The worker metrics test skips when TEST_WORKER_URL is not set. Set both variables to exercise the complete end-to-end contract.
Finally, inspect the API metrics endpoint.
curl -s localhost:8080/metrics | grep -c http_request_duration_secondsThe first failing assertion identifies the metric series, label, or endpoint that violates the contract. Check the exported metric name and its label values before investigating the application code that updates it.
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.
- Request duration is exported with bounded chi route labels and response status.
- Orders, WebSocket connections, and cache hits and misses update their respective metrics.
- The worker exports consumer lag for its consumer groups and topics.
- API and worker expose their own metrics and private pprof listeners.
- The metrics and pprof components follow the application's shutdown lifecycle.
Commands
cd backend && go get github.com/twmb/franz-go/pkg/kadmcd backend && make test W=6B2cd backend && TEST_API_URL=http://localhost:8080 TEST_WORKER_URL=http://localhost:8081 make test W=6B2curl -s localhost:8080/metrics | grep -c http_request_duration_secondsTests
TestW6B2_MetricsExposeTheFourSignalsinbackend/e2e/w6_test.goTestW6B2_RouteLabelIsThePatternNotTheRawPathinbackend/e2e/w6_test.goTestW6B2_OrdersPlacedCounterGoesUpinbackend/e2e/w6_test.goTestW6B2_CacheHitsAndMissesAreCountedinbackend/e2e/w6_test.goTestW6B2_PprofListensOnlyOnThePrivatePortinbackend/e2e/w6_test.goTestW6B2_WorkerExposesConsumerLaginbackend/e2e/w6_test.goTestW6B2_RequestDurationIsLabelledByRoutePatterninbackend/internal/metrics/metrics_test.goTestW6B2_RequestDurationRecordsTheStatusinbackend/internal/metrics/metrics_test.goTestW6B2_UnmatchedPathsShareOneRouteLabelinbackend/internal/metrics/metrics_test.goTestW6B2_OrdersPlacedCounterIncrementsinbackend/internal/metrics/metrics_test.goTestW6B2_WSConnectionsGaugeGoesUpAndDowninbackend/internal/metrics/metrics_test.goTestW6B2_ConsumerLagIsPerGroupAndTopicinbackend/internal/metrics/metrics_test.goTestW6B2_CacheRequestsAreSplitByResultinbackend/internal/metrics/metrics_test.go