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 /healthz with 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 :8080 with 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:

go
"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:

go
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:

    1. middleware.RequestID
    2. middleware.Logger
    3. middleware.Recoverer
    4. httpx.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 /healthz and return status 200 with the JSON body {"ok":true} using httpx.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.Server with:

    • Addr: ":8080"
    • ReadHeaderTimeout: 5 * time.Second
    • ReadTimeout: 10 * time.Second
    • WriteTimeout: 15 * time.Second
    • IdleTimeout: 60 * time.Second
  • Configure a JSON slog logger and set it as the default logger before starting the server.

  • Call ListenAndServe and handle its returned error. Treat http.ErrServerClosed as normal. For any other error, log it and exit with a non-zero status. Do not panic on startup errors.

  • Use the standard net/http handler 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:

bash
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
done

The expected status sequence is five 200 responses followed by two 429 responses.

Rejection headers and body: Inspect a rejected response with:

bash
curl -i -H "X-User-ID: me" localhost:8080/healthz

The 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/:

bash
TEST_API_URL=http://localhost:8080 make test W=1B6

The 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 includes Retry-After and the JSON error body.

Each test uses its own X-User-ID, so their rate-limit state does not interfere.

Finished Exercise 1.19?

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

Distributed rate limiting with Redis

Up next · Module 6 · 3 items · about 2 h 45 min

Start module 6

Implementation

Run locally

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

  1. cmd/api/main.go builds a chi router with request id, logger, recoverer and your RateLimit (capacity 5, refill 1 per second).
  2. GET /healthz returns {"ok":true}.
  3. The server sets read, write and idle timeouts.
  4. Seven quick curls print five 200s then 429s, and one second later it answers 200 again.
  5. /healthz is rate limited here only so the limit is easy to see; a real health check must not be.

Commands

terminal
cd backend && make run
terminal
for i in 1 2 3 4 5 6 7; do curl -s -o /dev/null -w "%{http_code}\n" localhost:8080/healthz; done
terminal
cd backend && TEST_API_URL=http://localhost:8080 make test W=1B6

Tests

  • TestW1B6_HealthzReturns429AfterTheBurst in backend/e2e/w1_test.go
  • TestW1D3_LimitRecoversAfterASecond in backend/e2e/w1_test.go
  • TestW1B5_RejectedBodyAndHeader in backend/e2e/w1_test.go