Performance, caching and load testing

5 modules · 7 lessons · 10 exercises · 17 available now

Week 6 overview

  1. 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
  2. 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
  3. 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
  4. Module 4 Backend hardening and admin stats
    • 6.13 Backend audit and soak gate
    • 6.14 Admin order statistics
  5. 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

  1. Module 1: Menu and list caching

    2 items

    You 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 singleflightLesson · 24 min

      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 updaterExercise · 90 min

      You build a Redis-backed restaurant menu and first-page list cache, plus a staff stock updater that persists in_stock and invalidates the affected menu key.

      Open exercise →
  2. Module 2: Service observability

    4 items

    You build observability and request diagnostics for the API and worker, then give database and Redis calls explicit deadlines.

    • 6.3Prometheus metric registrationLesson · 30 min

      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 metricsExercise · 72 min

      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 timeoutsLesson · 24 min

      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 layerExercise · 60 min

      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 →
  3. Module 3: Load-test baselines

    6 items

    You build repeatable browse and order load-test scripts that record API before numbers for the bottleneck analysis that follows.

    • 6.7k6 workload modelsLesson · 30 min

      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 profilingLesson · 24 min

      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 readingLesson · 24 min

      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 measurementsLesson · 35 min

      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 scriptsExercise · 90 min

      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 bottleneckExercise · 150 min

      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 →
  4. Module 4: Backend hardening and admin stats

    2 items

    You 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 gateExercise · 60 min

      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 statisticsExercise · 48 min

      You add Redis-backed admin order statistics that return order counts for a requested rolling window of up to 30 minutes.

      Open exercise →
  5. Module 5: Runtime and performance extensions

    3 items

    You build backend tools for runtime feature control, histogram percentiles and probabilistic cache refresh without blocking Week 6.

    • 6.15Runtime feature switchesExercise · 40 min · Optional

      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 utilityExercise · 50 min · Optional

      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 deciderExercise · 35 min · Optional

      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=W6 passes every graded test, including the optional exercises.
  • k6 run loadtest/browse.js completes 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.js ramps 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 audit passes, 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=N returns 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_seconds by route pattern and status, orders_placed_total, ws_connections, cache hits and misses, and kafka_consumer_lag by consumer group and topic. Keep pprof on a private port.
  • Every response carries X-Request-Id and echoes an incoming request id. Access log lines are JSON with request_id and, after authentication, user_id. A deadline exceeded returns 504; other errors return 500. 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_CONNS and 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 audit and 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 return 403 to customers.
Performance, caching and load testingWeek 6 · 17 items available
Start Module 1: Menu and list caching
Week 6: Performance, caching and load testing · Learn the Zomato tech stack from scratch