← Math
Math

Sums and series

How long does the client wait before it gives up?

Add every term when estimating a total wait or the work across repeated resizes.

Outcome

Add up geometric series for retry waits and array growth, fit retries to a deadline, and keep the total, average and largest term apart.

Terminology (6)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Geometric series
A sum where each term is the previous one times a fixed ratio, such as 100 + 200 + 400 + 800.
Closed form
A formula for a sum without adding term by term: a(g^n − 1)/(g − 1) for n terms starting at a with ratio g ≠ 1.
Finite sum
A sum of a known number of terms. Retries and resizes are always finite.
Growth factor
How much a growable buffer multiplies its capacity when it is full.
Amortized cost
Total cost of a sequence of operations divided by their number. An occasional expensive step can still give a small average over every allowed sequence; no random workload is assumed.
Resize
Allocating a larger buffer and copying the existing elements into it.

Why this matters

Backoff schedules, growable buffers, tiered storage and paginated fetches all produce terms that grow by a factor. What a deadline, a bill or a latency budget sees is the sum, while dashboards often show the largest term or the average. Mixing those three numbers sets deadlines that cut retries short and makes one slow append look like a design flaw.

This lesson assumes exponential growth and powers from earlier lessons. Its retry budget counts waits only; request execution and processing take additional time in a real client. The buffer model assumes each resize copies all held bytes into a new allocation.

From a growing sequence to its total

A sequence lists the amounts at successive steps; a series adds those amounts. A geometric sequence has a constant ratio between adjacent terms. The largest term, the total and the average describe different quantities even when they come from the same list.

Retry delays accumulate into a wait budget. Buffer resizes accumulate into copy work, which can then be averaged over the bytes appended. This connects exponential growth to total cost: one expensive step alone does not determine the average cost across the operation.

01Add the terms

Add the terms

A client retries a failed call six times, starting at 100 ms and doubling. The longest wait is 3.2 seconds, so someone set a 5-second request deadline. A bug report says the last retry never happens; compare that deadline with all the waits together. The same HTTP client reads each response body into a buffer that grows as bytes arrive, and a pull request wants to grow it by a fixed step to save memory.

Predict the three lines this program prints for the six retry delays.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const delays = [100, 200, 400, 800, 1600, 3200]; // ms before each retry

const total = delays.reduce((sum, delay) => sum + delay, 0);

console.log(total);
console.log(Math.max(...delays));
console.log(total / delays.length);
Which line should a request deadline be compared with?

02The closed form

The closed form

A geometric series with first term a, ratio g and n terms sums to a(gⁿ − 1)/(g − 1). For the retries, 100 × (2⁶ − 1)/(2 − 1) = 6,300. With ratio 2 and at least one term, the sum is always one first term short of twice the last term, which is why the last wait is just over half the total.

The formula divides by zero when g = 1, a constant delay, where the sum is simply a × n. A loop that adds the terms works directly for a few dozen retries. For a very large constant-delay count, a × n computes the same sum immediately.

03Running total, not one term

Running total, not one term

With a 10,000 ms deadline, how many retries fit? The running totals are 100, 300, 700, 1,500, 3,100, 6,300 and then 12,700.

How many retries fit within 10,000 ms?

04Amortized cost

Amortized cost

The client reads a response body into a buffer that starts with room for 1 byte and doubles when full. Reading a 10⁶-byte body copies 1, 2, 4, …, 2¹⁹ bytes along the way: 2²⁰ − 1 = 1,048,575 copies, about 1.05 per byte. The pull request’s fixed 1,000-byte step instead copies 1,000 + 2,000 + … + 999,000 = 499,500,000 bytes, about 500 per byte. Multiplying the capacity is what keeps the average bounded. The loop sums old capacities directly; a closed form must also keep its intermediate arithmetic exact. A product formed before division can exceed the exact integer range even when the final copy count fits.

Bytes copied while reading a 10⁶-byte response body
Growth policyResizesTotal copiesLargest copy
Double, from 1201,048,575524,288
Add 1,000, from 1,000999499,500,000999,000

Array.push grows the backing store as the engine sees fit; the specification does not fix a factor. The lab’s explicit copying model is separate from the engine’s chosen array representation.

05Total, average, largest

Total, average, largest

Reading exactly 1,024 bytes into a doubling buffer that starts at capacity 1: how many resizes?

06Tune retries and buffers

Tune retries and buffers

The client’s retry budget first needs the sum of every delay rather than the last or average wait. Fitting that sum to a deadline adds a stopping decision, including exact equality. The response-buffer review then uses the same geometric-sum reasoning to compare total copy work with the largest single pause and reject an extra resize at exact capacity.

In the frontend Retrying fetch within a deadline in Next.js and Svelte Optional

A retrying GET checks elapsed time plus the proposed next delay before scheduling it. This excerpt supports wait budgets from 1 to 60,000 ms and returns the last server response when another retry no longer fits. It rechecks after the timer wakes so a late timer does not launch another attempt. A timer or an in-flight fetch can still finish after the budget: this is a scheduling check, not a hard request-abort implementation.

Estimate.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// Check the prospective retry wait; this does not abort an in-flight request.
export async function fetchWithRetry(
  url: string,
  deadlineMs: number,
  signal?: AbortSignal
): Promise<Response> {
  if (!Number.isFinite(deadlineMs) || deadlineMs < 1 || deadlineMs > 60_000) {
    throw new RangeError("Wait budget must be 1–60,000 ms");
  }

  const started = performance.now();

  for (let delay = 100; ; delay *= 2) {
    const response = await fetch(url, { signal });

    if (response.status < 500) return response;
    if (performance.now() - started + delay > deadlineMs) return response; // the next wait would overrun

    await new Promise((resolve) => setTimeout(resolve, delay));

    if (performance.now() - started > deadlineMs) return response;
  }
}

Check this idea later
What is 1 + 2 + 4 + … + 2^(k−1)?
An array grows by 1.5× instead of 2×. Is the copy cost per append still bounded by a constant?
Sources

Values above were computed in Node 22 and run in Go 1.27, Rust 1.99 and Apple clang 17. The client library is a worked model.

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.