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 existing RateLimit middleware 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

  • Check must use the same mutex and fixed-window logic as the existing Allow method.
  • A request increments the window count only when it is allowed.
  • Remaining must be calculated after the request decision and must never be negative.
  • Reset must 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 Allow by delegating to Check.
  • Reuse the existing client-key logic through a shared unexported helper. Do not duplicate the X-User-ID and remote-address handling.
  • Set X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset on every response.
  • Express X-RateLimit-Reset as whole seconds, rounded up, in decimal string format.
  • On rejection, set Retry-After to exactly the same seconds value as X-RateLimit-Reset.
  • Return status 429 and the JSON response {"error":"rate_limited"} using WriteJSON and the existing JSON encoding in Go functionality.
  • Do not change the provided tests.

Acceptance criteria

  • Check reports 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-Remaining and X-RateLimit-Reset with the expected values.
  • Rejected HTTP responses return status 429, report zero remaining requests, include a matching Retry-After header and contain the expected JSON error body.

Run the provided tests:

bash
cd backend && make test W=1O5
Finished Exercise 1.30?

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 2 · Restaurants and menus with MySQL

Week 1 done · Up next · 9 modules

Open week 2

Implementation

Run locally

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

  1. ratelimit.Result has Allowed bool, Limit int, Remaining int and Reset time.Duration, and ratelimit.InfoLimiter has Check(key string) Result.
  2. (*FixedWindow).Check reports the remaining count and the time until the window ends, and it counts the request when it is allowed.
  3. httpx.RateLimitHeaders(l ratelimit.InfoLimiter) sets X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset on every response.
  4. A rejected request also gets status 429, Retry-After in whole seconds and the JSON body {"error":"rate_limited"}.
  5. make test W=1O5 passes.

Commands

terminal
cd backend && make test W=1O5

Tests

  • TestW1O5_CheckReportsLimitRemainingAndReset in backend/internal/httpx/ratelimit_headers_test.go
  • TestW1O5_AllowedResponsesCarryRateLimitHeaders in backend/internal/httpx/ratelimit_headers_test.go
  • TestW1O5_RejectedResponseHasRetryAfterAndZeroRemaining in backend/internal/httpx/ratelimit_headers_test.go