Request 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.
Ticket
Build the shared request context and timeout layer for the API. Add request-aware JSON logging, reusable read and write timeout contexts, and a common HTTP error helper. Integrate them into the restaurant, order, cache, and idempotency packages.
These changes make failures traceable across middleware and service code. They also prevent slow MySQL and Redis operations from leaving requests hanging. The next module, Load testing and bottleneck analysis, depends on predictable request behaviour and useful logs when the system is under load.
The tests call these exported declarations directly. Keep their names and signatures unchanged.
// internal/timeouts
func Read(ctx context.Context) (context.Context, context.CancelFunc)
func Write(ctx context.Context) (context.Context, context.CancelFunc)
// internal/reqlog
func Middleware(logger *slog.Logger) func(http.Handler) http.Handler
func From(ctx context.Context) *slog.Logger
// internal/httpx
func Fail(w http.ResponseWriter, err error)The restaurant test builds restaurant.NewHandler(restaurant.NewService(q)) and calls its existing Menu handler, so keep those names.
Acceptance criteria
- Every HTTP response carries a non-empty
X-Request-Idheader. - When a request supplies
X-Request-Id: abc-123, the response echoesabc-123unchanged. - A handler log and its access log are both valid JSON objects. Both contain the same
request_idas the response header. - Each access log line has
msg="request", the HTTP method, chi route pattern, response status, and numericduration_ms. - For a
GETrequest to/w6b3/public/77that returns HTTP202, the access log containsmethod="GET",route="/w6b3/public/{id}", andstatus=202. - A log emitted inside an authenticated handler includes
user_id=42when the authenticated principal has user ID42. - Calling
reqlog.Fromwithout request logging middleware returns a non-nil logger. timeouts.Readprovides a deadline approximately 500 milliseconds from creation. The tested remaining time is between 450 and 500 milliseconds.timeouts.Writeprovides a deadline approximately 2 seconds from creation. The tested remaining time is between 1.9 and 2 seconds.- When the parent context has a 50-millisecond deadline,
timeouts.Writepreserves that shorter deadline instead of extending it. - Calling the cancellation function returned by
timeouts.Readcloses the derived context'sDonechannel. httpx.Failmapscontext.DeadlineExceededto HTTP504.httpx.Failalso maps a wrappedcontext.DeadlineExceedederror to HTTP504.httpx.Failmaps an unexpected error such aserrors.New("boom")to HTTP500.- A deadline error produces the JSON response body
{"error":"timeout"}followed by a newline. - A restaurant menu request whose database call hangs returns HTTP
504instead of hanging. The request must complete within 1500 milliseconds, with the read budget set to 500 milliseconds. - The live API's
/healthzresponse includes a non-emptyX-Request-Idheader. - When the live API receives
X-Request-Id: w6b3-echo-123, it returns the same value in its response header.
Constraints
- Use chi's
middleware.RequestIDfor request ID generation and reuse. - Use the exact response header name
X-Request-Id. - Install request logging middleware after request ID middleware.
- Use
log/slogwith a JSON handler. Each log line must be one JSON object. - Use
request_idas the request ID log attribute anduser_idfor the authenticated principal. - Use
msg="request"for access log entries. - Use
duration_msas a numeric value, not a formatted string. - Define the read budget as
500 * time.Millisecondand the write budget as2 * time.Second. - Derive timeout contexts from their incoming parent contexts. Always call their cancellation functions.
- Use
errors.Isto recognisecontext.DeadlineExceeded, including errors wrapped with%w. - Return
{"error":"timeout"}for deadline failures. - Preserve existing business error responses:
404,400, and409. - Do not log secrets or request and response bodies.
- Do not modify the provided tests.
The restaurant menu read is the call the tests time.
Design direction
Keep the shared timeout budgets in backend/internal/timeouts/timeouts.go. The Read and Write helpers should derive contexts from the caller's context rather than creating independent background contexts. This preserves cancellation and any earlier parent deadline.
Keep request logging in backend/internal/reqlog/reqlog.go. Use middleware.RequestID to establish the request id before your logging middleware runs. Store the request-scoped logger in the context using a private key.
The From helper should retrieve the logger and fall back to slog.Default() when middleware has not installed one. It must look up the authenticated user at call time, rather than when the middleware creates the logger. The tests install reqlog.Middleware before the authentication middleware, so the user is not known when the request logger is initially created. Looking up the principal inside From allows logs emitted later in the handler to include user_id.
Use backend/internal/httpx/fail.go for unexpected error responses. Let handlers decide which errors are expected business outcomes. A missing resource should still return 404, invalid input should still return 400, and conflicts should still return 409.
Consider these implementation trade-offs:
- Reads receive 500 milliseconds, while writes receive 2 seconds. A write can need more time to finish a transaction, but neither operation should wait indefinitely.
- Deriving a timeout from the incoming context means an earlier caller deadline always wins. Creating a new context from
context.Background()would discard that protection. - Bound every MySQL and Redis call with the appropriate shared timeout helper, including calls in the order, cache, and idempotency packages. The menu read is the operation directly exercised by the hanging-database test.
- A timeout does not prove a write failed. MySQL may have committed the order before the caller observes the deadline. Use
context.WithoutCancelfor idempotencyReleaseandDoneoperations so cleanup and completion can proceed after request cancellation. - A common error helper can return
{"error":"internal_error"}with HTTP 500 for unexpected failures. Keep expected business outcomes outside this helper. - Keep logging middleware lightweight. It runs on every request, so measure duration and capture metadata without logging request bodies or allocating unnecessary data.
- When wrapping
http.ResponseWriter, preserve optional interfaces such ashttp.Flusherandhttp.Hijackerbecause existing WebSocket handlers depend on them.
Any package layout that meets the contract passes.
How to check your work
Run the unit tests from the repository root.
cd backend && make test W=6B3Start the API in a separate terminal.
cd backend && make runWith the API running, execute the end-to-end tests from another terminal.
cd backend && TEST_API_URL=http://localhost:8080 make test W=6B3Check the response header manually.
curl -si localhost:8080/healthz | grep -i x-request-idThe first failing assertion identifies the broken contract. Inspect the request header, parsed JSON log fields, response status and body, or remaining context deadline at the relevant boundary.
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.
Service observability
4 items
- 6.3Prometheus metric registrationnot completed
- 6.4API and worker metricsnot completed
- 6.5Request-scoped logging and timeoutsnot completed
- 6.6Request context and timeout layernot completed
Up next · Module 3 · 6 items · about 5 h 60 min
Implementation
Run locally
Write the code in your editor inside zomato-prep, then work through this list.
- Request IDs are generated or echoed and appear in response headers.
- Handler and access logs are JSON and share the same request ID.
- Authenticated logs include
user_idand access logs include route, status and duration. - The restaurant menu read uses the shared 500 ms timeout budget.
- Deadline errors return HTTP 504 and other unexpected errors return HTTP 500.
- Existing business errors and idempotency behaviour are preserved.
Commands
cd backend && make test W=6B3cd backend && TEST_API_URL=http://localhost:8080 make test W=6B3curl -si localhost:8080/healthz | grep -i x-request-idTests
TestW6B3_EveryResponseCarriesARequestIDinbackend/e2e/w6_test.goTestW6B3_ClientRequestIDIsEchoedinbackend/e2e/w6_test.goTestW6B3_DeadlineExceededIs504inbackend/internal/httpxtest/fail_test.goTestW6B3_WrappedDeadlineExceededIs504inbackend/internal/httpxtest/fail_test.goTestW6B3_OtherErrorsAre500inbackend/internal/httpxtest/fail_test.goTestW6B3_TimeoutBodyNamesTheErrorinbackend/internal/httpxtest/fail_test.goTestW6B3_ResponseCarriesTheRequestIDinbackend/internal/reqlog/reqlog_test.goTestW6B3_IncomingRequestIDIsEchoedinbackend/internal/reqlog/reqlog_test.goTestW6B3_EveryLogLineIsJSONWithTheRequestIDinbackend/internal/reqlog/reqlog_test.goTestW6B3_AccessLineHasMethodRouteStatusAndDurationinbackend/internal/reqlog/reqlog_test.goTestW6B3_UserIDAppearsOnceTheCallerIsAuthenticatedinbackend/internal/reqlog/reqlog_test.goTestW6B3_FromWithoutMiddlewareStillReturnsALoggerinbackend/internal/reqlog/reqlog_test.goTestW6B3_SlowDatabaseReturns504InsteadOfHanginginbackend/internal/restaurant/timeout_test.goTestW6B3_ReadTimeoutIs500msinbackend/internal/timeouts/timeouts_test.goTestW6B3_WriteTimeoutIs2sinbackend/internal/timeouts/timeouts_test.goTestW6B3_ParentDeadlineWinsWhenShorterinbackend/internal/timeouts/timeouts_test.goTestW6B3_CancelReleasesTheContextinbackend/internal/timeouts/timeouts_test.go