Start learning free

LESSON 44 OF 58 · FULL-STACK: WHEN THINGS GO WRONG

Project: Try Again, Safely

Practice

Some failures last only a moment: the network drops, or a gateway answers 502, 503 or 504 while the server restarts. Asking again a little later often works: that is a retry. Other answers never fix themselves: a 404 or a 409 would come back the same, and a 500 is a bug the same request would hit again.

A retry is only safe when sending the request twice can't do harm. A GET only reads. A POST changes things: if the first "Add to cart" reached the server before the 503, a second one adds a second mug. So a POST is tried again only when it carries an Idempotency-Key. The checkout page sends one, and the server answers a key it has already seen with the same order instead of making a new one.

Each new try waits longer than the one before, 300 ms and then 600 ms, so a busy server gets room to recover. After two new tries, the error goes to the page. Two JavaScript tools help, shown here on other values:

const options = { method: "POST", headers: { "Idempotency-Key": "k-42" } };
"Idempotency-Key" in options.headers;   // true: the object has that key
const next = { ...options, attempt: 1 }; // a copy of options, with attempt 1

The check fails the API once, then three times in a row. Your page must do this:

offline, open /products/1        →  300 ms later the GET is sent again: 200, the Mug shows
Add to cart, API answers 503     →  "Server error" at once, no second POST
open /products/2: 502, 503, 504  →  tried at 0, 300 and 900 ms, then "Server error"
Pay, API answers 503 once        →  300 ms later the POST is sent again: 201, the Orders page
GET /payments (port 8002)        →  200  [one payment of $12]

Your task: in client/src/api.js, add the waits and a wait function, pass the caller's headers on, count the attempts and work out canRetry. Then, when fetch fails or the answer is 502, 503 or 504 and canRetry is true, wait and call api again.


Assignment
Follow the Coding Tutorial to make api() try a request again, at most twice, after a network failure or a 502, 503 or 504, and never repeat a POST without an Idempotency-Key.


Hint
A new try is api calling itself with attempt one more. return that call: without it, the code goes on past the wait and throws anyway.


STEP 1 OF 12
    Ctrl + Enter to check