Timeouts
easy 30 minA timeout is the longest time you are willing to wait for something.
A deadline through a chain of services
Read it, run it, change a line and run it again.
Loading editor…
A fake clock makes it repeatable. Each service refuses what cannot finish, keeps a little time and passes on the rest.
The same in TypeScript
// The limit also cancels the work. Promise.race alone would leave it running.class TimeoutError extends Error {}async function withTimeout<T>(ms: number, fn: (signal: AbortSignal) => Promise<T>): Promise<T> { if (ms <= 0) throw new TimeoutError("no time left"); const stop = new AbortController(); let timer: ReturnType<typeof setTimeout> | undefined; const late = new Promise<never>((_, reject) => { timer = setTimeout(() => { stop.abort(); reject(new TimeoutError("after " + ms + " ms")); }, ms); }); try { return await Promise.race([fn(stop.signal), late]); } finally { clearTimeout(timer); }}interface Ctx { deadline: number } // epoch ms on this machineconst left = (ctx: Ctx, reserve = 0) => ctx.deadline - Date.now() - reserve;async function getUser(id: string, ctx: Ctx) { return withTimeout(Math.min(400, left(ctx)), async (signal) => { const res = await fetch("https://api.example.com/users/" + id, { signal }); if (!res.ok) throw new Error("HTTP " + res.status); return res.json(); // the limit covers the body too });}async function createOrder(charge: (ms: number) => Promise<string>, ctx: Ctx) { const ms = left(ctx, 200); // keep 200 ms for the last step if (ms <= 0) throw new TimeoutError("refused: not enough time"); return charge(ms); // pass the remaining time on}const ctx = { deadline: Date.now() + 1000 };createOrder(async (ms) => "charged with " + (ms > 700 ? "enough" : "little") + " time", ctx).then(console.log);withTimeout(50, (s) => new Promise((r) => { const t = setTimeout(r, 5000); s.addEventListener("abort", () => clearTimeout(t)); })) .catch((e) => console.log(e.message));The same in Go
package mainimport ( "context" "database/sql" "errors" "fmt" "net" "net/http" "time")func newClient() *http.Client { return &http.Client{ Timeout: 3 * time.Second, // the whole call, body included Transport: &http.Transport{ DialContext: (&net.Dialer{Timeout: 500 * time.Millisecond}).DialContext, TLSHandshakeTimeout: time.Second, ResponseHeaderTimeout: 2 * time.Second, IdleConnTimeout: 90 * time.Second, MaxIdleConnsPerHost: 10, }, }}// The context carries the deadline: a child can only be shorter than its parent.func createOrder(ctx context.Context, charge func(context.Context) error) error { deadline, ok := ctx.Deadline() if !ok { return errors.New("every request needs a deadline") } child, cancel := context.WithDeadline(ctx, deadline.Add(-200*time.Millisecond)) // keep 200 ms defer cancel() if child.Err() != nil { return fmt.Errorf("refused: %w", context.DeadlineExceeded) } return charge(child)}// Read every row before cancel runs, otherwise the rows are closed under you.func names(ctx context.Context, db *sql.DB) ([]string, error) { ctx, cancel := context.WithTimeout(ctx, time.Second) defer cancel() rows, err := db.QueryContext(ctx, "SELECT name FROM users LIMIT 100") if err != nil { return nil, err } defer rows.Close() var out []string for rows.Next() { var n string if err := rows.Scan(&n); err != nil { return nil, err } out = append(out, n) } return out, rows.Err()}func main() { _ = newClient() ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() err := createOrder(ctx, func(c context.Context) error { select { case <-time.After(5 * time.Second): return nil case <-c.Done(): return c.Err() } }) fmt.Println(errors.Is(err, context.DeadlineExceeded))}The same in Java
import java.net.URI;import java.net.http.*;import java.sql.*;import java.time.*;import java.util.concurrent.*;public class Timeouts { static final HttpClient CLIENT = HttpClient.newBuilder().connectTimeout(Duration.ofMillis(500)).build(); static String get(String url, Duration left) throws Exception { if (left.isNegative() || left.isZero()) throw new TimeoutException("no time left"); HttpRequest r = HttpRequest.newBuilder(URI.create(url)).timeout(left).GET().build(); HttpResponse<String> res = CLIENT.send(r, HttpResponse.BodyHandlers.ofString()); // HttpTimeoutException if (res.statusCode() >= 400) throw new RuntimeException("HTTP " + res.statusCode()); return res.body(); } // orTimeout completes the future, it does not stop the task. Cancel the task yourself. static <T> T limited(ExecutorService pool, Callable<T> task, Duration limit) throws Exception { Future<T> f = pool.submit(task); try { return f.get(limit.toMillis(), TimeUnit.MILLISECONDS); } catch (TimeoutException e) { f.cancel(true); throw e; } // interrupts the thread } static int countUsers(Connection c) throws SQLException { try (PreparedStatement s = c.prepareStatement("SELECT count(*) FROM users")) { s.setQueryTimeout(1); // seconds try (ResultSet rs = s.executeQuery()) { rs.next(); return rs.getInt(1); } } } static Duration forChild(Instant deadline) throws TimeoutException { Duration left = Duration.between(Instant.now(), deadline).minusMillis(200); // keep 200 ms if (left.isNegative() || left.isZero()) throw new TimeoutException("refused"); return left; } public static void main(String[] args) throws Exception { ExecutorService pool = Executors.newFixedThreadPool(2); System.out.println(forChild(Instant.now().plusSeconds(1)).toMillis() > 500); try { limited(pool, () -> { Thread.sleep(5000); return 1; }, Duration.ofMillis(50)); } catch (TimeoutException e) { System.out.println("timed out and cancelled"); } pool.shutdownNow(); }}