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.
In Go, a retry is a for loop with a condition and a counter. Here a shop asks a news service at most 2 times:
client := http.Client{Timeout: time.Second}
attempt := 1
reply, err := client.Get(news + "/headlines")
for err == nil && reply.StatusCode >= 500 && attempt < 2 {
reply.Body.Close()
attempt = attempt + 1
reply, err = client.Get(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: client.Get returns an error, the err == nil check ends the loop, and a slow supplier has already cost the customer a second. Close each failed answer's body before you ask again.
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 handler for GET /products/{id}/supplier-stock, count the calls in a variable tries, call the supplier again while there is no error, it answers 500 or more and fewer than 3 tries were made, and add "tries" to the 502 answer.
Assignment
Follow the Coding Tutorial to add retries, with a limit, to the supplier call in the supplier-stock handler.
Hint
Declare tries := 1 below the client line: the first call is try number 1. Join the loop's three checks with &&. Inside the loop, close the body, add 1 to tries and call again with =, not :=. The 502 map becomes a map[string]any, so it can hold a number.
Free plan: 30 tutor messages. PRO is unlimited.
