How-To Guide

How to Implement Deadlines and Cancellation Across Services

Propagate a single deadline through a call graph and cancel work in flight so a slow leaf does not tie up every caller above it.

On this page

  1. Introduction
  2. Why Per-Call Timeouts Are Not Enough
  3. Deadlines as Absolute Times
  4. Propagating the Deadline
  5. Cancellation in Flight
  6. Hedging Versus Cancellation
  7. The Last Hop and Budget Accounting
  8. Conclusion

Introduction

A per-call timeout is not enough in a distributed system. If a request passes through five services and each applies its own ten-second timeout, the total worst case is fifty seconds, and the client gave up long ago. Worse, when the client gives up, the servers upstream keep working on a request nobody wants, burning resources for a result that will be discarded. A deadline fixes both: the caller sets an absolute time by which the whole operation must finish, that deadline propagates with the request, every service budgets against it, and when it expires the work is cancelled everywhere.

Why Per-Call Timeouts Are Not Enough

Independent timeouts compose additively, not multiplicatively, so the total latency a caller can observe is the sum of the timeouts along the path. Each service believes it is bounded, yet the end-to-end operation is not. Meanwhile cancellation does not propagate: a client that times out closes its connection, but the server keeps executing unless it is told to stop, and a chain of such abandoned requests can consume the capacity of every service it touched.

A deadline expresses the requirement once, at the entry point, as an absolute time. Each hop subtracts the time already spent and passes the remainder, so no hop can extend the budget. When the deadline passes, the context is cancelled and every operation under it stops, freeing resources for requests that can still succeed.

Deadlines as Absolute Times

Represent a deadline as an absolute instant, not a duration, because a duration must be recomputed at every hop and clock skew between hosts makes the recomputation inconsistent. Pass the absolute time, and each service computes the remaining budget as the deadline minus its own clock. A small skew tolerance absorbs minor clock differences.

package main

import (
	"context"
	"net/http"
	"time"
)

// The entry point sets one deadline for the whole request.
func handler(w http.ResponseWriter, r *http.Request) {
	ctx, cancel := context.WithTimeout(r.Context(), 3*time.Second)
	defer cancel()

	if err := serviceA(ctx); err != nil {
		http.Error(w, "request failed", http.StatusGatewayTimeout)
		return
	}
	w.WriteHeader(http.StatusOK)
}

// Downstream calls inherit the same context, so the deadline propagates.
func serviceA(ctx context.Context) error {
	req, _ := http.NewRequestWithContext(ctx, http.MethodGet, "http://service-b/do", nil)
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return err // context deadline exceeded cancels the call automatically
	}
	defer resp.Body.Close()
	return nil
}

Propagating the Deadline

Propagation needs a transport for the deadline. gRPC carries it as a timeout on the wire, automatically converting the absolute deadline to a remaining duration at send time, and re-establishing it at the receiver. For HTTP you add a header such as a deadline-in-milliseconds value or a request timeout header, and the receiver reconstructs its context from it. The important part is that the value is derived from the absolute deadline, so latency already spent is deducted.

When you propagate, always round down the remaining budget by a small amount for the network hop, so the downstream expires slightly before the upstream. If the downstream deadline equalled the upstream, the upstream would give up first and the downstream’s cancellation would arrive after it had already finished, wasting its work.

Cancellation in Flight

Deadline propagation only pays off if the work actually stops. Every layer that does meaningful work must accept a cancellation signal and check it: a long loop should test for cancellation periodically, a database call should be issued with a cancellable context, and any goroutine or task spawned should be tied to the parent so it is cancelled when the parent is. Where the framework supports it, the request’s context is cancelled automatically when the client disconnects, and the handler must honour it.

// Node: propagate an AbortSignal to fetch and to a cancellable loop
async function fetchWithDeadline(url, signal) {
  const res = await fetch(url, { signal });
  if (!res.ok) throw new Error('upstream: ' + res.status);
  return res.json();
}

async function processBatch(items, signal) {
  const results = [];
  for (const item of items) {
    if (signal.aborted) throw new Error('cancelled');
    results.push(await fetchWithDeadline('/items/' + item, signal));
  }
  return results;
}

// The server sets the deadline; a client disconnect aborts it too.
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 3000);
try {
  await processBatch(ids, controller.signal);
} finally {
  clearTimeout(timer);
}

Hedging Versus Cancellation

Cancellation reduces wasted work; hedging reduces tail latency by issuing a second request when the first is slow and taking whichever returns first. The two interact: if you hedge, you must cancel the loser, or you double the work under load and make the problem worse. Hedge sparingly, only for idempotent requests and only on a small fraction of calls, and always cancel the losing request when one wins.

For non-idempotent writes, do not hedge; retrying a write can create duplicates. Use a deadline and idempotency key instead, so a retry is safe and a timeout does not leave the caller unsure whether the write happened. Deadlines bound the wait, and idempotency makes the outcome decidable.

The Last Hop and Budget Accounting

The last hop is the database or a third-party API, and it must participate or the deadline is meaningless. A database call issued without a cancellable context continues after the deadline, holding a connection and locks. Set a statement timeout on every query as a backstop, and thread the deadline into the client so a cancelled request actually stops server-side work.

Track how much of the total deadline each hop consumes. A hop that routinely uses most of the budget is the bottleneck, and knowing the split tells you where to optimise. Without per-hop timing, a deadline tells you the request failed but not why or where.

Conclusion

A deadline is a single absolute time set at the entry point and propagated with the request, so every service budgets against the same requirement instead of compounding independent timeouts. Propagate the remaining budget, subtract a hop allowance, cancel work in flight when it expires, and make the last hop cancellable with a statement timeout as a backstop. Hedge only when you cancel the loser and the request is idempotent. Accounting for the per-hop budget shows where the time goes, so a deadline becomes a diagnostic as well as a bound.

Sources: gRPC: deadlines, Go context package, Patterns for distributed transactions: cancellation.

FAQ

Why propagate a deadline instead of a timeout?
Independent timeouts compose additively, so the end-to-end wait is the sum along the path. An absolute deadline is set once and inherited, so no hop can extend the total budget, and when it passes the work is cancelled everywhere.
What happens when the client disconnects?
A good framework cancels the request context, and handlers must honour it by stopping work in flight. Without that, the server keeps computing a result nobody will receive, consuming resources that could serve a live request.

Related Examples