Request-scoped logging and timeouts

You can propagate request IDs through JSON logs and bound dependency calls so the API returns a controlled timeout instead of leaving requests hanging.

Learning outcomes

  • Produce JSON logs with log/slog and correlate every request's log entries using a shared request id.
  • Propagate request-scoped loggers through Go contexts and include the authenticated user's ID when available.
  • Apply separate 500 ms read and 2 second write deadlines to database and Redis operations.
  • Recognise wrapped deadline errors and return HTTP 504 instead of allowing dependency failures to leave requests hanging.
  • Preserve idempotency when a timed-out write may already have committed.

A customer requests a restaurant menu, the API queries MySQL, and the handler returns a response. If MySQL takes several seconds instead of its normal response time, you need to identify the affected request and prevent the slow query from blocking the API indefinitely.

You need two things: structured logging that connects activity across the request lifecycle, and timeouts that put an upper bound on dependency calls. Both use Go's context to carry information through the application.

JSON log records

Plain text logs are difficult to search when thousands of requests are being processed.

Consider this log entry:

go
log.Println("User 42 requested restaurant 15 and got status 200")

A human can read it, but your log aggregation system cannot reliably identify the user ID or status without parsing the message. Different parts of the application may also describe the same event differently.

Structured logging represents each event as named fields with typed values. Go provides log/slog in its standard library.

JSON handlers

A JSON handler writes each log entry as one JSON object. This makes fields available for filtering and aggregation in a log aggregation system.

Create a logger using slog.NewJSONHandler:

go
logger := slog.New(
    slog.NewJSONHandler(os.Stdout, nil),
)

logger.Info("order created",
    "order_id", 1042,
    "user_id", 42,
    "status", "confirmed",
)

A resulting log line looks like this:

json
{"time":"2026-11-04T01:00:00Z","level":"INFO","msg":"order created","order_id":1042,"user_id":42,"status":"confirmed"}

The timestamp and exact metadata depend on the handler. The important part is that every attribute has a separate key.

You can search for order_id=1042, filter by status, or group events by user ID without parsing arbitrary sentences.

Logger fields and levels

A logger often contains information that should accompany every message from a component.

Use Logger.With to attach these fields once:

go
orderLogger := logger.With(
    "component", "orders",
    "service", "api",
)

orderLogger.Info("order created", "order_id", 1042)
orderLogger.Warn("confirmation delayed", "order_id", 1042)

Both log entries inherit the component and service attributes. You do not need to repeat them in every call.

slog provides four commonly used levels:

  • Debug: detailed information useful during development.
  • Info: normal application events, such as successful order creation.
  • Warn: unexpected conditions that the application can recover from.
  • Error: failures that prevent an operation from completing successfully.

Choose levels based on operational importance. Logging every successful database query at information level can generate enormous volumes of data on a busy endpoint.

You can configure the minimum level through slog.HandlerOptions:

go
handler := slog.NewJSONHandler(os.Stdout,
    &slog.HandlerOptions{
        Level: slog.LevelInfo,
    },
)
logger := slog.New(handler)

Debug messages are filtered out with this configuration.

Request IDs and context loggers

One HTTP request can produce several log entries. A customer loading an order summary might trigger a handler log, a service log, and an error from a dependency.

Without a shared identifier, finding all these entries becomes difficult.

A Request id gives every incoming request an identifier that can connect its log entries across application layers.

Request ID generation

Chi provides middleware.RequestID for this purpose.

It reads an incoming X-Request-Id header or generates an ID when the client does not supply one. It stores that ID in the request context.

You can retrieve it with middleware.GetReqID:

go
router := chi.NewRouter()

router.Use(middleware.RequestID)
router.Get("/healthz", healthHandler)

The ordering matters. Middleware registered after middleware.RequestID can read the generated or supplied identifier.

Your API must also return the ID to the client through the X-Request-Id response header. A client can then include that ID when reporting a failed request.

Request-scoped loggers

The request context is the natural place to store information that belongs to one request.

Go's context package carries cancellation, deadlines and request-scoped values across function calls. The context.WithValue function creates a derived context containing an additional value.

Use a private key type for the logger:

