Skip to content

Retry Only When the Contract Allows It

The Course
•
18 min study

The decision

A retry is another operation, not a cure for every failure. Retrying a validation error wastes work; retrying a non-idempotent write can duplicate it. Define which failures are temporary and which operations are safe to repeat.

Read, predict, run

The model allows one temporary status only for an idempotent operation with attempts left. The pure policy can be tested independently of timers and network calls. A real client also needs a deadline, backoff and a maximum attempt count:

JavaScript
export function run({ status, idempotent, attempt }) {
  return idempotent && attempt < 3 && status === 503;
}

Before pressing Run, predict what run returns for {"status": 503, "idempotent": true, "attempt": 1} and {"status": 400, "idempotent": true, "attempt": 1}, from the code above. Write your answers down first: after Run, the case table shows the expected values beside the actual ones.

Retry Only When the Contract Allows It Next.js · 5 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <strong>Review Queue · Practice lab</strong> </header> {children} </body> </html> ); } import Cases from "./Cases.jsx"; export default function Page() { return ( <main> <h1>Retry Only When the Contract Allows It</h1> <p> Read the input and predict the result before running. Change lib/contract.js for the exercise. </p> <Cases /> </main> ); } import { run, examples } from "@/lib/contract.js"; const text = (value) => JSON.stringify(value) ?? "undefined"; export default async function Cases() { const results = await Promise.all( examples.map(async ([input, expected]) => { // Record the input before running, to show whether run changed it. const before = text(input); const actual = await run(input); return { input: before, expected, actual, kept: text(input) === before, pass: text(actual) === text(expected), }; }), ); return ( <section> <h2>Executable cases</h2> <p> Checks: {results.filter((row) => row.pass).length}/{results.length}{" "} passed </p> <table> <thead> <tr> <th>Input</th> <th>Expected</th> <th>Actual</th> <th>Input kept</th> </tr> </thead> <tbody> {results.map((row, i) => ( <tr key={i}> <td> <code>{row.input}</code> </td> <td> <code>{text(row.expected)}</code> </td> <td className={row.pass ? "pass" : "fail"}> <code>{text(row.actual)}</code> </td> <td className={row.kept ? "pass" : "fail"}> {row.kept ? "yes" : "no: run changed it"} </td> </tr> ))} </tbody> </table> </section> ); } body { font: 16px/1.5 system-ui; margin: 0; color: #182b3c; background: #f4f8fc; } header, main { max-width: 900px; margin: auto; padding: 20px; } header { border-bottom: 1px solid #cbd5e1; } a { color: #075985; } button, input, textarea, select { font: inherit; padding: 8px; margin: 4px; } button { cursor: pointer; } table { border-collapse: collapse; width: 100%; } th, td { padding: 10px; border: 1px solid #cbd5e1; text-align: left; vertical-align: top; } pre, code { white-space: pre-wrap; overflow-wrap: anywhere; } .pass { color: #166534; } .fail, [role="alert"] { color: #a01818; } section { margin: 16px 0; padding: 12px; background: white; border-radius: 8px; } nav { display: flex; gap: 16px; } export function run({ status, idempotent, attempt }) { return idempotent && attempt < 3 && status === 503; } export const examples = [ [{ status: 503, idempotent: true, attempt: 1 }, true], [{ status: 400, idempotent: true, attempt: 1 }, false], ];
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
Check your prediction
  • Input {"status": 503, "idempotent": true, "attempt": 1} → true.
  • Input {"status": 400, "idempotent": true, "attempt": 1} → false.

The case table computes these results on the server side of the simulation. It compares values; it does not prove a production deployment or database works.

The failure to avoid

A blanket catch-and-retry loop can turn an outage into a request storm. Do not retry merely because an error message contains a familiar word.

Compare a loop that retries any error three times with this policy. A 400 invalid_input is retried three times and fails three times. A POST that timed out after the server saved it is retried and saved again. This policy says no to both.

Exercise

Extend the contract

Allow 429 as well as 503, but only when a valid retryAfterSeconds between 0 and 30 is supplied for 429.

Start by deciding what a missing or very large retryAfterSeconds should mean. Write one case for each, with the result you chose, before changing the code.

Edit lib/contract.js, then rerun the original cases. If the requested rule changes an earlier result, update that expected value deliberately. Keep the other cases. Add the acceptance cases to examples so the preview checks them too.

  • Input {"status": 429, "idempotent": true, "attempt": 1, "retryAfterSeconds": 5} must return true.
Your working space Next.js · 5 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <strong>Review Queue · Practice lab</strong> </header> {children} </body> </html> ); } import Cases from "./Cases.jsx"; export default function Page() { return ( <main> <h1>Retry Only When the Contract Allows It</h1> <p> Read the input and predict the result before running. Change lib/contract.js for the exercise. </p> <Cases /> </main> ); } import { run, examples } from "@/lib/contract.js"; const text = (value) => JSON.stringify(value) ?? "undefined"; export default async function Cases() { const results = await Promise.all( examples.map(async ([input, expected]) => { // Record the input before running, to show whether run changed it. const before = text(input); const actual = await run(input); return { input: before, expected, actual, kept: text(input) === before, pass: text(actual) === text(expected), }; }), ); return ( <section> <h2>Executable cases</h2> <p> Checks: {results.filter((row) => row.pass).length}/{results.length}{" "} passed </p> <table> <thead> <tr> <th>Input</th> <th>Expected</th> <th>Actual</th> <th>Input kept</th> </tr> </thead> <tbody> {results.map((row, i) => ( <tr key={i}> <td> <code>{row.input}</code> </td> <td> <code>{text(row.expected)}</code> </td> <td className={row.pass ? "pass" : "fail"}> <code>{text(row.actual)}</code> </td> <td className={row.kept ? "pass" : "fail"}> {row.kept ? "yes" : "no: run changed it"} </td> </tr> ))} </tbody> </table> </section> ); } body { font: 16px/1.5 system-ui; margin: 0; color: #182b3c; background: #f4f8fc; } header, main { max-width: 900px; margin: auto; padding: 20px; } header { border-bottom: 1px solid #cbd5e1; } a { color: #075985; } button, input, textarea, select { font: inherit; padding: 8px; margin: 4px; } button { cursor: pointer; } table { border-collapse: collapse; width: 100%; } th, td { padding: 10px; border: 1px solid #cbd5e1; text-align: left; vertical-align: top; } pre, code { white-space: pre-wrap; overflow-wrap: anywhere; } .pass { color: #166534; } .fail, [role="alert"] { color: #a01818; } section { margin: 16px 0; padding: 12px; background: white; border-radius: 8px; } nav { display: flex; gap: 16px; } export function run({ status, idempotent, attempt }) { return idempotent && attempt < 3 && status === 503; } export const examples = [ [{ status: 503, idempotent: true, attempt: 1 }, true], [{ status: 400, idempotent: true, attempt: 1 }, false], ];
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
Hint 1: the idea

A 429 is the server asking you to wait. It's worth retrying only when the server said how long and the wait is reasonable; otherwise a retry is just more load.

Hint 2: a first step

A rate limit is not permission to hammer the service; validate the server’s delay before scheduling another attempt.

Show one solution

Replace the exported run function and any constants shown here; keep the examples export underneath it. Compare the result with your own approach.

JavaScript
export function run({ status, idempotent, attempt, retryAfterSeconds }) {
  return (
    idempotent &&
    attempt < 3 &&
    (status === 503 ||
      (status === 429 &&
        Number.isFinite(retryAfterSeconds) &&
        retryAfterSeconds >= 0 &&
        retryAfterSeconds <= 30))
  );
}

The 429 branch needs a finite retryAfterSeconds from 0 to 30, so a missing value, NaN or an hour all say no. The idempotency and attempt checks still apply to both statuses, so a rate-limited POST is never retried blindly. Capping the wait at 30 is a product decision: longer waits are better shown to the reader than hidden in a retry.

Explain it without the code

Write which of these a client should retry: a 503 on GET, a 503 on a POST with no idempotency key, a 429 with no delay, a 400.

Going further

Read the Next.js guide for the framework boundary around this rule. The preview runs code-playpad's Next.js simulation. Real caching, hydration, authentication and persistence require the real-server checks described on Day 7.

Was this article helpful?

Your response is saved on this device.