RateLimit HTTP middleware that returns 429

Write net/http middleware that keys by X-User-ID or the client IP, calls a Limiter, and rejects with 429, Retry-After and a JSON body.

Objective

Build HTTP rate-limiting middleware that uses the existing limiter abstraction to admit or reject requests, returning a consistent JSON response when a client exceeds its limit. By the end:

  • RateLimit wraps an HTTP handler and checks each request against a limiter.
  • Requests are keyed by X-User-ID when present, otherwise by the client's IP address without its port.
  • Rejected requests receive HTTP 429, a Retry-After header, and a JSON error body.
  • Allowed requests pass through to the next handler unchanged.
  • JSON responses are written through one shared WriteJSON helper.

Deliverables

Write these files in backend/internal/httpx/, using package httpx.

  • backend/internal/httpx/json.go: implement a shared JSON response helper using encoding/json and log/slog.

    go
    func WriteJSON(w http.ResponseWriter, status int, v any)

    It must set Content-Type: application/json, write the status, encode the value, and log an encoding failure with slog.Error.

  • backend/internal/httpx/ratelimit.go: implement the middleware and its unexported client-key helper. Import the limiter package from github.com/yashdagar/zomato-prep/backend/internal/ratelimit.

    go
    func RateLimit(l ratelimit.Limiter) func(http.Handler) http.Handler
    func clientKey(r *http.Request) string

Requirements

Constraints

  • Depend only on the ratelimit.Limiter interface, not on TokenBucket, FixedWindow, or another concrete implementation.
  • Implement RateLimit as HTTP middleware: it accepts a limiter and returns a function that wraps the next handler.
  • Derive the request key in the unexported clientKey helper. Prefer the X-User-ID header when it is non-empty. Otherwise, use the host part of r.RemoteAddr, prefixed with ip:.
  • Use net.SplitHostPort to remove the port from RemoteAddr. If splitting fails, use the complete RemoteAddr value as the host portion.
  • Treat X-User-ID as a teaching stand-in for an authenticated identity. Do not trust arbitrary client-supplied identity headers in a production deployment.
  • Do not use X-Forwarded-For. Without a trusted proxy boundary, clients can forge it.
  • Call l.Allow(key) once per request. If it returns true, call next.ServeHTTP(w, r) with the original request and response writer.
  • If the limiter rejects the request, set Retry-After to "1", write a JSON response with status 429 and body {"error":"rate_limited"}, then return immediately without calling the next handler.
  • Use the HTTP handler and response writer APIs correctly. Set headers before writing the status because writing the status commits the response headers.
  • Use WriteJSON for the rejection response. Set Content-Type to application/json, write the status, then encode the value with the standard library's JSON encoding support.
  • If JSON encoding fails, log the failure with slog.Error. Do not attempt to write a second response after the status has already been committed.
  • Keep the key helper unexported and avoid global mutable state.
  • The middleware must use HTTP 429 Too Many Requests for rejection and include the Retry-After header.

Acceptance criteria

User identity key: TestW1B5_KeyIsUserIDThenIP in the provided ratelimit_test.go must pass.

  • A request with X-User-ID: 42 is passed to the limiter with key "42".
  • A request without that header and with RemoteAddr set to 10.0.0.1:5555 produces a non-empty key that is not the raw address with its port.

Rejected request: TestW1B5_RejectWrites429WithRetryAfterAndJSON must pass.

  • A limiter rejection produces HTTP status 429.
  • The response includes a Retry-After header.
  • The response body decodes as JSON with "error": "rate_limited".
  • The next handler is not called.

Allowed request: TestW1B5_AllowedRequestPassesThrough must pass.

  • The next handler is called.
  • Its response is returned without middleware modification.

Integration: From backend/, run:

bash
make test W=1B5

The raw package test command is:

bash
go test -race -count=1 ./internal/httpx/

The end-to-end test TestW1B5_RejectedBodyAndHeader arrives in exercise 1.19, once the server is running. It verifies the middleware response through the running HTTP server.

Finished Exercise 1.18?

Implementation

Run locally

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

  1. httpx.RateLimit(l ratelimit.Limiter) func(http.Handler) http.Handler.
  2. The key is the X-User-ID header when present, otherwise ip: plus the host part of r.RemoteAddr.
  3. A rejected request gets status 429, header Retry-After: 1 and the JSON body {"error":"rate_limited"}.
  4. The next handler is not called after a reject.
  5. An allowed request reaches the next handler untouched.
  6. make test W=1B5 passes.

Commands

terminal
cd backend && make test W=1B5

Tests

  • TestW1B5_KeyIsUserIDThenIP in backend/internal/httpx/ratelimit_test.go
  • TestW1B5_RejectWrites429WithRetryAfterAndJSON in backend/internal/httpx/ratelimit_test.go
  • TestW1B5_AllowedRequestPassesThrough in backend/internal/httpx/ratelimit_test.go