go
type loggerKey struct{}

func WithLogger(ctx context.Context, logger *slog.Logger) context.Context {
    return context.WithValue(ctx, loggerKey{}, logger)
}

A private key type avoids collisions with context values stored by other packages.

The logger retrieval function should return the default logger when request logging middleware has not installed one:

go
func loggerFrom(ctx context.Context) *slog.Logger {
    logger, ok := ctx.Value(loggerKey{}).(*slog.Logger)
    if !ok {
        return slog.Default()
    }
    return logger
}

This fallback matters because service code should not need to check whether logging middleware is present before logging an event.

Request logging middleware

The request logging middleware reads the request ID, copies it into the response header, and attaches a logger carrying that ID to the request context.

go
func requestLogger(logger *slog.Logger) func(http.Handler) http.Handler {
    return func(next http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            id := middleware.GetReqID(r.Context())
            w.Header().Set("X-Request-Id", id)

            scoped := logger.With("request_id", id)
            ctx := WithLogger(r.Context(), scoped)

            next.ServeHTTP(w, r.WithContext(ctx))
        })
    }
}

This is an illustrative outline. Your middleware also needs to wrap the downstream response and record an access log when the handler finishes.

Register the two middleware functions in this order:

go
router.Use(middleware.RequestID)
router.Use(reqlog.Middleware(slog.Default()))

The request ID must exist before the logger middleware tries to read it.

The incoming header is useful for correlation, but it is not an authentication credential. Never use a request ID to identify or authorize a customer.

Authenticated user information

Authentication usually runs after the request logging middleware.

This creates an important timing detail. When the logger middleware initially creates the request-scoped logger, the authenticated principal may not exist yet.

Therefore, reqlog.From(ctx) must look up the principal when the application requests the logger, not when the middleware initially creates it.

The retrieval logic has two responsibilities:

  1. Retrieve the logger from the context, falling back to slog.Default().
  2. Check the current context for an authenticated principal and attach its user ID when available.

For example:

go
func From(ctx context.Context) *slog.Logger {
    logger := loggerFrom(ctx)

    if p, ok := auth.From(ctx); ok {
        return logger.With("user_id", p.UserID)
    }
    return logger
}

A handler that logs after authentication can now include user_id automatically:

go
reqlog.From(r.Context()).Info(
    "inside the handler",
    "operation", "load order",
)

The resulting record contains both request_id and user_id.

This avoids requiring every handler and service function to manually attach the same identity fields.

Service-layer logging

Service functions must retrieve the logger from the context too. Otherwise, the HTTP handler logs will have a request ID while service logs will not.

go
func (s *Service) Create(ctx context.Context, userID int64) error {
    logger := reqlog.From(ctx)

    logger.Info("creating order",
        "user_id", userID,
    )

    return nil
}

Pass the original request context from the handler into the service and onward to its dependencies.

Do not create a background context to perform service logging. That would discard the request-scoped logger and other information carried by the original context.

Access log lines

Application logs describe individual events. Access logs describe HTTP requests.

An HTTP middleware function can record one access log line after the downstream handler returns. At that point, the middleware knows how long the request took and which status the handler returned.

For the Zomato API, an access log line needs:

  • method: the HTTP method.
  • route: the matched route pattern.
  • status: the response status code.
  • duration_ms: the elapsed time in milliseconds.
  • request_id: the identifier shared by the request's other logs.

Capturing the response status

The handler writes its response through http.ResponseWriter. A small wrapper can record the first status passed to WriteHeader.

go
type statusWriter struct {
    http.ResponseWriter
    status int
}

func (w *statusWriter) WriteHeader(status int) {
    if w.status != 0 {
        return
    }
    w.status = status
    w.ResponseWriter.WriteHeader(status)
}

If the handler writes a response body without calling WriteHeader, Go sends HTTP 200 implicitly. Your middleware must account for that default after the downstream handler returns.

You should also preserve optional response-writer interfaces such as http.Flusher and http.Hijacker. Existing WebSocket handlers depend on these capabilities.

Reading the chi route pattern

The Chi router stores the matched route pattern in its routing context.

