Performance, caching and load testing
5 modules · 7 lessons · 10 exercises · 17 available now
Week 6 overview
- Module 1 Menu and list caching
- 6.1 Cache-aside with jitter and singleflightCache-aside, TTL jitter, Thundering herd, singleflight, Cache invalidation
- 6.2 Menu cache and stock updater
- Module 2 Service observability
- 6.3 Prometheus metric registrationPrometheus metrics, Histogram metric, Counter metric, Gauge metric, Label cardinality, Four golden signals
- 6.4 API and worker metrics
- 6.5 Request-scoped logging and timeoutsStructured logging, Request id, 504 gateway timeout
- 6.6 Request context and timeout layer
- Module 3 Load-test baselines
- 6.7 k6 workload modelsLoad test, Virtual user, Load stages, Latency percentile, k6 threshold
- 6.8 CPU and heap profilingpprof, CPU profile, Heap profile, Goroutine leak
- 6.9 MySQL query-plan readingEXPLAIN access type, Using filesort, SHOW PROCESSLIST
- 6.10 Capacity from measurementsSaturation, Headroom, Capacity statement
- 6.11 Browse and order k6 scripts
- 6.12 Find and fix the first bottleneck
- Module 4 Backend hardening and admin stats
- 6.13 Backend audit and soak gate
- 6.14 Admin order statistics
- Module 5 Runtime and performance extensions
- 6.15 Runtime feature switches (optional)
- 6.16 Histogram quantile utility (optional)
- 6.17 XFetch cache refresh decider (optional)
Weekly learning objectives
Week 5 made the system live. This week you make it hold up under load: cache hot reads, measure requests, run load tests, find the first bottleneck and compare the before and after numbers.
- Menu and list caching: Cache restaurant menus and first-page listings with jittered TTLs, singleflight and invalidation when stock changes.
- Service observability: Add API and worker metrics, private pprof, request ids, JSON access logs and per-call deadlines.
- Load-test baselines: Build repeatable k6 browse and order scripts and record the API before numbers.
- Backend hardening and admin stats: Add release checks, a bounded database pool and per-minute order statistics for restaurant staff.
- Runtime and performance extensions: Add optional tools for runtime feature control, histogram percentiles and probabilistic cache refresh.
System architecture and changes
The shape of the system does not change this week. Redis now sits in front of hot menu and list reads, every database and Redis call has a deadline, and both binaries expose operational metrics. You measure the system under load before changing it, then compare the same measurements after fixing a bottleneck.
How to complete the coursework
Build the cache and observability before running the load tests. Record the before numbers, change one thing per run and save the k6 summaries and pprof output. Use them to document the before and after numbers in the README.
Start the dependencies with make up, then run cd backend && make test W=W6 to run every graded test, including the optional build-tagged exercises. Set TEST_REDIS_ADDR=127.0.0.1:6379 for Redis-dependent tests. Run the API and worker for the end-to-end tests using TEST_API_URL=http://localhost:8080 and TEST_WORKER_URL=http://localhost:8081.
The full list of lessons and exercises is shown below.
Modules
Module 1: Menu and list caching
2 itemsYou build cached restaurant menus and first-page listings, reducing repeated database reads while stock updates invalidate stale menu data.
6.1Cache-aside with jitter and singleflight
You can combine cache-aside, jitter and singleflight so concurrent menu reads share a rebuild instead of stampeding MySQL.
Open lesson →6.2Menu cache and stock updater
You build a Redis-backed restaurant menu and first-page list cache, plus a staff stock updater that persists
Open exercise →in_stockand invalidates the affected menu key.
Module 2: Service observability
4 itemsYou build observability and request diagnostics for the API and worker, then give database and Redis calls explicit deadlines.
6.3Prometheus metric registration
You can register bounded Prometheus counters, gauges, and histograms so the next exercise can expose service behaviour without creating a series for every URL.
Open lesson →6.4API and worker metrics
You build API and worker metrics that expose request duration, order creation, cache lookups, WebSocket connections, and Kafka consumer lag. Route labels use chi patterns, never raw paths.
Open exercise →6.5Request-scoped logging and timeouts
You can propagate request IDs through JSON logs and bound dependency calls so the API returns a controlled timeout instead of leaving requests hanging.
Open lesson →6.6Request context and timeout layer
You build request context middleware and shared timeout and error helpers that carry request ids, bound database and Redis calls, and map deadline failures to HTTP 504.
Open exercise →
Module 3: Load-test baselines
6 itemsYou build repeatable browse and order load-test scripts that record API before numbers for the bottleneck analysis that follows.
6.7k6 workload models
You can choose a closed virtual-user workload for browsing and an open arrival-rate workload for orders to generate the traffic patterns you need to measure.
Open lesson →6.8CPU and heap profiling
You can capture CPU and heap profiles during a load test to locate expensive code and goroutines that remain blocked under pressure.
Open lesson →6.9MySQL query-plan reading
You can read MySQL access types and process-list state to identify scans or sorting that slow restaurant and menu queries.
Open lesson →6.10Capacity from measurements
You can turn measured throughput and latency into a capacity statement with explicit headroom before deciding what to scale or optimize.
Open lesson →6.11Browse and order k6 scripts
You build browse and order k6 scripts that exercise the restaurant and order APIs and save reproducible before-number summaries.
Open exercise →6.12Find and fix the first bottleneck
You add a bounded MySQL connection pool and live Prometheus metrics while finding and fixing the first bottleneck under the 300 VU browse workload and recording before-and-after results.
Open exercise →
Module 4: Backend hardening and admin stats
2 itemsYou build backend release checks and per-minute order statistics so deployments stay safer and restaurant staff can monitor order volume.
6.13Backend audit and soak gate
You add a backend audit target and a 10-minute soak script that scan dependencies, lint production code, run race tests, and check goroutine recovery.
Open exercise →6.14Admin order statistics
You add Redis-backed admin order statistics that return order counts for a requested rolling window of up to 30 minutes.
Open exercise →
Module 5: Runtime and performance extensions
3 itemsYou build backend tools for runtime feature control, histogram percentiles and probabilistic cache refresh without blocking Week 6.
6.15Runtime feature switches
You build a runtime feature-switch component that stores named flags and routes each request to a feature handler or fallback. Unknown flags stay enabled, and updates affect subsequent requests.
Open exercise →6.16Histogram quantile utility
You build a histogram quantile utility that parses Prometheus exposition samples into sorted buckets and calculates a requested latency percentile. Matching series are merged by bucket boundary before quantile calculation.
Open exercise →6.17XFetch cache refresh decider
You build a pure XFetch refresh decision function that uses expiry time, recomputation duration, beta and an injected random source to decide whether a cache entry should refresh early.
Open exercise →
Completion checklist
What should be true at the end of the week.
cd backend && make test W=W6passes every graded test, including the optional exercises.k6 run loadtest/browse.jscompletes the default 300-VU, three-minute run without failed checks. The after-browse p99 is under 300 ms and is not worse than before.k6 run loadtest/order.jsramps to 100 orders per second over two minutes, with a distinct order created per iteration.- The README before and after section records p50, p95, p99 and error rate, along with the change that moved the measurements.
make auditpasses, and the CI workflow runs govulncheck. The soak script samples goroutines and heap, and goroutines return to baseline after a burst.GET /v1/admin/stats?minutes=Nreturns recent order counts for a window of 1 to 30 minutes, including the current minute.
Week requirements
Rules every piece of code this week must follow.
- Menu caching uses
menu:{restaurant id}with a base TTL plus random jitter (the test uses 100 seconds plus up to 20). Concurrent misses load once, loader errors are not cached, and unreachable Redis falls back to the loader. - Stock updates invalidate the affected restaurant's cached menu. Only that restaurant's staff can change its stock. Cache only the first restaurant-list page.
- Expose
http_request_duration_secondsby route pattern and status,orders_placed_total,ws_connections, cache hits and misses, andkafka_consumer_lagby consumer group and topic. Keep pprof on a private port. - Every response carries
X-Request-Idand echoes an incoming request id. Access log lines are JSON withrequest_idand, after authentication,user_id. A deadline exceeded returns504; other errors return500. Read and write timeouts are 500 ms and 2 seconds. - Bound the database connection pool by default. Read its maximum open connections from
DB_MAX_OPEN_CONNSand export pool statistics. - Browse load tests default to 300 VUs for three minutes and assert p99. Order load tests ramp to 100 orders per second over two minutes and create distinct orders per iteration. After-browse must have no server errors, must not be worse than before and must have p99 under 300 ms.
- Record p50, p95, p99 and error rate in the README before and after section. Run govulncheck, golangci-lint and race tests through
make auditand CI. The soak script must sample goroutines and heap. Admin stats use one Redis bucket per UTC minute, expire after 31 minutes, sum orders within each minute, count missing buckets as zero, reject windows outside 1 to 30 minutes and return403to customers.