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:

go
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:59 in the IST fixed time zone produces the key orders: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 0 without 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, 31 and 1000 return ErrBadWindow from Orders.
  • Placing a new order increases a restaurant staff user's recent order count by at least 1. A customer requesting GET /v1/admin/stats?minutes=5 receives HTTP 403. The successful response body is JSON containing an orders field.
  • Requests with minutes=0, minutes=31, minutes=-1 and minutes=abc receive HTTP 400. A restaurant user requesting minutes=30 receives HTTP 200.

Constraints

  • Generate Redis keys with the prefix orders: and the UTC format yyyymmddhhmm.
  • 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:

bash
cd backend
TEST_REDIS_ADDR=127.0.0.1:6379 make test W=6B7
TEST_API_URL=http://localhost:8080 make test W=6B7

Start 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:

http
GET /v1/admin/stats?minutes=5

Confirm 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.

Finished Exercise 6.14?

Backend hardening and admin stats

2 items

  • 6.13Backend audit and soak gatenot completed
  • 6.14Admin order statisticsnot completed

Runtime and performance extensions

Up next · Module 5 · 3 items · about 2 h

Start module 5

Implementation

Run locally

Write the code in your editor inside zomato-prep, then work through this list.

  1. Redis keys use UTC minute buckets with the orders: prefix.
  2. Recording increments buckets and sets their 31-minute expiration.
  3. Rolling windows use one MGET and treat missing buckets as zero.
  4. Admin statistics return the correct order count for 1 to 30 minutes.
  5. Only restaurant-role users can access the statistics endpoint.
  6. New orders are recorded without changing idempotency or order reliability.

Commands

terminal
cd backend && TEST_REDIS_ADDR=127.0.0.1:6379 make test W=6B7
terminal
cd backend && TEST_API_URL=http://localhost:8080 make test W=6B7

Tests

  • TestW6B7_AdminStatsCountsRecentOrders in backend/e2e/w6_test.go
  • TestW6B7_MinutesOutsideTheWindowIsRejected in backend/e2e/w6_test.go
  • TestW6B7_KeyIsOneBucketPerUTCMinute in backend/internal/stats/stats_test.go
  • TestW6B7_OrdersInTheSameMinuteAreSummed in backend/internal/stats/stats_test.go
  • TestW6B7_WindowCoversTheLastMinutesIncludingTheCurrentOne in backend/internal/stats/stats_test.go
  • TestW6B7_MissingBucketsCountAsZero in backend/internal/stats/stats_test.go
  • TestW6B7_BucketExpiresAfterThirtyOneMinutes in backend/internal/stats/stats_test.go
  • TestW6B7_WindowOutsideOneToThirtyIsRejected in backend/internal/stats/stats_test.go