Deadline is a context.Context method that reports whether a deadline is set and, when present, returns its time. The deadline marks when the context begins reporting expiration. Use Done to observe completion and Err to learn why the context ended; reading Done is preferred to comparing Deadline with time.Now(). section 10.6.1
Use deadlines to control work across service boundaries:
- Create a child context with WithDeadline for a specific timestamp or WithTimeout for a duration; WithTimeout is more common for remote calls. section 10.6.2
- Give separate downstream calls their own child context and deadline when one request invokes multiple services, so slow calls can be identified precisely. section 10.6.3
- Account for network latency and avoid limits that are unnecessarily strict; otherwise remote calls can hang indefinitely. section 10.6 section 10.8
Protecting a database call
Create a 100-millisecond child context before calling the repository, defer its cancellation, and pass the child to db.Add. A timeout test can block for two seconds, select on ctx.Done(), and expect context.DeadlineExceeded.


