Start learning free

LESSON 106 OF 173 · BACKEND: PAYMENTS AND OTHER SERVICES

Try Again, a Few Times

Practice

Many failures of another service last only a moment: it restarts, or one of its servers hiccups, and the next request works. So before giving up, your shop can retry: ask again, a few times. It must also stop at some point, or a service that is really down would keep the customer waiting forever.

A retry is a while loop with a counter. Here a shop asks a news service at most 2 times:

var attempt = 1;
var reply = await http.GetAsync(NEWS + "/headlines");
while ((int)reply.StatusCode >= 500 && attempt < 2) {
    attempt = attempt + 1;
    reply = await http.GetAsync(NEWS + "/headlines");
}

Only answers of 500 or more are worth another try: they are the other service's own trouble, and they often pass. A 404 stays a 404 however often you ask. A timeout is not retried either: when a call's 1-second limit runs out, GetAsync throws a TaskCanceledException, which jumps straight to the catch and its 504. A slow supplier has already cost the customer a second.

The checks make the supplier fail on purpose: POST /check/supplier-down with {"times": 2} makes its next 2 calls answer 500. Your shop must answer:

(the supplier will fail its next 2 calls)
GET /products/1/supplier-stock  →  200  {"product_id": 1, "supplier_stock": 120}
(the supplier will fail its next 4 calls)
GET /products/3/supplier-stock  →  502  {"error": "The supplier is not answering", "tries": 3}
GET /products/3/supplier-stock  →  200  {"product_id": 3, "supplier_stock": 8}
GET /products/6/supplier-stock  →  404  {"error": "The supplier doesn't sell this product"}
(the supplier will be slow once)
GET /products/1/supplier-stock  →  504  {"error": "The supplier took too long"}

Your task: in the /products/{id}/supplier-stock route, call the supplier again while it answers 500 or more and fewer than 3 tries were made, count the calls in a variable tries, and add tries to the 502 answer.


Assignment
Follow the Coding Tutorial to add retries, with a limit, to the supplier call in the /products/{id}/supplier-stock route.


Hint
Join the loop's two conditions with &&. Inside the loop, add 1 to tries and make the same call again, with its own 1-second token. Declare tries below the url line, starting at 1: the first call is try number 1.


STEP 1 OF 5
    Ctrl + Enter to check