How It Works Features Pricing Blog Error Guides
Log In Start Free Trial
Echo · Go

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

2024/03/15 18:30:22 echo: GET /api/aggregated -> main.GetAggregated | 500 | 10002.104ms | 127.0.0.1 goroutine 34 [running]: runtime/debug.Stack() /usr/local/go/src/runtime/debug/stack.go:24 +0x5e main.GetAggregated({0x1029e4f80, 0x14000226000}) /app/handlers/aggregate.go:22 +0x2d8 net/http.(*Client).do(0x14000196040, 0x14000226060) /usr/local/go/src/net/http/client.go:597 +0x484 net/http.(*Client).Get(0x14000196040, {0x1028f1e60, 0x25}) /usr/local/go/src/net/http/client.go:393 +0x48 context.(*timerCtx).Err(0x14000196040) /usr/local/go/src/context/context.go:590 +0x24

Here's what each line means:

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.

Before (broken)
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)
}
After (fixed)
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:

  1. Notice the error alert or see it in your monitoring tool
  2. Open the error dashboard and read the stack trace
  3. Identify the file and line number from the stack trace
  4. Open your IDE and navigate to the file
  5. Read the surrounding code to understand context
  6. Reproduce the error locally
  7. Identify the root cause
  8. Write the fix
  9. Run the test suite locally
  10. Fix any failing tests
  11. Write new tests covering the edge case
  12. Run the full test suite again
  13. Create a new git branch
  14. Commit and push your changes
  15. Open a pull request
  16. Wait for code review
  17. Merge and deploy to production
  18. 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:

  1. Captures the stack trace and request context
  2. Pulls the relevant source files from your GitHub repo
  3. Analyzes the error and understands the code context
  4. Generates a minimal, verified fix
  5. Runs your existing test suite
  6. Pushes through your CI/CD pipeline
  7. 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)

  1. Run go test ./... locally to confirm timeout handling works.
  2. Open a pull request with the context deadline changes.
  3. Wait for CI checks to pass on the PR.
  4. Have a teammate review and approve the PR.
  5. 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.