Back to course

Context: Cancellation and Deadlines

Go (Golang) for Cloud-Native Microservices

Mastering Context

In microservices, you don't want a request to run forever if the client has already disconnected. The context package handles this.

go ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel()

// Pass ctx to DB calls or external APIs req, _ := http.NewRequestWithContext(ctx, "GET", url, nil)

If the timeout is reached, all downstream processes are notified to stop, saving resources.