Optional: X-RateLimit response headers
Report the limit, remaining requests and time until reset on every response, and send a matching Retry-After on a 429.
Objective
This optional exercise extends the fixed-window limiter to report useful rate-limit information to HTTP clients. You will implement rate-limit response headers that communicate the configured limit, remaining requests and time until reset. When a request is rejected, the middleware will also send a matching Retry-After header and an HTTP 429 Too Many Requests response. This exercise is optional and never blocks completion of Week 1.
By the end:
- You will understand how HTTP middleware can inspect a request, make a decision and set response headers.
- You will extend an existing limiter using Go interfaces and Go methods and receivers.
- You will expose the state of a fixed-window counter without duplicating its counting logic.
- You will report consistent rate-limit information on both accepted and rejected requests.
Deliverables
-
backend/internal/ratelimit/info.go: Define the result returned by an informational limiter and its interface.go type Result struct { Allowed bool Limit int Remaining int Reset time.Duration } type InfoLimiter interface { Check(key string) Result } func (fw *FixedWindow) Check(key string) Result -
backend/internal/httpx/ratelimit_headers.go: Implement the middleware that reports rate-limit information on every response.go func RateLimitHeaders(l ratelimit.InfoLimiter) func(http.Handler) http.Handler -
backend/internal/httpx/ratelimit.go: Update the existingRateLimitmiddleware to reuse a shared, unexported client-key helper. Both middleware implementations must derive the same key from the request.
Create the two new files and update the existing ratelimit.go. The provided tests are already written in backend/internal/httpx/ratelimit_headers_test.go. Run them without editing the test file.
Requirements
Constraints
Checkmust use the same mutex and fixed-window logic as the existingAllowmethod.- A request increments the window count only when it is allowed.
Remainingmust be calculated after the request decision and must never be negative.Resetmust represent the duration between the current time and the end of the active window, using the Go time package.- Keep one source of truth for the fixed-window counting logic. You may implement
Allowby delegating toCheck. - Reuse the existing client-key logic through a shared unexported helper. Do not duplicate the
X-User-IDand remote-address handling. - Set
X-RateLimit-Limit,X-RateLimit-RemainingandX-RateLimit-Reseton every response. - Express
X-RateLimit-Resetas whole seconds, rounded up, in decimal string format. - On rejection, set
Retry-Afterto exactly the same seconds value asX-RateLimit-Reset. - Return status
429and the JSON response{"error":"rate_limited"}usingWriteJSONand the existing JSON encoding in Go functionality. - Do not change the provided tests.
Acceptance criteria
Checkreports the configured limit, remaining requests and reset duration correctly. An allowed request consumes one request, while a rejected request does not increase the count.- Allowed HTTP responses contain
X-RateLimit-Limit,X-RateLimit-RemainingandX-RateLimit-Resetwith the expected values. - Rejected HTTP responses return status
429, report zero remaining requests, include a matchingRetry-Afterheader and contain the expected JSON error body.
Run the provided tests:
cd backend && make test W=1O5The 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.
Optional extensions
5 items
- 1.26Optional: Sliding window log limiternot completed
- 1.27Optional: Sliding window counter limiternot completed
- 1.28Optional: Leaky bucket limiternot completed
- 1.29Optional: Token bucket in Redis with Lua and EVALSHAnot completed
- 1.30Optional: X-RateLimit response headersnot completed
Week 1 done · Up next · 9 modules
Implementation
Run locally
Write the code in your editor inside zomato-prep, then work through this list.
ratelimit.ResulthasAllowed bool,Limit int,Remaining intandReset time.Duration, andratelimit.InfoLimiterhasCheck(key string) Result.(*FixedWindow).Checkreports the remaining count and the time until the window ends, and it counts the request when it is allowed.httpx.RateLimitHeaders(l ratelimit.InfoLimiter)setsX-RateLimit-Limit,X-RateLimit-RemainingandX-RateLimit-Reseton every response.- A rejected request also gets status 429,
Retry-Afterin whole seconds and the JSON body{"error":"rate_limited"}. make test W=1O5passes.
Commands
cd backend && make test W=1O5Tests
TestW1O5_CheckReportsLimitRemainingAndResetinbackend/internal/httpx/ratelimit_headers_test.goTestW1O5_AllowedResponsesCarryRateLimitHeadersinbackend/internal/httpx/ratelimit_headers_test.goTestW1O5_RejectedResponseHasRetryAfterAndZeroRemaininginbackend/internal/httpx/ratelimit_headers_test.go