Model partial failures and request deadlines
Model partial failures and request deadlines
A distributed request crosses process boundaries: one dependency can succeed while another fails. A timeout means the caller stopped waiting, not that the remote operation did not happen. Pass a context through the call chain, choose a total deadline and allocate smaller budgets for dependencies. Decide explicitly whether missing data permits a partial response.
package main
import ( "context" "errors" "fmt" "time")
func fetch(ctx context.Context) (string, error) { if err := ctx.Err(); err != nil { return "", err } return "catalog", nil}func main() { ctx, cancel := context.WithDeadline(context.Background(), time.Unix(0, 0)) defer cancel() v, err := fetch(ctx) fmt.Println(v == "", errors.Is(err, context.DeadlineExceeded))}The deadline is already in the past; the operation refuses to start. Real HTTP clients should attach this context to the request. Cancellation is cooperative; a remote commit can still be successful even when the response is lost.
Expected output:
true truePreserve the parent budget
package main
import ( "context" "fmt" "time")
func main() { parent, stop := context.WithTimeout(context.Background(), time.Minute) defer stop() child, cancel := context.WithTimeout(parent, time.Hour) defer cancel() a, _ := parent.Deadline() b, _ := child.Deadline() fmt.Println(a.Equal(b))}A child cannot extend an earlier parent deadline. Use separate error categories for optional data and mandatory data. Avoid replacing a request context with Background merely to make a dependency succeed; work that must outlive a request needs explicit ownership.
Expected output:
trueTry it locally
Create a canceled context. Write lookup that checks ctx.Err before returning a fixed value. Print whether the error is context.Canceled.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Distributed services 01: Model partial failures and request deadlines
Check the lesson objective before moving on.
A remote write times out. What is known?
Can a child context extend its parent deadline?