Admin order statistics
You add Redis-backed admin order statistics that return order counts for a requested rolling window of up to 30 minutes.
Ticket
Build a Redis-backed statistics store and an authenticated admin handler. The store maintains one counter per UTC minute and returns the total orders for a requested rolling window. Expose the statistics through GET /v1/admin/stats?minutes=N.
The product needs these counts so restaurant staff can monitor recent order volume without repeatedly querying MySQL. Connect the store to successful order creation, preserving idempotency and ensuring that a Redis failure never changes the result of an already-created order.
The tests exercise these exported declarations directly:
func New(rdb *redis.Client) *Stats
func Key(at time.Time) string
func (s *Stats) Record(ctx context.Context, at time.Time) error
func (s *Stats) Orders(ctx context.Context, now time.Time, minutes int) (int, error)
var ErrBadWindow error
type Stats struct { ... }The route GET /v1/admin/stats?minutes=N returns JSON {"orders": n} to restaurant staff, HTTP 403 to customers and HTTP 400 when the requested window is outside 1 to 30 or is not a number. How you wire the handler into the API and record statistics from the order path is up to you.
Acceptance criteria
- A timestamp of
2026-11-04 07:05:59in theISTfixed time zone produces the keyorders:202611040135. Two instants within the same UTC minute produce the same key. - Recording three orders in the same minute produces an aggregated count of
3. - A 5-minute window includes the current minute and the minute four minutes ago, but excludes the minute five minutes ago. A 30-minute window includes all four recorded orders in the test.
- An empty 30-minute window returns
0without an error. - A recorded bucket has a Redis TTL greater than 30 minutes and no greater than 31 minutes.
- Requests for windows of
0,-1,31and1000returnErrBadWindowfromOrders. - Placing a new order increases a restaurant staff user's recent order count by at least
1. A customer requestingGET /v1/admin/stats?minutes=5receives HTTP403. The successful response body is JSON containing anordersfield. - Requests with
minutes=0,minutes=31,minutes=-1andminutes=abcreceive HTTP400. A restaurant user requestingminutes=30receives HTTP200.
Constraints
- Generate Redis keys with the prefix
orders:and the UTC formatyyyymmddhhmm. - Keep each bucket for more than 30 minutes and at most 31 minutes.
- Use Redis rather than MySQL for recent order aggregation.
- Accept rolling windows from 1 to 30 minutes, inclusive.
- Do not modify, remove, skip or weaken the provided tests.
Design direction
Keep Redis storage and HTTP handling separate. Let the stats package own key generation, recording and aggregation. Let the HTTP handler validate the request and translate errors into HTTP responses.
Use Redis INCR and EXPIRE together in a pipeline when recording an order. An increment without expiration would leave old buckets in Redis indefinitely. A 31-minute expiration provides a small margin for the oldest bucket in a 30-minute window. See Redis TTL for the expiration behaviour.
For aggregation, construct the keys for the current minute and the preceding minutes - 1 minutes. Fetch them together using MGET. Missing buckets represent minutes without orders, so count them as zero. Avoid issuing one Redis command per minute.
Keep the HTTP handler small. Authenticate the caller through the existing JWT authentication middleware and allow only the restaurant role. Use the established read timeout and httpx.Fail for Redis errors. The existing HTTP handler conventions should determine the response format.
Integrate the recorder after a newly created order succeeds. Do not record an idempotent replay. Use context.WithoutCancel so client disconnection does not cancel the statistics operation. Log recording failures without changing the successful order response.
Think about the trade-off between a short-lived counter and a full analytics system. Per-minute buckets suit recent operational counts, but they do not provide long-term history or per-restaurant breakdowns. The resulting order count is one of the operational measurements used alongside the four golden signals. Any layout that meets the contract passes.
How to check your work
Start Docker Compose services, including Redis, before running the tests.
From the repository root:
cd backend
TEST_REDIS_ADDR=127.0.0.1:6379 make test W=6B7
TEST_API_URL=http://localhost:8080 make test W=6B7Start the API with make run in another terminal before running the end-to-end command. The second test command needs the API listening at localhost:8080.
For a manual check, authenticate as a restaurant staff user and request:
GET /v1/admin/stats?minutes=5Confirm that the response contains an orders field with the count for the last five minutes. Then try the same request as a customer and confirm HTTP 403. Test explicit windows such as minutes=30 and minutes=0 to verify the upper limit and validation.
When a test fails, read its first failing assertion. It identifies whether the problem is UTC key generation, bucket aggregation, expiration, window validation, order recording or HTTP authorization.
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.
Backend hardening and admin stats
2 items
- 6.13Backend audit and soak gatenot completed
- 6.14Admin order statisticsnot completed
Up next · Module 5 · 3 items · about 2 h
Implementation
Run locally
Write the code in your editor inside zomato-prep, then work through this list.
- Redis keys use UTC minute buckets with the
orders:prefix. - Recording increments buckets and sets their 31-minute expiration.
- Rolling windows use one MGET and treat missing buckets as zero.
- Admin statistics return the correct order count for 1 to 30 minutes.
- Only restaurant-role users can access the statistics endpoint.
- New orders are recorded without changing idempotency or order reliability.
Commands
cd backend && TEST_REDIS_ADDR=127.0.0.1:6379 make test W=6B7cd backend && TEST_API_URL=http://localhost:8080 make test W=6B7Tests
TestW6B7_AdminStatsCountsRecentOrdersinbackend/e2e/w6_test.goTestW6B7_MinutesOutsideTheWindowIsRejectedinbackend/e2e/w6_test.goTestW6B7_KeyIsOneBucketPerUTCMinuteinbackend/internal/stats/stats_test.goTestW6B7_OrdersInTheSameMinuteAreSummedinbackend/internal/stats/stats_test.goTestW6B7_WindowCoversTheLastMinutesIncludingTheCurrentOneinbackend/internal/stats/stats_test.goTestW6B7_MissingBucketsCountAsZeroinbackend/internal/stats/stats_test.goTestW6B7_BucketExpiresAfterThirtyOneMinutesinbackend/internal/stats/stats_test.goTestW6B7_WindowOutsideOneToThirtyIsRejectedinbackend/internal/stats/stats_test.go