Share a Context Deadline Across Steps

Derive one deadline for a multi-step operation, check the remaining budget before each call, and fail fast with a wrapped error.

GoResilience

Code

gosnippet
57 lines
package main

import (
	"context"
	"fmt"
	"time"
)

type Step struct {
	Name string
	Cost time.Duration
}

func runSteps(ctx context.Context, steps []Step) error {
	for _, step := range steps {
		if err := ctx.Err(); err != nil {
			return fmt.Errorf("before step %q: %w", step.Name, err)
		}
		if deadline, ok := ctx.Deadline(); ok {
			remaining := time.Until(deadline)
			if remaining < step.Cost {
				return fmt.Errorf(
					"step %q needs %s but only %s remains: %w",
					step.Name,
					step.Cost,
					remaining.Round(time.Millisecond),
					context.DeadlineExceeded,
				)
			}
		}

		timer := time.NewTimer(step.Cost)
		select {
		case <-ctx.Done():
			timer.Stop()
			return fmt.Errorf("step %q interrupted: %w", step.Name, ctx.Err())
		case <-timer.C:
			fmt.Printf("completed %q in %s\n", step.Name, step.Cost)
		}
	}
	return nil
}

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 80*time.Millisecond)
	defer cancel()

	steps := []Step{
		{Name: "load-config", Cost: 20 * time.Millisecond},
		{Name: "fetch-profile", Cost: 25 * time.Millisecond},
		{Name: "render-report", Cost: 60 * time.Millisecond},
	}
	if err := runSteps(ctx, steps); err != nil {
		fmt.Println("stopped:", err)
	}
}

What the code does

One reading of the file: the functions runSteps and main, doing all the work.

The one repetition in this snippet is the loop for _, step := range steps. Error handling is inline: 2 places test err != nil and branch immediately. Deferred at entry, executed at exit: defer keeps cleanup adjacent to acquisition.

What to watch for

  • Nothing third-party is pulled in; the snippet is dependency-free.
  • The function reports failure by returning error — callers branch on it before touching other results.

Applying it

Entry signature: func runSteps(ctx context.Context, steps []Step) error

Output lines are prefixed (completed, stopped:), letting every output line be matched up with its originating step.

Launch the file; main takes over and steps through runSteps.

Statements that matter most here

return fmt.Errorf("step %q interrupted: %w", step.Name, ctx.Err())
return fmt.Errorf("before step %q: %w", step.Name, err)
return fmt.Errorf(
"step %q needs %s but only %s remains: %w",
step.Name,
step.Cost,
remaining.Round(time.Millisecond),
context.DeadlineExceeded,
)

Interactive Tools for This Topic

FAQ

Does the snippet panic on failure?
No exceptions — `error` returns checked at 2 sites, and callers branch on `err` first.
What does Share a Context Deadline Across Steps print when run?
Execute the whole file; each printed line is prefixed with a label like `completed`, `stopped:`.