Fix ContextDeadlineExceeded: context deadline exceeded (Client.Timeout exceeded while awaiting headers) in Echo
This error occurs when an Echo handler makes an outbound HTTP call that exceeds the client timeout, or when the request context deadline passes before the handler completes. Fix it by setting explicit timeouts on your HTTP client, propagating the request context to downstream calls, and returning meaningful timeout error responses.
Reading the Stack Trace
Here's what each line means:
- main.GetAggregated({0x1029e4f80, 0x14000226000}) /app/handlers/aggregate.go:22 +0x2d8: The GetAggregated handler at line 22 makes an outbound HTTP call that exceeds the timeout deadline.
- net/http.(*Client).do(0x14000196040, 0x14000226060): The HTTP client's do method returns an error because the context deadline was exceeded.
- context.(*timerCtx).Err(0x14000196040): The context's timer expires, canceling all operations derived from this context.
Common Causes
1. Using http.DefaultClient with no timeout
The default HTTP client has no timeout, but the request context has one, causing unexpected deadline errors.
func GetAggregated(c echo.Context) error {
resp, err := http.Get("https://slow-service.example.com/data") // no timeout
if err != nil {
return c.JSON(500, map[string]string{"error": err.Error()})
}
defer resp.Body.Close()
// ...
}
2. Request context not propagated to downstream calls
The handler creates a new context instead of using the request context, so cancellation signals are not forwarded.
func GetAggregated(c echo.Context) error {
req, _ := http.NewRequest("GET", url, nil) // no context
resp, _ := client.Do(req)
// ...
}
3. Sequential downstream calls exceed total timeout
Multiple sequential API calls each take a fraction of the timeout, but together they exceed it.
func GetAggregated(c echo.Context) error {
users, _ := http.Get("https://api/users") // 3s
orders, _ := http.Get("https://api/orders") // 3s
invoices, _ := http.Get("https://api/invoices") // 3s → total 9s > 5s timeout
}
The Fix
Create an HTTP client with an explicit timeout. Propagate the request context to downstream calls with NewRequestWithContext. Check for context.DeadlineExceeded to return a meaningful 504 Gateway Timeout response.
func GetAggregated(c echo.Context) error {
resp, err := http.Get("https://slow-service.example.com/data")
if err != nil {
return c.JSON(500, map[string]string{"error": err.Error()})
}
defer resp.Body.Close()
var data map[string]interface{}
json.NewDecoder(resp.Body).Decode(&data)
return c.JSON(200, data)
}
var httpClient = &http.Client{
Timeout: 5 * time.Second,
}
func GetAggregated(c echo.Context) error {
ctx, cancel := context.WithTimeout(c.Request().Context(), 4*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://slow-service.example.com/data", nil)
if err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to create request"})
}
resp, err := httpClient.Do(req)
if err != nil {
if errors.Is(err, context.DeadlineExceeded) {
return c.JSON(http.StatusGatewayTimeout, map[string]string{"error": "upstream service timed out"})
}
return c.JSON(http.StatusBadGateway, map[string]string{"error": "upstream service error"})
}
defer resp.Body.Close()
var data map[string]interface{}
if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{"error": "invalid upstream response"})
}
return c.JSON(http.StatusOK, data)
}
Testing the Fix
package handlers_test
import (
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/labstack/echo/v4"
"github.com/stretchr/testify/assert"
)
func TestGetAggregated_Timeout(t *testing.T) {
// Simulate slow upstream
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(5 * time.Second)
}))
defer upstream.Close()
e := echo.New()
req := httptest.NewRequest(http.MethodGet, "/api/aggregated", nil)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
err := GetAggregated(c)
assert.NoError(t, err)
assert.Equal(t, http.StatusGatewayTimeout, rec.Code)
}
func TestGetAggregated_Success(t *testing.T) {
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"status": "ok"}`))
}))
defer upstream.Close()
e := echo.New()
req := httptest.NewRequest(http.MethodGet, "/api/aggregated", nil)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
err := GetAggregated(c)
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, rec.Code)
}
Run your tests:
go test ./handlers/... -v
Pushing Through CI/CD
git checkout -b fix/echo-context-deadline-error,git add handlers/aggregate.go handlers/aggregate_test.go,git commit -m "fix: propagate context and handle timeouts for upstream API calls",git push origin fix/echo-context-deadline-error
Your CI config should look something like this:
name: CI
on:
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: '1.22'
- run: go mod download
- run: go vet ./...
- run: go test ./... -race -coverprofile=coverage.out
- run: go build ./...
The Full Manual Process: 18 Steps
Here's every step you just went through to fix this one bug:
- Notice the error alert or see it in your monitoring tool
- Open the error dashboard and read the stack trace
- Identify the file and line number from the stack trace
- Open your IDE and navigate to the file
- Read the surrounding code to understand context
- Reproduce the error locally
- Identify the root cause
- Write the fix
- Run the test suite locally
- Fix any failing tests
- Write new tests covering the edge case
- Run the full test suite again
- Create a new git branch
- Commit and push your changes
- Open a pull request
- Wait for code review
- Merge and deploy to production
- Monitor production to confirm the error is resolved
Total time: 30-60 minutes. For one bug.
Or Let bugstack Fix It in Under 2 minutes
Every step above? bugstack does it automatically.
Step 1: Install the SDK
go get github.com/bugstack/sdk
Step 2: Initialize
import "github.com/bugstack/sdk"
func init() {
bugstack.Init(os.Getenv("BUGSTACK_API_KEY"))
}
Step 3: There is no step 3.
bugstack handles everything from here:
- Captures the stack trace and request context
- Pulls the relevant source files from your GitHub repo
- Analyzes the error and understands the code context
- Generates a minimal, verified fix
- Runs your existing test suite
- Pushes through your CI/CD pipeline
- Deploys to production (or opens a PR for review)
Time from error to fix deployed: Under 2 minutes.
Human involvement: zero.
Try bugstack Free →No credit card. 5-minute setup. Cancel anytime.
Deploying the Fix (Manual Path)
- Run go test ./... locally to confirm timeout handling works.
- Open a pull request with the context deadline changes.
- Wait for CI checks to pass on the PR.
- Have a teammate review and approve the PR.
- Merge to main and verify in staging.
Frequently Asked Questions
BugStack validates timeout handling with simulated slow upstream services, checks context propagation, and ensures proper HTTP status codes are returned before marking it safe to deploy.
BugStack never pushes directly to production. Every fix goes through a pull request with full CI checks, so your team can review it before merging.
No. Set timeouts based on the expected response time of each service. A fast cache lookup should have a shorter timeout than a complex database query.
Use errgroup.Group with a derived context. This lets you make concurrent calls, respects the parent timeout, and cancels remaining calls if one fails.