You must read it after the downstream handler completes. Reading it before the handler runs can produce an empty or incomplete pattern because chi has not finished routing the request.

For example, these requests:

GET /v1/restaurants/11/menu
GET /v1/restaurants/12/menu

Both match:

/v1/restaurants/{id}/menu

Use the route pattern rather than the concrete URL in your access log.

If no route pattern is available, use the fixed value unmatched.

This keeps access log fields consistent and avoids grouping every request under a different restaurant ID.

Measuring duration

Capture the start time before calling the downstream handler.

After it returns, calculate the elapsed duration:

go
start := time.Now()

next.ServeHTTP(w, r)

durationMS := time.Since(start).Milliseconds()

durationMS is an integer number of milliseconds. You can also use a floating-point value when you need fractional milliseconds.

Write the access log with the message request:

go
reqlog.From(r.Context()).Info(
    "request",
    "method", r.Method,
    "route", route,
    "status", status,
    "duration_ms", durationMS,
)

The msg field identifies this as an access log line. The other attributes remain independently searchable.

For example, a request to /w6b3/public/77 returning HTTP 202 must produce fields equivalent to:

json
{"msg":"request","method":"GET","route":"/w6b3/public/{id}","status":202,"duration_ms":12}

The numeric duration here is illustrative, not a performance target.

Per-call timeouts

Request IDs help identify slow operations. Timeouts prevent those operations from occupying resources indefinitely.

Consider a restaurant menu request that queries MySQL. If the database call hangs, the HTTP handler remains blocked while waiting for the result.

When several requests experience the same delay, goroutines accumulate. Database connections remain occupied, the connection pool becomes exhausted, and unrelated requests begin failing.

A timeout context places an upper bound on how long a dependency operation can take.

Parent contexts and deadlines

Go's context.WithTimeout creates a child context with a deadline.

The child inherits cancellation from its parent. If the parent request has an earlier deadline, the child's deadline cannot extend it.

For this backend, use two time budgets:

OperationTimeout
Database and Redis reads500 ms
Database and Redis writes2 seconds

The shared timeout package provides Read and Write helpers:

go
func Read(parent context.Context) (context.Context, context.CancelFunc) {
    return context.WithTimeout(parent, 500*time.Millisecond)
}

func Write(parent context.Context) (context.Context, context.CancelFunc) {
    return context.WithTimeout(parent, 2*time.Second)
}

Both functions derive their contexts from the incoming parent. This preserves an earlier request deadline.

Database calls

Use the read budget for operations such as loading restaurant menus.

go
ctx, cancel := timeouts.Read(parent)
defer cancel()

rows, err := queries.ListItemsByRestaurant(ctx, restaurantID)

The bounded context must reach the actual database operation. Creating a timeout context but passing the original context to the query does not protect the database call.

The same rule applies to writes. Use the longer write budget for operations such as creating orders or changing stock.

go
ctx, cancel := timeouts.Write(parent)
defer cancel()

err := queries.CreateOrder(ctx, params)

The exact generated query method depends on the existing sqlc code. The important point is that the operation receives the bounded context.

Redis calls

Redis operations need the same protection.

A menu cache lookup is a read, so it uses the read budget:

go
ctx, cancel := timeouts.Read(parent)
defer cancel()

value, err := redisClient.Get(ctx, "menu:15").Result()

A cache write uses the write budget:

go
ctx, cancel := timeouts.Write(parent)
defer cancel()

err := redisClient.Set(ctx, key, data, ttl).Err()

Use the shared helpers throughout the restaurant, order, cache and idempotency packages. Every database and Redis operation should receive an appropriate bounded context.

Create a fresh timeout context for each independent operation. Reusing an old context can leave a later call with very little time remaining.

Always invoke the cancellation function. defer cancel() releases resources associated with the derived context even when the operation returns early.

Connection-level server timeouts

Per-call timeouts protect database and Redis operations. HTTP server timeouts protect the connection itself.

The API server also uses read and write timeouts:

go
srv := &http.Server{
    Addr:         ":8080",
    Handler:      router,
    ReadTimeout:  500 * time.Millisecond,
    WriteTimeout: 2 * time.Second,
}

