Project setup and rate limiting
9 modules · 16 lessons · 14 exercises · 30 available now
Week 1 overview
- Module 1 Project setup
- 1.1 The Go toolchain, modules and packagesGo modules, Go packages
- 1.2 Makefile, golangci-lint and Docker ComposeMakefile, Go linter, Docker Compose
- 1.3 Create the repo, Makefile, lint config and docker-compose
- Module 2 Go fundamentals
- 1.4 Go basics: types, functions and deferGo functions, Go control flow, Go defer
- 1.5 Structs, pointers, slices and mapsGo structs, Go pointers, Go slices, Go maps
- 1.6 Methods and receiversGo methods and receivers
- 1.7 Interfaces and Go errorsGo interfaces, Go errors
- 1.8 Practice: write your first Go program (optional)
- Module 3 Rate limiting and token bucket algorithms
- 1.9 Rate limiting: why, and the five algorithmsRate limiting, Token bucket, Fixed-window counter, Sliding-window log, Sliding-window counter, Leaky bucket, Fail-open behavior, HTTP 429 Too Many Requests, Retry-After header, Rate-limit response headers
- 1.10 Mutexes and time: making a limiter safe and testableMutex, Go time package, Injected clock
- 1.11 Token bucket limiter with lazy refill
- Module 4 Alternative rate limiters and testing
- 1.12 Go testing: testing.T, subtests and table-driven testsGo testing, Table-driven tests
- 1.13 Goroutines, WaitGroup and the race detectorGoroutines, sync.WaitGroup, Data race, Go race detector
- 1.14 Limiter interface and a FixedWindow implementation
- 1.15 Table-driven tests with a fake clock, plus one race test
- Module 5 HTTP rate limiting
- 1.16 net/http handlers and middlewareHTTP handler, HTTP middleware, HTTP rate-limit identity key, JSON encoding in Go
- 1.17 The chi router and context.ContextChi router, Go context, Context timeout and deadline
- 1.18 RateLimit HTTP middleware that returns 429
- 1.19 chi server with /healthz and a rate limit
- Module 6 Distributed rate limiting with Redis
- 1.20 Redis fundamentals and the Go clientRedis INCR and EXPIRE, Redis TTL, Redis connection from Go, Redis pipelines
- 1.21 Redis atomicity, transactions, Lua and failure handlingRedis transactions, Redis Lua scripts, Redis EVALSHA, Redis fail-open behavior
- 1.22 Redis fixed-window limiter that fails open
- Module 7 Continuous integration
- 1.23 GitHub Actions for GoGitHub Actions, Service containers in CI
- 1.24 GitHub Actions: lint and race tests on every push
- Module 8 Capacity estimation and user load
- 1.25 Capacity: how many users can this rate limiter serve?Capacity estimation, Requests per second (RPS), Little's Law, Peak factor
- Module 9 Optional extensions
- 1.26 Optional: Sliding window log limiter (optional)
- 1.27 Optional: Sliding window counter limiter (optional)
- 1.28 Optional: Leaky bucket limiter (optional)
- 1.29 Optional: Token bucket in Redis with Lua and EVALSHA (optional)
- 1.30 Optional: X-RateLimit response headers (optional)
Weekly learning objectives
By the end of Week 1, you will have a working Go service that demonstrates rate limiting from the algorithm level through HTTP integration and deployment automation.
- The repo and tooling: Set up the
zomato-preprepository as a Go module, organize its packages, and configure a Makefile, golangci-lint, and Docker Compose. MySQL and Redis will be available as local services for the broader course. - The token bucket limiter: Implement an in-memory token bucket that tracks request allowance per key. It supports bursts while enforcing a configured refill rate.
- The fixed window limiter: Define a common
Limiterinterface and implement a fixed-window counter. Both algorithms expose the same operation, even though their internal state and decisions differ. - Tests, including a race test: Write table-driven tests, control time through an injected clock, and exercise concurrent access. Run the race detector to catch unsafe shared-memory access.
- The HTTP middleware and chi server: Connect the limiter to HTTP middleware that identifies clients, rejects excess requests with HTTP 429, and provides a
Retry-Afterheader. Build a chi server with a/healthzendpoint that demonstrates the rate limit in action. - The Redis-backed limiter: Move fixed-window counting into Redis so multiple application instances can share request counts. Add an in-memory fallback for Redis failures and make the fail-open behavior explicit.
- CI: Configure GitHub Actions to run linting and tests, including race-enabled tests, with Redis available for integration tests.
System architecture and changes
You start with isolated Go implementations and gradually connect them into a service. By the end of the week, requests pass through a router and middleware, while the limiter implementation decides whether each request can proceed. The in-memory token bucket and Redis-backed fixed window demonstrate two different ways to enforce a limit. CI checks that the code remains consistent and that the tests pass.


