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.

go
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.CounterVec

Acceptance criteria

  • GET /metrics on the API returns HTTP 200 and includes http_request_duration_seconds, orders_placed_total, and ws_connections.
  • Requests to /w6b2/items/11 and /w6b2/items/12 produce two observations under the same http_request_duration_seconds_count series with method="GET", route="/w6b2/items/{id}", and status="200". Neither raw path appears in the exported metrics.
  • A handler that writes HTTP 418 produces an observation with method="GET", route="/w6b2/teapot", and status="418".
  • Unmatched requests to /w6b2/attack-1 and /w6b2/attack-2 share the route label unmatched and record status 404. Neither raw path appears in the metrics.
  • Calling metrics.OrdersPlaced.Inc() twice increases orders_placed_total by exactly 2.
  • Calling metrics.WSConnections.Inc() twice increases ws_connections by 2. Calling Dec() afterward reduces it to one above its original value.
  • SetConsumerLag("w6b2-group", "w6b2-topic", 42) exports kafka_consumer_lag{group="w6b2-group",topic="w6b2-topic"} with value 42. Setting the same series to 0 makes its value return to 0.
  • CacheRequests maintains separate cache_requests_total series for result="hit" and result="miss". One hit increment and two miss increments increase their respective values by exactly 1 and 2.
  • Requests to the live API produce the route label /v1/restaurants/{id}/menu for restaurant menu reads. Concrete restaurant IDs and unmatched raw paths never appear as route labels.
  • Placing one new order increases orders_placed_total by exactly 1.
  • 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 HTTP 200 for /debug/pprof/. The same path on the public API port returns HTTP 404.
  • The worker's /metrics endpoint exposes kafka_consumer_lag.

Constraints

  • Use only the labels method, route, and status on http_request_duration_seconds.
  • Use the single route label unmatched when chi matched no route.
  • Keep the API pprof listener private, defaulting to 127.0.0.1:6060. The pprof test reads TEST_PPROF_ADDR when set, otherwise it uses this default.
  • The worker serves /metrics on 127.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.

bash
cd backend
go get github.com/twmb/franz-go/pkg/kadm
TEST_REDIS_ADDR=127.0.0.1:6379 make test W=6B2

Start the infrastructure in its own terminal.

bash
cd backend
make up

Run the migrations in another terminal.

bash
cd backend
make migrate

Start the API in another terminal.

bash
cd backend
make run

Start the worker in another terminal.

bash
cd backend
make worker

With the API and worker running, execute the end-to-end tests from another terminal.

bash
cd backend
TEST_API_URL=http://localhost:8080 TEST_WORKER_URL=http://localhost:8081 make test W=6B2

The 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.

bash
curl -s localhost:8080/metrics | grep -c http_request_duration_seconds

The 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.

Finished Exercise 6.4?

Implementation

Run locally

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

  1. Request duration is exported with bounded chi route labels and response status.
  2. Orders, WebSocket connections, and cache hits and misses update their respective metrics.
  3. The worker exports consumer lag for its consumer groups and topics.
  4. API and worker expose their own metrics and private pprof listeners.
  5. The metrics and pprof components follow the application's shutdown lifecycle.

Commands

terminal
cd backend && go get github.com/twmb/franz-go/pkg/kadm
terminal
cd backend && make test W=6B2
terminal
cd backend && TEST_API_URL=http://localhost:8080 TEST_WORKER_URL=http://localhost:8081 make test W=6B2
terminal
curl -s localhost:8080/metrics | grep -c http_request_duration_seconds

Tests

  • TestW6B2_MetricsExposeTheFourSignals in backend/e2e/w6_test.go
  • TestW6B2_RouteLabelIsThePatternNotTheRawPath in backend/e2e/w6_test.go
  • TestW6B2_OrdersPlacedCounterGoesUp in backend/e2e/w6_test.go
  • TestW6B2_CacheHitsAndMissesAreCounted in backend/e2e/w6_test.go
  • TestW6B2_PprofListensOnlyOnThePrivatePort in backend/e2e/w6_test.go
  • TestW6B2_WorkerExposesConsumerLag in backend/e2e/w6_test.go
  • TestW6B2_RequestDurationIsLabelledByRoutePattern in backend/internal/metrics/metrics_test.go
  • TestW6B2_RequestDurationRecordsTheStatus in backend/internal/metrics/metrics_test.go
  • TestW6B2_UnmatchedPathsShareOneRouteLabel in backend/internal/metrics/metrics_test.go
  • TestW6B2_OrdersPlacedCounterIncrements in backend/internal/metrics/metrics_test.go
  • TestW6B2_WSConnectionsGaugeGoesUpAndDown in backend/internal/metrics/metrics_test.go
  • TestW6B2_ConsumerLagIsPerGroupAndTopic in backend/internal/metrics/metrics_test.go
  • TestW6B2_CacheRequestsAreSplitByResult in backend/internal/metrics/metrics_test.go