Timeouts, Retries & Jitter
“The solution isn’t to remove backoff. It’s to add jitter.” — Marc Brooker، Exponential Backoff and Jitter، AWS Architecture Blog، ۴ مارس ۲۰۱۵
خلاصه (Summary): timeout تعیین میکند چقدر حاضریم صبر کنیم، retry تعیین میکند دوباره بپرسیم یا نه، backoff تعیین میکند پیش از آن چقدر مکث کنیم، و jitter کاری میکند که هزار client در یک میلیثانیهٔ یکسان برنگردند. هر کدام بهتنهایی ارزاناند و با تنظیم غلط خطرناک، چون با هم تصمیم میگیرند یک خرابی کوچک کوچک میماند یا نه. تمرکز (Focus): timeoutهای connect، read، write، request، idle و total؛ deadline و بودجهٔ هر hop؛ انتخاب مقدار از صدکهای تأخیر؛ لایهبندی timeout بین load balancer، proxy، برنامه و دیتابیس؛ context.WithTimeout، http.Client و net.Dialer در Go؛ statement_timeout، lock_timeout و idle_in_transaction_session_timeout در PostgreSQL؛ timeout در Redis، PDO و HTTP client لاراول؛ timeout در برابر retry_after در job صف؛ چه چیزی امن برای retry است، طبقهبندی خطا، retry budget، per-try timeout، retry storm؛ backoff ثابت، خطی، نمایی و full/equal/decorrelated jitter؛ Retry-After؛ idempotency key؛ hedging؛ retry در صف (tries، backoff، retryUntil)؛ پیشفرض کتابخانهها (AWS SDK، gRPC، Guzzle، go-retryablehttp، Envoy، NGINX)؛ مشاهدهپذیری و تست با fake clock. هدف یادگیری (Learning goal): برای فراخوانی سرویس A به سرویس B بتوانید همهٔ timeoutهای مسیر را با عدد بنویسید، بگویید کدام خطاها را میشود دوباره امتحان کرد و کدام را نه، یک حلقهٔ retry با backoff، jitter، budget و deadline را در Go و لاراول بنویسید و با fake clock ثابت کنید جایی که باید میایستد.
این فصل کتاب آشپزی گروه Resilience است. فهرست timeoutها، عددها، فرمولهای backoff و jitter و قاعدهٔ retry با این صفحه است. سازوکار ارسال deadline بین سرویسها در Service Communication آمده؛ خسارتی که retry هنگام خرابی یک وابستگی میزند در Cascading Failures؛ مؤلفهای که صدا زدن وابستگی مرده را قطع میکند Circuit Breaker است؛ کلیدی که POST را قابلتکرار میکند در API Idempotency؛ عددهای تأخیر دُم و درخواست hedged در Latency Budgets and Tail Latency؛ و retry درون broker در Retry, Backoff & Delayed Delivery. اینجا قطعهها را کنار هم میگذاریم.
نقشهٔ صفحه
| اگر دنبال این هستید | به اینجا بروید |
|---|---|
| کل صفحه در چهار جدول | همهچیز در یک دقیقه |
| چرا نبود timeout یا retry ساده قطعی میسازد | چرا وجود دارد |
| Brooker 2015، Builders' Library، کتاب SRE، gRPC A6، RFC 9110 | از کجا آمده |
| timeoutهای connect، read، write، request، idle و total | انواع timeout |
| deadline، بودجهٔ هر hop، لایهبندی بین LB، proxy، برنامه، DB | Deadline و لایهبندی |
| کدام عدد را بگذاریم | انتخاب مقدار timeout |
| timeout در PostgreSQL، Redis، PDO | timeout دیتابیس و کش |
| timeout job در برابر retry_after | timeout صف |
| چه چیزی را میشود دوباره فرستاد | امن برای retry، طبقهبندی خطا |
| budget، per-try timeout، فقط یک لایه، retry storm | Budget، Per-try، یک لایه |
| backoff ثابت، خطی، نمایی | Backoff |
| jitter کامل، برابر و decorrelated | Jitter |
| Retry-After، pushback در gRPC، 429 و 503 | راهنمایی سرور |
| idempotency key | Idempotency key |
| hedging در برابر retry | Hedging |
| jobهای لاراول: tries، backoff، retryUntil | Retry در صف |
| AWS SDK adaptive، gRPC، Guzzle، go-retryablehttp، Envoy | Retry کتابخانهها |
| متریک retry، تست با fake clock | مشاهدهپذیری، تست |
| knobها، فرمولها، پیامهای خطا | سازوکار |
| کد | Go، Laravel |
| حادثههای کلاسیک و راهحل | حل مسئلههای کلاسیک |
| کدام سیاست برای کدام فراخوانی | انتخاب |
| از monolith تا چند-region | در معماری |
| خودتان عددها را دربیاورید | آزمایشگاه |
| باورهای غلط، چکیده، آزمون، واژهها | بدفهمیها، چکیده، خودآزمایی، واژهنامه |
همهچیز در یک دقیقه
پنج timeout یک فراخوانی. هر فراخوانی شبکه در پنج جا میتواند گیر کند و هر جا حد خودش را میخواهد.
| Timeout | چه چیزی را محدود میکند | مقدار معمول (فراخوانی با p99 حدود 200 ms) | knob در Go | knob در Laravel |
|---|---|---|---|---|
| Connect timeout | اتصال TCP (و TLS اگر با هم اندازهگیری شود) | 0.5 تا 1 s | net.Dialer.Timeout، Transport.TLSHandshakeTimeout | connectTimeout() (پیشفرض 10 s) |
| Write timeout | فرستادن بایتهای درخواست | 1 تا 5 s | http.Server.WriteTimeout (سمت سرور) | timeout در Guzzle شامل آن است |
| Read timeout | انتظار برای بایتهای پاسخ | 1 تا 3 s | Transport.ResponseHeaderTimeout | timeout() (پیشفرض 30 s) |
| Request (total) timeout | کل یک تلاش: connect، ارسال، انتظار، خواندن body | 2 تا 5 s | http.Client.Timeout، context.WithTimeout | timeout() |
| Idle timeout | اتصالی که چیزی روی آن در جریان نیست | 30 تا 120 s، کوتاهتر از طرف مقابل | Transport.IdleConnTimeout، http.Server.IdleTimeout | استفادهٔ مجدد از اتصال در Guzzle/cURL |
retry چه میتواند بکند. پرسش فقط «شکست خورد؟» نیست، «آیا سرور کاری کرد؟» است.
| شکست | آیا سرور اقدام کرده؟ | retry برای فراخوانی غیرidempotent؟ | retry برای فراخوانی idempotent؟ |
|---|---|---|---|
| Connection refused، dial timeout | خیر | بله | بله |
| 429 Too Many Requests، 503 Service Unavailable | معمولاً خیر (از ابتدا رد شده) | بله، به Retry-After احترام بگذارید | بله |
| Read timeout، بدون پاسخ | شاید (مبهم) | خیر | بله |
| Connection reset بعد از ارسال درخواست | شاید (مبهم) | خیر | بله |
| 500، 502، 504 | شاید (مبهم) | خیر | بله |
| 400، 401، 403، 404، 409، 422 | قابلاعمال نیست | هرگز | هرگز |
چهار فرمول backoff (attempt از 1 شروع میشود؛ cap بیشترین مکث؛ base اولین مکث).
| نام | فرمول | منبع |
|---|---|---|
| Capped exponential | sleep = min(cap, base * 2^(attempt-1)) | Brooker 2015 |
| Full jitter | sleep = random(0, min(cap, base * 2^(attempt-1))) | Brooker 2015 |
| Equal jitter | t = min(cap, base * 2^(attempt-1))، sleep = t/2 + random(0, t/2) | Brooker 2015 |
| Decorrelated jitter | sleep = min(cap, random(base, previous_sleep * 3)) | Brooker 2015 |
عددهایی که باید به خاطر بسپارید.
| عدد | معنی | منبع |
|---|---|---|
| 243x | پنج لایه که هر کدام سه بار تلاش میکنند، برای یک درخواست کاربر 243 فراخوانی به دیتابیس میفرستند | AWS Builders' Library |
| 10% | retry budget: وقتی retryها بیش از 10% درخواستها شد دیگر retry نکن | کتاب Google SRE، فصل 21 |
| 1.1x | بدترین رشد با budget دهدرصدی (بدون آن نزدیک 3x) | کتاب Google SRE، فصل 21 |
| 0.1% / p99.9 | از نرخ false-timeout قابلقبول شروع کن و صدک متناظر را بردار | AWS Builders' Library |
| 3 attempt | تعداد تلاش پیشفرض حالت standard در AWS SDK | راهنمای مرجع AWS SDK |
| 5 attempt | gRPC مقدار maxAttempts بیشتر از 5 را 5 حساب میکند | پیشنهاد gRPC A6 |
| 60 s | پیشفرض proxy_read_timeout در NGINX و idle timeout در AWS ALB | مستندات NGINX و AWS ALB |
چرا وجود دارد
یک فراخوانی شبکه هیچ سقف زمانی ندارد مگر خودتان بگذارید. سرور ممکن است با توقف GC متوقف شود، لینک ممکن است بیصدا بستهها را بریزد، load balancer ممکن است اتصالی را نگه دارد که کسی به آن سرویس نمیدهد. بدون timeout فراخواننده بهاندازهٔ عمر خرابی منتظر میماند و در تمام این مدت thread، connection، حافظه و جایی در صف را اشغال میکند. با 200 thread و یک وابستگی گیرکرده، درخواست 201 رد میشود در حالی که کد خودتان سالم است. همینطور خرابی یک سرویس به خرابی فراخوانندههایش تبدیل میشود (نگاه کنید به Cascading Failures).
retry هست چون بسیاری از خطاها کوتاهاند: یک pod داشت ریستارت میشد، یک replica مشغول بود، یک بسته گم شد. دوباره پرسیدن معمولاً جواب میدهد. تله اینجاست که حالتی که retry بیشترین کمک را میکند (خطای گذرا) و حالتی که بیشترین ضرر را میزند (سرور بیشازحد بارگذاریشده) از دید client یکسان دیده میشوند و یک حلقهٔ ساده حالت دوم را برای همه بدتر میکند.
| بدون آن | با آن | هزینهٔ راهحل |
|---|---|---|
| یک فراخوانی گیرکرده thread را برای همیشه نگه میدارد | فراخوانی در زمانی مشخص شکست میخورد | بعضی فراخوانیهای کند ولی سالم قطع میشوند (false timeout) |
| یک خطای گذرا به خطای کاربر تبدیل میشود | یک retry آن را پنهان میکند | بار اضافه، احتمال اثر جانبی تکراری |
| clientها همزمان retry میکنند و سرور در حال بازیابی را میکشند | jitter آنها را در زمان پخش میکند | بدترین انتظار کمی بیشتر |
| retry در هر لایه بار را ضرب میکند | یک لایه با budget retry میکند | لایههای درونی باید سریع شکست بخورند و روشن گزارش کنند |
تصویری از زندگی روزمره، در سراسر صفحه. به رستورانی زنگ میزنید تا میز رزرو کنید. از قبل تصمیم میگیرید چقدر بگذارید زنگ بخورد (timeout). اگر کسی برنداشت دوباره زنگ میزنید، ولی نه فوراً و نه دقیقاً همان دقیقهای که همهٔ مشتریهای دیگر هم دوباره شماره میگیرند (backoff و jitter). اگر گفتند «پر هستیم، بعد از هشت زنگ بزنید» باور میکنید (Retry-After). و اگر وسط جملهٔ «لطفاً میز 5 را رزرو کنید» تماس قطع شد، نمیدانید رزرو انجام شده یا نه؛ پس پیش از رزرو دوباره، شمارهٔ رزرو را میپرسید (idempotency).
سه بدفهمی رایج، از همین اول
- «timeout یعنی درخواست شکست خورد.» یعنی شما از انتظار دست کشیدید. سرور ممکن است هنوز کار کند و یک ثانیه بعد اقدام را کامل کند. این همان شکست مبهم (ambiguous failure) است و دلیل اینکه retry پرداخت بعد از timeout بدون idempotency key خطرناک است.
- «retry سیستم را قابلاعتمادتر میکند.» فقط برای خطاهای گذرا و جدا از هم. در برابر وابستگی بیشازحد بارگذاریشده retry بار اضافه است: با سه تلاش سیستم دقیقاً وقتی که کمترین توان را دارد تا سه برابر ترافیک میفرستد.
- «backoff نمایی مشکل thundering herd را حل میکند.» بهتنهایی نه. اگر هزار client در یک لحظه شکست بخورند و همه 100 ms، 200 ms، 400 ms بخوابند، هر بار با هم برمیگردند. چیزی که آنها را پخش میکند jitter است، نه توان دو.
از کجا آمده
| منبع | چه چیزی اضافه کرد | از کجا تأیید شد |
|---|---|---|
| Marc Brooker، Exponential Backoff and Jitter، AWS Architecture Blog، 2015 | «Full Jitter»، «Equal Jitter» و «Decorrelated Jitter» را در شبیهسازی clientهای رقیب نامگذاری و مقایسه کرد؛ بهروزرسانی 2023 میگوید بیشتر AWS SDKها حالا backoff نمایی و jitter دارند | صفحهٔ وبلاگ، ذخیرهشده |
| Marc Brooker، Timeouts, retries, and backoff with jitter، Amazon Builders' Library، دسامبر 2019 | انتخاب timeout از صدکهای تأخیر، مثال 243x، retry در یک نقطه، محدودسازی retry با token bucket، idempotency | مقاله، ذخیرهشده |
| کتاب Google SRE، فصل 21 «Handling Overload» | budget سهتلاشی برای هر درخواست، budget دهدرصدی برای هر client (رشد 1.1x به جای نزدیک 3x) | فصل، ذخیرهشده |
| RFC 9110 (HTTP Semantics)، 2022 | تعریف متدهای idempotent، قاعدهٔ retry خودکار، Retry-After | متن RFC، ذخیرهشده |
| پیشنهاد gRPC A6 «Client Retries» | سیاست retry (maxAttempts، backoff، status codeها)، سیاست hedging، retry throttling با token، pushback سرور | پیشنهاد، ذخیرهشده |
| Michael Nygard، Release It! | «Timeouts» و «Circuit Breaker» بهعنوان الگوی پایداری؛ سرچشمهٔ واژگان circuit breaker | از منبعنامهٔ بخش نام برده شده؛ برای این صفحه دوباره خوانده نشد |
تاریخها را ببینید. فرمولهای jitter مال 2015 است؛ ایدهٔ budget در SRE از همان دوره است؛ حالتهای «standard» و «adaptive» در AWS SDK در دههٔ 2020 آنها را بین زبانها یکدست کردند. هیچچیز اینجا تازه نیست، و برای همین نادیدهگرفتنش گران تمام میشود.
فهرست مفاهیم
هر بلوک همان ترتیب ثابت را دارد: به زبان ساده، بدفهمی رایج، تعریف، خط زمانی یا جریان درخواست، سناریوهای واقعی، آنچه هر محصول فراهم میکند، و راهحل.
انواع timeout: connect، read، write، request، idle حیاتی
به زبان ساده: «timeout» یک عدد نیست. یک فراخوانی مرحله دارد (پیدا کردن host، باز کردن اتصال، ارسال، انتظار، دریافت)، یک اتصال هم میتواند بیکار بماند، و هر مرحله جداگانه میتواند گیر کند. یک حد برای کل تلاش لازم است ولی کافی نیست، چون نمیگوید کدام مرحله کند بود.
بدفهمی رایج: «timeout=5 گذاشتم پس فراخوانی هرگز بیشتر از 5 ثانیه طول نمیکشد.» در بسیاری از clientها این مقدار timeout یک socket است که با هر خواندن موفق از نو شروع میشود. سروری که هر 4 ثانیه یک بایت میفرستد هرگز آن را نمیشکند. NGINX همین را برای proxy_read_timeout مینویسد: فقط «between two successive read operations, not for the transmission of the whole response.»
تعریف:
- Connect timeout: بیشترین زمانی که client برای تمام شدن handshake TCP (و بسته به client، حل نام و TLS) صبر میکند. اتصال ردشده فوراً شکست میخورد؛ آدرس black-hole فقط وقتی این تایمر شلیک کند. مستندات
net.Dialer.Timeoutدر Go میگوید سیستمعامل ممکن است «may impose its own earlier timeout. For instance, TCP timeouts are often around 3 minutes» و پیشفرض بدون timeout است. - Write timeout: بیشترین زمان ارسال درخواست. برای آپلود حجیم و clientهای کندخوان در سمت سرور مهم است (
http.Server.WriteTimeout). - Read timeout: بیشترین زمانی که client منتظر بایتهای بعدی پاسخ میماند. Go آن را دو تکه میکند:
Transport.ResponseHeaderTimeout(زمان تا header پاسخ بعد از نوشته شدن کامل درخواست) و خواندن body که با timeout کلی یا context محدود میشود. - Request (total) timeout: یک حد برای کل تلاش.
http.Client.Timeoutدر Go «includes connection time, any redirects, and reading the response body» و حتی وقتیResponse.Bodyرا میخوانید ادامه دارد. - Idle timeout: مدت مجاز یک اتصال بدون درخواست در جریان. در هر دو سمت هست (
Transport.IdleConnTimeoutدر client،http.Server.IdleTimeout، idle timeout پیشفرض 60 ثانیه در AWS ALB،keepalive_timeoutدر NGINX). سمتی که idle timeout کوتاهتر دارد اول میبندد؛ اگر client اتصالی را نگه دارد که سرور بسته، درخواست بعدی با reset شکست میخورد. - Total deadline: نقطهٔ زمانیِ مطلقی که کل عملیات (همهٔ تلاشها، همهٔ مکثها، همهٔ فراخوانیهای پاییندست) باید تا آن تمام شود. ویژگی درخواست کاربر است، نه یک فراخوانی. نگاه کنید به Deadline و لایهبندی.
Phases of one attempt and the timeout that guards each one
1 resolve name -> resolver timeout (OS / Resolver.Dial)
2 TCP connect (SYN, SYN-ACK, ACK) -> connect timeout (net.Dialer.Timeout)
3 TLS handshake -> TLSHandshakeTimeout
4 write request headers + body -> write timeout (server side) / total
5 wait for first response byte -> read timeout (ResponseHeaderTimeout)
6 read response body -> total timeout / context deadline
7 connection returns to the pool -> idle timeout (IdleConnTimeout)سناریوهای واقعی: فراخوانی API به hostی که پایین است و بستهها را میریزد: بدون connect timeout فراخوانی حدود 3 دقیقه در kernel منتظر میماند؛ client موبایل روی شبکهٔ ضعیف آپلود 20 MB را کند میفرستد و WriteTimeout سرور یا proxy_send_timeout برابر 60 ثانیه قطعش میکند؛ اتصال keep-alive از NATی رد میشود که اتصالهای بیکار را بعد از 5 دقیقه فراموش میکند و اولین درخواست بعد از سکوت با «connection reset» شکست میخورد؛ دانلود streaming که هر چند ثانیه یک بایت میفرستد از read timeout رد میشود ولی از total timeout بیرون میزند.
هر محصول چه فراهم میکند:
| محصول | Connect | Read / پاسخ | Total | Idle |
|---|---|---|---|---|
client در net/http Go | net.Dialer.Timeout (پیشفرض ندارد) | Transport.ResponseHeaderTimeout (پیشفرض ندارد) | http.Client.Timeout (پیشفرض ندارد) یا context درخواست | Transport.IdleConnTimeout |
سرور در net/http Go | قابلاعمال نیست | ReadTimeout، ReadHeaderTimeout | http.TimeoutHandler | IdleTimeout، WriteTimeout |
| HTTP client لاراول (Guzzle/cURL) | connectTimeout()، پیشفرض 10 s | timeout()، پیشفرض 30 s | timeout() | cache اتصال cURL |
| proxy در NGINX | proxy_connect_timeout 60 s | proxy_read_timeout 60 s | برای کل پاسخ ندارد | keepalive_timeout |
| router در Envoy | connect_timeout خوشه | per-try timeout | timeout مسیر، پیشفرض 15 s | idle_timeout |
| AWS ALB | قابلاعمال نیست | قابلاعمال نیست | قابلاعمال نیست | connection idle timeout، پیشفرض 60 s |
راهحل: همه را صریح تنظیم کنید. clientی که پیشفرض دارد یا «بدون حد» است (Go) یا «30 ثانیه» (Laravel)؛ هر دو برای یک فراخوانی تعاملی غلطاند. کد Go و Laravel در بخشهای Go و Laravel است.
Deadline، بودجهٔ هر hop و لایهبندی timeout حیاتی
به زبان ساده: کاربر برای کل درخواست یک مقدار زمان میدهد. هر hop مقداری از آن را خرج میکند، پس هر hop باید بداند چقدر مانده، و حدها هرچه به درون میرویم باید کوچکتر شوند؛ وگرنه لایهٔ بیرونی دست میکشد در حالی که لایهٔ درونی هنوز کار میکند.
بدفهمی رایج: «هر سرویس timeout 30 ثانیهای خودش را دارد، پس امنیم.» اگر A با timeout 30 s به B زنگ بزند و B با timeout 30 s به C، A ممکن است در 30 s دست بکشد در حالی که B تا 30 s بعد منتظر C است و کاری میکند که کسی نمیخواهد. timeoutهای مستقل ترکیب نمیشوند؛ باید از یک deadline مشتق شوند.
تعریف: Deadline زمان مطلق است؛ timeout مدت. در لبه تبدیل کنید: deadline = now + total. هر hop محاسبه میکند timeout = min(own_cap, remaining - margin). بودجهٔ timeout (timeout budget) همین زمان باقیمانده است. انتشار deadline (deadline propagation) یعنی فرستادن زمان باقیمانده به سرویس بعدی (grpc-timeout در gRPC، headerهایی مثل Request-Timeout-Ms نسبی، x-envoy-upstream-rq-timeout-ms در Envoy) تا بتواند کاری را که نمیرسد رد کند. سازوکار header در Service Communication است؛ عددهای هر hop در Latency Budgets.
Timeout layering: outer limit > inner limit, gap = time for the outer layer to react
1 Browser / mobile app 10 s total (user patience)
2 CDN / edge / load balancer 9 s request deadline (ALB idle timeout 60 s is separate)
3 API gateway / NGINX / Envoy 8 s proxy_read_timeout / route timeout
4 Application handler 7 s context.WithTimeout / request budget
5 Downstream HTTP call, per try 1.5 s x up to 3 tries + sleeps (fits in what is left)
6 PostgreSQL statement_timeout 1 s (aborts before the client's per-try timeout)
7 Result: the innermost layer fails first, with a precise error; outer layers still have time to answerسناریوهای واقعی: NGINX جلوی برنامه proxy_read_timeout 60s دارد و برنامه برای گزارش 120 s اجازه میدهد، پس کاربر در 60 s خطای 504 میبیند و برنامه به محاسبه ادامه میدهد؛ idle timeout کوتاهتر load balancer از keep-alive برنامه 502 پراکنده میسازد؛ برنامه query را در 5 s timeout میکند ولی PostgreSQL statement_timeout ندارد و query رهاشده به اجرا ادامه میدهد و یک connection را نگه میدارد؛ retry در gateway وقتی شروع میشود که کاربر رفته است.
چه چیزی فراهمش میکند:
| سازوکار | محصول | چه میکند |
|---|---|---|
context.WithTimeout، ctx.Deadline() | Go | deadline را از میان هر فراخوانیِ دارای context عبور میدهد |
header grpc-timeout، deadline در ctx | gRPC | زمان باقیمانده را خودکار بین سرویسها منتشر میکند |
x-envoy-upstream-rq-timeout-ms | Envoy | «an outer time limit for a request, including any retries that take place» |
proxy_read_timeout، proxy_next_upstream_timeout | NGINX | حد هر خواندن و سقف زمان صرفشده برای امتحان upstreamهای دیگر |
Http::timeout() بهعلاوهٔ شیء بودجهٔ درخواست | Laravel | timeout هر hop از بودجهٔ باقیمانده |
statement_timeout | PostgreSQL | سرور statement را قطع میکند حتی اگر client رفته باشد |
راهحل: جدول بالا را برای سیستم خودتان پیش از نوشتن کد بنویسید، با این پایهی ثابت: client > edge > proxy > app > per-try x tries > database.
انتخاب timeout از روی صدکها حیاتی
به زبان ساده: timeout را طوری بگذارید که وابستگی سالم تقریباً هرگز از آن رد نشود. یعنی یک صدک از تأخیر واقعیاش، نه عدد گرد دلخواه.
بدفهمی رایج: «timeout کوتاهتر همیشه امنتر است.» خیلی کوتاه false timeout میسازد: فراخوانیهای سالم قطع و retry میشوند و بار اضافه میآورند. Builders' Library دو خطر مقدار پایین را میگوید: client فراخوانیهایی را قطع میکند که موفق میشدند، و retryها ترافیک اضافه میکنند. همچنین سرویسی را شرح میدهد که درست بعد از deploy timeout میخورد چون تایمر 20 ms آن شامل برپایی یک اتصال امن جدید بود.
تعریف: نرخ false-timeout قابلقبول را انتخاب کنید (مثال Builders' Library برابر 0.1%) و صدک متناظر تأخیر پاییندست را بردارید (p99.9). وقتی p99.9 به p50 نزدیک است padding اضافه کنید و از دید فراخواننده اندازه بگیرید، با احتساب برپایی اتصال.
| p50 وابستگی | p99 | p99.9 | per-try timeout پیشنهادی | دلیل |
|---|---|---|---|---|
| 5 ms | 20 ms | 60 ms | 100 تا 150 ms | p99.9 بهعلاوهٔ padding؛ با 0.1% false timeout |
| 40 ms | 150 ms | 400 ms | 600 تا 800 ms | دُم پهن است؛ padding نسبتاً کوچکتر |
| 200 ms | 800 ms | 2 s | 3 تا 4 s | وابستگی کند؛ hedging ممکن است از timeout بلندتر بهتر باشد |
| 2 s (API دستهای) | 5 s | 9 s | 12 تا 15 s | بعد از حدود 10 s async (job) را ترجیح دهید |
| کران تنگ (p50 = 20 ms، p99.9 = 25 ms) | 24 ms | 25 ms | 60 ms | padding بدهید: واریانس کوچک نباید آن را بشکند |
این ردیفها نمونهٔ کار روشاند، نه اندازهگیری.
Timeline: why a too-low timeout hurts right after a deploy (Builders' Library story)
1 t=0 ms new server starts, first request needs a new TLS connection
2 t=0 ms client starts a 20 ms timer that includes connection setup
3 t=35 ms connection established (35 ms), timer already fired at 20 ms -> timeout
4 t=40 ms client retries on the now-warm connection -> succeeds in 3 ms
5 result a burst of errors and extra load at every deployment, none in steady stateسناریوهای واقعی: region جدید تأخیر بیشتری دارد و همهٔ فراخوانیها timeout میخورند تا وقتی که timeoutها دوباره مشتق شوند؛ timeout برابر p99 یک درصد فراخوانیهای سالم را قطع میکند؛ job دستهای و فراخوانی تعاملی یک پیکربندی client را شریکاند و یکی از آنها همیشه غلط است.
راهحل: از داشبورد مشتق کنید (p99.9 وابستگی از دید فراخواننده)، بعد از هر تغییر معماری بازبینی کنید و پیکربندی را برای هر وابستگی جدا نگه دارید، نه یک عدد سراسری. مکانیک صدکها در Latency Budgets است.
timeout دیتابیس و کش: PostgreSQL، Redis، PDO مهم
به زبان ساده: دیتابیس هم باید کارها را متوقف کند. اگر فقط client دست بکشد، سرور ممکن است queryی را اجرا کند که کسی منتظرش نیست، و تراکنش بازمانده قفل نگه میدارد و جلوی پاکسازی را میگیرد.
بدفهمی رایج: «timeout HTTP من از دیتابیس محافظت میکند.» بستن connection توسط client همیشه statement را فوراً لغو نمیکند، و statementی که در سرور در حال اجراست تمام میشود (و قفل نگه میدارد) مگر خود سرور حد داشته باشد. PostgreSQL برای سه مسئلهٔ جدا سه حد جدا دارد.
تعریف (PostgreSQL، از مستندات runtime configuration):
| پارامتر | چه چیزی را محدود میکند | پیشفرض | خطا | SQLSTATE |
|---|---|---|---|---|
statement_timeout | هر statement که «takes more than the specified amount of time» | 0 (غیرفعال) | canceling statement due to statement timeout | 57014 query_canceled |
lock_timeout | statementی که برای گرفتن قفل (table، index، row) بیش از این منتظر بماند، برای هر بار گرفتن قفل | 0 (غیرفعال) | canceling statement due to lock timeout | 55P03 lock_not_available |
idle_in_transaction_session_timeout | session بیکار درون تراکنش باز | 0 (غیرفعال) | terminating connection due to idle-in-transaction timeout | 25P03 |
idle_session_timeout | session بیکار بیرون تراکنش | 0 (غیرفعال) | terminating connection due to idle-session timeout | 57P05 |
transaction_timeout (PostgreSQL 17) | مدت کل تراکنش | 0 (غیرفعال) | terminating connection due to transaction timeout | 25P04 |
مستندات هشدار میدهد قرار دادن statement_timeout در postgresql.conf «is not recommended because it would affect all sessions»؛ آن را برای هر role، دیتابیس، session یا تراکنش (SET LOCAL) بگذارید. همچنین میگوید اگر statement_timeout غیرصفر است، گذاشتن lock_timeout برابر یا بزرگتر از آن «rather pointless» است. idle-in-transaction فراتر از قفل مهم است: تراکنش باز مانع «vacuuming away recently-dead tuples» میشود و باعث bloat هم میشود. مکانیک قفل در Locks & Concurrency، رفتار deadlock در Deadlocks و اندازهٔ pool در Connection Pooling است.
-- Per role: web requests are short, the reporting role may run longer.
ALTER ROLE app_web SET statement_timeout = '3s';
ALTER ROLE app_web SET lock_timeout = '500ms';
ALTER ROLE app_web SET idle_in_transaction_session_timeout = '10s';
ALTER ROLE app_reporting SET statement_timeout = '5min';
-- Per transaction: tighter than the role default, derived from the request budget.
BEGIN;
SET LOCAL statement_timeout = '800ms';
SET LOCAL lock_timeout = '200ms';
SELECT balance FROM accounts WHERE id = 42 FOR UPDATE; -- waits at most 200 ms for the row lock
COMMIT;دیگر ذخیرهگاهها:
| ذخیرهگاه | Timeout | نکته |
|---|---|---|
| Redis server | timeout 0 در redis.conf کلاینت بیکار بعد از N ثانیه را میبندد؛ پیشفرض 0 (غیرفعال) | حدهای سمت client مهمترند |
| go-redis | Options.DialTimeout، ReadTimeout، WriteTimeout، MaxRetries، MinRetryBackoff، MaxRetryBackoff، ContextTimeoutEnabled | client خودش retry دارد (MaxRetries): آن را یک لایهٔ retry حساب کنید |
| Redis در Laravel (phpredis / Predis) | timeout، read_timeout در config/database.php | هر دو را بگذارید؛ خواندن مسدودشده وگرنه پیشفرض را منتظر میماند |
| PDO | PDO::ATTR_TIMEOUT بر حسب ثانیه | راهنما میگوید «Not all drivers support this option, and its meaning may differ» |
| MySQL | max_execution_time (برای SELECT)، innodb_lock_wait_timeout | نامها فرق دارند، نقشها یکی است |
راهحل: پیشفرضهای سطح role را در دیتابیس بگذارید، برای هر تراکنش از بودجهٔ درخواست یک SET LOCAL کوچکتر مشتق کنید، و لغو سمت client را نگه دارید (در Go: context را به QueryContext بدهید) تا driver سیگنال cancel بفرستد. کمکتابع Go در Go است.
timeout صف: timeout job در برابر retry_after مهم
به زبان ساده: worker صف دو ساعت جدا دارد: یک job چقدر اجازهٔ اجرا دارد (timeout)، و صف چقدر بعد فرض کند worker مرده و job را به کس دیگری بدهد (retry_after، visibility timeout). اگر اولی از دومی بلندتر باشد، همان job همزمان دو بار اجرا میشود.
بدفهمی رایج: «retry_after فاصلهٔ بین retryهاست.» در Laravel این visibility timeout است: چقدر یک job رزروشده پنهان میماند تا دوباره آزاد شود. فاصلهٔ بین retryها backoff است.
تعریف (مستندات queue در Laravel 13): مقدار پیشفرض queue:work --timeout برابر «60 seconds» است؛ retry_after اتصال (نمونهٔ Redis برابر 90) زمانی است که job هنوز در حال پردازش آزاد میشود: «The --timeout value should always be at least several seconds shorter than your retry_after configuration value... If your --timeout option is longer than your retry_after configuration value, your jobs may be processed twice.» attribute Timeout روی job مقدار CLI را لغو میکند، و jobی که فراخوانی HTTP بدون timeout خودش دارد ممکن است timeout job را نادیده بگیرد، پس «when using these features, you should always attempt to specify a timeout using their APIs as well.» SQS مقدار retry_after ندارد: Default Visibility Timeout در AWS تصمیم میگیرد.
Three nested clocks of one queued job (seconds)
1 Http::timeout(10) HTTP call inside the job gives up
2 #[Timeout(30)] / --timeout worker kills the job process
3 retry_after = 90 queue releases the job to another worker
4 Rule: 10 < 30 < 90. Break it (timeout 120, retry_after 90) and the job runs twice at onceسناریوهای واقعی: export دو دقیقهای با retry_after برابر 90 روی دو worker اجرا میشود و دو ایمیل میفرستد؛ Default Visibility Timeout برابر 30 s در SQS با jobی 60 ثانیهای؛ jobی بدون timeout HTTP تا کشته شدن worker گیر میکند.
چه چیزی فراهمش میکند:
| صف | ساعت تحویل | حد زمان job |
|---|---|---|
| Laravel Redis / database | retry_after در config/queue.php | --timeout، #[Timeout]، نیاز به PCNTL |
| Laravel SQS / Amazon SQS | Default Visibility Timeout (AWS) | timeout worker، همان قاعده |
| RabbitMQ | consumer acknowledgement timeout | زمان پردازش consumer |
| Kafka | max.poll.interval.ms | فاصلهٔ بین pollها |
جزئیات سمت broker در Retry, Backoff & Delayed Delivery است.
راهحل: این سه عدد را با هم تنظیم کنید (بخش config در Laravel است).
چه چیزی امن برای retry است: idempotency و شکست مبهم حیاتی
به زبان ساده: retry فقط وقتی امن است که دوبار انجام دادن با یکبار انجام دادن یکی باشد. خواندن اینطور است. «آدرس را بگذار X» اینطور است. «100 به موجودی اضافه کن» نیست.
بدفهمی رایج: «اگر فراخوانی شکست خورد، کار انجام نشده.» timeout یا reset فقط میگوید پاسخ را نگرفتید. Builders' Library صریح میگوید: «A timeout or failure doesn't necessarily mean that side effects haven't happened.»
تعریف: عملیات idempotent است اگر تکرارش اثری برابر با یکبار انجام آن داشته باشد. RFC 9110 بخش 9.2.2: «PUT, DELETE, and safe request methods are idempotent»؛ «A client SHOULD NOT automatically retry a request with a non-idempotent method unless it has some means to know that the request semantics are actually idempotent... or some means to detect that the original request was never applied»؛ و «A proxy MUST NOT automatically retry non-idempotent requests.» طبقهبندی شکستها به قطعاً اجرا نشده، قطعاً شکست خورده و مبهم در بلوک بعد است.
The ambiguous failure: POST /charge, client read timeout 1.5 s
1 client -> server POST /charge {order 7, 100.00}
2 server executes the charge, commits (takes 1.8 s because of a slow bank)
3 client timeout at 1.5 s, sees no response
4 client -> server POST /charge {order 7, 100.00} (naive retry)
5 server executes the charge again -> customer charged twice
6 with Idempotency-Key: k1 on both requests, step 5 returns the stored result of step 2سناریوهای واقعی: پرداخت، ثبت سفارش، ارسال ایمیل، کمکردن موجودی انبار، افزایش شمارنده، webhook (گیرنده تکراری دریافت میکند) و انتشار پیام (publish تکراری پیام را دوبل میکند).
چه چیزی فراهمش میکند:
| عملیات | ذاتاً idempotent است؟ | چطور امنش کنیم |
|---|---|---|
| GET، HEAD، OPTIONS | بله (safe) | کاری لازم نیست |
| PUT، DELETE | طبق تعریف بله | handler باید واقعاً اینطور رفتار کند |
| POST برای ساخت | خیر | idempotency key که با نتیجه ذخیره شود؛ یا شناسهٔ انتخابشده توسط client (PUT /orders/{uuid}) |
شمارندهٔ += 1 | خیر | مقدار مطلق بگذارید یا با شناسهٔ عملیات dedupe کنید |
| بهروزرسانی شرطی با نسخه (compare-and-set) | در عمل بله | ستون version، نگاه کنید به Optimistic Locking |
راهحل: عملیات را idempotent طراحی کنید، بعد key بدهید؛ ذخیره، عمر و مدیریت race کلید در API Idempotency است. بخش Idempotency key نشان میدهد چطور در حلقهٔ retry سیمش کنید.
طبقهبندی خطا: چه چیزی را retry کنیم حیاتی
به زبان ساده: پیش از نگاه به ساعت، شکستها را در سه دسته بگذارید: «هرگز به سرور نرسید» (همیشه امن)، «سرور شاید اقدام کرده» (فقط اگر idempotent باشد)، و «هرگز موفق نمیشود» (بایست).
بدفهمی رایج: «روی هر 5xx و هر timeout retry کن.» 501 و بیشتر 4xxها هرگز موفق نمیشوند؛ 500 ممکن است باگی باشد که هر بار یکسان شکست میخورد؛ و 4xx در سیستم eventually consistent ممکن است لحظهای بعد موفق شود (Builders' Library میگوید سازگاری این مرز را «significantly blurs»).
تعریف: از سه دسته استفاده کنید: Retryable (سرور پیش از اقدام درخواست را رد کرد)، Ambiguous (نتیجه معلوم نیست)، Fatal (retry نتیجه را عوض نمیکند). بستهٔ retry همین صفحه جدول زیر را کد کرده است.
| خطا | دسته | چرا | retry برای غیرidempotent؟ | راهنمای backoff معمول |
|---|---|---|---|---|
Connection refused (ECONNREFUSED) | Retryable | کسی گوش نمیداد؛ درخواست هرگز نرفت | بله | کوتاه، با jitter |
شکست DNS (no such host) | Retryable | درخواستی فرستاده نشد | بله | کوتاه؛ شاید cap بلندتر لازم باشد |
| Dial یا connect timeout | Retryable | اتصال هرگز برقرار نشد | بله | jitter |
| شکست یا timeout در TLS handshake | Retryable | handshake پیش از درخواست است | بله | jitter |
| 429 Too Many Requests | Retryable | rate limiter رد کرد | بله | در صورت وجود Retry-After |
| 503 Service Unavailable | Retryable | معمولاً پیش از پردازش shed شده | بله | در صورت وجود Retry-After |
| Read timeout (بدون پاسخ) | Ambiguous | سرور شاید هنوز کار میکند | خیر | jitter، فقط idempotent |
| Connection reset یا EOF بعد از ارسال | Ambiguous | crash یا kill در میانهٔ درخواست | خیر | jitter، فقط idempotent |
| 500 Internal Server Error | Ambiguous | شاید خطای گذرا یا باگ قطعی؛ شاید نیمهکاره اجرا شده | خیر | تلاشهای کم |
| 502 Bad Gateway، 504 Gateway Timeout | Ambiguous | gateway فرستاد و پاسخ را گم کرد | خیر | jitter، فقط idempotent |
| 408 Request Timeout | Ambiguous | سرور هنگام خواندن درخواست timeout خورد | خیر | jitter |
| 400، 401، 403، 404، 405، 409، 410، 422 | Fatal | اول درخواست، token یا state را درست کنید | هرگز | ندارد |
| 501 Not Implemented | Fatal | عوض نمیشود | هرگز | ندارد |
context.Canceled (فراخواننده رفت) | Fatal | کاربر رفت؛ همهچیز را متوقف کنید | هرگز | ندارد |
دستهها قضاوت است و برای این صفحه گرفته شده (503 و 429 معمولاً پیش از پردازش رد میشوند ولی HTTP چنین تضمینی نمیدهد)؛ اصل از RFC 9110 است: درخواست غیرidempotent را فقط وقتی retry میکنید که بتوانید بفهمید اصلی اعمال نشده. NGINX همین برش را دارد: proxy_next_upstream پیشفرض error timeout است و «requests with a non-idempotent method (POST, LOCK, PATCH) are not passed to the next server» مگر non_idempotent را اضافه کنید.
Request flow: classification decides the next step
1 attempt fails with err
2 errors.Is(err, context.Canceled)? -> stop (caller gave up)
3 status 400..499 except 408/429? -> stop (fatal)
4 refused / dial timeout / 429 / 503 -> retryable: go to budget check
5 read timeout / reset / 500 / 502 / 504 -> ambiguous: go on only if idempotent or keyed
6 otherwise -> stop and surface the errorسناریوهای واقعی: client بعد از انقضای token پنج بار روی 401 retry میکند (یک بار refresh و بعد بایستید)؛ retry حلقهوار 409 روی optimistic lock (اول دوباره بخوانید)؛ POST که بعد از 504 retry شده رکورد تکراری میسازد.
راهحل: classifier را برای هر client یک بار بنویسید، با جدول تست کنید (نگاه کنید به TestAmbiguousFailureNeedsIdempotency در بخش Go) و دسته را به متریکها بفرستید (نگاه کنید به مشاهدهپذیری).
Retry budget حیاتی
به زبان ساده: retry budget سهمیهٔ ترافیک اضافه است: «به ازای هر ده درخواست حداکثر یک retry». وقتی سهمیه تمام شد، شکستها بهجای تکرار به فراخواننده برمیگردند.
بدفهمی رایج: «سه تلاش برای هر درخواست حد است، پس تقویت حداکثر 3x است و اشکالی ندارد.» سه برابر ترافیک روی وابستگیای که همین حالا خراب است همان مشکل است. حد هر درخواست حد مجموع را نمیگذارد؛ budget میگذارد.
تعریف: کتاب SRE گوگل دو لایه میگوید. «First, we implement a per-request retry budget of up to three attempts.» «Secondly, we implement a per-client retry budget. Each client keeps track of the ratio of requests that correspond to retries. A request will only be retried as long as this ratio is below 10%.» بدترین حالت از «just below 3X» به «just 1.1x in the general case» میرسد. Builders' Library با token bucket همین هدف را دنبال میکند: «This allows all calls to retry as long as there are tokens, and then retry at a fixed rate when the tokens are exhausted.» در gRPC A6 سطل با موفقیتها پر میشود (tokenRatio) و در نیمهٔ maxTokens یا کمتر retry متوقف میشود.
Token-bucket retry budget (ratio 0.1, max 10 tokens)
1 start tokens = 10
2 every first attempt tokens = min(10, tokens + 0.1) # deposit
3 a retry is wanted tokens >= 1 ? tokens -= 1 : give up # withdraw
4 dependency 100% down, 1000 requests, 3 attempts each:
5 without budget 3000 calls (+200%)
6 with budget 1109 calls (+11%) <- measured by cmd/jittersim on this pageسناریوهای واقعی: failover دیتابیس برای 30 ثانیه؛ کشی که خالی ریستارت میشود؛ deploy بد یک وابستگی؛ خرابی region که همهٔ clientها retry میکنند. در همهٔ اینها budget بار اضافهٔ client را نزدیک 10% نگه میدارد، در حالی که یک تکان تکنمونهای هنوز retry میگیرد چون سطل پر است.
چه چیزی فراهمش میکند:
| محصول | سازوکار budget | پیشفرض |
|---|---|---|
| gRPC | retryThrottling با maxTokens و tokenRatio برای هر نام سرور | فعال نیست مگر پیکربندی شود |
| AWS SDK (حالت standard) | retry quota: token bucket که برای هر retry کم و با موفقیت پر میشود | فعال؛ «During normal operation, the quota stays full and has no effect» |
| Envoy | retry budget و circuit-breaker max_retries برای هر cluster (سقف retryهای همزمان) | صریح پیکربندی کنید |
بستهٔ retry در Go اینجا | Budget{ratio, max} | Budget: retry.NewBudget(0.1, 10) بدهید |
Http::retry() در Laravel | ندارد | با شمارندهٔ Cache/Redis بپیچید یا از middleware Guzzle استفاده کنید |
راهحل: برای هر وابستگی یک budget مشترک (نه برای هر درخواست، وگرنه دوباره حد هر درخواست میشود). کد Go در Go. در Laravel budget باید در state مشترک باشد (Redis INCR با expiry)، چون هر درخواست PHP یک process تازه است.
Per-try timeout در برابر deadline کلی حیاتی
به زبان ساده: دو ساعت همزمان کار میکنند: یکی برای هر تلاش، یکی برای کل کار. per-try timeout نمیگذارد یک تلاش گیرکرده کل زمان را بخورد؛ deadline کلی نمیگذارد همهٔ تلاشها با هم از صبر کاربر بیشتر شوند.
بدفهمی رایج: «timeout برابر 3 s، 3 تلاش، پس فراخوانی حداکثر 3 s طول میکشد.» تا 3 x 3 s بهعلاوهٔ مکثها، یعنی بیش از 9 s. و خطای عکسش هم رایج است: یک timeout کلی 3 s بدون حد per-try اجازه میدهد اولین تلاش گیرکرده همه چیز را بخورد و برای retryای که جواب میداد زمانی نماند.
تعریف: per_try_timeout = min(per_try_cap, remaining_time). وقتی now + next_sleep بعد از deadline است بایستید. Envoy همین تفکیک را دارد: x-envoy-upstream-rq-timeout-ms «is an outer time limit for a request, including any retries that take place»، Envoy «will not retry when a request exceeds» آن، و «Use x-envoy-upstream-rq-per-try-timeout-ms if you want to retry when individual attempts take too long.» طراحی معمول: deadline برابر 3 s، per-try برابر 1 s، سه تلاش، و مکثها 0 تا 100 ms تا تلاش سوم هنوز زمان داشته باشد.
Deadline 3 s, per-try 1 s, full jitter backoff (base 100 ms)
1 t=0.00 s attempt 1 starts limit = min(1 s, 3 s left)
2 t=1.00 s attempt 1 times out (ambiguous: only idempotent calls continue)
3 t=1.00 s sleep random(0,100 ms) -> 0.06 s
4 t=1.06 s attempt 2 starts limit = min(1 s, 1.94 s left)
5 t=2.06 s attempt 2 times out
6 t=2.06 s sleep random(0,200 ms) -> 0.15 s, 2.21 + 0.79 left -> attempt 3 limit = 0.79 s
7 t=3.00 s deadline; give up with the last errorسناریوهای واقعی: جستجو با deadline برابر 2 s و replica گیرکرده: per-try برابر 400 ms، retry به replica دیگر میرسد و در مجموع 600 ms جواب میدهد؛ checkoutی که باید در 10 s جواب دهد ولی با پنج وابستگی کار میکند، پس به هرکدام سهمی میرسد.
چه چیزی فراهمش میکند: در Go، context.WithTimeout برای هر تلاش از context والد؛ در Envoy، per_try_timeout در سیاست retry مسیر؛ در gRPC رفتار هر تلاش از deadline فراخوانی پیروی میکند (بعد از گذشتن deadline retry متوقف میشود)؛ در Laravel، Http::timeout() برای هر تلاش است، پس برای حد کلی از شیء بودجهٔ درخواست استفاده کنید (نگاه کنید به PaymentsClient).
راهحل: همیشه حد per-try را از زمان باقیمانده حساب کنید و تلاش (یا مکثی) را که نمیرسد شروع نکنید. تابع retry.Do هر دو را انجام میدهد.
فقط در یک لایه retry کنید؛ retry storm حیاتی
به زبان ساده: اگر هر سطح پشته retry کند، تعداد فراخوانی در پایین حاصلضرب تلاشهاست، نه مجموع.
بدفهمی رایج: «retryهای هر لایه مستقل و کوچکاند.» Builders' Library حسابش را میکند: «Consider a system where the customer's call causes a five-deep stack of service calls. It ends with a query to a database, and three retries at each layer. What happens when the database starts failing queries under load? If each layer retries independently, the load on the database will increase 243x». و انتخاب مقابل هم هزینه دارد: «retrying at the highest layer of the stack may waste work from previous calls». قاعدهٔ کلی آن برای عملیات ارزان «retry at a single point in the stack» است.
تعریف: Retry storm (یا retry amplification، retry avalanche) اضافهبار خودنگهدارِ ناشی از retryهاست: وابستگی کند میشود، clientها timeout میخورند و retry میکنند، بار اضافه آن را کندتر میکند، clientهای بیشتری timeout میخورند. حالتی metastable است: حذف محرک (تکان اولیه) آن را تمام نمیکند، فقط shed کردن بار retry تمامش میکند. Thundering herd همان clientهاییاند که با هم عمل میکنند؛ jitter زمانبندی را درمان میکند و budget حجم را.
The amplification, layer by layer (3 attempts each)
1 edge 1 x 3 = 3 calls into service A per user request
2 service A 3 x 3 = 9 calls into B
3 service B 9 x 3 = 27 calls into C
4 service C 27 x 3 = 81 calls into D
5 service D 81 x 3 = 243 calls into the database
6 fix: only the edge retries (3 attempts, 10% budget); A, B, C, D fail fast and say whyسناریوهای واقعی: CPU دیتابیس 90% است و timeout شروع میشود؛ هر pod هر سرویس retry میکند؛ بعد از رفع علت اصلی CPU روی 100% میماند. deploy باگدار نرخ خطا را بالا میبرد و SDK، sidecar مش و برنامه همه retry میکنند. اپ موبایل بعد از قطعی کوتاه روی هر صفحه retry میکند و backend درست لحظهٔ بالا آمدن 10 برابر ترافیک میبیند.
چه چیزی فراهمش میکند:
| کنترل | محصول | اثر |
|---|---|---|
| retry در لبه، fail fast در درون | قاعدهٔ طراحی | حاصلضرب تلاشها میشود تلاشهای لبه |
| Retry budget | gRPC، AWS SDK، Envoy | سقف مجموع |
| Circuit breaker | Resilience4j، outlier detection در Envoy، Istio | وقتی شکست از آستانه رد شد فراخوانی را قطع میکند؛ نگاه کنید به Circuit Breaker |
| Load shedding | سمت سرور | وابستگی سریع رد میکند؛ نگاه کنید به Load Shedding |
| Rate limiting | gateway | ورودی را محدود میکند؛ نگاه کنید به Rate Limiting |
| وقتی برنامه retry میکند retry مش را خاموش کنید | Istio / Envoy | از لایهٔ دوم پنهان جلوگیری میکند |
راهحل: همهٔ لایههایی که میتوانند retry کنند را فهرست کنید (SDK، HTTP client، sidecar مش، gateway، صف job، مرورگر کاربر)، یکی را انتخاب کنید و بقیه را صفر کنید. کنار جدول timeout مستندش کنید.
Backoff: ثابت، خطی، نمایی، با cap حیاتی
به زبان ساده: backoff یعنی پیش از تلاش بعدی مکث کردن، و هر بار بیشتر. ایده این است که به وابستگی جا بدهیم بازیابی شود.
بدفهمی رایج: «تلاش بیشتر با فاصلهٔ ثابت کوتاه مقاومتر است.» پنج retry فوری یعنی پنج برابر بار در چند میلیثانیه. Builders' Library: «Instead of retrying immediately and aggressively, the client waits some amount of time between tries.»
تعریف:
| استراتژی | فرمول (attempt = 1، 2، ...) | شکل | ضعف |
|---|---|---|---|
| Constant | sleep = d | صاف | هر دور همان فشار؛ clientها همزمان میمانند |
| Linear | sleep = min(cap, n * step) | شیب | شیب کند؛ باز هم همزمان |
| Exponential | sleep = base * 2^(n-1) | 100، 200، 400، 800 ms | بیکران رشد میکند؛ همزمان |
| Capped exponential | sleep = min(cap, base * 2^(n-1)) | 100، 200، 400، ... cap | همه در cap باز هم همزماناند |
| با jitter | نگاه کنید به Jitter | پخش | میانگین زمان دیواری کمی بیشتر |
خط زمانی 4 client بدون jitter («clusters of calls» در توصیف Brooker):
Four clients fail together at t=0, capped exponential, base 100 ms, no jitter
1 t=0 calls: A B C D (4 calls, one wins)
2 t=100 ms calls: B C D (all sleep exactly 100 ms)
3 t=300 ms calls: C D (all sleep exactly 200 ms more)
4 t=700 ms calls: D
5 every round has all remaining clients calling at the same instant; the gaps in between are idleسناریوهای واقعی: دیتابیس در حال بازیابی که هر 800 ms یک موج همزمان میگیرد؛ حلقهٔ OCC که N نویسنده روی یک ردیف برخورد میکنند.
چه چیزی فراهمش میکند: Http::retry(3, 100) در Laravel ثابت است؛ Http::retry([100, 200, 400]) برنامهٔ صریح است؛ queue:work --backoff=3 ثابت است؛ #[Backoff([10, 30, 60])] روی job یک برنامه است (آخرین مقدار تکرار میشود)؛ پیشفرض go-retryablehttp نمایی بین RetryWaitMin و RetryWaitMax است؛ AWS SDK نمایی با full jitter دارد؛ gRPC نمایی با jitter برابر +/-20% دارد.
راهحل: همیشه cap بگذارید، همیشه jitter اضافه کنید و تعداد تلاش را کم نگه دارید (3 برای فراخوانی تعاملی، تا 5 برای کار پسزمینه).
Jitter: full، equal، decorrelated حیاتی
به زبان ساده: jitter تصادفیبودنی است که به مکث اضافه میشود تا clientهایی که با هم شکست خوردند با هم برنگردند. «Initially, jitter may appear to be a counter-intuitive idea: trying to improve the performance of a system by adding randomness.»
بدفهمی رایج: «کمی jitter (به اندازهٔ ±10%) کافی است.» gRPC از ±20% استفاده میکند تا از کوبیدن «at the same time from a large number of clients» جلوگیری کند، که شروع هر دور را کمی پخش میکند، ولی قویترین نتیجه در شبیهسازی Brooker full jitter است که مکث در کل بازهٔ 0 تا سقف نمایی پخش میشود.
تعریف (Brooker 2015، فرمولها از شکلهای وبلاگ بیرون نوشته شده):
| گونه | sleep = | بازه در attempt 4 (base 100 ms، cap 5 s) |
|---|---|---|
| بدون jitter | min(cap, base * 2^(n-1)) | دقیقاً 800 ms |
| Full jitter | random(0, min(cap, base * 2^(n-1))) | 0 تا 800 ms |
| Equal jitter | t/2 + random(0, t/2) با t = min(cap, base * 2^(n-1)) | 400 تا 800 ms |
| Decorrelated jitter | min(cap, random(base, previous * 3)) | 100 ms تا 3 برابر مکث قبلی |
نتایج Brooker برای clientهای رقیب: «the number of calls is approximately the same for 'Full' and 'Equal' jitter, and higher for 'Decorrelated'»؛ «Of the jittered approaches, 'Equal Jitter' is the loser. It does slightly more work than 'Full Jitter', and takes much longer»؛ و «The 'Full Jitter' approach uses less work, but slightly more time» نسبت به decorrelated. مرجع AWS SDK انتخاب عرضهشده را میگوید: «The SDK uses exponential backoff with full jitter.»
1000 clients, 4th retry, base 100 ms: how many wake up in each 100 ms slot of [0, 800 ms)
1 no jitter all 1000 wake at exactly 800 ms, every slot before it is empty
2 full jitter about 125 per slot in all 8 slots (uniform)
3 equal jitter about 250 per slot in slots 4 to 7 (400-800 ms)
4 decorrelated depends on each client's own previous sleep: no two clients stay in stepسناریوهای واقعی: کشی که برای همهٔ clientها ساعت 12:00:00 منقضی میشود؛ deployی که 500 pod را ریستارت میکند و clientهایشان همه با هم وصل میشوند؛ cron شبانهٔ 00:00 روی همهٔ hostها؛ retry زمانبندیشده «5 دقیقهٔ بعد» برای همهٔ webhookهای شکستخورده.
چه چیزی فراهمش میکند: AWS SDKها (full jitter)؛ gRPC (±0.2)؛ LinearJitterBackoff در go-retryablehttp؛ Laravel برای Http::retry() یا آرایهٔ backoff job هیچ jitter اضافه نمیکند، شما در closure یا متد backoff() اضافه میکنید؛ تأخیر پیشفرض Middleware::retry در Guzzle نمایی و بدون jitter است، callable $delay خودتان را بدهید.
راهحل: full jitter پیشفرض درست است (کمترین کار، ساده). equal jitter را وقتی حداقل مکث تضمینشده لازم دارید؛ decorrelated را وقتی تأخیرها باید از قبلی بیایند نه از شمارندهٔ تلاش (وقتی تلاشها کاملاً پشتسرهم نیستند مفید است).
راهنمایی سرور: Retry-After، pushback، 429 و 503 مهم
به زبان ساده: سرور بهتر از فرمول شما میداند کی آماده میشود. اگر گفت «30 ثانیهٔ دیگر بیا»، باور کنید.
بدفهمی رایج: «Retry-After فقط برای 503 است.» RFC 9110 آن را برای هر پاسخی تعریف میکند، با معنای ویژه برای 503 (سرویس چقدر در دسترس نخواهد بود) و 3xx (حداقل زمان پیش از دنبال کردن redirect)؛ 429 آن را به عرف استفاده میکند.
تعریف: Retry-After = HTTP-date / delay-seconds با delay-seconds = 1*DIGIT. نمونههای RFC: Retry-After: Fri, 31 Dec 1999 23:59:59 GMT و Retry-After: 120. client شما باید هر دو شکل را parse کند، بزرگتر از backoff خودش و hint را بردارد، و اگر hint از باقیماندهٔ deadline بیشتر بود بایستد. gRPC معادلش را در metadata دارد: grpc-retry-pushback-ms؛ مقدار منفی یا غیرقابلparse یعنی اصلاً retry نکن، و مقدار معتبر باعث میشود client دقیقاً بعد از همان تأخیر retry کند. A6 اضافه میکند اگر client maxAttempts را مصرف کرده باشد، فراخوانی «even if the server says to retry after a given delay» دوباره انجام نمیشود.
Retry-After in a call
1 client -> server GET /report
2 server -> client 429 Too Many Requests Retry-After: 2
3 client computes backoff = random(0, 200 ms) = 140 ms; hint = 2000 ms; sleep = max = 2000 ms
4 client waits 2 s (fake clock in tests)
5 client -> server GET /report -> 200سناریوهای واقعی: محدودیت نرخ API (429 به سبک GitHub با زمان reset)؛ پنجرهٔ نگهداری (503 با تاریخ)؛ سروری که بار را shed میکند و Retry-After کوچک با پخش تصادفی میدهد تا clientها همزمان نشوند؛ edge در CDN که هنگام failover مبدأ 503 میدهد.
چه چیزی فراهمش میکند: go-retryablehttp روی 429 در DefaultBackoff و روی 429 یا 503 در RateLimitLinearJitterBackoff آن را parse میکند؛ AWS SDK برای خطاهای throttling بیشتر از خطاهای گذرا صبر میکند؛ Http::retry() در Laravel خودش آن را نمیخواند، شما در closure مکث میخوانیدش (PaymentsClient).
راهحل: parse کنید، با deadline محدودش کنید، و سمت سرور هنگام فرستادن یک جزء تصادفی اضافه کنید تا یک میلیون client دقیقاً در یک ثانیه برنگردند.
Idempotency key درون حلقهٔ retry حیاتی
به زبان ساده: idempotency key اسمی است برای «این تلاش برای انجام این کار». همهٔ retryهای یک عملیات همان اسم را دارند، پس سرور تکرار را تشخیص میدهد و پاسخ اول را برمیگرداند.
بدفهمی رایج: «برای هر درخواست یک UUID تازه بساز.» key تازه برای هر retry یعنی هر بار عملیات جدید، و محافظت از بین رفته است. key باید پیش از اولین تلاش ساخته شود و از همهٔ retryها (و در jobهای پسزمینه، از هر تحویل مجدد job) عبور کند.
تعریف: client روی POST مقدار Idempotency-Key: <opaque id> میفرستد؛ سرور key را با نتیجهٔ اول ذخیره میکند و برای تکرار همان نتیجه را برمیگرداند. عمر، ذخیره، همروندی و رفتار خطا در API Idempotency است. RunInstances در EC2 مثال Builders' Library از «explicit token-based mechanisms to provide idempotency» است.
One logical charge, three attempts, one key
1 key = uuid() # outside the loop, stored with the order row
2 attempt 1 POST /charge key=K -> read timeout (ambiguous)
3 attempt 2 POST /charge key=K -> 503 Retry-After: 1 (retryable)
4 attempt 3 POST /charge key=K -> 200 {charge_id: c1} (or the stored result of attempt 1)
5 the customer is charged exactly once either wayسناریوهای واقعی: capture پرداخت، ثبت سفارش، ارسال ایمیل یا SMS، ثبت در دفتر کل، صدور کوپن، ساخت منبع ابری.
چه چیزی فراهمش میکند: headerهای Idempotency-Key به سبک Stripe (نگاه کنید به Payment Processing)، client tokenهای AWS، قید unique روی شناسهٔ عملیات در دیتابیس خودتان، ShouldBeUnique در Laravel برای تکرار در صف (مسئلهٔ دیگری است: از دو job در صف جلوگیری میکند، نه از اثر جانبی تکراری).
راهحل: اگر میشود key را از خود عملیات بسازید (شناسهٔ سفارش بهعلاوهٔ اقدام) تا process ریستارتشده دوباره از همان استفاده کند؛ وگرنه key ساختهشده را پیش از ارسال ذخیره کنید. PHP در Laravel آن را یک بار بیرون از retry() میسازد.
Hedging در برابر retry مهم
به زبان ساده: retry صبر میکند تا تلاش اول شکست بخورد. درخواست hedged نسخهٔ دوم را وقتی میفرستد که اولی هنوز در جریان است و از معمول کندتر شده، و هر کدام زودتر جواب داد را برمیدارد.
بدفهمی رایج: «hedging فقط retry با timeout کوتاهتر است.» تلاش اول با timeout لغو نمیشود؛ ادامه دارد، پس هزینهٔ دو فراخوانی همزمان را میدهید و سرور باید تکرار را تحمل کند. فصل latency عددها را دارد: hedging بعد از p95 حدود 5% بار اضافه میآورد و دُم را کم میکند.
تعریف: gRPC A6 سیاست hedging را تعریف میکند («aggressively sending multiple copies of a single request without waiting for a response») با maxAttempts و hedgingDelay، همان tokenهای throttling را روی hedgeها هم اعمال میکند، و هشدار میدهد hedged RPCها «may be executed multiple times on the server side, typically by different backends» پس فقط برای methodهایی است که «safe to execute multiple times». هر RPC تابع سیاست retry یا hedging است، نه هر دو. Envoy گزینهٔ hedge_on_per_try_timeout دارد.
| جنبه | Retry | Hedge |
|---|---|---|
| محرک | شکست یا per-try timeout | تأخیر (حدود p95) بدون پاسخ |
| تلاش اول | تمامشده (شکست یا لغو) | هنوز در حال اجرا |
| بار اضافه | فقط وقتی شکست رخ دهد | حدود 5% در حالت پایدار (Dean و Barroso) |
| چه چیزی را کم میکند | نرخ خطا | تأخیر دُم (p99) |
| نیاز به idempotency | برای شکست مبهم بله | همیشه بله (هر دو ممکن است اجرا شوند) |
| Budget | Retry budget | همان budget؛ hedging نباید هنگام قطعی اجرا شود |
سناریوهای واقعی: خواندن از ذخیرهگاه replicaدار که یک replica در GC pause است؛ fan-out جستجو که یک shard کند است؛ هرگز پرداخت. جزئیات و اندازهگیری: Latency Budgets.
راهحل: خواندنها را hedge کنید، با همان budget retry سقف بگذارید و بازندهٔ مسابقه را از راه context لغو کنید.
Retry در صف: tries، backoff، retryUntil مهم
به زبان ساده: job صف با برگشتن به صف retry میشود. پرسشها همانهاست (چند بار، با چه فاصله، کی ایست)، ولی پاسخها در پیکربندی worker و attributeهای job است.
بدفهمی رایج: «job تا موفق شدن retry میشود.» در Laravel «By default, Laravel will only attempt a job once.» چیزهای زیادی یک attempt را مصرف میکنند: exception مدیریتنشده، $this->release()، middlewareای که قفل نگیرد، timeout. Tries خیلی کم، تنازع قفل را به شکست دائمی تبدیل میکند (مستندات: «leaving Tries to 1 as it is by default would prevent any overlapping job from being retried later»).
تعریف (queueهای Laravel 13):
| Knob | معنی | مثال |
|---|---|---|
--tries / #[Tries(n)] / tries() | بیشترین attempt؛ attribute روی job از CLI برنده است؛ --tries=0 برای همیشه retry میکند | #[Tries(8)] |
retryUntil() / #[RetryFor(hours: 1)] | پنجرهٔ زمانی بهجای تعداد؛ retryUntil بر tries «takes precedence» | now()->plus(hours: 6) |
--backoff / #[Backoff(3)] / backoff() | ثانیههای انتظار بعد از exception؛ آرایه برنامهٔ افزایشی است و آخرین مقدار تکرار میشود | #[Backoff([10, 30, 60])] |
#[MaxExceptions(n)] | attempt زیاد ولی بعد از n exception (نه release) شکست | #[Tries(25)] #[MaxExceptions(3)] |
$this->release($seconds) | صفگذاری مجدد دستی با تأخیر؛ یک attempt مصرف میکند | release(10)؛ releaseUsingBackoff() |
#[Timeout(n)]، --timeout | بیشترین زمان اجرای یک attempt | پیشفرض 60 s |
#[FailOnTimeout] | بهجای retry هنگام timeout شکستخورده علامت بزن | |
ThrottlesExceptions(n, seconds) | middleware: بعد از n exception، attemptها تا پایان بازه نگه داشته میشوند | breaker برای job |
retry_after (اتصال) | Visibility timeout | 90 |
A job with #[Tries(5)] #[Backoff([10, 30, 60])] on the Redis queue
1 t=0 attempt 1 throws -> released with delay 10 s
2 t=10 attempt 2 throws -> delay 30 s
3 t=40 attempt 3 throws -> delay 60 s
4 t=100 attempt 4 throws -> delay 60 s (last value repeats)
5 t=160 attempt 5 throws -> attempts exhausted -> failed_jobs, failed() calledسناریوهای واقعی: تحویل webhook به endpoint مشتری که یک ساعت پایین است (retryUntil و backoff افزایشی)؛ ارائهدهندهٔ ایمیل با محدودیت نرخ (release() با Retry-After)؛ jobی که قفل توزیعشده دارد و باید بعداً retry کند.
چه چیزی فراهمش میکند: Laravel همانطور که آمد؛ Kafka retry تکپیام ندارد پس retry topic مینویسید؛ RabbitMQ از TTL queue یا delayed-message plugin استفاده میکند؛ SQS از visibility timeout و maxReceiveCount. نگاه کنید به Retry, Backoff & Delayed Delivery و parking lot در Dead Letter Queues.
راهحل: از #[Backoff] با آرایه یا متد backoff() با jitter استفاده کنید (PHP در Laravel)؛ retryUntil را با MaxExceptions ترکیب کنید؛ jobها را idempotent نگه دارید، چون jobهای «released» و «timed out» دوباره اجرا میشوند.
Retry کتابخانهها: پیشفرضها واقعاً چه میکنند مهم
به زبان ساده: بسیاری از clientها خودشان retry میکنند. اگر حلقهٔ خودتان را رویشان بگذارید، پشتهٔ 243x را در یک process ساختهاید.
بدفهمی رایج: «SDK retry نمیکند مگر بخواهم.» AWS SDKها بهطور پیشفرض retry میکنند؛ gRPC در بعضی حالتها شفاف retry میکند؛ go-redis دستورها را retry میکند (MaxRetries)؛ sidecar مش شما هم ممکن است retry کند.
| کتابخانه | رفتار پیشفرض | Knobها | Retry budget |
|---|---|---|---|
| AWS SDKها (حالت standard) | backoff نمایی با jitter؛ 3 attempt (DynamoDB: 4)؛ تأخیر کوتاهتر برای خطای گذرا و بلندتر برای throttling | retry_mode، max_attempts، AWS_MAX_ATTEMPTS | Retry quota (token bucket) |
| AWS SDKها (حالت adaptive) | standard بهعلاوهٔ rate limiter سمت client که میتواند اولین درخواست را هم عقب بیندازد؛ برای هر SDK client | retry_mode=adaptive | rate limiter بهعلاوهٔ quota؛ «not recommended as a general default» |
| gRPC | سیاست retry در service config: maxAttempts (سقف 5)، initialBackoff، maxBackoff، backoffMultiplier، retryableStatusCodes، jitter برابر ±20% | JSON سرویسکانفیگ | retryThrottling (maxTokens، tokenRatio) |
| Envoy | retry_on (5xx، gateway-error، reset، connect-failure، refused-stream)، num_retries، per_try_timeout؛ تعداد retry پیشفرض 1 | سیاست retry مسیر یا virtual host، headerها | Retry budget و circuit-breaker max_retries در cluster |
| NGINX | proxy_next_upstream error timeout؛ POST بدون non_idempotent retry نمیشود؛ proxy_next_upstream_tries، proxy_next_upstream_timeout | برای هر location | ندارد |
| go-retryablehttp | خطاهای اتصال و 5xx بهجز 501 را retry میکند؛ backoff نمایی بین RetryWaitMin و RetryWaitMax؛ RetryMax | CheckRetry، Backoff | ندارد |
| Guzzle | retry ندارد مگر GuzzleHttp\Middleware::retry($decider, $delay) را push کنید؛ تأخیر پیشفرض نمایی است | callableهای decider و delay | ندارد |
Http::retry() در Laravel | روی هر exception (از جمله RequestException) retry میکند مگر callable when تصمیم بگیرد | times، sleep (عدد، آرایه یا closure)، when، throw | ندارد |
| go-redis | MaxRetries با MinRetryBackoff و MaxRetryBackoff؛ cluster client داخلی retry میکند | Options | ندارد |
سناریوهای واقعی: برنامه AWS SDK را در حلقهٔ سهتلاشی خودش میپیچد (9 تلاش برای هر فراخوانی)؛ sidecar Envoy روی 503 retry میکند و برنامه هم؛ middleware Guzzle روی POST بدون key retry میکند.
راهحل: پیشفرضها را بخوانید، لایهای را که لازم ندارید خاموش کنید (max_attempts=1 در AWS وقتی حلقهٔ خودتان مالک retry است، num_retries: 0 در Envoy) و لایهٔ باقیمانده را همانی کنید که idempotency را میشناسد.
retry و circuit breaker تکمیلی
به زبان ساده: retry میپرسد «دوباره امتحان کنم؟». circuit breaker میپرسد «مدتی اصلاً امتحان نکنم؟». با هم کار میکنند: وقتی شکست گذرا نیست breaker حفاظت قویتر است.
بدفهمی رایج: «circuit breaker جای retry را میگیرد.» نمیگیرد؛ retry شکستهای گذرای تکدرخواست را درمان میکند، breaker وقتی شکست فراگیر است خسارت را محدود میکند. Builders' Library میگوید breakerها «introduce modal behavior into systems that can be difficult to test» و خط دفاع اول را token bucket محلی روی retryها میداند. طراحی و حالتها (closed، open، half-open) در Circuit Breaker است.
تعریف و ترتیب: breaker یا بیرون حلقهٔ retry برای کل عملیات مینشیند یا درون آن برای هر تلاش، بسته به اینکه مدار باز باید یک retry مصرف کند یا نه. انتخاب رایج: هر تلاش اول از breaker میپرسد؛ مدار باز یک خطای «فعلاً fatal» است که حلقه retry نمیکند و فوراً بالا میدهد.
راهحل: «circuit open» را یک دستهٔ خطای جدا با متریک جدا بگیرید.
مشاهدهپذیری retry مهم
به زبان ساده: اگر نبینید چند retry و چرا رخ میدهد، فقط وقتی متوجه میشوید که خودشان قطعی شدهاند.
بدفهمی رایج: «نرخ موفقیت کافی است.» نرخ موفقیت 99.9% میتواند پنهان کند که از هر سه درخواست یکی تلاش دوم لازم داشته، و budget خیلی پیش از آنکه هشداری شلیک شود تمام میشود.
تعریف: بشمارید و برچسب بزنید: تعداد تلاش برای هر درخواست (histogram)، retryها بر حسب دستهٔ دلیل و status، give-upها بر حسب دلیل (max attempts، budget، deadline، fatal، ambiguous)، زمان خواب، توکنهای باقیماندهٔ budget، per-try timeoutها. هر تلاش را یک span فرزند با retry.attempt و error.type ثبت کنید. روی نسبت retry به تلاش اول و روی اتمام budget هشدار بدهید، نه روی شمارش خام. نگاه کنید به Observability و هشدار SLO در Alerting That Actually Works.
| متریک | نوع | Labelها | هشدار وقتی |
|---|---|---|---|
client_attempts_total | Counter | dependency، attempt (1، 2، 3+) | نسبت attempt 2+ به attempt 1 بیش از 5% برای 10 دقیقه |
client_retries_total | Counter | dependency، reason (دسته و کد) | دلیل جدیدی ظاهر شود |
client_giveups_total | Counter | dependency، reason | budget exhausted بزرگتر از 0 برای 5 دقیقه |
client_retry_sleep_seconds | Histogram | dependency | میانهٔ مکث روی cap باشد |
client_timeouts_total | Counter | dependency، kind (connect، read، total) | بعد از deploy بالا برود |
retry_budget_tokens | Gauge | dependency | کمتر از 20% بیشینه |
راهحل: هوک OnRetry در retry.Policy Go تنها جای انتشار آنهاست؛ در Laravel از closure retry و eventهای HTTP client (RequestSending، ResponseReceived، ConnectionFailed) استفاده کنید.
تست retry با fake clock مهم
به زبان ساده: حلقهٔ retry با sleep واقعی تست را کند و ناپایدار میکند، پس تستها ساعت را جایگزین میکنند: «sleep» میشود «زمان را جلو ببر و بنویس».
بدفهمی رایج: «کد retry بسیار به زمان وابسته است و unit test نمیشود.» فقط اگر ساعت واقعی را بخواند. اگر زمان و تصادف تزریق شوند هر ویژگی (تأخیرها، شرطهای توقف، budget) قطعی است.
تعریف: Clock (Now، Sleep) و Rand را تزریق کنید. در تست Sleep شمارنده را جلو میبرد و تأخیر را ثبت میکند؛ Rand یا PCG با seed ثابت است یا ثابت (0.0 و 0.999 کرانها را میآزمایند). چهار نوع ویژگی را بررسی کنید: برنامه (مکثهای دقیق برای attemptهای مشخص)، کرانها (jitter درون بازهاش برای بسیاری seed)، قواعد توقف (deadline، حداکثر attempt، budget، fatal، ambiguous)، اثرها (تعداد فراخوانی به سرور).
A fake-clock test (TestDeadlineStopsBeforeASleepThatCannotFit)
1 policy: Overall 1 s, Backoff constant 400 ms, MaxAttempts 10
2 attempt at t=0.0 fails 503; next sleep ends at 0.4 <= 1.0 -> sleep (fake: now = 0.4)
3 attempt at t=0.4 fails 503; sleep ends at 0.8 <= 1.0 -> sleep (now = 0.8)
4 attempt at t=0.8 fails 503; sleep would end at 1.2 > 1.0 -> give up "deadline"
5 assert: calls == 3, slept == 800 ms, test runs in microsecondsسناریوهای واقعی: اثبات اینکه POST غیرidempotent بعد از read timeout تکرار نمیشود؛ اثبات اینکه Retry-After: 7 مکث 7 ثانیهای میدهد؛ اثبات اینکه قطعی هزار-درخواستی حداکثر 11% فراخوانی اضافه خرج میکند.
چه چیزی فراهمش میکند: Go: interface Clock خودتان (یا testing/synctest)؛ Laravel: Sleep::fake() برای helper Sleep، Http::fake() با Http::sequence() برای برگرداندن 503، 503 و بعد 200، Http::assertSentCount() و منبع تصادفی با seed که به کلاس Backoff داده میشود. فراتر از unit test، در staging خطا تزریق کنید (تأخیر، reset) همانطور که در Chaos Engineering آمده.
راهحل: جدول (خطا، idempotent، تعداد فراخوانی مورد انتظار) را نگه دارید، مثل TestAmbiguousFailureNeedsIdempotency.
سازوکار (Mechanics)
فرمولها و حساب
| کمیت | فرمول | مثال |
|---|---|---|
| بدترین مدت فراخوانی با retry | attempts x per_try + sum(sleeps) ولی هرگز بیشتر از deadline | 3 x 1.5 s + حدود 0.3 s = 4.8 s |
| سقف مکث در attempt n | min(cap, base * 2^(n-1)) | base 100 ms و cap 5 s: 100، 200، 400، 800، 1600، 3200، 5000 ms |
| فراخوانیهایی که به ته پشته میرسند | حاصلضرب تلاشها در هر لایه | 3^5 = 243 |
| بار اضافه با budget با نسبت r | حداکثر r از تلاشهای اول بهعلاوهٔ ذخیرهٔ اولیه | r = 0.1: حدود +10% (اندازهگیری +11%) |
| بار اضافه بدون budget در قطعی کامل | (attempts - 1) x 100% | 3 attempt: +200% |
| نرخ false-timeout برای صدک p | 1 - p | timeout روی p99.9: 0.1% فراخوانیهای سالم قطع میشوند |
| حاشیهٔ timeout سمت سرور | statement_timeout = request_deadline_remaining - margin | 2 s مانده، margin برابر 200 ms: 1.8 s |
Knobها به تفکیک محصول
| محصول | Knob | پیشفرض | معنی |
|---|---|---|---|
net.Dialer در Go | Timeout | ندارد | بیشترین زمان برقراری اتصال؛ سیستمعامل ممکن است زودتر قطع کند (حدود 3 دقیقه برای TCP) |
http.Transport در Go | TLSHandshakeTimeout، ResponseHeaderTimeout، IdleConnTimeout، ExpectContinueTimeout | ندارد (DefaultTransport چندتا میگذارد) | حد هر مرحله |
http.Client در Go | Timeout | ندارد | کل تلاش با خواندن body |
http.Server در Go | ReadTimeout، ReadHeaderTimeout، WriteTimeout، IdleTimeout | ندارد | حدهای سمت سرور؛ http.TimeoutHandler handler را محدود میکند |
context در Go | WithTimeout، WithDeadline، WithTimeoutCause | قابلاعمال نیست | deadlineای که هر فراخوانی مسدودکننده باید رعایت کند؛ همیشه defer cancel() |
| PostgreSQL | statement_timeout، lock_timeout، idle_in_transaction_session_timeout، idle_session_timeout، transaction_timeout | 0 (همه غیرفعال) | حد سمت سرور برای هر role، دیتابیس، session یا SET LOCAL |
| Redis server | timeout | 0 | client بیکار را ببند |
| go-redis | DialTimeout، ReadTimeout، WriteTimeout، MaxRetries، ContextTimeoutEnabled | به مستندات Options نگاه کنید | همه را صریح بگذارید |
| HTTP client لاراول | timeout()، connectTimeout()، retry() | 30 s، 10 s، ندارد | برای هر تلاش |
| Guzzle | timeout، connect_timeout، read_timeout | 0 (بدون حد) | حد انتقال، اتصال و خواندن stream |
| صف Laravel | retry_after، --timeout، --tries، --backoff، #[Timeout]، #[Tries]، #[Backoff]، retryUntil() | 90 (نمونه)، 60 s، 1، 0 | visibility timeout، زمان اجرا، تعداد attempt |
| NGINX | proxy_connect_timeout، proxy_send_timeout، proxy_read_timeout، proxy_next_upstream، proxy_next_upstream_tries | 60 s، 60 s، 60 s، error timeout، 0 (بدون حد) | حد هر مرحله و retry روی upstream دیگر |
| route در Envoy | timeout، retry_policy.retry_on، num_retries، per_try_timeout | 15 s، ندارد، 1 وقتی retry_on تنظیم شود | کلی، کدام شکستها، چند بار، هر تلاش |
| AWS ALB | connection idle timeout | 60 s | اتصال بیکار را ببند؛ idle timeout برنامه را بزرگتر نگه دارید |
| gRPC | deadline، retryPolicy، hedgingPolicy، retryThrottling | ندارد | JSON سرویسکانفیگ |
| AWS SDK | retry_mode، max_attempts | standard، 3 | AWS_RETRY_MODE، AWS_MAX_ATTEMPTS |
پیامهای خطایی که واقعاً میبینید
| کجا | پیام یا کد | معنی | اولین اصلاح |
|---|---|---|---|
| Go | context deadline exceeded | deadline یک context گذشت (per-try، کلی یا فراخواننده) | بفهمید کدام؛ علت را با WithTimeoutCause لاگ کنید |
| Go | net/http: request canceled (Client.Timeout exceeded while awaiting headers) | Client.Timeout پیش از header شلیک کرد | سرور را درست یا حد را بالا ببرید؛ پیش از retry ابهام را بسنجید |
| Go | net/http: TLS handshake timeout | TLSHandshakeTimeout شلیک کرد | Retryable: درخواستی نرفته |
| Go | dial tcp 192.0.2.10:443: i/o timeout | timeout در Dialer | Retryable: چیزی فرستاده نشده |
| Go | dial tcp 192.0.2.10:443: connect: connection refused | کسی گوش نمیدهد | Retryable؛ deploy را بررسی کنید |
| Go | read tcp ...: connection reset by peer، EOF | طرف مقابل بعد از درخواست بست | Ambiguous: فقط idempotent |
| PostgreSQL | ERROR: canceling statement due to statement timeout (57014) | statement_timeout رسید | query را درست کنید یا برای آن role بالا ببرید |
| PostgreSQL | ERROR: canceling statement due to lock timeout (55P03) | lock_timeout رسید | بعداً retry کنید؛ مسدودکننده را بررسی کنید |
| PostgreSQL | FATAL: terminating connection due to idle-in-transaction timeout (25P03) | client تراکنش را باز رها کرد | مسیر کدی را که BEGIN را باز نگه میدارد درست کنید |
| Laravel HTTP | cURL error 28: Operation timed out after 3001 milliseconds | timeout() رسید؛ ConnectionException | Ambiguous: فقط keyed یا idempotent |
| Laravel HTTP | cURL error 7: Failed to connect ... Connection refused | ConnectionException | Retryable |
| صف Laravel | MaxAttemptsExceededException ... has been attempted too many times | attemptها تمام شد | failed() و failed_jobs را ببینید |
| صف Laravel | TimeoutExceededException، خروج worker | --timeout یا #[Timeout] رسید | فراخوانی کند را درست کنید؛ timeout را زیر retry_after نگه دارید |
| NGINX | 504 Gateway Time-out، upstream timed out (110: Connection timed out) while reading response header from upstream | proxy_read_timeout رسید | با deadline برنامه هماهنگ کنید |
| NGINX | 502 Bad Gateway بعد از بیکاری طولانی | upstream اتصالی را بست که NGINX دوباره استفاده کرد | idle timeout upstream را از NGINX بلندتر کنید |
| AWS ALB | 504 Gateway Timeout؛ 502 وقتی برنامه ناپسند میبندد | idle یا target timeout | idle timeout برنامه بزرگتر از ALB (پیشفرض 60 s) |
| Envoy | 503 با upstream_reset_before_response_started، 504 با upstream request timeout | reset پیش از اولین بایت، یا timeout مسیر | per_try_timeout و retry_on را بررسی کنید |
| HTTP | 429 با Retry-After، 503 با Retry-After | محدودیت نرخ یا shedding | از hint پیروی کنید |
متن پیامها از کاربرد رایج و فهرست کدهای خطا نقل شده؛ کدهای SQLSTATE با پیوست کدهای خطای PostgreSQL مطابقت داده شدند.
Go
ماژول academy/timeouts-retries-jitter فقط از کتابخانهٔ استاندارد استفاده میکند. retry حلقه است، httpclient فهرست timeoutها بهعلاوهٔ GET idempotent است، dbtimeouts حدهای PostgreSQL را از تراکنش database/sql اعمال میکند و cmd/jittersim عددهای این صفحه را چاپ میکند.
Before
پنج retry فوری یک POST از راه http.DefaultClient: بدون timeout، بدون تأخیر، بدون jitter، بدون طبقهبندی، بدون key.
// Before: the three classic mistakes in one file.
// 1. http.DefaultClient has no timeout, so a hung peer hangs us forever.
// 2. Every layer retries immediately, so three layers multiply (3 x 3 x 3).
// 3. No jitter, no budget, no classification: POST is retried after an ambiguous failure.
package main
import (
"fmt"
"net/http"
"strings"
)
// callWithRetry retries five times with no delay, whatever the error was.
func callWithRetry(url string) (*http.Response, error) {
var lastErr error
for i := 0; i < 5; i++ {
resp, err := http.DefaultClient.Post(url, "application/json", strings.NewReader(`{"amount":100}`))
if err == nil && resp.StatusCode < 500 {
return resp, nil
}
lastErr = err
// no sleep, no jitter, no budget, no idempotency key
}
return nil, fmt.Errorf("gave up: %w", lastErr)
}
func main() {
_, err := callWithRetry("http://payments.internal.example/charge")
fmt.Println(err)
}After
ساعت. interface Clock و FakeClock که مکثها را ثبت میکند و بیانتظار جلو میرود.
package retry
import (
"context"
"sync"
"time"
)
// Clock is the only way the package reads or spends time, so tests can fake it.
type Clock interface {
Now() time.Time
// Sleep waits for d or until ctx ends, whichever is first.
Sleep(ctx context.Context, d time.Duration) error
}
// RealClock uses the wall clock and a timer.
type RealClock struct{}
func (RealClock) Now() time.Time { return time.Now() }
func (RealClock) Sleep(ctx context.Context, d time.Duration) error {
if d <= 0 {
return ctx.Err()
}
t := time.NewTimer(d)
defer t.Stop()
select {
case <-t.C:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
// FakeClock never waits: Sleep advances Now and records the delay.
type FakeClock struct {
mu sync.Mutex
now time.Time
Sleeps []time.Duration
}
// NewFakeClock starts at a fixed instant so output is reproducible.
func NewFakeClock() *FakeClock {
return &FakeClock{now: time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)}
}
func (c *FakeClock) Now() time.Time {
c.mu.Lock()
defer c.mu.Unlock()
return c.now
}
func (c *FakeClock) Sleep(ctx context.Context, d time.Duration) error {
if err := ctx.Err(); err != nil {
return err
}
c.mu.Lock()
defer c.mu.Unlock()
c.Sleeps = append(c.Sleeps, d)
c.now = c.now.Add(d)
return nil
}
// Total returns the sum of all recorded sleeps.
func (c *FakeClock) Total() time.Duration {
c.mu.Lock()
defer c.mu.Unlock()
var sum time.Duration
for _, d := range c.Sleeps {
sum += d
}
return sum
}استراتژیهای backoff. ثابت، خطی، نمایی با cap، و jitter کامل، برابر و decorrelated، با منبع تصادفی تزریقپذیر.
package retry
import (
"math"
"time"
)
// Backoff chooses how long to wait before retry number `attempt` (1 = first retry).
// prev is the delay returned for the previous retry (zero for the first one);
// only decorrelated jitter needs it.
type Backoff interface {
Next(attempt int, prev time.Duration) time.Duration
}
// Rand returns a float in [0, 1). Inject math/rand/v2 in production and a
// seeded or constant source in tests.
type Rand func() float64
type constant struct{ d time.Duration }
// Constant waits the same time before every retry.
func Constant(d time.Duration) Backoff { return constant{d} }
func (c constant) Next(int, time.Duration) time.Duration { return c.d }
type linear struct{ step, max time.Duration }
// Linear waits step, 2*step, 3*step ... up to max.
func Linear(step, max time.Duration) Backoff { return linear{step, max} }
func (l linear) Next(attempt int, _ time.Duration) time.Duration {
return min(time.Duration(attempt)*l.step, l.max)
}
// expCap is min(cap, base * 2^(attempt-1)) without integer overflow.
func expCap(base, max time.Duration, attempt int) time.Duration {
if attempt < 1 {
attempt = 1
}
f := float64(base) * math.Pow(2, float64(attempt-1))
if f >= float64(max) {
return max
}
return time.Duration(f)
}
type exponential struct{ base, max time.Duration }
// Exponential is capped exponential backoff with no randomness:
// sleep = min(cap, base * 2^(attempt-1)).
func Exponential(base, max time.Duration) Backoff { return exponential{base, max} }
func (e exponential) Next(attempt int, _ time.Duration) time.Duration {
return expCap(e.base, e.max, attempt)
}
type fullJitter struct {
base, max time.Duration
rnd Rand
}
// FullJitter: sleep = random(0, min(cap, base * 2^(attempt-1))).
func FullJitter(base, max time.Duration, rnd Rand) Backoff { return fullJitter{base, max, rnd} }
func (f fullJitter) Next(attempt int, _ time.Duration) time.Duration {
return time.Duration(f.rnd() * float64(expCap(f.base, f.max, attempt)))
}
type equalJitter struct {
base, max time.Duration
rnd Rand
}
// EqualJitter: t = min(cap, base * 2^(attempt-1)); sleep = t/2 + random(0, t/2).
func EqualJitter(base, max time.Duration, rnd Rand) Backoff { return equalJitter{base, max, rnd} }
func (e equalJitter) Next(attempt int, _ time.Duration) time.Duration {
t := expCap(e.base, e.max, attempt)
return t/2 + time.Duration(e.rnd()*float64(t/2))
}
type decorrelated struct {
base, max time.Duration
rnd Rand
}
// Decorrelated: sleep = min(cap, random(base, prev * 3)). It remembers the
// last delay instead of the attempt number.
func Decorrelated(base, max time.Duration, rnd Rand) Backoff { return decorrelated{base, max, rnd} }
func (d decorrelated) Next(_ int, prev time.Duration) time.Duration {
if prev < d.base {
prev = d.base
}
hi := prev * 3
s := d.base + time.Duration(d.rnd()*float64(hi-d.base))
return min(s, d.max)
}retry budget. token bucketی که ترافیک پرش میکند و retryها خالیش میکنند.
package retry
import "sync"
// Budget is a retry budget: a token bucket that traffic refills and retries drain.
// With ratio 0.1 the steady-state extra load from retries is at most about 10%
// of first attempts, however many attempts each request is allowed.
type Budget struct {
mu sync.Mutex
tokens float64
max float64
ratio float64
}
// NewBudget starts full. max is the burst reserve (retries allowed with no traffic).
func NewBudget(ratio, max float64) *Budget {
return &Budget{tokens: max, max: max, ratio: ratio}
}
// Deposit is called once per logical request (its first attempt).
func (b *Budget) Deposit() {
b.mu.Lock()
defer b.mu.Unlock()
b.tokens = min(b.tokens+b.ratio, b.max)
}
// Withdraw takes one token for a retry; false means the budget is exhausted.
func (b *Budget) Withdraw() bool {
b.mu.Lock()
defer b.mu.Unlock()
if b.tokens < 1 {
return false
}
b.tokens--
return true
}
// Tokens reports the current balance (for metrics and tests).
func (b *Budget) Tokens() float64 {
b.mu.Lock()
defer b.mu.Unlock()
return b.tokens
}طبقهبندی و راهنمایی سرور. Retryable، Ambiguous، Fatal؛ StatusError که Retry-After را حمل میکند؛ ParseRetryAfter برای ثانیه و HTTP-date.
package retry
import (
"context"
"errors"
"fmt"
"io"
"net"
"net/http"
"strconv"
"strings"
"syscall"
"time"
)
// Class says what a failure means for retrying.
type Class int
const (
// Fatal: retrying cannot help (4xx, bad input, context cancelled by the caller).
Fatal Class = iota
// Retryable: the request was certainly not processed (connection refused,
// dial timeout, 429, 503), so even a non-idempotent call may be repeated.
Retryable
// Ambiguous: the server may or may not have acted (read timeout, connection
// reset, 500, 502, 504). Retry only idempotent operations.
Ambiguous
)
func (c Class) String() string {
return [...]string{"fatal", "retryable", "ambiguous"}[c]
}
// StatusError is an HTTP failure with the server's Retry-After hint, if any.
type StatusError struct {
Code int
RetryAfter time.Duration
}
func (e *StatusError) Error() string { return fmt.Sprintf("http status %d", e.Code) }
// HintError attaches a server-provided wait (Retry-After, gRPC pushback) to any error.
type HintError struct {
Err error
RetryAfter time.Duration
}
func (e *HintError) Error() string { return e.Err.Error() }
func (e *HintError) Unwrap() error { return e.Err }
// Classifier maps an error to a Class.
type Classifier func(error) Class
// Default is a conservative classifier for HTTP and TCP errors.
func Default(err error) Class {
var se *StatusError
if errors.As(err, &se) {
switch se.Code {
case http.StatusTooManyRequests, http.StatusServiceUnavailable:
return Retryable
case http.StatusInternalServerError, http.StatusBadGateway, http.StatusGatewayTimeout, http.StatusRequestTimeout:
return Ambiguous
default:
return Fatal
}
}
if errors.Is(err, context.Canceled) {
return Fatal
}
if errors.Is(err, syscall.ECONNREFUSED) {
return Retryable // nothing was listening: the request never left
}
var op *net.OpError
if errors.As(err, &op) && op.Op == "dial" {
return Retryable // connect failed or timed out: no request bytes were processed
}
if errors.Is(err, context.DeadlineExceeded) ||
errors.Is(err, syscall.ECONNRESET) || errors.Is(err, syscall.EPIPE) ||
errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) {
return Ambiguous // the request may have been executed
}
var ne net.Error
if errors.As(err, &ne) && ne.Timeout() {
return Ambiguous
}
return Fatal
}
// ParseRetryAfter reads a Retry-After value: delay-seconds or an HTTP-date (RFC 9110).
func ParseRetryAfter(v string, now time.Time) (time.Duration, bool) {
v = strings.TrimSpace(v)
if v == "" {
return 0, false
}
if secs, err := strconv.Atoi(v); err == nil && secs >= 0 {
return time.Duration(secs) * time.Second, true
}
if t, err := http.ParseTime(v); err == nil {
return max(t.Sub(now), 0), true
}
return 0, false
}
func hintOf(err error) time.Duration {
var se *StatusError
if errors.As(err, &se) {
return se.RetryAfter
}
var he *HintError
if errors.As(err, &he) {
return he.RetryAfter
}
return 0
}حلقه. Do طبقهبندی، idempotency، تعداد تلاش، backoff، hint، budget، per-try timeout و deadline کلی را ترکیب میکند و *GiveUp برمیگرداند که میگوید چرا ایستاد.
// Package retry is a small, testable retry loop: classification, capped
// exponential backoff with jitter, a retry budget, a per-try timeout and an
// overall deadline, all driven by an injectable clock.
package retry
import (
"context"
"errors"
"fmt"
"time"
)
// Policy configures Do. The zero value of optional fields is safe.
type Policy struct {
MaxAttempts int // total attempts including the first (3 is a good default)
PerTry time.Duration // timeout of one attempt; 0 = only the overall deadline
Overall time.Duration // total time for all attempts and sleeps; 0 = ctx deadline only
Backoff Backoff // nil = no waiting
Budget *Budget // nil = unlimited retries (not recommended)
Idempotent bool // true: ambiguous failures may be retried
Classify Classifier // nil = Default
Clock Clock // nil = RealClock
OnRetry func(attempt int, err error, delay time.Duration)
}
// GiveUp is returned when the loop stops without a success.
type GiveUp struct {
Attempts int
Reason string // "fatal", "ambiguous and not idempotent", "max attempts", "retry budget exhausted", "deadline", "context"
Err error // the last error from the operation
}
func (g *GiveUp) Error() string {
return fmt.Sprintf("retry: gave up after %d attempt(s): %s: %v", g.Attempts, g.Reason, g.Err)
}
func (g *GiveUp) Unwrap() error { return g.Err }
// Do runs op until it succeeds or the policy says stop. attempt starts at 1.
func Do[T any](ctx context.Context, p Policy, op func(ctx context.Context, attempt int) (T, error)) (T, error) {
var zero T
clock := p.Clock
if clock == nil {
clock = RealClock{}
}
classify := p.Classify
if classify == nil {
classify = Default
}
maxAttempts := max(p.MaxAttempts, 1)
var deadline time.Time
if p.Overall > 0 {
deadline = clock.Now().Add(p.Overall)
}
if d, ok := ctx.Deadline(); ok && (deadline.IsZero() || d.Before(deadline)) {
deadline = d
}
var prev time.Duration
for attempt := 1; ; attempt++ {
if attempt == 1 && p.Budget != nil {
p.Budget.Deposit()
}
tryCtx, cancel := tryContext(ctx, p.PerTry, deadline, clock)
v, err := op(tryCtx, attempt)
cancel()
if err == nil {
return v, nil
}
if ctx.Err() != nil { // the caller gave up: never retry
return zero, &GiveUp{attempt, "context", err}
}
switch class := classify(err); {
case class == Fatal:
return zero, &GiveUp{attempt, "fatal", err}
case class == Ambiguous && !p.Idempotent:
return zero, &GiveUp{attempt, "ambiguous and not idempotent", err}
}
if attempt >= maxAttempts {
return zero, &GiveUp{attempt, "max attempts", err}
}
var delay time.Duration
if p.Backoff != nil {
delay = p.Backoff.Next(attempt, prev)
}
prev = delay
if hint := hintOf(err); hint > delay {
delay = hint // the server knows better than our formula
}
if !deadline.IsZero() && clock.Now().Add(delay).After(deadline) {
return zero, &GiveUp{attempt, "deadline", err}
}
if p.Budget != nil && !p.Budget.Withdraw() {
return zero, &GiveUp{attempt, "retry budget exhausted", err}
}
if p.OnRetry != nil {
p.OnRetry(attempt, err, delay)
}
if serr := clock.Sleep(ctx, delay); serr != nil {
return zero, &GiveUp{attempt, "context", errors.Join(err, serr)}
}
}
}
// tryContext derives the context of one attempt: the smaller of the per-try
// timeout and the time left until the overall deadline.
func tryContext(ctx context.Context, perTry time.Duration, deadline time.Time, clock Clock) (context.Context, context.CancelFunc) {
limit := perTry
if !deadline.IsZero() {
left := deadline.Sub(clock.Now())
if limit == 0 || left < limit {
limit = left
}
}
if limit <= 0 {
return ctx, func() {}
}
return context.WithTimeout(ctx, limit)
}تستها با fake clock. کرانهای هر گونهٔ jitter، قواعد دقیق توقف و budget دهدرصدی.
package retry
import (
"math/rand/v2"
"testing"
"time"
)
const (
base = 100 * time.Millisecond
cap_ = 5 * time.Second
)
func TestDeterministicShapes(t *testing.T) {
if got := Constant(time.Second).Next(7, 0); got != time.Second {
t.Fatalf("constant: %v", got)
}
lin := Linear(100*time.Millisecond, 350*time.Millisecond)
want := []time.Duration{100, 200, 300, 350, 350}
for i, w := range want {
if got := lin.Next(i+1, 0); got != w*time.Millisecond {
t.Fatalf("linear attempt %d: %v", i+1, got)
}
}
exp := Exponential(base, cap_)
want = []time.Duration{100, 200, 400, 800, 1600, 3200, 5000, 5000}
for i, w := range want {
if got := exp.Next(i+1, 0); got != w*time.Millisecond {
t.Fatalf("exponential attempt %d: %v want %v", i+1, got, w*time.Millisecond)
}
}
// Huge attempt numbers must not overflow into negative durations.
if got := exp.Next(10_000, 0); got != cap_ {
t.Fatalf("overflow guard: %v", got)
}
}
func TestJitterBounds(t *testing.T) {
r := rand.New(rand.NewPCG(1, 2))
rnd := Rand(r.Float64)
full, equal, deco := FullJitter(base, cap_, rnd), EqualJitter(base, cap_, rnd), Decorrelated(base, cap_, rnd)
prev := time.Duration(0)
for attempt := 1; attempt <= 12; attempt++ {
ceil := Exponential(base, cap_).Next(attempt, 0)
for i := 0; i < 2000; i++ {
if d := full.Next(attempt, 0); d < 0 || d > ceil {
t.Fatalf("full jitter %v outside [0,%v]", d, ceil)
}
if d := equal.Next(attempt, 0); d < ceil/2 || d > ceil {
t.Fatalf("equal jitter %v outside [%v,%v]", d, ceil/2, ceil)
}
}
d := deco.Next(attempt, prev)
if d < base || d > cap_ || d > max(prev*3, base*3) {
t.Fatalf("decorrelated %v (prev %v) outside [base, min(cap, 3*prev)]", d, prev)
}
prev = d
}
}
func TestJitterSpreadsClients(t *testing.T) {
// 1000 clients retry for the 4th time: without jitter they all sleep 800ms;
// with full jitter they spread across [0, 800ms).
r := rand.New(rand.NewPCG(3, 4))
full := FullJitter(base, cap_, r.Float64)
buckets := make([]int, 8) // 100ms wide
for i := 0; i < 1000; i++ {
buckets[int(full.Next(4, 0)/(100*time.Millisecond))]++
}
for i, n := range buckets {
if n < 60 || n > 190 { // expected 125 per bucket
t.Fatalf("bucket %d has %d clients: not uniform enough: %v", i, n, buckets)
}
}
if got := Exponential(base, cap_).Next(4, 0); got != 800*time.Millisecond {
t.Fatalf("no-jitter control: %v", got)
}
}package retry
import (
"context"
"errors"
"fmt"
"net"
"net/http"
"sync/atomic"
"syscall"
"testing"
"time"
)
func status(code int) error { return &StatusError{Code: code} }
func TestRetriesTransientThenSucceeds(t *testing.T) {
clock := NewFakeClock()
calls := 0
got, err := Do(context.Background(), Policy{
MaxAttempts: 4, Backoff: Exponential(100*time.Millisecond, time.Second),
Idempotent: true, Clock: clock,
}, func(ctx context.Context, attempt int) (string, error) {
calls++
if attempt < 3 {
return "", status(503)
}
return "ok", nil
})
if err != nil || got != "ok" || calls != 3 {
t.Fatalf("got %q err %v calls %d", got, err, calls)
}
if fmt.Sprint(clock.Sleeps) != "[100ms 200ms]" {
t.Fatalf("sleeps %v", clock.Sleeps)
}
}
func TestMaxAttemptsAndGiveUpType(t *testing.T) {
_, err := Do(context.Background(), Policy{MaxAttempts: 3, Idempotent: true, Clock: NewFakeClock()},
func(context.Context, int) (int, error) { return 0, status(503) })
var g *GiveUp
if !errors.As(err, &g) || g.Attempts != 3 || g.Reason != "max attempts" {
t.Fatalf("err = %v", err)
}
var se *StatusError
if !errors.As(err, &se) || se.Code != 503 {
t.Fatal("original error must stay reachable with errors.As")
}
}
func TestAmbiguousFailureNeedsIdempotency(t *testing.T) {
for _, tc := range []struct {
name string
err error
idempotent bool
wantCalls int
}{
{"POST read timeout is not repeated", context.DeadlineExceeded, false, 1},
{"GET read timeout is repeated", context.DeadlineExceeded, true, 3},
{"POST connection refused is repeated", syscall.ECONNREFUSED, false, 3},
{"POST 503 is repeated", status(503), false, 3},
{"POST 500 is not repeated", status(500), false, 1},
{"GET 500 is repeated", status(500), true, 3},
{"404 is never repeated", status(404), true, 1},
{"connection reset needs idempotency", syscall.ECONNRESET, false, 1},
} {
calls := 0
_, _ = Do(context.Background(), Policy{MaxAttempts: 3, Idempotent: tc.idempotent, Clock: NewFakeClock()},
func(context.Context, int) (int, error) { calls++; return 0, tc.err })
if calls != tc.wantCalls {
t.Errorf("%s: calls = %d, want %d", tc.name, calls, tc.wantCalls)
}
}
}
func TestRetryAfterBeatsFormula(t *testing.T) {
clock := NewFakeClock()
_, _ = Do(context.Background(), Policy{
MaxAttempts: 2, Backoff: Constant(10 * time.Millisecond), Idempotent: true, Clock: clock,
}, func(context.Context, int) (int, error) {
return 0, &StatusError{Code: 429, RetryAfter: 7 * time.Second}
})
if len(clock.Sleeps) != 1 || clock.Sleeps[0] != 7*time.Second {
t.Fatalf("sleeps %v, want [7s]", clock.Sleeps)
}
}
func TestDeadlineStopsBeforeASleepThatCannotFit(t *testing.T) {
clock := NewFakeClock()
calls := 0
_, err := Do(context.Background(), Policy{
MaxAttempts: 10, Overall: time.Second, Backoff: Constant(400 * time.Millisecond),
Idempotent: true, Clock: clock,
}, func(context.Context, int) (int, error) { calls++; return 0, status(503) })
var g *GiveUp
if !errors.As(err, &g) || g.Reason != "deadline" {
t.Fatalf("err = %v", err)
}
// attempts at t=0, 0.4, 0.8; the next sleep would end at 1.2 s > 1 s.
if calls != 3 || clock.Total() != 800*time.Millisecond {
t.Fatalf("calls %d, slept %v", calls, clock.Total())
}
}
func TestRetryAfterLongerThanDeadlineGivesUpAtOnce(t *testing.T) {
clock := NewFakeClock()
calls := 0
_, err := Do(context.Background(), Policy{MaxAttempts: 5, Overall: 2 * time.Second, Idempotent: true, Clock: clock},
func(context.Context, int) (int, error) {
calls++
return 0, &StatusError{Code: 503, RetryAfter: time.Minute}
})
var g *GiveUp
if !errors.As(err, &g) || g.Reason != "deadline" || calls != 1 || clock.Total() != 0 {
t.Fatalf("err %v calls %d slept %v", err, calls, clock.Total())
}
}
func TestPerTryTimeoutCutsAHungAttempt(t *testing.T) {
var seen atomic.Int32
start := time.Now()
got, err := Do(context.Background(), Policy{
MaxAttempts: 3, PerTry: 30 * time.Millisecond, Idempotent: true, Clock: NewFakeClock(),
}, func(ctx context.Context, attempt int) (string, error) {
seen.Add(1)
if attempt == 1 {
<-ctx.Done() // a hung server: only the per-try timeout ends this
return "", ctx.Err()
}
return "fast", nil
})
if err != nil || got != "fast" || seen.Load() != 2 {
t.Fatalf("got %q err %v attempts %d", got, err, seen.Load())
}
if el := time.Since(start); el > 2*time.Second {
t.Fatalf("took %v", el)
}
}
func TestCallerCancellationIsNeverRetried(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
calls := 0
_, err := Do(ctx, Policy{MaxAttempts: 5, Idempotent: true, Clock: NewFakeClock()},
func(context.Context, int) (int, error) { calls++; cancel(); return 0, status(503) })
var g *GiveUp
if !errors.As(err, &g) || g.Reason != "context" || calls != 1 {
t.Fatalf("err %v calls %d", err, calls)
}
}
func TestBudgetCapsExtraLoadAtTenPercent(t *testing.T) {
// The dependency is fully down. 1000 requests, up to 3 attempts each.
budget := NewBudget(0.1, 10)
calls := 0
for i := 0; i < 1000; i++ {
_, _ = Do(context.Background(), Policy{MaxAttempts: 3, Idempotent: true, Budget: budget, Clock: NewFakeClock()},
func(context.Context, int) (int, error) { calls++; return 0, status(503) })
}
extra := float64(calls-1000) / 1000
if extra > 0.12 || extra < 0.08 {
t.Fatalf("extra load %.3f, want about 0.10 (calls=%d)", extra, calls)
}
// Control: without a budget the same outage triples the load.
calls = 0
for i := 0; i < 1000; i++ {
_, _ = Do(context.Background(), Policy{MaxAttempts: 3, Idempotent: true, Clock: NewFakeClock()},
func(context.Context, int) (int, error) { calls++; return 0, status(503) })
}
if calls != 3000 {
t.Fatalf("no budget: calls = %d, want 3000", calls)
}
}
func TestClassifyRealNetworkErrors(t *testing.T) {
// Connection refused: listen, note the port, close, dial.
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
addr := ln.Addr().String()
ln.Close()
_, derr := net.DialTimeout("tcp", addr, time.Second)
if derr == nil || Default(derr) != Retryable {
t.Fatalf("refused dial: %v classified %v", derr, Default(derr))
}
for err, want := range map[error]Class{
context.Canceled: Fatal,
context.DeadlineExceeded: Ambiguous,
status(http.StatusBadRequest): Fatal,
status(429): Retryable,
status(502): Ambiguous,
errors.New("boom"): Fatal,
} {
if got := Default(err); got != want {
t.Errorf("%v: %v, want %v", err, got, want)
}
}
}
func TestParseRetryAfter(t *testing.T) {
now := time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC)
for _, tc := range []struct {
in string
want time.Duration
ok bool
}{
{"120", 120 * time.Second, true},
{"0", 0, true},
{"Thu, 01 Jan 2026 12:00:30 GMT", 30 * time.Second, true},
{"Wed, 31 Dec 2025 23:59:59 GMT", 0, true}, // date in the past: wait nothing
{"soon", 0, false},
{"-5", 0, false},
{"", 0, false},
} {
got, ok := ParseRetryAfter(tc.in, now)
if got != tc.want || ok != tc.ok {
t.Errorf("%q: got %v,%v want %v,%v", tc.in, got, ok, tc.want, tc.ok)
}
}
}
func TestHintErrorWorksForAnyError(t *testing.T) {
clock := NewFakeClock()
_, _ = Do(context.Background(), Policy{
MaxAttempts: 2, Idempotent: true, Clock: clock,
Classify: func(error) Class { return Retryable },
}, func(context.Context, int) (int, error) {
return 0, &HintError{Err: errors.New("grpc UNAVAILABLE"), RetryAfter: 250 * time.Millisecond}
})
if len(clock.Sleeps) != 1 || clock.Sleeps[0] != 250*time.Millisecond {
t.Fatalf("sleeps %v", clock.Sleeps)
}
}همهٔ timeoutهای یک HTTP client در یک جا، و GET idempotent که به Retry-After احترام میگذارد؛ تستها از httptest واقعی استفاده میکنند (503 با Retry-After، تلاش اول گیرکرده، پورت بسته).
// Package httpclient shows every timeout of a Go HTTP client in one place and
// wraps GET in the retry package.
package httpclient
import (
"context"
"fmt"
"io"
"net"
"net/http"
"time"
"academy/timeouts-retries-jitter/retry"
)
// Timeouts are the knobs. Typical values for an internal service call.
type Timeouts struct {
Dial time.Duration // TCP connect (net.Dialer.Timeout)
TLSHandshake time.Duration // Transport.TLSHandshakeTimeout
ResponseHeader time.Duration // request written -> response headers (Transport.ResponseHeaderTimeout)
IdleConn time.Duration // how long a keep-alive connection may sit unused
Total time.Duration // http.Client.Timeout: dial + redirects + reading the body
}
// Defaults: budgets of a call whose p99 is about 200 ms.
var Defaults = Timeouts{
Dial: 500 * time.Millisecond,
TLSHandshake: 1 * time.Second,
ResponseHeader: 1 * time.Second,
IdleConn: 30 * time.Second, // keep below the server/LB idle timeout (e.g. 60 s)
Total: 3 * time.Second,
}
// NewHTTPClient builds a client that can never wait forever.
func NewHTTPClient(t Timeouts) *http.Client {
dialer := &net.Dialer{Timeout: t.Dial, KeepAlive: 15 * time.Second}
return &http.Client{
Timeout: t.Total,
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: dialer.DialContext,
TLSHandshakeTimeout: t.TLSHandshake,
ResponseHeaderTimeout: t.ResponseHeader,
IdleConnTimeout: t.IdleConn,
MaxIdleConnsPerHost: 16,
},
}
}
// Client retries idempotent GETs with the policy it was built with.
type Client struct {
HTTP *http.Client
Policy retry.Policy
}
// Get returns the body of a 2xx response. 4xx/5xx become *retry.StatusError
// carrying Retry-After so the retry loop can honour it.
func (c *Client) Get(ctx context.Context, url string) ([]byte, error) {
p := c.Policy
p.Idempotent = true // GET is idempotent (RFC 9110, 9.2.2)
clock := p.Clock
if clock == nil {
clock = retry.RealClock{}
}
return retry.Do(ctx, p, func(ctx context.Context, _ int) ([]byte, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, err
}
resp, err := c.HTTP.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
io.Copy(io.Discard, io.LimitReader(resp.Body, 4096)) // let the connection be reused
after, _ := retry.ParseRetryAfter(resp.Header.Get("Retry-After"), clock.Now())
return nil, &retry.StatusError{Code: resp.StatusCode, RetryAfter: after}
}
b, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("read body: %w", err)
}
return b, nil
})
}package httpclient
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
"time"
"academy/timeouts-retries-jitter/retry"
)
func newTestClient(clock retry.Clock) *Client {
return &Client{
HTTP: NewHTTPClient(Timeouts{Dial: time.Second, TLSHandshake: time.Second, ResponseHeader: 200 * time.Millisecond, IdleConn: time.Second, Total: 2 * time.Second}),
Policy: retry.Policy{
MaxAttempts: 4, PerTry: 300 * time.Millisecond, Overall: 5 * time.Second,
Backoff: retry.Exponential(50*time.Millisecond, time.Second),
Budget: retry.NewBudget(0.1, 10), Clock: clock,
},
}
}
func TestHonoursRetryAfterAndRecovers(t *testing.T) {
var n atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if n.Add(1) == 1 {
w.Header().Set("Retry-After", "2")
w.WriteHeader(http.StatusServiceUnavailable)
return
}
w.Write([]byte("hello"))
}))
defer srv.Close()
clock := retry.NewFakeClock()
body, err := newTestClient(clock).Get(context.Background(), srv.URL)
if err != nil || string(body) != "hello" {
t.Fatalf("body %q err %v", body, err)
}
if len(clock.Sleeps) != 1 || clock.Sleeps[0] != 2*time.Second {
t.Fatalf("sleeps %v: Retry-After: 2 must beat the 50 ms formula", clock.Sleeps)
}
}
func TestDoesNotRetryClientErrors(t *testing.T) {
var n atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
n.Add(1)
http.NotFound(w, r)
}))
defer srv.Close()
_, err := newTestClient(retry.NewFakeClock()).Get(context.Background(), srv.URL)
var se *retry.StatusError
if !errors.As(err, &se) || se.Code != 404 || n.Load() != 1 {
t.Fatalf("err %v calls %d", err, n.Load())
}
}
func TestSlowServerHitsResponseHeaderTimeoutThenRecovers(t *testing.T) {
var n atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if n.Add(1) == 1 {
select { // hung first attempt
case <-time.After(3 * time.Second):
case <-r.Context().Done():
}
return
}
w.Write([]byte("second try"))
}))
defer srv.Close()
start := time.Now()
body, err := newTestClient(retry.NewFakeClock()).Get(context.Background(), srv.URL)
if err != nil || string(body) != "second try" {
t.Fatalf("body %q err %v", body, err)
}
if el := time.Since(start); el > time.Second {
t.Fatalf("took %v: the 200 ms header timeout should have cut the first attempt", el)
}
}
func TestConnectionRefusedIsRetriedAndExhausts(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
url := srv.URL
srv.Close() // nothing listens any more
clock := retry.NewFakeClock()
_, err := newTestClient(clock).Get(context.Background(), url)
var g *retry.GiveUp
if !errors.As(err, &g) || g.Attempts != 4 || g.Reason != "max attempts" {
t.Fatalf("err %v", err)
}
if len(clock.Sleeps) != 3 {
t.Fatalf("sleeps %v", clock.Sleeps)
}
}timeout دیتابیس از Go. معادل SET LOCAL با set_config(..., true)، و کمکتابعی که deadline context را با یک حاشیه به statement_timeout تبدیل میکند.
// Package dbtimeouts applies PostgreSQL timeouts from Go without a driver
// dependency: it only needs database/sql.
package dbtimeouts
import (
"context"
"database/sql"
"fmt"
"time"
)
// Limits are the three server-side timeouts that matter for a request path.
type Limits struct {
Statement time.Duration // statement_timeout: abort any statement longer than this
Lock time.Duration // lock_timeout: abort when waiting for a lock longer than this
IdleInTx time.Duration // idle_in_transaction_session_timeout: kill a session that sits idle inside BEGIN
}
// Apply sets the limits for the current transaction only (set_config with
// is_local = true is SET LOCAL), so a pooled connection is never left changed.
func Apply(ctx context.Context, tx *sql.Tx, l Limits) error {
for name, d := range map[string]time.Duration{
"statement_timeout": l.Statement,
"lock_timeout": l.Lock,
"idle_in_transaction_session_timeout": l.IdleInTx,
} {
if d <= 0 {
continue
}
if _, err := tx.ExecContext(ctx, "SELECT set_config($1, $2, true)", name, fmt.Sprintf("%dms", d.Milliseconds())); err != nil {
return fmt.Errorf("set %s: %w", name, err)
}
}
return nil
}
// Budget turns the remaining context deadline into a statement_timeout slightly
// shorter than the caller's deadline, so the server aborts before the client gives up
// and the connection is not left running a query nobody waits for.
func Budget(ctx context.Context, margin time.Duration) (time.Duration, bool) {
dl, ok := ctx.Deadline()
if !ok {
return 0, false
}
left := time.Until(dl) - margin
if left <= 0 {
return 0, true
}
return left, true
}package dbtimeouts
import (
"context"
"testing"
"time"
)
func TestBudgetLeavesAMargin(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
d, ok := Budget(ctx, 200*time.Millisecond)
if !ok || d > 1800*time.Millisecond || d < 1500*time.Millisecond {
t.Fatalf("d=%v ok=%v", d, ok)
}
if _, ok := Budget(context.Background(), time.Second); ok {
t.Fatal("no deadline must report ok=false")
}
}شبیهسازی پشت جدولها (با seed ثابت؛ خروجی هر بار یکسان است):
// jittersim prints the numbers used on the page. It is deterministic (seeded).
//
// go run ./cmd/jittersim
//
// Table 1 models Marc Brooker's contention case from "Exponential Backoff And
// Jitter" (AWS Architecture Blog, 2015) in a simplified, slotted form: N clients
// start together, each 10 ms slot lets exactly ONE of the clients that call in
// that slot succeed, the rest fail and back off. It is my model, not his simulator.
package main
import (
"context"
"fmt"
"math/rand/v2"
"time"
"academy/timeouts-retries-jitter/retry"
)
const slot = 10 * time.Millisecond
type client struct {
next int // slot of the next call
attempt int
prev time.Duration
done bool
}
type result struct {
calls int
finish time.Duration
}
func contention(n int, b retry.Backoff, rng *rand.Rand) result {
cs := make([]*client, n)
for i := range cs {
cs[i] = &client{}
}
var res result
remaining := n
for s := 0; remaining > 0; s++ {
var callers []*client
for _, c := range cs {
if !c.done && c.next == s {
callers = append(callers, c)
}
}
if len(callers) == 0 {
continue
}
res.calls += len(callers)
callers[rng.IntN(len(callers))].done = true // the winner
remaining--
res.finish = time.Duration(s+1) * slot
for _, c := range callers {
if c.done {
continue
}
c.attempt++
d := b.Next(c.attempt, c.prev)
c.prev = d
// +0 or +1 slot of network delay variance, so "no jitter" is not artificially perfect.
c.next = s + 1 + int(d/slot) + rng.IntN(2)
}
}
return res
}
func main() {
const n = 100
base, ceiling := 10*time.Millisecond, time.Second
fmt.Printf("1) %d clients contend for one slot per %v (cap %v, base %v)\n", n, slot, ceiling, base)
fmt.Printf(" %-26s %8s %12s\n", "strategy", "calls", "finish")
for _, s := range []struct {
name string
mk func(rnd retry.Rand) retry.Backoff
}{
{"constant 10ms (no jitter)", func(retry.Rand) retry.Backoff { return retry.Constant(base) }},
{"exponential, no jitter", func(retry.Rand) retry.Backoff { return retry.Exponential(base, ceiling) }},
{"full jitter", func(r retry.Rand) retry.Backoff { return retry.FullJitter(base, ceiling, r) }},
{"equal jitter", func(r retry.Rand) retry.Backoff { return retry.EqualJitter(base, ceiling, r) }},
{"decorrelated jitter", func(r retry.Rand) retry.Backoff { return retry.Decorrelated(base, ceiling, r) }},
} {
// Average 20 seeded runs.
var calls int
var finish time.Duration
const runs = 20
for i := 0; i < runs; i++ {
rng := rand.New(rand.NewPCG(uint64(i+1), 7))
r := contention(n, s.mk(rng.Float64), rng)
calls += r.calls
finish += r.finish
}
fmt.Printf(" %-26s %8d %12v\n", s.name, calls/runs, (finish / runs).Round(10*time.Millisecond))
}
fmt.Println("\n2) Dependency is 100% down, 1000 requests, MaxAttempts=3, GET (idempotent)")
fmt.Printf(" %-28s %8s %10s\n", "policy", "calls", "extra load")
for _, bud := range []*retry.Budget{nil, retry.NewBudget(0.1, 10)} {
calls := 0
for i := 0; i < 1000; i++ {
_, _ = retry.Do(context.Background(), retry.Policy{
MaxAttempts: 3, Idempotent: true, Budget: bud, Clock: retry.NewFakeClock(),
}, func(context.Context, int) (int, error) {
calls++
return 0, &retry.StatusError{Code: 503}
})
}
name := "3 attempts, no budget"
if bud != nil {
name = "3 attempts + 10% budget"
}
fmt.Printf(" %-28s %8d %9.0f%%\n", name, calls, float64(calls-1000)/10)
}
fmt.Println("\n3) Layered retries multiply: 3 attempts at each of 5 layers")
total := 1
for layer := 1; layer <= 5; layer++ {
total *= 3
fmt.Printf(" layers=%d calls reaching the database per user request = %d\n", layer, total)
}
}نگاه Go
| ویژگی Go | کاربرد برای timeout و retry | نکته |
|---|---|---|
context.WithTimeout(parent, d) | یک تلاش، یک بودجه | همیشه defer cancel()؛ ctx را اول بدهید |
ctx.Deadline() | زمان باقیمانده را بخوانید تا hop بعد را اندازه کنید | با margin ترکیب کنید |
context.WithTimeoutCause | بگویید کدام timeout شلیک کرد | context.Cause(ctx) را لاگ کنید |
http.NewRequestWithContext | درخواست در جریان را لغو کنید | بدونش تلاش timeoutخورده ادامه میدهد |
http.Client.Timeout | کل تلاش با body | «The timer remains running after Get, Head, Post, or Do return» |
فیلدهای http.Transport | حد هر مرحله و pooling | ResponseHeaderTimeout، TLSHandshakeTimeout، IdleConnTimeout، MaxIdleConnsPerHost |
net.Dialer{Timeout, KeepAlive} | حد connect و keep-alive TCP | پیشفرض بدون timeout |
errors.Is، errors.As | طبقهبندی (syscall.ECONNREFUSED، *net.OpError، net.Error.Timeout()) | با %w wrap کنید تا دسته بماند |
time.NewTimer با select | مکث قابللغو | در کدی که context دارد time.Sleep خالی نگذارید |
math/rand/v2 | jitter | rand.Float64() برای همزمانی امن است؛ برای تست تزریق کنید |
QueryContext در database/sql | driver با پایان context سیگنال cancel میفرستد | با statement_timeout سرور جفت کنید |
github.com/hashicorp/go-retryablehttp | client آمادهٔ retry | 5xx بهجز 501 را retry میکند؛ idempotency را خودتان بسنجید |
golang.org/x/time/rate | محدود کردن retryهای خودتان | جایگزین token budget |
Laravel
Before
Http::retry(5, 100) روی POST بدون timeout و بدون key. در Laravel 13 timeout پیشفرض 30 ثانیه است و retry ثابت 100 ms میخوابد.
<?php
namespace App\Before;
use Illuminate\Support\Facades\Http;
// Before: default 30 s timeout, retry on everything including POST, fixed delay, no key.
class PaymentsClientBefore
{
public function charge(int $orderId, int $amount): array
{
return Http::retry(5, 100) // 5 attempts, always 100 ms, no jitter
->post('https://payments.internal.example/charge', [
'order_id' => $orderId,
'amount' => $amount,
]) // no timeout(): up to 30 s per attempt, 150 s worst case
->json(); // no idempotency key: a retry can double-charge
}
}After
کمککلاس backoff با تصادف تزریقپذیر (jitter کامل، برابر، decorrelated و parse کردن Retry-After).
<?php
namespace App\Support;
/**
* Backoff delays in milliseconds. Attempt 1 is the first RETRY.
* The random source is injectable so tests can pin it.
*/
final class Backoff
{
/** @param null|callable():float $rand returns a float in [0, 1) */
public function __construct(
private readonly int $baseMs = 100,
private readonly int $capMs = 5000,
private $rand = null,
) {
$this->rand ??= static fn (): float => mt_rand() / (mt_getrandmax() + 1);
}
/** min(cap, base * 2^(attempt-1)) */
public function ceiling(int $attempt): int
{
$exp = min($attempt - 1, 30); // avoid float overflow for huge attempts
return (int) min($this->capMs, $this->baseMs * (2 ** $exp));
}
/** random(0, ceiling) */
public function full(int $attempt): int
{
return (int) (($this->rand)() * $this->ceiling($attempt));
}
/** ceiling/2 + random(0, ceiling/2) */
public function equal(int $attempt): int
{
$half = intdiv($this->ceiling($attempt), 2);
return $half + (int) (($this->rand)() * $half);
}
/** min(cap, random(base, previous * 3)) */
public function decorrelated(int $previousMs): int
{
$previousMs = max($previousMs, $this->baseMs);
$hi = $previousMs * 3;
return (int) min($this->capMs, $this->baseMs + ($this->rand)() * ($hi - $this->baseMs));
}
/** Parse Retry-After: delay-seconds or HTTP-date. Returns milliseconds or null. */
public static function retryAfterMs(?string $value, ?int $now = null): ?int
{
$value = trim((string) $value);
if ($value === '') {
return null;
}
if (ctype_digit($value)) {
return (int) $value * 1000;
}
$ts = strtotime($value);
if ($ts === false) {
return null;
}
return max(0, ($ts - ($now ?? time())) * 1000);
}
}client پرداخت. connectTimeout، timeout، یک idempotency key بیرون حلقه، retry() با closure مکثی که full jitter و Retry-After را اعمال میکند، callable when که طبقهبندی میکند، و throw: true.
<?php
namespace App\Clients;
use App\Support\Backoff;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
use Throwable;
/**
* Timeouts, a classified retry with full jitter, Retry-After, and ONE idempotency
* key shared by all attempts of one logical charge.
*/
final class PaymentsClient
{
private const MAX_ATTEMPTS = 3;
private const PER_TRY_SECONDS = 1.5; // read timeout of one attempt
private const CONNECT_SECONDS = 0.5; // connect timeout
public function __construct(private readonly Backoff $backoff = new Backoff(100, 2000)) {}
public function charge(int $orderId, int $amountMinor, ?string $idempotencyKey = null): array
{
// Generated ONCE, outside the retry loop. A key made inside the closure defeats the point.
$key = $idempotencyKey ?? (string) Str::uuid();
$attempt = 0;
$response = Http::baseUrl('https://payments.internal.example')
->withHeaders(['Idempotency-Key' => $key])
->connectTimeout(self::CONNECT_SECONDS)
->timeout(self::PER_TRY_SECONDS)
// retry(times, sleepMs, when, throw): sleepMs may be a closure(attempt, exception)
->retry(
self::MAX_ATTEMPTS,
function (int $attemptNo, Throwable $e) use (&$attempt): int {
$attempt = $attemptNo;
$hint = $e instanceof RequestException
? Backoff::retryAfterMs($e->response->header('Retry-After'))
: null;
return max($this->backoff->full($attemptNo), $hint ?? 0);
},
when: fn (Throwable $e, PendingRequest $request): bool => $this->isRetryable($e),
throw: true,
)
->post('/charge', ['order_id' => $orderId, 'amount' => $amountMinor]);
return $response->json();
}
/**
* Safe to retry because the POST carries an idempotency key.
* Without a key, only the "never reached the server" cases would be safe.
*/
private function isRetryable(Throwable $e): bool
{
if ($e instanceof ConnectionException) {
return true; // refused, DNS, connect or read timeout (ambiguous, hence the key)
}
if ($e instanceof RequestException) {
return in_array($e->response->status(), [408, 429, 500, 502, 503, 504], true);
}
return false;
}
}همان سیاست بهصورت Guzzle retry middleware، برای کدی که مستقیم از Guzzle استفاده میکند.
<?php
namespace App\Support;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
/**
* The same policy as a Guzzle retry middleware (GuzzleHttp\Middleware::retry),
* for code that uses Guzzle directly instead of Laravel's Http facade.
*/
final class GuzzleRetry
{
public static function client(int $maxRetries = 2): Client
{
$backoff = new Backoff(100, 2000);
$decider = static function (
int $retries,
RequestInterface $request,
?ResponseInterface $response = null,
?\Throwable $exception = null,
) use ($maxRetries): bool {
if ($retries >= $maxRetries) {
return false;
}
// Only idempotent methods, or requests that carry an idempotency key.
$safe = in_array($request->getMethod(), ['GET', 'HEAD', 'PUT', 'DELETE', 'OPTIONS'], true)
|| $request->hasHeader('Idempotency-Key');
if (! $safe) {
return false;
}
if ($exception instanceof ConnectException) {
return true;
}
return $response !== null && in_array($response->getStatusCode(), [429, 502, 503, 504], true);
};
// $retries is 1 for the first retry. Returns milliseconds.
$delay = static fn (int $retries, ?ResponseInterface $response = null): int => max(
$backoff->full($retries),
Backoff::retryAfterMs($response?->getHeaderLine('Retry-After')) ?? 0,
);
$stack = HandlerStack::create();
$stack->push(Middleware::retry($decider, $delay), 'retry');
return new Client([
'handler' => $stack,
'connect_timeout' => 0.5,
'timeout' => 3.0, // total time of one transfer (one attempt)
'read_timeout' => 1.5, // idle time while reading a streamed body
]);
}
}job صف با Tries، MaxExceptions، Timeout، متد backoff() با jitter، retryUntil() و ThrottlesExceptions.
<?php
namespace App\Jobs;
use App\Support\Backoff;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\MaxExceptions;
use Illuminate\Queue\Attributes\Timeout;
use Illuminate\Queue\Attributes\Tries;
use Illuminate\Queue\Middleware\ThrottlesExceptions;
use Illuminate\Support\Facades\Http;
use Throwable;
/**
* Retries in a queue: attempts, a backoff, a time window, a hard job timeout.
* The retry_after of the queue connection must be larger than #[Timeout].
*/
#[Tries(8)]
#[MaxExceptions(5)]
#[Timeout(30)]
class SendInvoiceWebhook implements ShouldQueue
{
use Queueable;
public function __construct(private readonly int $invoiceId, private readonly string $url) {}
/** Seconds before attempt N+1. A method can add jitter; an attribute array cannot. */
public function backoff(): array
{
$b = new Backoff(baseMs: 5_000, capMs: 600_000);
// Full jitter around 5 s, 10 s, 20 s ... capped at 10 min (seconds, not ms).
return array_map(static fn (int $n): int => max(1, intdiv($b->full($n), 1000)), range(1, 7));
}
/** Stop trying 6 hours after dispatch even if tries remain (retryUntil beats tries). */
public function retryUntil(): \DateTimeInterface
{
return now()->plus(hours: 6);
}
/** @return array<int, object> */
public function middleware(): array
{
// After 10 exceptions inside 5 minutes, hold ALL attempts of this job for 5 minutes (a breaker).
return [new ThrottlesExceptions(10, 5 * 60)];
}
public function handle(): void
{
// The HTTP timeout must be below the job timeout, which must be below retry_after.
Http::connectTimeout(2)
->timeout(10)
->withHeaders(['Idempotency-Key' => "invoice-{$this->invoiceId}"])
->post($this->url, ['invoice_id' => $this->invoiceId])
->throw();
}
public function failed(Throwable $e): void
{
report($e); // alert, park the invoice, or send to a dead-letter table
}
}refresh ضدطوفان. Cache::lock با expiry و block()، و helper retry() با closure دارای jitter.
<?php
namespace App\Services;
use App\Support\Backoff;
use Illuminate\Contracts\Cache\LockTimeoutException;
use Illuminate\Support\Facades\Cache;
/**
* Many clients retrying the same refresh at once is a stampede. One caller refreshes
* under a lock with an expiry; the others wait a bounded time and read the result.
*/
final class StampedeSafeRefresh
{
public function __construct(private readonly Backoff $backoff = new Backoff(50, 800)) {}
public function rates(): array
{
if (($cached = Cache::get('fx:rates')) !== null) {
return $cached;
}
$lock = Cache::lock('fx:rates:refresh', 10); // auto-expires: a crashed holder cannot block forever
try {
$lock->block(2); // wait at most 2 s, then LockTimeoutException
// Another process may have refreshed while we waited.
return Cache::remember('fx:rates', 60, fn () => $this->fetchFromUpstream());
} catch (LockTimeoutException) {
// Could not get the lock in time: serve stale data or fail fast; do NOT hammer upstream.
return Cache::get('fx:rates:stale', []);
} finally {
$lock->release();
}
}
/** retry() helper with full jitter: sleep (ms) may be a closure of the attempt number. */
private function fetchFromUpstream(): array
{
return retry(
3,
fn () => ['USD' => 1.0], // call the upstream here
fn (int $attempt) => $this->backoff->full($attempt),
fn (\Throwable $e) => $e instanceof \RuntimeException, // only retry transient errors
);
}
}سه ساعت تودرتوی اتصال صف:
<?php
// config/queue.php (excerpt). The three numbers must nest: HTTP timeout < job timeout < retry_after.
return [
'connections' => [
'redis' => [
'driver' => 'redis',
'connection' => env('REDIS_QUEUE_CONNECTION', 'default'),
'queue' => env('REDIS_QUEUE', 'default'),
// A job still running after 90 s is released and may run a second time.
'retry_after' => (int) env('REDIS_QUEUE_RETRY_AFTER', 90),
'block_for' => null,
],
],
];
// php artisan queue:work redis --tries=3 --timeout=60 --backoff=5
// --timeout=60 (job may run 60 s) is below retry_after=90, so a frozen worker is killed before the job is re-released.unit test کرانهای backoff و parse کردن Retry-After:
<?php
namespace Tests\Unit;
use App\Support\Backoff;
use PHPUnit\Framework\TestCase;
class BackoffTest extends TestCase
{
public function test_ceiling_doubles_and_caps(): void
{
$b = new Backoff(100, 5000);
$this->assertSame([100, 200, 400, 800, 1600, 3200, 5000, 5000], array_map($b->ceiling(...), range(1, 8)));
$this->assertSame(5000, $b->ceiling(10_000));
}
public function test_full_and_equal_jitter_stay_inside_their_ranges(): void
{
foreach ([0.0, 0.25, 0.999] as $r) {
$b = new Backoff(100, 5000, fn () => $r);
for ($n = 1; $n <= 12; $n++) {
$ceil = $b->ceiling($n);
$this->assertGreaterThanOrEqual(0, $b->full($n));
$this->assertLessThanOrEqual($ceil, $b->full($n));
$this->assertGreaterThanOrEqual(intdiv($ceil, 2), $b->equal($n));
$this->assertLessThanOrEqual($ceil, $b->equal($n));
}
}
}
public function test_decorrelated_never_exceeds_cap_or_goes_below_base(): void
{
$b = new Backoff(100, 5000, fn () => 0.999);
$prev = 0;
for ($i = 0; $i < 20; $i++) {
$prev = $b->decorrelated($prev);
$this->assertGreaterThanOrEqual(100, $prev);
$this->assertLessThanOrEqual(5000, $prev);
}
}
public function test_retry_after_parses_seconds_and_dates(): void
{
$now = strtotime('2026-01-01 12:00:00 UTC');
$this->assertSame(120_000, Backoff::retryAfterMs('120'));
$this->assertSame(30_000, Backoff::retryAfterMs('Thu, 01 Jan 2026 12:00:30 GMT', $now));
$this->assertSame(0, Backoff::retryAfterMs('Wed, 31 Dec 2025 23:59:59 GMT', $now));
$this->assertNull(Backoff::retryAfterMs('soon'));
$this->assertNull(Backoff::retryAfterMs(null));
}
}نگاه Laravel
| ویژگی Laravel | کاربرد برای timeout و retry | نکته (مستندات Laravel 13) |
|---|---|---|
Http::timeout(seconds) | حد پاسخ در هر تلاش | «By default, the HTTP client will timeout after 30 seconds»؛ ConnectionException پرتاب میکند |
Http::connectTimeout(seconds) | حد connect | پیشفرض 10 ثانیه |
Http::retry($times, $sleep, $when, throw: false) | retry با برنامه | $sleep میتواند عدد، آرایهٔ ms یا closure (attempt, exception) باشد؛ $when میتواند درخواست را تغییر دهد |
Http::retry(...) وقتی همهٔ تلاشها شکست بخورند | سیاست exception | RequestException، یا با throw: false آخرین پاسخ؛ شکست اتصال باز هم ConnectionException میاندازد |
helper retry($times, $callback, $sleep, $when) | retry هر کدی | همان شکلهای sleep؛ آرگومان چهارم exceptionها را محدود میکند |
Http::fake()، Http::sequence()، assertSentCount() | 503، 503، 200 را بدون سرور تست کنید | whenEmpty() پیشفرض میگذارد |
| eventهای HTTP client | RequestSending، ResponseReceived، ConnectionFailed | متریک retry را از listenerها منتشر کنید |
queue:work --tries --timeout --backoff | پیشفرض worker | attributeهای job بر مقدارهای CLI برندهاند |
#[Tries]، #[Backoff]، #[Timeout]، #[MaxExceptions]، #[RetryFor]، #[FailOnTimeout] | سیاست هر job | attributeها در Illuminate\Queue\Attributes |
retryUntil() | پنجرهٔ زمانی | وقتی هر دو باشند بر tries برنده است |
ThrottlesExceptions، WithoutOverlapping، RateLimited | middleware job | releaseها attempt مصرف میکنند: tries را بالا ببرید |
Cache::lock($name, $seconds)->block($wait) | یک refreshکننده، منتظرهای محدود | وقتی انتظار تمام شود LockTimeoutException |
Sleep::fake() | sleepها را بدون انتظار تست کنید | مدتهای ثبتشده را assert کنید |
DB::statement('SET LOCAL statement_timeout = ...') درون DB::transaction | حد سمت سرور برای هر تراکنش | PostgreSQL؛ تنظیم با پایان تراکنش تمام میشود |
حل مسئلههای کلاسیک
«سرویس وقتی وابستگی پایین است چند دقیقه گیر میکند»
| گام | اقدام | نتیجه |
|---|---|---|
| 1 | فراخوانیهایی را که connect یا read timeout ندارند پیدا کنید (HTTP، Redis، DB، SDK) | فهرست انتظارهای بیحد |
| 2 | حدهای connect، per-try و کلی را از p99.9 هر وابستگی بگذارید | شکست ثانیهها طول میکشد، نه دقیقهها |
| 3 | statement_timeout و idle_in_transaction_session_timeout را برای هر role اضافه کنید | سرور کار رهاشده را متوقف میکند |
| 4 | bulkhead اضافه کنید (pool جدا برای هر وابستگی) | یک وابستگی همهٔ threadها را نمیبرد؛ نگاه کنید به Bulkheads |
| 5 | روی تعداد timeout هر وابستگی هشدار بگذارید | پیش از کاربر میبینید |
«یک تکان به قطعی طولانی تبدیل شد: retry storm»
Timeline of a retry storm
1 t=0 database CPU 85%, p99 400 ms; per-try timeout 500 ms
2 t=10 s a slow query pushes p99 to 700 ms -> 20% of calls time out at 500 ms
3 t=10 s each timeout retries (3 attempts): load becomes 1.2x -> 1.6x -> CPU 100%
4 t=30 s now 90% time out, load is 2.8x; the slow query is gone but nothing recovers
5 t=5 min operator disables retries (or sheds load); the database recovers in seconds
6 fix one retry layer, 10% budget, circuit breaker, load shedding on the server| کاهشدهنده | کی | کجا توضیح داده شده |
|---|---|---|
| retry را خاموش کنید (feature flag) | هنگام حادثه | runbook |
| Retry budget | همیشه | Budget |
| فقط در لبه retry | طراحی | یک لایه |
| Circuit breaker | نرخ شکست بالای آستانه | Circuit Breaker |
shedding سمت سرور و Retry-After | سرور | Load Shedding |
| backoff نمایی با full jitter | همیشه | Jitter |
«مشتریها دو بار شارژ شدند»
| گام | اقدام |
|---|---|
| 1 | POSTای را که بعد از read timeout retry شده پیدا کنید |
| 2 | Idempotency-Key اضافه کنید که یک بار برای هر عملیات ساخته و پیش از اولین ارسال ذخیره شود |
| 3 | در سرور key و نتیجه را در یک تراکنش ذخیره کنید (نگاه کنید به API Idempotency) |
| 4 | client فقط فراخوانیهای keyed یا idempotent را retry کند (جدول طبقهبندی) |
| 5 | تکراریهای موجود را با query دفتر کل تطبیق دهید |
-- Server side: the unique constraint is the safety net under every client retry.
CREATE TABLE idempotency_keys (
key text PRIMARY KEY,
request_hash text NOT NULL,
response jsonb,
created_at timestamptz NOT NULL DEFAULT now()
);
-- INSERT ... ON CONFLICT (key) DO NOTHING; a conflict means "return the stored response".«همه نیمهشب retry میکنند»
| علت | راهحل |
|---|---|
| cron در همهٔ hostها ساعت 00:00 | تأخیر شروع تصادفی (jitter) از 0 تا 60 s بگذارید |
| کلید cache برای همهٔ clientها همزمان منقضی میشود | jitter تصادفی روی TTL و قفل refresh (Cache::lock) |
| همهٔ podها بعد از deploy دوباره وصل میشوند | full jitter روی reconnect؛ rollout مرحلهای |
| retry webhook با زمانبندی «5 دقیقهٔ بعد» | به زمانبندی jitter اضافه کنید |
«صف job مرا دو بار اجرا میکند»
| علت | راهحل |
|---|---|
--timeout بزرگتر از retry_after | timeout را چند ثانیه کوچکتر از retry_after کنید |
| visibility timeout در SQS کوچکتر از زمان job | Default Visibility Timeout را بالا ببرید |
| job timeout میخورد و retry میشود | job را idempotent کنید؛ اگر retry غلط است FailOnTimeout بگذارید |
release() attempt مصرف میکند | Tries را بالا ببرید یا retryUntil بگذارید |
«timeout در production شلیک میکند ولی در تست نه»
| علت | راهحل |
|---|---|
| اتصالهای جدید TLS را در اولین درخواست دارند | برپایی را در بودجه بشمارید؛ اتصالها را گرم نگه دارید؛ پیشاتصال |
| جغرافیای متفاوت | از صدکهای خود فراخواننده دوباره مشتق کنید |
| توقف (GC، throttling CPU در container) | padding اضافه کنید؛ حد CPU را بررسی کنید |
| ناهماهنگی idle timeout که reset میسازد | idle timeout client کوتاهتر از سرور |
انتخاب
کدام سیاست retry برای کدام فراخوانی
| فراخوانی | Timeout (هر تلاش) | تلاشها | Backoff | Budget | Idempotency |
|---|---|---|---|---|---|
| خواندن تعاملی از یک سرویس | p99.9 بهعلاوهٔ padding، 0.2 تا 1 s | 2 تا 3 | full jitter، base برابر 50 ms، cap برابر 500 ms | 10% | ذاتی |
| نوشتن تعاملی (پرداخت، سفارش) | 2 تا 5 s | 2 تا 3 | full jitter، base برابر 100 ms | 10% | key اجباری |
| job پسزمینه که API صدا میزند | 10 تا 30 s | 5 تا 8 یا retryUntil چند ساعت | نمایی، jitter، cap چند دقیقه | برای هر کلاس job | اجباری |
| تحویل webhook به مشتری | 5 تا 10 s | 8 تا 10 در چند ساعت | آرایهٔ افزایشی با jitter | برای هر endpoint | گیرنده با شناسه dedupe میکند |
| Cache یا Redis | 20 تا 100 ms | 1 تا 2 | ثابت کوچک با jitter | بله | ذاتی |
| تراکنش دیتابیس | statement_timeout برابر 0.5 تا 3 s | فقط روی 40001 و 40P01 | jitter کوتاه | بله | کل تراکنش تکرار میشود |
| فراخوانیهای درون پشتهٔ عمیق | deadline باقیمانده | 0 (fail fast) | ندارد | ندارد | قابلاعمال نیست |
| health check | 1 تا 2 s | 0 (چک بعدی همان retry است) | ندارد | ندارد | ذاتی |
کدام jitter
| نیاز | انتخاب | دلیل |
|---|---|---|
| پیشفرض برای همه | Full jitter | کمترین کار در شبیهسازی Brooker، ساده |
| حداقل مکث تضمینشده | Equal jitter | حداقل نصف سقف؛ ولی «takes much longer» |
| تأخیرهایی که از تأخیر قبلی رشد کنند | Decorrelated jitter | شمارندهٔ attempt لازم ندارد |
| سازگاری با gRPC | +/-20% تأخیر نمایی | کاری که gRPC میکند؛ پخش سبک |
| کار زمانبندیشده روی ناوگان | offset شروع تصادفی | اولین فراخوانی را پخش میکند، نه فقط retryها |
کجا retry کنیم
| لایه | وقتی retry کنید | وقتی نکنید |
|---|---|---|
| مرورگر یا اپ موبایل | کاربر میبیند و میتواند دوباره بزند | سرور بیشازحد بارگذاریشده: حلقه اینجا به DDoS تبدیل میشود |
| edge یا gateway | idempotency را (method، key) میشناسد | backendها خودشان retry میکنند |
| سرویس A که B را صدا میزند | A مالک عملیات و deadline آن است | لایهٔ بالاتر هم retry میکند |
| sidecar مش | روی برنامه کنترل ندارید | برنامه خودش retry میکند |
| SDK | پیشفرضها به کارتان میآید (AWS standard) | حلقهٔ خودتان را رویش میگذارید |
| driver دیتابیس | برپایی اتصال | هرگز درون تراکنش بدون اجرای مجدد کل تراکنش |
در معماری: از یک پردازه تا سیستم توزیعشده
Monolith (یکپارچه): یک پردازه، یک دیتابیس
بیشتر فراخوانیها درون پردازهاند؛ فقط دیتابیس، کش و چند API بیرونی از شبکه میگذرند. سادهترین چیدمان درست: connect timeout و request timeout روی هر HTTP client خروجی؛ statement_timeout و idle_in_transaction_session_timeout روی role دیتابیس برنامه؛ retry فقط برای (الف) deadlock و شکست serialization (SQLSTATE 40P01 و 40001، با تکرار کل تراکنش) و (ب) خواندنهای بیرونی idempotent. مثال: برنامهٔ Laravel که کارت را شارژ میکند، API پرداخت را با timeout(5)، idempotency key ذخیرهشده و retry(2, ...) صدا میزند و role وب آن statement_timeout = 3s دارد.
Modular monolith: مرز بدون شبکه
ماژولها درون پردازه یکدیگر را صدا میزنند، پس بینشان timeout نیست، ولی ممکن است دیتابیس مشترک باشد. ماژول کند هنوز میتواند connection pool را نگه دارد. به هر ماژول اندازهٔ pool یا role جدا (با statement_timeout خودش) بدهید، فراخوانیهای بیرونی را پشت client متعلق به ماژول نگه دارید و برای هر وابستگی بیرونی تعیین کنید چه کسی مالک retry است. اگر قرار است ماژولی بعداً سرویس شود، همین حالا به فراخوانی درونپردازهاش پارامتر Context یا بودجه بدهید.
Microservices (میکروسرویسها): هر hop از بودجه خرج میکند
درخواست کاربر از gateway، سرویس A، B و C میگذرد. gateway یک deadline میگذارد (مثلاً 3 s) و پایین میفرستد (نگاه کنید به Service Communication)؛ هر hop timeout = min(own cap, remaining - margin) را میگذارد؛ فقط لبه (یا تنها سرویسی که مالک عملیات است) با budget retry میکند؛ سرویسهای درونی هنگام اضافهبار سریع 503 با Retry-After میدهند؛ retry sidecar مش روی این مسیرها خاموش است.
Request flow with one retry layer
1 client -> gateway deadline 3 s; gateway: per-try 1 s, 3 attempts, budget 10%
2 gateway -> A remaining 2.9 s, A: no retries
3 A -> B remaining 2.7 s
4 B -> C remaining 2.5 s; C is slow
5 B -> A 504 at 1 s (B's per-try); A returns 503 fast to the gateway
6 gateway sleeps full-jitter(0..100 ms), retries A (second attempt), 1.9 s leftPaymentsClient و httpclient در Go دقیقاً همین شکل را دارند.
داده توزیعشده (Distributed data): replica، cache، region
retry با داده تعامل دارد: خواندن retryشده روی replica دیگر ممکن است داده کهنه بدهد؛ نوشتن retryشده بعد از failover primary ممکن است به leader جدیدی برسد که نوشتن اول را اعمال کرده (باز idempotency)؛ cache stampede همان retry storm روی مبدأ است (قفل refresh، jitter روی TTL، stale-while-revalidate)؛ فراخوانیهای بین-region زمان connect بلند دارند، پس connect و per-try timeout را از همان جفت region مشتق کنید، نه از عددهای محلی. ذخیرهگاههای quorum timeout خودشان را دارند (read و write request timeout در Cassandra، retry سمت client در DynamoDB)؛ نگاه کنید به Caching و Replication Topologies.
مسیر مقیاس (Scaling path): ۱×، ۱۰×، ۱۰۰×
| بار | چه چیزی کافی است | چه چیزی میشکند | گام بعد |
|---|---|---|---|
| 1x | timeout روی هر client، 2 تا 3 تلاش، backoff ثابت یا نمایی | هنوز چیزی | jitter و طبقهبندی را اضافه کنید |
| 10x | full jitter، deadline هر تلاش و کلی، Idempotency-Key روی نوشتنها | retry هنگام حادثه مهم میشود؛ thundering herd در ساعتهای cron | retry budget، یک لایهٔ retry |
| 100x | budget مشترک برای هر وابستگی، deadline منتشرشده، خواندن hedged، breaker، load shedding | retry پنهان در SDK و مش؛ شکستهای metastable | تست آشوب رفتار retry، SLO برای هر وابستگی |
| چند-region | timeout آگاه از region، failover با reconnect دارای jitter | طوفان reconnect وقتی region برمیگردد | slow-start ترافیک هنگام بازیابی |
آزمایشگاه: timeout، retry و jitter که خودتان اجرا میکنید
همهٔ گامهای بلوک اول روی دستگاه نویسنده اجرا شد (Go 1.27، بدون container)؛ بلوکهای بعدی خروجی موردانتظار هستند و اجرا نشدهاند.
آزمایش 1: تستها و شبیهسازی را اجرا کنید (اجرا شد).
cd docs/snippets/system-design/timeouts-retries-jitter/go
1 go vet ./... && go test -count=1 ./...
2 ok academy/timeouts-retries-jitter/dbtimeouts
3 ok academy/timeouts-retries-jitter/httpclient
4 ok academy/timeouts-retries-jitter/retry
5 go run ./cmd/jittersim
6 1) 100 clients contend for one slot per 10ms (cap 1s, base 10ms)
7 constant 10ms (no jitter) 2121 calls finish 1.02s
8 exponential, no jitter 1152 calls finish 15.7s
9 full jitter 717 calls finish 2.12s
10 equal jitter 698 calls finish 2.76s
11 decorrelated jitter 701 calls finish 2.1s
12 2) 3 attempts, no budget 3000 calls (+200%); 3 attempts + 10% budget 1109 calls (+11%)
13 3) layers=5 -> 243 calls reaching the database per user requestخواندن جدول: jitter فراخوانیها را از 1152 به حدود 700 و زمان را از 15.7 s به حدود 2 s میرساند؛ equal jitter کندترین گونهٔ jitterدار است، همانطور که Brooker یافت. مدل (یک برندهٔ هر slot دهمیلیثانیهای، بهعلاوهٔ 0 یا 1 slot واریانس شبکه) نسخهٔ سادهشدهٔ سناریوی اوست، نه شبیهساز او.
آزمایش 2: statement_timeout را ببینید (خروجی موردانتظار؛ اجرا نشده؛ نیاز به PostgreSQL). session 1 و 2 دو پنجرهٔ psql هستند.
-- session 1
BEGIN; SELECT * FROM accounts WHERE id = 1 FOR UPDATE; -- holds the row lock, stays open
-- session 2
SET lock_timeout = '300ms';
UPDATE accounts SET balance = balance + 1 WHERE id = 1;
-- expected: ERROR: canceling statement due to lock timeout (SQLSTATE 55P03) after ~300 ms
SET statement_timeout = '200ms';
SELECT pg_sleep(2);
-- expected: ERROR: canceling statement due to statement timeout (57014) after ~200 ms
-- session 1, leave it open and set:
SET idle_in_transaction_session_timeout = '3s';
-- expected after ~3 s idle: FATAL: terminating connection due to idle-in-transaction timeout (25P03)آزمایش 3: دنبالهٔ retry در Laravel با سرور HTTP جعلی (خروجی موردانتظار؛ اجرا نشده).
Http::fake([
'payments.internal.example/*' => Http::sequence()
->push('', 503, ['Retry-After' => '1'])
->push('', 503)
->push(['charge_id' => 'c1'], 200),
]);
Sleep::fake();
$result = app(PaymentsClient::class)->charge(7, 10000, 'key-1');
// expected: $result['charge_id'] === 'c1'
Http::assertSentCount(3);
Sleep::assertSleptTimes(2); // the first sleep is at least 1000 ms because of Retry-Afterآزمایش 4: NGINX و برنامه هماهنگ نیستند (خروجی موردانتظار؛ اجرا نشده).
1 NGINX: proxy_read_timeout 5s; app: sleep(8) in a route
2 curl -i -m 20 http://127.0.0.1:8080/slow (a local test address)
3 expected: HTTP/1.1 504 Gateway Time-out after about 5 s, app log shows the handler still running until 8 s
4 fix: app deadline 4 s < proxy_read_timeout 5 s; the app returns a clean 503 at 4 sآزمایش 5: ساعتهای صف (خروجی موردانتظار؛ اجرا نشده). retry_after را 20 بگذارید و --timeout=60 با jobی که 30 s میخوابد.
1 php artisan queue:work redis --timeout=60 --tries=3
2 t=0 worker A reserves the job, sleeping
3 t=20 retry_after elapsed -> the job is released; worker B reserves it (second concurrent run)
4 t=30 A finishes; t=50 B finishes -> the side effect happened twice
5 fix: --timeout=15 (below retry_after) or retry_after=90 and the job made idempotentبدفهمیهای رایج
| باور | واقعیت |
|---|---|
| timeout یعنی درخواست شکست خورد | یعنی از انتظار دست کشیدید؛ سرور ممکن است بعداً کامل کند (شکست مبهم) |
| retry بیشتر یعنی قابلیت اطمینان بیشتر | فقط برای خطای گذرای تکی؛ هنگام اضافهبار بار بیشتر است؛ تعداد را محدود و budget بگذارید |
| backoff نمایی بهتنهایی herd را حل میکند | بدون jitter همهٔ clientها یکقدر میخوابند و با هم برمیگردند |
| jitter با ±10% کافی است | بهترین نتیجهٔ Brooker full jitter روی کل بازه است |
| هر 5xx قابل retry است | 501 و 500های قطعی هرگز موفق نمیشوند؛ 500، 502، 504 برای فراخوانی غیرidempotent مبهماند |
Http::timeout(3) کل فراخوانی را در 3 s میبندد | برای هر تلاش است؛ با retry(3) فراخوانی میتواند 9 s بهعلاوهٔ مکثها طول بکشد |
| timeout HTTP پیشفرض خوب است | Go ندارد؛ Laravel 30 s دارد؛ هر دو خیلی بالاتر از بودجهٔ تعاملیاند |
| برای امنیت باید در هر لایه retry گذاشت | بار ضرب میشود (243x برای پنج لایهٔ سهتلاشی)؛ در یک لایه retry کنید |
| key تازه برای هر retry اشکالی ندارد | key باید بین retryها ثابت باشد وگرنه از چیزی محافظت نمیکند |
retry_after فاصلهٔ بین retryهای job است | visibility timeout است؛ فاصله backoff است |
| circuit breaker retry را بینیاز میکند | مسئلهٔ متفاوتی را حل میکنند؛ breaker خسارت را محدود میکند، retry تکانها را درمان |
| idempotent یعنی بیحد retry کردن امن است | باز هم بار اضافه است؛ budget و backoff همچنان لازماند |
| بسته شدن connection توسط client query دیتابیس را متوقف میکند | فقط اگر driver cancel بفرستد و سرور رعایت کند؛ statement_timeout بگذارید |
چکیده
| موضوع | به خاطر بسپارید |
|---|---|
| پنج timeout | connect، write، read، total (request)، idle؛ همه را بگذارید، هیچ «پیشفرض امنی» نیست |
| لایهبندی | client > edge > proxy > app > per-try x tries > database، مشتق از یک deadline |
| انتخاب مقدار | صدکِ متناظر با نرخ false-timeoutِ قابلقبول (p99.9 برای 0.1%)، بهعلاوهٔ padding، از دید فراخواننده |
| Go | context.WithTimeout برای هر تلاش، http.Client.Timeout، net.Dialer.Timeout، ResponseHeaderTimeout، defer cancel() |
| Laravel | timeout(…)، connectTimeout(…)، retry($times, $sleep, $when, throw: …)؛ key بیرون closure ساخته شود |
| PostgreSQL | statement_timeout، lock_timeout، idle_in_transaction_session_timeout؛ برای هر role یا SET LOCAL، نه در postgresql.conf |
| صفها | --timeout کمتر از retry_after؛ پیشفرض Tries برابر 1؛ retryUntil بر tries برنده است؛ آرایهٔ backoff آخرین مقدار را تکرار میکند |
| چه چیزی retry شود | خطاهای «هرگز نرسید» همیشه؛ مبهمها فقط اگر idempotent یا keyed؛ fatalها هرگز |
| Budget | retry حداکثر 10% درخواستها؛ یک سطل مشترک برای هر وابستگی |
| لایهها | در یک لایه retry کنید؛ بقیه fail fast؛ 3 تلاش x 5 لایه = 243 |
| Backoff | پیشفرض: نمایی با cap و full jitter: random(0, min(cap, base * 2^(n-1))) |
| راهنمایی سرور | Retry-After (ثانیه یا HTTP-date)، pushback در gRPC: بزرگتر از hint و backoff را بخوابید؛ اگر از deadline بیشتر بود بایستید |
| Hedging | retry منتظر شکست میماند، hedging بعد از حدود p95 نسخه میفرستد؛ فقط خواندن؛ همان budget |
| تستها | Clock و Rand را تزریق کنید؛ برنامه، کرانها، قواعد توقف و تعداد فراخوانی را assert کنید |
| مشاهدهپذیری | تلاش برای هر درخواست، retry بر حسب دلیل، give-up بر حسب دلیل، توکن باقیماندهٔ budget |
خودآزمایی: پرسش و پاسخ
- حیاتی تقریباً در هر مصاحبه پرسیده میشود
- مهم پرتکرار؛ در سطح senior انتظار میرود
- تکمیلی عمق بیشتر؛ تمایز ایجاد میکند
۱ — یک POST بعد از 1.5 s timeout میخورد. آیا میشود دوباره فرستاد؟ تحت چه شرطی؟ حیاتی
پاسخ
پاسخ: فقط اگر idempotent باشد یا key پایدار داشته باشد، چون read timeout شکست مبهم است: سرور ممکن است اجرایش کرده باشد. RFC 9110 میگوید client نباید درخواست غیرidempotent را خودکار retry کند مگر بتواند بفهمد اصلی هرگز اعمال نشده.
۲ — چرا Http::retry(3, 100)->timeout(3) فراخوانی را به 3 ثانیه محدود نمیکند؟ حیاتی
پاسخ
پاسخ: timeout() برای هر تلاش است. با سه تلاش و دو مکث 100 ms بدترین حالت حدود 9.2 s است. علاوه بر timeout هر تلاش، از بودجهٔ درخواست یا deadline کلی استفاده کنید.
۳ — پنج سرویس زنجیرهای هر کدام سه بار retry میکنند. برای یک درخواست کاربر چند فراخوانی به دیتابیس میرسد و راهحل چیست؟ حیاتی
پاسخ
پاسخ: 3^5 = 243. فقط در یک لایه (معمولاً لبه) با budget retry کنید و لایههای درونی را fail fast کنید.
۴ — سقف مکث retry پنجم را با base برابر 100 ms و cap برابر 5 s حساب کنید و بازهٔ full و equal jitter را بگویید. مهم
پاسخ
پاسخ: سقف = min(5000، 100 x 2^4) = 1600 ms. Full jitter: 0 تا 1600 ms. Equal jitter: 800 تا 1600 ms.
۵ — سرور 429 با Retry-After: 30 میدهد ولی backoff شما 200 ms میدهد. چقدر میخوابید و کی بهجای خوابیدن تسلیم میشوید؟ مهم
پاسخ
پاسخ: بزرگتر یعنی 30 s. اگر 30 s پیش از deadline کلی جا نمیشود، بهجای خوابیدن فوراً تسلیم شوید.
۶ — چرا idempotency key باید بیرون حلقهٔ retry ساخته شود؟ حیاتی
پاسخ
پاسخ: همهٔ تلاشهای یک عملیات منطقی باید key یکسان داشته باشند تا سرور تکرار را تشخیص دهد؛ key جدید برای هر تلاش هر تلاش را عملیات جدید میکند.
۷ — job لاراول شما --timeout=120 دارد و اتصال Redis مقدار retry_after=90. چه میشود؟ مهم
پاسخ
پاسخ: در 90 s صف job در حال اجرا را آزاد میکند و worker دیگری ممکن است آن را شروع کند، پس همزمان دو بار اجرا میشود. timeout را کوچکتر از retry_after کنید.
۸ — سه timeout PostgreSQL در برابر چه چیزی محافظت میکنند؟ مهم
پاسخ
پاسخ: statement_timeout statementهای طولانی را محدود میکند، lock_timeout انتظار برای قفل را، و idle_in_transaction_session_timeout sessionهایی را میکشد که درون تراکنش باز بیکار نشستهاند (قفل نگه میدارند و جلوی vacuum را میگیرند).
۹ — تفاوت retry budget با حد تعداد تلاش برای هر درخواست چیست؟ مهم
پاسخ
پاسخ: حد تعداد تلاش یک درخواست را محدود میکند (3 تلاش). budget مجموع را: retry بهعنوان کسری از کل درخواستها؛ پس در قطعی کامل بار اضافه حدود 10% است، نه 200%.
۱۰ — چرا در تستهای retry fake clock میگذاریم؟ تکمیلی
پاسخ
پاسخ: خواب را آنی میکند و تأخیرها را ثبت میکند، پس برنامهها، کرانها، deadlineها و budgetها قطعی و سریع assert میشوند.
۱۱ — hedging کی از retry بهتر است و عملیات باید چه ویژگیای داشته باشد؟ تکمیلی
پاسخ
پاسخ: وقتی تلاش اول فقط کند است (دُم) نه شکستخورده؛ نسخه بعد از حدود p95 فرستاده میشود. عملیات باید اجرای چندباره را تحمل کند و بار اضافه با همان budget سقف داشته باشد.
۱۲ — سه دستهٔ شکست را با یک مثال برای هر کدام بگویید. حیاتی
پاسخ
پاسخ: Retryable (connection refused، 503)، ambiguous (read timeout، connection reset، 500)، fatal (400، 404، لغو context).
واژهنامه
| واژه | معنی |
|---|---|
| Timeout (محدودیت زمان) | حد مدت انتظار برای چیزی |
| Connect timeout | حد برقراری اتصال |
| Read timeout | حد انتظار برای بایتهای پاسخ |
| Write timeout | حد فرستادن درخواست |
| Request timeout | حد یک تلاش کامل (timeout کل هم گفته میشود) |
| Idle timeout | حد اتصال بدون چیزی در جریان |
| Deadline (مهلت) | زمان مطلقی که عملیات باید تا آن تمام شود |
| Total deadline | deadline که همهٔ تلاشها و مکثهای یک درخواست کاربر را میپوشاند |
| Deadline propagation | رساندن زمان باقیمانده به سرویس بعدی |
| Timeout budget | زمانی که هنوز برای hopهای باقیمانده خرجکردنی است |
| Timeout layering | چیدن حدها تا هر حد درونی کوتاهتر از حد اطرافش باشد |
| False timeout | فراخوانی سالمی که چون timeout پایین است قطع میشود |
| Retry | تکرار عملیات شکستخورده |
| Idempotent | تکرارش اثری برابر یکبار انجام آن دارد |
| Idempotency key | شناسهای از client که به سرور اجازهٔ تشخیص تکرار میدهد |
| Ambiguous failure | شکستی که پس از آن نمیدانید سرور اقدام کرده یا نه |
| Error classification | دستهبندی شکستها به retryable، ambiguous و fatal |
| Retry budget | سقف retry بهصورت کسری از ترافیک (مثلاً 10%) |
| Per-try timeout | حد یک تلاش، کوچکتر از deadline کلی |
| Retry storm | اضافهبار خودنگهدارِ ناشی از retry |
| Thundering herd | clientهای بسیار که در یک لحظه عمل میکنند |
| Backoff | مکث بین تلاشها |
| Exponential backoff | دو برابر کردن مکث در هر تلاش |
| Cap | بیشترین backoff |
| Jitter | تصادفیبودنی که به تأخیر اضافه میشود |
| Full jitter | random(0, ceiling) |
| Equal jitter | ceiling/2 + random(0, ceiling/2) |
| Decorrelated jitter | min(cap, random(base, previous * 3)) |
| Retry-After | header HTTP که انتظار را به ثانیه یا تاریخ میدهد |
| Pushback | metadata grpc-retry-pushback-ms در gRPC که میگوید کی یا آیا retry شود |
| Hedged request | نسخهٔ دومی که بعد از تأخیر و بدون لغو اولی فرستاده میشود |
| Circuit breaker | مؤلفهای که برای مدتی فراخوانی وابستگی خراب را قطع میکند |
| Adaptive retry | حالت AWS SDK با rate limiter سمت client علاوه بر retry استاندارد |
| gRPC retry policy | JSON سرویسکانفیگ با maxAttempts، backoff و retryableStatusCodes |
| Retry quota | token bucket در AWS SDK برای retry |
retry_after | visibility timeout صف Laravel، نه تأخیر retry |
tries | بیشترین attempt یک job صف |
| backoff array | برنامهٔ ثانیهها برای هر attempt که آخرین مقدار تکرار میشود |
retryUntil | زمانی که job از آن به بعد retry نمیشود |
| Fake clock | ساعت تستی که sleep آن زمان را آنی جلو میبرد |
منابع
- Marc Brooker، Exponential Backoff and Jitter، AWS Architecture Blog، 2015.
- Marc Brooker، Timeouts, retries, and backoff with jitter، Amazon Builders' Library، 2019.
- Google، Handling Overload و Addressing Cascading Failures، Site Reliability Engineering.
- gRPC proposal A6: Client Retries.
- RFC 9110: HTTP Semantics، بخشهای 9.2.2 و 10.2.3.
- PostgreSQL، Client Connection Defaults و Error Codes.
- Go، context، net/http، net، net/http/httptest.
- go-retryablehttp و مخزن آن؛ go-redis؛ redis.conf.
- Laravel 13، HTTP Client، Queues، Helpers، Cache.
- Guzzle، Handlers and Middleware و Middleware.php.
- AWS، SDK retry behavior و ALB attributes.
- NGINX، ngx_http_proxy_module؛ Envoy، router filter و route components.
- PHP، PDO::setAttribute.