These settings serve a different purpose from context.WithTimeout.

The server read timeout limits how long the server spends reading a request. The write timeout limits response writing. Neither replaces the need to give MySQL and Redis calls their own bounded contexts.

Deadline errors and HTTP responses

A dependency timeout eventually becomes an error returned to the calling service.

For example, a restaurant menu query that exceeds its 500 ms budget can return context.DeadlineExceeded. Intermediate functions may wrap that error with additional context.

Use error wrapping to preserve the original error:

go
func loadMenu(ctx context.Context) error {
    err := queryMenu(ctx)
    if err != nil {
        return fmt.Errorf("load menu: %w", err)
    }
    return nil
}

The %w verb preserves the relationship between the new error and the underlying error.

Use errors.Is to check for the original deadline error:

go
func isTimeout(err error) bool {
    return errors.Is(err, context.DeadlineExceeded)
}

This works even when several functions have wrapped the original error.

Gateway timeout responses

When a dependency exceeds its deadline, the API returns HTTP 504 Gateway Timeout.

A shared HTTP error helper handles this mapping consistently.

The HTTP status code for an unexpected internal error is HTTP 500. A deadline error is different because the dependency did not complete within the configured time budget.

For this API, the expected responses are:

ErrorHTTP statusJSON body
Deadline exceeded504{"error":"timeout"}
Other unexpected error500{"error":"internal_error"}

The helper must recognise wrapped deadline errors with errors.Is, not by comparing error strings.

A deadline response looks like this:

json
{"error":"timeout"}

The newline at the end is part of the JSON encoder's output.

Do not route every error through this helper. Expected business errors still belong to their existing handler paths:

  • Missing resources return 404.
  • Invalid input returns 400.
  • Conflicts return 409.

The shared helper handles unexpected failures, not normal business outcomes.

Logging errors at the correct boundary

A common mistake is logging the same error in every function that encounters it.

For example, the repository logs a failed query, the service logs the returned error, and the handler logs it again. One failure then produces several nearly identical entries.

Instead, wrap errors with useful context as they move through the application. Log the failure at the boundary where it is handled.

Use the request-scoped logger for service-layer messages so the request ID remains available. Avoid logging the same error at every layer.

Timeouts during writes

A timeout does not prove that a database write failed.

Imagine a customer submits an order. MySQL commits the transaction, but the response takes too long to reach the API. The request context expires, and the handler observes a deadline error.

From the client's perspective, the outcome is unknown. The order may already exist.

This is why the order creation endpoint uses an Idempotency-Key.

When a client retries with the same key, the backend can recognise the original operation instead of creating another order.

The idempotency store has three relevant operations:

  • Claim reserves a key before the work begins.
  • Done records the completed order ID.
  • Release removes a key when the operation fails before completion.

There is a subtle cancellation issue here. When the original request expires, ordinary request cancellation can prevent cleanup or completion operations from running.

For idempotency Done and Release, use context.WithoutCancel to detach the cleanup operation from request cancellation. The store should still apply its own bounded write timeout to its Redis call.

Request deadlines in the exercise

The next exercise, Request context and timeout layer, connects these ideas across the existing API.

You will add JSON request logging to the middleware chain, make the request logger available to handlers and services, and use separate timeout helpers for database and Redis work.

The restaurant menu handler provides the concrete timeout case. A hanging database query must produce HTTP 504 instead of leaving the handler blocked indefinitely.

The exercise also checks that a supplied request ID is echoed unchanged, handler and access logs share that ID, and authentication adds user_id to logs emitted after the principal becomes available.

Keep three boundaries clear:

  1. Middleware owns request correlation and access logging.
  2. Shared timeout helpers own dependency deadlines.
  3. The HTTP error helper owns unexpected error mapping.

This separation lets you change logging or timeout policy without rewriting every handler.

Check your understanding

Question 1 of 4

A customer sends a request with X-Request-Id: abc-123. Your API uses chi's request ID middleware. What should happen?

Pick an answer, then say how sure you are.

References

Everything above is explained on this page; these are where it comes from (Go, log/slog).

Finished Lesson 6.5?