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.

go
// 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-Id header.
  • When a request supplies X-Request-Id: abc-123, the response echoes abc-123 unchanged.
  • A handler log and its access log are both valid JSON objects. Both contain the same request_id as the response header.
  • Each access log line has msg="request", the HTTP method, chi route pattern, response status, and numeric duration_ms.
  • For a GET request to /w6b3/public/77 that returns HTTP 202, the access log contains method="GET", route="/w6b3/public/{id}", and status=202.
  • A log emitted inside an authenticated handler includes user_id=42 when the authenticated principal has user ID 42.
  • Calling reqlog.From without request logging middleware returns a non-nil logger.
  • timeouts.Read provides a deadline approximately 500 milliseconds from creation. The tested remaining time is between 450 and 500 milliseconds.
  • timeouts.Write provides 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.Write preserves that shorter deadline instead of extending it.
  • Calling the cancellation function returned by timeouts.Read closes the derived context's Done channel.
  • httpx.Fail maps context.DeadlineExceeded to HTTP 504.
  • httpx.Fail also maps a wrapped context.DeadlineExceeded error to HTTP 504.
  • httpx.Fail maps an unexpected error such as errors.New("boom") to HTTP 500.
  • A deadline error produces the JSON response body {"error":"timeout"} followed by a newline.
  • A restaurant menu request whose database call hangs returns HTTP 504 instead of hanging. The request must complete within 1500 milliseconds, with the read budget set to 500 milliseconds.
  • The live API's /healthz response includes a non-empty X-Request-Id header.
  • 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.RequestID for request ID generation and reuse.
  • Use the exact response header name X-Request-Id.
  • Install request logging middleware after request ID middleware.
  • Use log/slog with a JSON handler. Each log line must be one JSON object.
  • Use request_id as the request ID log attribute and user_id for the authenticated principal.
  • Use msg="request" for access log entries.
  • Use duration_ms as a numeric value, not a formatted string.
  • Define the read budget as 500 * time.Millisecond and the write budget as 2 * time.Second.
  • Derive timeout contexts from their incoming parent contexts. Always call their cancellation functions.
  • Use errors.Is to recognise context.DeadlineExceeded, including errors wrapped with %w.
  • Return {"error":"timeout"} for deadline failures.
  • Preserve existing business error responses: 404, 400, and 409.
  • 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.WithoutCancel for idempotency Release and Done operations 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 as http.Flusher and http.Hijacker because 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.

bash
cd backend && make test W=6B3

Start the API in a separate terminal.

bash
cd backend && make run

With the API running, execute the end-to-end tests from another terminal.

bash
cd backend && TEST_API_URL=http://localhost:8080 make test W=6B3

Check the response header manually.

bash
curl -si localhost:8080/healthz | grep -i x-request-id

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

Finished Exercise 6.6?

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

Load-test baselines

Up next · Module 3 · 6 items · about 5 h 60 min

Start module 3

Implementation

Run locally

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

  1. Request IDs are generated or echoed and appear in response headers.
  2. Handler and access logs are JSON and share the same request ID.
  3. Authenticated logs include user_id and access logs include route, status and duration.
  4. The restaurant menu read uses the shared 500 ms timeout budget.
  5. Deadline errors return HTTP 504 and other unexpected errors return HTTP 500.
  6. Existing business errors and idempotency behaviour are preserved.

Commands

terminal
cd backend && make test W=6B3
terminal
cd backend && TEST_API_URL=http://localhost:8080 make test W=6B3
terminal
curl -si localhost:8080/healthz | grep -i x-request-id

Tests

  • TestW6B3_EveryResponseCarriesARequestID in backend/e2e/w6_test.go
  • TestW6B3_ClientRequestIDIsEchoed in backend/e2e/w6_test.go
  • TestW6B3_DeadlineExceededIs504 in backend/internal/httpxtest/fail_test.go
  • TestW6B3_WrappedDeadlineExceededIs504 in backend/internal/httpxtest/fail_test.go
  • TestW6B3_OtherErrorsAre500 in backend/internal/httpxtest/fail_test.go
  • TestW6B3_TimeoutBodyNamesTheError in backend/internal/httpxtest/fail_test.go
  • TestW6B3_ResponseCarriesTheRequestID in backend/internal/reqlog/reqlog_test.go
  • TestW6B3_IncomingRequestIDIsEchoed in backend/internal/reqlog/reqlog_test.go
  • TestW6B3_EveryLogLineIsJSONWithTheRequestID in backend/internal/reqlog/reqlog_test.go
  • TestW6B3_AccessLineHasMethodRouteStatusAndDuration in backend/internal/reqlog/reqlog_test.go
  • TestW6B3_UserIDAppearsOnceTheCallerIsAuthenticated in backend/internal/reqlog/reqlog_test.go
  • TestW6B3_FromWithoutMiddlewareStillReturnsALogger in backend/internal/reqlog/reqlog_test.go
  • TestW6B3_SlowDatabaseReturns504InsteadOfHanging in backend/internal/restaurant/timeout_test.go
  • TestW6B3_ReadTimeoutIs500ms in backend/internal/timeouts/timeouts_test.go
  • TestW6B3_WriteTimeoutIs2s in backend/internal/timeouts/timeouts_test.go
  • TestW6B3_ParentDeadlineWinsWhenShorter in backend/internal/timeouts/timeouts_test.go
  • TestW6B3_CancelReleasesTheContext in backend/internal/timeouts/timeouts_test.go