chi server with /healthz and a rate limit
Wire the middleware into a chi server with request id and logging, serve GET /healthz, and curl it until it answers 429.
Objective
Build and run the API server that brings the rate limiter and HTTP middleware together. The server exposes a JSON health endpoint and applies a shared token bucket to incoming requests, making the middleware's 429 behavior observable through real HTTP calls. By the end:
- A chi v5 router serves
GET /healthzwith status 200 and{"ok":true}. - The router uses RequestID, Logger, Recoverer, and rate-limit middleware in the required order.
- One shared token bucket allows a burst of five requests and refills at one token per second.
- The HTTP server listens on
:8080with explicit read, write, and idle timeouts. - The server logs in JSON format and handles listener errors without panicking.
Deliverables
Write this file in your zomato-prep repository, under backend/.
backend/cmd/api/main.go: configure logging, construct the limiter, set up the router and health handler, configure the HTTP server, and start listening.
Use these imports and APIs:
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/yashdagar/zomato-prep/backend/internal/httpx"
"github.com/yashdagar/zomato-prep/backend/internal/ratelimit"The health handler should use the shared response helper:
httpx.WriteJSON(w, http.StatusOK, map[string]bool{"ok": true})Requirements
Constraints
-
Use chi v5 for routing. If it is not already in the module, add it with
go get github.com/go-chi/chi/v5. -
Register middleware in exactly this order:
middleware.RequestIDmiddleware.Loggermiddleware.Recovererhttpx.RateLimit(...)
-
Use the existing rate-limit middleware from
internal/httpx. Do not duplicate its key derivation or rejection response logic in the server. -
Construct the limiter once in
main, outside all handlers, using a token bucket with capacity 5 and refill rate 1 token per second:go ratelimit.NewTokenBucket(5, 1, nil) -
Share this limiter across requests. Do not construct a new limiter inside a handler or middleware callback.
-
Apply rate limiting to every route, including
/healthz, for this exercise. This is a demonstration arrangement so the 429 response can be observed easily. In a real deployment, register the health check outside the limiter because load balancers and orchestrators poll it. -
Register
GET /healthzand return status 200 with the JSON body{"ok":true}usinghttpx.WriteJSON. -
Use the request's request context through
r.Context()when a handler needs request-scoped context. Do not create unrelated background contexts for request handling. -
Configure an
http.Serverwith:Addr: ":8080"ReadHeaderTimeout: 5 * time.SecondReadTimeout: 10 * time.SecondWriteTimeout: 15 * time.SecondIdleTimeout: 60 * time.Second
-
Configure a JSON
sloglogger and set it as the default logger before starting the server. -
Call
ListenAndServeand handle its returned error. Treathttp.ErrServerClosedas normal. For any other error, log it and exit with a non-zero status. Do not panic on startup errors. -
Use the standard
net/httphandler interfaces and keep server setup separate from the health handler. -
Do not implement graceful shutdown in this exercise. It is covered later in the course.
Acceptance criteria
Health endpoint: A request to GET /healthz returns status 200 and a JSON body containing "ok": true while the limiter has available capacity.
Middleware order: RequestID, Logger, Recoverer, and RateLimit are registered in the specified order. Rejected requests are still logged.
Burst behavior: Start the server with make run. Send seven requests using the same X-User-ID:
for i in 1 2 3 4 5 6 7; do
curl -s -o /dev/null -w "%{http_code}\n" -H "X-User-ID: me" localhost:8080/healthz
doneThe expected status sequence is five 200 responses followed by two 429 responses.
Rejection headers and body: Inspect a rejected response with:
curl -i -H "X-User-ID: me" localhost:8080/healthzThe response includes status 429, Retry-After: 1, and the JSON body {"error":"rate_limited"}.
Refill behavior: After the burst has been exhausted, wait at least one second and send another request with the same key. It should return 200 once a token has refilled.
End-to-end tests: With the server running, execute the provided tests from backend/:
TEST_API_URL=http://localhost:8080 make test W=1B6The existing black-box tests in backend/e2e/w1_test.go must pass:
TestW1B6_HealthzReturns429AfterTheBurst: eight requests with one user ID produce an initial 200, at least one 429, and a final 429.TestW1D3_LimitRecoversAfterASecond: after exhausting the burst, a request is rejected, then a request after 1.2 seconds is allowed.TestW1B5_RejectedBodyAndHeader: a rejected response includesRetry-Afterand the JSON error body.
Each test uses its own X-User-ID, so their rate-limit state does not interfere.
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.
HTTP rate limiting
4 items
- 1.16net/http handlers and middlewarenot completed
- 1.17The chi router and context.Contextnot completed
- 1.18RateLimit HTTP middleware that returns 429not completed
- 1.19chi server with /healthz and a rate limitnot completed
Up next · Module 6 · 3 items · about 2 h 45 min
Implementation
Run locally
Write the code in your editor inside zomato-prep, then work through this list.
cmd/api/main.gobuilds a chi router with request id, logger, recoverer and yourRateLimit(capacity 5, refill 1 per second).GET /healthzreturns{"ok":true}.- The server sets read, write and idle timeouts.
- Seven quick curls print five 200s then 429s, and one second later it answers 200 again.
/healthzis rate limited here only so the limit is easy to see; a real health check must not be.
Commands
cd backend && make runfor i in 1 2 3 4 5 6 7; do curl -s -o /dev/null -w "%{http_code}\n" localhost:8080/healthz; donecd backend && TEST_API_URL=http://localhost:8080 make test W=1B6Tests
TestW1B6_HealthzReturns429AfterTheBurstinbackend/e2e/w1_test.goTestW1D3_LimitRecoversAfterASecondinbackend/e2e/w1_test.goTestW1B5_RejectedBodyAndHeaderinbackend/e2e/w1_test.go