Limiter interface and a FixedWindow implementation
Add a second Limiter, a mutex-protected fixed window counter, and see the window boundary behaviour that the token bucket does not have.
Objective
Add a second implementation of the Limiter interface from exercise 1.11: a per-key fixed-window counter. Unlike the token bucket, this limiter counts requests within fixed time intervals and resets a key's count when a new interval begins.
By the end:
FixedWindowimplements the existingLimiterinterface.- Each key has an independent request count and window start time.
- Requests beyond the configured limit are rejected until the next window.
- The implementation is safe for concurrent access.
- Both
FixedWindowandTokenBucketare checked against the interface at compile time.
Deliverables
-
backend/internal/ratelimit/fixed_window.go: Replace the temporary stub from exercise 1.11 with the real implementation.Define a window record using a struct to store the window start time and request count. Define
FixedWindowwith async.Mutex, a map of per-key window records, the request limit, the window size, and an injected clock.Implement the constructor:
go func NewFixedWindow(limit int, size time.Duration, now func() time.Time) *FixedWindowA nil clock must default to
time.Now.Implement the admission method:
go func (fw *FixedWindow) Allow(key string) boolAdd a compile-time interface assertion:
go var _ Limiter = (*FixedWindow)(nil) -
backend/internal/ratelimit/token_bucket.go: Keep the token bucket implementation from exercise 1.11. Add a compile-time assertion to verify that it also implementsLimiter:go var _ Limiter = (*TokenBucket)(nil) -
backend/internal/ratelimit/limiter.go: Keep the existingLimiterinterface unchanged.go type Limiter interface { Allow(key string) bool } -
backend/internal/ratelimit/limiter_test.go: The provided test file already containsTestW1B3_FixedWindowBoundary. Do not rewrite it.The test uses a fake clock with a limit of
2and a window size of one second. The first two calls for keyureturntrue, the third returnsfalse, and the first call after advancing the clock by one second returnstruebecause a new window has started.
Requirements
Constraints
- Implement
FixedWindowas another implementation of the existingLimiterinterface. Review the interface and method concepts from lessons 1.7 and 1.6. - Store a window start time and request count for each key.
- Protect the map and all per-key window state with a mutex.
- The mutex must cover the entire read-modify-write operation for a key: lookup, window comparison, reset, limit check, and increment.
- Calculate the current window start using
now.Truncate(size), wherenowcomes only from the injected clock. - Read time only through the
nowfield. Calltime.Nowonly when selecting the default clock in the constructor. - When a key has no record, or its stored window start is older than the current window start, begin a fresh record with count zero.
- Reject a request when the count is already at the configured limit. Otherwise, increment the count and allow the request.
- Keep counts independent across keys.
- Do not carry unused requests or counts into the next window.
- Remove the temporary
FixedWindowstub from exercise 1.11. Thefixed_window.gofile must now contain the real implementation, not both the stub and the real type. - Keep
limiter.gounchanged. - Do not introduce package-level mutable state or global variables.
- Use the existing fake clock and tests. Do not redeclare test helpers or test functions.
- Every access to the map must happen while holding the lock. In exercise 1.15, the limiter will be called from many goroutines under the race detector. An unsynchronized map access can cause a data race or a concurrent map access panic.
Acceptance criteria
Run the tests from backend/:
make test W=1B3For verbose output, run:
make test W=1B3 V=1You can also run both the token bucket and fixed-window tests directly:
go test -race -count=1 -run "TestW1B2|TestW1B3" ./internal/ratelimit/The implementation must satisfy these behaviors:
- Limit within one window: With a limit of
3and a window size of10seconds, three calls for the same key at the same instant returntrue,true, andtrue. The fourth returnsfalse. - Reset at the next window: At the first instant of the next 10-second window, the same key can make another request, which returns
true. - Independent keys: Two different keys each have their own count. Reaching the limit for one key must not prevent requests for another.
- No carryover: If a key uses only part of its allowance in one window, the unused requests do not carry into the next window. The new window starts with a fresh count of zero.
- Boundary behavior: A fixed window can allow up to twice the configured limit across a boundary: requests can use the remaining allowance just before the boundary and the full allowance immediately after it.
- Interface compatibility: Both
FixedWindowandTokenBucketsatisfyLimiter, verified by compile-time assertions. - Package tests compile: The real
FixedWindowreplaces the temporary stub, somake test W=1B2andmake test W=1B3both run without the stub.
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.
NewFixedWindow(limit int, size time.Duration, now func() time.Time)returns a*FixedWindowthat satisfiesLimiter.- Within one window at most
limitcalls per key are allowed. - The window start is the injected clock truncated to the window size, so a new window resets the count.
make test W=1B3passes.
Commands
cd backend && make test W=1B3Tests
TestW1B3_FixedWindowBoundaryinbackend/internal/ratelimit/limiter_test.go