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.
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);
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.
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.
| Growth policy | Resizes | Total copies | Largest copy |
|---|---|---|---|
| Double, from 1 | 20 | 1,048,575 | 524,288 |
| Add 1,000, from 1,000 | 999 | 499,500,000 | 999,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
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.
A client library
Add up the waits, fit the deadline, then count the copies.
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.
// 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;
}
}
See MDN: fetch and Svelte {#await}.
Check this idea later
Sources
- Go blog: slices, usage and internals
- Rust: Vec capacity and reallocation
- C++: std::vector::push_back
- AWS Builders’ Library: timeouts, retries and backoff with jitter
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.
Sign in to keep your read marks on every device. Sign in
Was this helpful?