Menu cache and stock updater
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.
Ticket
Build the restaurant menu cache and stock updater. A generic Redis cache helper wraps the fully assembled menu and the first page of restaurant listings. The stock update writes items.in_stock and deletes the affected restaurant's menu key.
Popular menus receive repeated reads, but stock changes must not leave customers seeing unavailable items. Use Cache-aside to keep Redis in front of MySQL, and make sure a successful stock update triggers Cache invalidation.
The next module, Metrics, logging and timeouts, measures cache hits and misses. Your cache helper needs to report whether a read was a hit or a miss so those measurements can be recorded.
The cache tests call these exported declarations directly:
type Cache struct{}
func New(rdb *redis.Client, ttl, jitter time.Duration) *Cache
func (c *Cache) Invalidate(ctx context.Context, key string) error
func GetOrLoad[T any](
ctx context.Context,
c *Cache,
key string,
dst *T,
load func(context.Context) (T, error),
) error
func GetOrLoadResult[T any](
ctx context.Context,
c *Cache,
key string,
dst *T,
load func(context.Context) (T, error),
) (bool, error)Acceptance criteria
- Twenty concurrent misses for the same key run the loader exactly once. All callers receive the loaded value, and the next read does not run the loader again.
- Calling
Invalidatecauses the next read to load again. The test expects a load count of2and the newly loaded value to haveID: 2. - When 40 keys are loaded with a base TTL of
100sand jitter of20s, their Redis TTLs stay between99sand121s. At least three distinct TTL values must remain after rounding to seconds. - A loader error is returned to the caller and is not cached. After the first load returns
context.DeadlineExceeded, the next load succeeds withID: 7. - When Redis is unreachable at
127.0.0.1:1,GetOrLoadreturns the loader's value,ID: 9, without an error. - A cache configured with zero jitter does not panic. The loader returns the expected value,
ID: 3. GetOrLoadResultreportsfalsefor the first read andtruefor the second read of the same key.- Reading a restaurant menu twice returns HTTP
200withX-Cache: HITon the second response. - After a successful stock update, the next menu read is not served with
X-Cache: HITand shows the updated item'sin_stockasfalse. The following menu read returnsX-Cache: HIT. The stock update test accepts HTTP200or204. - A customer attempting to change stock receives HTTP
403. Staff belonging to another restaurant also receive HTTP403. The owning restaurant's staff receive HTTP404when updating an unknown item. - The second read of the first restaurant-list page returns
X-Cache: HIT. A cursor-page read must not be served withX-Cache: HIT.
Constraints
Cache helper
- Keep the generic helper in
backend/internal/cache/cache.go. - Accept the cache key from the caller and store values as Redis JSON.
- Calculate expiry as the configured base TTL plus random jitter. A zero jitter configuration is valid.
- Use
context.Contextfor Redis operations and loader calls.
Database and service
- Add
items.in_stockthroughbackend/db/migrations/0008_items_in_stock.up.sqlasTINYINT(1) NOT NULL DEFAULT 1. - The down migration must remove the
in_stockcolumn. - Every item query returning a whole item row must select
id,restaurant_id,name,sortandin_stock. - Add
SetItemStocktobackend/db/queries/menu.sql. Its update condition must include bothidandrestaurant_id. - Regenerate the database code with
sqlc. - Preserve the existing uncached
NewService,MenuandListbehaviour when no cache is configured.
Caching configuration
- Use
menu:{restaurant_id}as the menu cache key. - Set the assembled menu cache TTL to 10 minutes, with up to 60 seconds of random jitter.
- Set the restaurant-list cache TTL to 60 seconds.
- Only cache the first list page. Requests containing a cursor bypass the list cache and must not include
X-Cache.
Stock update
- Use
PUT /v1/admin/restaurants/{id}/items/{item_id}with anin_stockboolean in the JSON body. - A stock update must be scoped to both the restaurant ID and item ID.
- Use the authenticated restaurant principal and the
RestaurantOflookup to verify ownership before changing stock.
Design direction
Keep Redis-specific behaviour in internal/cache. The helper should own JSON encoding, TTL calculation, Redis access and singleflight coordination. It should accept a generic loader and caller-supplied key, without knowing anything about restaurants.
Keep cache keys and loading decisions in internal/restaurant/service.go. The service should cache the fully assembled menu rather than individual database query results. Use the existing sqlc queries to load the item rows and their related sizes, groups, options and prices.
Keep request parsing and authorization in the restaurant HTTP handler. The handler should resolve the authenticated staff member's restaurant before calling the service. The service should update MySQL before requesting invalidation.
Think about these trade-offs:
- Cache the completed menu response rather than separate table results. This makes reads and invalidation easier to reason about, but each cached value contains the assembled menu.
- Use singleflight to coordinate concurrent misses for the same key within one API process. It does not coordinate loads across separate API instances.
- Prefer Fail-open behavior behaviour when Redis is unavailable. Reads remain available through MySQL, but Redis failures can increase database load. A failed invalidation can leave stale data until the Redis TTL expires, so invalidation remains the primary strategy.
Any layout that meets the contract passes.
Notes
How to check your work
Run the migration and regenerate the database code:
cd backend && make up && make migrate && make sqlcRun the cache tests with Redis available:
cd backend && TEST_REDIS_ADDR=127.0.0.1:6379 make test W=6B1Start the API:
cd backend && MYSQL_DSN="root:dev@tcp(127.0.0.1:3306)/zomato?parseTime=true" JWT_SECRET=dev-secret-change-me-32-bytes-min make runIn another terminal, run the API tests:
cd backend && TEST_REDIS_ADDR=127.0.0.1:6379 TEST_API_URL=http://localhost:8080 make test W=6B1Read the first failing assertion before changing code. A loader count points to miss coordination, a TTL assertion points to jitter calculation, a cache header points to hit detection or cursor handling, and a stock assertion points to authorization or invalidation.
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.
Menu and list caching
2 items
- 6.1Cache-aside with jitter and singleflightnot completed
- 6.2Menu cache and stock updaternot completed
Up next · Module 2 · 4 items · about 3 h
Implementation
Run locally
Write the code in your editor inside zomato-prep, then work through this list.
- Add the
in_stockmigration and regenerate the sqlc code. - Implement the generic Redis cache with jitter and singleflight.
- Cache assembled menus and first-page restaurant listings.
- Add the staff-only stock updater and invalidate the affected menu key.
- Pass the cache and API tests with Redis running.
Commands
cd backend && make up && make migrate && make sqlccd backend && TEST_REDIS_ADDR=127.0.0.1:6379 make test W=6B1cd backend && MYSQL_DSN="root:dev@tcp(127.0.0.1:3306)/zomato?parseTime=true" JWT_SECRET=dev-secret-change-me-32-bytes-min make runcd backend && TEST_REDIS_ADDR=127.0.0.1:6379 TEST_API_URL=http://localhost:8080 make test W=6B1Tests
TestW6B1_SecondMenuReadIsACacheHitinbackend/e2e/w6_test.goTestW6B1_StockUpdateInvalidatesTheCachedMenuinbackend/e2e/w6_test.goTestW6B1_OnlyThatRestaurantsStaffCanChangeStockinbackend/e2e/w6_test.goTestW6B1_OnlyTheFirstListPageIsCachedinbackend/e2e/w6_test.goTestW6B1_ConcurrentMissesLoadOnceinbackend/internal/cache/cache_test.goTestW6B1_InvalidateForcesReloadinbackend/internal/cache/cache_test.goTestW6B1_TTLIsJitteredWithinBoundsinbackend/internal/cache/cache_test.goTestW6B1_LoaderErrorIsNotCachedinbackend/internal/cache/cache_test.goTestW6B1_UnreachableRedisFallsBackToTheLoaderinbackend/internal/cache/cache_test.goTestW6B1_ZeroJitterIsAllowedinbackend/internal/cache/cache_test.goTestW6B1_GetOrLoadResultReportsHitOrMissinbackend/internal/cache/cache_test.go