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:
RateLimitwraps an HTTP handler and checks each request against a limiter.- Requests are keyed by
X-User-IDwhen present, otherwise by the client's IP address without its port. - Rejected requests receive HTTP 429, a
Retry-Afterheader, and a JSON error body. - Allowed requests pass through to the next handler unchanged.
- JSON responses are written through one shared
WriteJSONhelper.
Deliverables
Write these files in backend/internal/httpx/, using package httpx.
-
backend/internal/httpx/json.go: implement a shared JSON response helper usingencoding/jsonandlog/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 withslog.Error. -
backend/internal/httpx/ratelimit.go: implement the middleware and its unexported client-key helper. Import the limiter package fromgithub.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.Limiterinterface, not onTokenBucket,FixedWindow, or another concrete implementation. - Implement
RateLimitas HTTP middleware: it accepts a limiter and returns a function that wraps the next handler. - Derive the request key in the unexported
clientKeyhelper. Prefer theX-User-IDheader when it is non-empty. Otherwise, use the host part ofr.RemoteAddr, prefixed withip:. - Use
net.SplitHostPortto remove the port fromRemoteAddr. If splitting fails, use the completeRemoteAddrvalue as the host portion. - Treat
X-User-IDas 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, callnext.ServeHTTP(w, r)with the original request and response writer. - If the limiter rejects the request, set
Retry-Afterto"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
WriteJSONfor the rejection response. SetContent-Typetoapplication/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: 42is passed to the limiter with key"42". - A request without that header and with
RemoteAddrset to10.0.0.1:5555produces 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-Afterheader. - 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:
make test W=1B5The raw package test command is:
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.
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.
httpx.RateLimit(l ratelimit.Limiter) func(http.Handler) http.Handler.- The key is the
X-User-IDheader when present, otherwiseip:plus the host part ofr.RemoteAddr. - A rejected request gets status 429, header
Retry-After: 1and the JSON body{"error":"rate_limited"}. - The next handler is not called after a reject.
- An allowed request reaches the next handler untouched.
make test W=1B5passes.
Commands
cd backend && make test W=1B5Tests
TestW1B5_KeyIsUserIDThenIPinbackend/internal/httpx/ratelimit_test.goTestW1B5_RejectWrites429WithRetryAfterAndJSONinbackend/internal/httpx/ratelimit_test.goTestW1B5_AllowedRequestPassesThroughinbackend/internal/httpx/ratelimit_test.go