To Retry or Not to Retry: Exponential Backoff, Jitter and Idempotency Keys Done Right
Hầu như dev nào cũng từng viết một vòng for i in range(3) bọc quanh một HTTP call, rồi tự tin là hệ thống đã "resilient". Mình cũng vậy, cho đến một đêm payment gateway của đối tác chậm khoảng 2 giây. Service của tụi mình retry ngay lập tức, 3 lần, trên 40 instance. Một sự cố nhỏ thành ra một cơn retry storm, và gateway sập hẳn. Tệ hơn nữa, vài khách hàng bị trừ tiền 2 lần vì request đầu thật ra…
Retry decisions should not be based solely on the number of attempts but rather on whether the error is temporary and if the operation is idempotent. A flowchart outlines the steps: if the request failed, determine if the error is temporary (timeouts, 429, 502, 503, 504), if the action is idempotent (GET, PUT, DELETE, or with Idempotency-Key), and if there's budget left (number of tries or total time).
If it's not temporary, fail immediately. If it is, check if the operation is idempotent; if not, add an Idempotency-Key or stop retrying. Consider the remaining budget (tries or time) before retrying. Use exponential backoff with jitter to avoid thundering herd. Implement retry logic using libraries like tenacity in Python to manage retries based on retries or time budgets.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.