Key concepts and principles
Three engineering ideas connect the entire implementation:
- The interface hides the algorithm: HTTP middleware depends on a
Limiterinterface, not on a token bucket or fixed-window implementation. You can change the algorithm without rewriting the middleware. - Injected time makes tests deterministic: Rate limiters depend on time, but tests should not have to wait for real seconds to pass. Supplying a controllable clock lets you test refills, window boundaries, and expiration precisely.
- Redis failures require an explicit decision: A distributed limiter depends on an external service. When Redis becomes unavailable, the application must decide whether to reject requests or allow them using a local fallback. This week uses a fail-open approach and makes its limitations visible.
How to complete the coursework
Work through each module's lessons before attempting its exercise. Lessons introduce the concepts and explain the implementation decisions. Exercises ask you to apply those ideas in the repository. Do not skip ahead when an exercise depends on a concept you have not studied yet.
Module 2 includes an optional practice exercise to help you get comfortable writing Go before implementing the rate limiter. Module 8 contains optional extensions, including alternative algorithms and more advanced Redis techniques. These are opportunities to explore further, not requirements for completing Week 1.
Before starting exercises that depend on local services, run make up from the repository. This starts the services defined in Docker Compose. Keep them running while working on exercises that use them.
Write and run your code in your own editor inside the zomato-prep repository. Each exercise's Run locally panel lists the commands to execute and describes what passing looks like. Use those checks as you work, rather than waiting until the end to discover that something is broken.
One detail about the server demonstration: /healthz is rate limited in this week's implementation so you can observe HTTP 429 behavior through a real endpoint. This is a teaching choice, not a production recommendation. In a production service, health checks used by load balancers and orchestration systems should generally remain available independently of application rate limits.
Modules
Module 1: Project setup
3 itemsInstall the toolchain, learn how Go organises code, and create the repository, Makefile, lint configuration and local MySQL and Redis that every later exercise uses.
1.1The Go toolchain, modules and packages
Install Go, read a go.mod, understand what a package is, how imports resolve inside a module, and how the standard commands (build, run, test, vet, fmt) fit together.
Open lesson →1.2Makefile, golangci-lint and Docker Compose
The three files that make a backend repo repeatable: a Makefile of short commands, a golangci-lint config that catches bugs before review, and a docker-compose.yml that starts MySQL and Redis with one command.
Open lesson →1.3Create the repo, Makefile, lint config and docker-compose
Create the backend module with the cmd/ and internal/ layout, a Makefile with lint, test, run, up and down targets, a golangci-lint config, and a docker-compose file for MySQL and Redis.
Open exercise →
Module 2: Go fundamentals
5 itemsLearn the parts of Go a rate limiter is built from: functions and control flow, structs, pointers, slices and maps, methods, interfaces and errors.
1.4Go basics: types, functions and defer
The parts of Go you need before writing a limiter: variables and types, constants, control flow, functions with multiple return values, and defer.
Open lesson →1.5Structs, pointers, slices and maps
The data structures a rate limiter is built from: structs for state, pointers for shared mutable state, slices and maps for collections, with the gotchas that bite beginners.
Open lesson →1.6Methods and receivers
Attach behaviour to a struct with methods, choose between value and pointer receivers, and write the constructor and method set a limiter type needs.
Open lesson →1.7Interfaces and Go errors
Describe what a type can do with an interface, satisfy it implicitly, and handle failure with error values. This is how Limiter, TokenBucket and FixedWindow fit together.
Open lesson →1.8Practice: write your first Go program
A short warm-up with no repo tests: a small program with a struct, a method, a map, a function with two return values, an error and a defer.
Open exercise →
Module 3: Rate limiting and token bucket algorithms
3 itemsLearn why APIs limit requests and how the five main algorithms work, then learn the mutex and clock patterns and implement a token bucket.
1.9Rate limiting: why, and the five algorithms
Why an API limits requests, how to choose a key, what a good 429 response looks like, and a full tour of the token bucket, fixed window counter, sliding window log, sliding window counter and leaky bucket, with their trade-offs.
Open lesson →1.10Mutexes and time: making a limiter safe and testable
Why a map shared by many requests needs a lock, how sync.Mutex protects it, how the time package measures elapsed time, and why a limiter takes its clock as a function so tests can control time.
Open lesson →1.11Token bucket limiter with lazy refill
Implement the Limiter interface and a token bucket with a mutex-protected map of buckets, lazy refill from elapsed time and an injected clock.
Open exercise →
Module 4: Alternative rate limiters and testing
4 itemsLearn Go testing and concurrency, implement a fixed window limiter, and write table-driven and race tests for both limiters.
1.12Go testing: testing.T, subtests and table-driven tests
How go test works, how to write table-driven tests with subtests, and how to test time-dependent code by advancing a fake clock instead of sleeping.
Open lesson →1.13Goroutines, WaitGroup and the race detector
Start concurrent work with goroutines, wait for it with sync.WaitGroup, and find unsynchronised access with go test -race. This is how you prove a limiter is safe under load.
Open lesson →1.14Limiter 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.
Open exercise →1.15Table-driven tests with a fake clock, plus one race test
Write your own table-driven tests for both limiters using a fake clock, and add a concurrent test that passes under the race detector.
Open exercise →
Module 5: HTTP rate limiting
4 itemsLearn net/http handlers, middleware, the chi router and context, then wrap the limiter in middleware and serve it.
1.16net/http handlers and middleware
How a Go HTTP server turns a request into a call to a handler, what the ResponseWriter and Request give you, and how middleware wraps a handler to add behaviour such as rate limiting.
Open lesson →1.17The chi router and context.Context
Route requests with chi, add the standard middleware (request id, logger, recoverer), read the request context, and understand why context carries cancellation and deadlines.
Open lesson →1.18RateLimit 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.
Open exercise →1.19chi server with /healthz and a rate limit
Wire the middleware into a chi server with request id and logging, serve GET /healthz, and curl it until it answers 429.
Open exercise →
Module 6: Distributed rate limiting with Redis
3 itemsLearn Redis and its Go client, atomic operations and failure handling, then share one fixed window across API instances with a fail-open fallback.
1.20Redis fundamentals and the Go client
What Redis is, keys and expiry, INCR and EXPIRE, how a pipeline batches commands, and how to create a go-redis client and call it with a context and a timeout.
Open lesson →1.21Redis atomicity, transactions, Lua and failure handling
Why INCR then EXPIRE must not be split, how MULTI/EXEC and a Lua script make steps atomic, how EVALSHA caches a script, and how to fail open with an in-memory fallback and a single log line.
Open lesson →1.22Redis fixed-window limiter that fails open
Share a fixed window across API instances with Redis INCR and EXPIRE NX in a transaction pipeline, with a short timeout and an in-memory fallback that logs once.
Open exercise →
Module 7: Continuous integration
2 itemsLearn GitHub Actions and run lint and the race detector on every push, with a Redis service container.
1.23GitHub Actions for Go
Run lint and tests on every push: workflows, jobs, steps and triggers, caching Go modules, and service containers that give a job real MySQL and Redis.
Open lesson →1.24GitHub Actions: lint and race tests on every push
Add a workflow that runs golangci-lint and go test -race with a Redis service container on every push and pull request.
Open exercise →
Module 8: Capacity estimation and user load
1 itemsLearn back-of-the-envelope capacity estimation and work through the full calculation for the Week 1 rate limiter.
1.25Capacity: how many users can this rate limiter serve?
Back-of-the-envelope capacity estimation with the full calculation: requests per second, peak load, Little's Law, Redis throughput and memory, and how many API instances and Redis primaries the Week 1 limiter needs for a million registered users.
Open lesson →
Module 9: Optional extensions
5 itemsExtra exercises for the other algorithms and for response headers. They never block the week.
1.26Optional: Sliding window log limiter
Implement a limiter that records one timestamp per allowed request and counts the ones inside the last window, so it has no boundary burst.
Open exercise →1.27Optional: Sliding window counter limiter
Implement a limiter that keeps two counters per key, the current and previous fixed windows, and estimates the sliding count by weighting the previous window by how much of it still overlaps.
Open exercise →1.28Optional: Leaky bucket limiter
Implement the leaky bucket as a meter: each request adds one unit to a bucket that drains at a constant rate, and a request is rejected when it would overflow.
Open exercise →1.29Optional: Token bucket in Redis with Lua and EVALSHA
Move the token bucket into Redis as one Lua script that refills and takes a token atomically, run through go-redis with EVALSHA, sharing state across instances and failing open.
Open exercise →1.30Optional: 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.
Open exercise →
Completion checklist
What should be true at the end of the week.
- Running
go test -race ./...locally and in CI completes successfully. - Running
make lintreports no issues. - Seven quick curls to
/healthzreturn five200responses followed by a429, and a request one second later returns200again. - The
429response includes aRetry-Afterheader and a JSON body containing{"error":"rate_limited"}. - Stopping Redis does not make the API fail, and the first Redis failure is logged exactly once.
- The GitHub Actions workflow completes successfully on the
mainbranch.
Week requirements
Rules every piece of code this week must follow.
- All rate-limiting algorithms implement the same
Limiterinterface. - The clock is injected as a
func() time.Time, and tests never calltime.Sleep. - All shared mutable state is protected by a mutex, and the race detector reports no data races.
- No package-level mutable state is permitted.
- Every rate-limit rejection returns a
429response with the JSON body{"error":"rate_limited"}and aRetry-Afterheader. - Every Redis call uses a short context timeout, and the limiter fails open when Redis is unavailable.
- Optional extras must never block completion of the required Week 1 work.