valyala/fasthttp · error

cannot write timed out response

Error message

cannot write timed out response

What it means

This error is created inside writeResponse when the RequestCtx has a timeoutResponse set. It means the request already timed out and an error response was staged; writing the normal response afterwards is forbidden, so fasthttp refuses to write it.

Source

Thrown at server.go:2859

		// when we do not keep hijacked connections,
		// it is closed in hijackConnHandler.
		return nil
	}

	return c.Conn.Close()
}

// LastTimeoutErrorResponse returns the last timeout response set
// via TimeoutError* call.
//
// This function is intended for custom server implementations.
func (ctx *RequestCtx) LastTimeoutErrorResponse() *Response {
	return ctx.timeoutResponse
}

func writeResponse(ctx *RequestCtx, w *bufio.Writer) error {
	if ctx.timeoutResponse != nil {
		return errors.New("cannot write timed out response")
	}
	err := ctx.Response.Write(w)

	return err
}

const (
	defaultReadBufferSize  = 4096
	defaultWriteBufferSize = 4096
)

func acquireByteReader(ctxP **RequestCtx) (*bufio.Reader, error) {
	ctx := *ctxP
	s := ctx.s
	c := ctx.c
	s.releaseCtx(ctx)

	//nolint:wastedassign // Make GC happy, so it could garbage collect ctx while we wait for the

View on GitHub (pinned to c96f600972)

Solutions

  1. Make the handler complete within the deadline or reduce its work; check timeouts on downstream calls.
  2. Don't attempt to write a response after the ctx timed out; inspect ctx.LastTimeoutErrorResponse().
  3. Add Server-level timeouts (ReadTimeout/WriteTimeout) consistent with handler expectations.

Example fix

// before
go doSlowWork(ctx) // overruns deadline, then writes response
// after
result := doWorkWithTimeout(ctx, 2*time.Second)
ctx.Write(result) // within deadline, no timeoutResponse set
Defensive patterns

Strategy: type-guard

Validate before calling

if ctx.LastTimeoutErrorResponse() != nil {
    // request already timed out; do not attempt normal response writes
    return
}

Type guard

func canWriteResponse(ctx *fasthttp.RequestCtx) bool {
    return ctx.LastTimeoutErrorResponse() == nil
}

Prevention

When it happens

Trigger: A handler exceeds its deadline (Server.Sleep/timeout wrapper or client-side timeout) causing fasthttp to prepare a timeout response, then the normal response write path still tries to emit the regular response.

Common situations: Handlers doing long blocking work (slow DB queries, upstream calls) that overrun request deadlines; using LastTimeoutErrorResponse consumers who see this error bubbled from writeResponse.

Understand the failure class

Related errors


AI-assisted analysis of valyala/fasthttp@c96f600972 (2026-08-31). Data as JSON: /api/errors/56755a622e8eedd2. Report an issue: GitHub.