Cascading Failures: How One Service Takes Down Everything
"A cascading failure is a failure that grows over time as a result of positive feedback." — Mike Ulrich، Addressing Cascading Failures، کتاب Google SRE، فصل ۲۲
خلاصه (Summary): خرابی آبشاری (Cascading Failure) از چیزی کوچک شروع میشود (یک جهش ترافیک، از دست رفتن یک zone، یک deploy بد، یک cache سرد) و واکنشهای خود سیستم (retry، کشتن سرور با health check، failover، autoscaling، صفهایی که بیسقف رشد میکنند) آن را به قطعی کامل تبدیل میکنند؛ قطعیای که اغلب بیشتر از خود ماشه (trigger) عمر میکند. تمرکز (Focus): کالبدشناسی مارپیچ مرگ (Death Spiral): اضافهبار، بالا رفتن تأخیر، retry، تمام شدن poolها، timeout در لایهٔ بالاتر، شکست health check و حذف ظرفیت؛ همهٔ حلقههای بازخورد مثبت (Positive Feedback Loop) که در عمل دیده میشوند (retry storm، cache stampede، autoscaler lag، GC pressure، صف شدن روی connection pool، هجوم بعد از انقضای TTL در DNS، cronهای همزمان، leader thrash)؛ slow vs down؛ عمق صف و صف بیسقف؛ انواع تمام شدن منابع (CPU، حافظه، file descriptor، thread، connection، ephemeral port)؛ آزمون بار برای پیدا کردن زانو؛ پیشگیری (deadline، retry budget و jitter، circuit breaker، bulkhead، load shedding و admission control، backpressure، graceful degradation، headroom)؛ تشخیص (four golden signals)؛ بازیابی (shed، قطع retry، بستن ترافیک در edge، slow start، gradual recovery)؛ پنج postmortem عمومی؛ و یک شبیهساز Go که عددهایش در همین صفحه آمده است. هدف یادگیری (Learning goal): با نگاه به نمودار یک معماری، حلقههایی را نشان دهید که یک خطای کوچک را به قطعی تبدیل میکنند، روی هر حلقه یک قطعکنندهٔ ارزان بگذارید، با آزمون بار فراتر از زانو ثابتش کنید، و ترتیب درست کارها را برای برگرداندن یک سیستم فروریخته بدون فروریختن دوباره بدانید.
این فصل گروه Resilience را باز میکند و مالک تصویر سطح سیستم است: خرابی چطور پخش میشود، عددهای پشت آن، جدولهای بدهبستان و دستورالعمل بازیابی. هر دفاع فصل خودش را دارد و هر جا لازم شد در یک جمله به آن پیوند دادهایم: Timeouts, Retries & Jitter، Circuit Breaker، Bulkheads & Graceful Degradation، Load Shedding، Rate Limiting و Chaos Engineering. همسایهها: بودجهٔ هر hop در Latency Budgets & Tail Latency، health check در Load Balancing و Service Discovery، autoscaling در Scaling Strategies، مصرف بودجهٔ SLO در SLAs, SLOs, SLIs & Error Budgets، port و socket در Ports, Sockets & Connections، pool دیتابیس در Connection Pooling و backpressure در سطح پیام در Backpressure & Flow Control.
نقشهٔ صفحه
| دنبال چه هستید | بروید به |
|---|---|
| کل صفحه در سه جدول و یک تصویر | همهچیز در یک دقیقه |
| چرا یک لرزش یکدقیقهای قطعی دوساعته میشود | چرا وجود دارد |
| Nygard، Google SRE، AWS، مقالهٔ metastable failures | از کجا آمده |
| بازخورد مثبت، اضافهبار، goodput، زانو | خرابی آبشاری، اضافهبار و goodput |
| مارپیچ مرگ و خرابی metastable | مارپیچ مرگ |
| Retry storm و تقویت retry | Retry storm |
| چرا کند بدتر از قطع است؛ تأخیر دوحالته | Slow vs down |
| عمق صف، صف بیسقف، head-of-line blocking | صفها |
| CPU، حافظه و GC، thread، file descriptor، connection، ephemeral port | تمام شدن منابع |
| Health check flapping و حذف ظرفیت | Health check |
| Thundering herd، cache stampede، cache سرد | Thundering herd |
| Autoscaler lag؛ cron همزمان، TTL در DNS، leader thrash | Autoscaler lag، بار همزمان |
| Query of death، rollout، drain، رشد طبیعی | ماشهها |
| Deadline، انتشار و لغو | Deadline |
| Retry budget و jitter | Retry budget |
| Load shedding، admission control، صف محدود، backpressure | Load shedding |
| Circuit breaker، bulkhead، جداسازی وابستگی، fail fast | جداسازی |
| Graceful degradation و criticality | تنزل آبرومندانه |
| Headroom، N + 2، آزمون بار تا زانو | Headroom و آزمون بار |
| درخواست hedged و محدودیتهایش | Hedging |
| Four golden signals، saturation، مصرف SLO | تشخیص |
| Shed، قطع retry، بستن در edge، slow start | بازیابی |
| Postmortem بیسرزنش | Postmortem |
| S3 2017، Cloudflare 2019، GitHub 2018، Slack 2021، Google 2020 | مطالعهٔ موردی |
| فرمولها، تنظیمها، پیامهای خطا | سازوکار |
| کد و شبیهساز | Go، Laravel |
| حادثههای کلاسیک و راهحلشان | حل مسئلههای کلاسیک |
| کدام دفاع برای کدام نشانه | انتخاب |
| از monolith تا چند-region | در معماری |
| مارپیچ مرگ را خودتان اجرا کنید | آزمایشگاه |
| باورهای غلط، چکیده، خودآزمایی، واژهها | بدفهمیها، چکیده، خودآزمایی، واژهنامه |
همهچیز در یک دقیقه
کالبدشناسی یک آبشار (Google SRE فصل ۲۲ و Nygard)، قدم به قدم.
| قدم | چه اتفاقی میافتد | چرا قدم بعد را تغذیه میکند |
|---|---|---|
| ۱. ماشه (Trigger) | جهش ترافیک، از دست رفتن cluster یا zone، deploy، query of death، پاک شدن cache | بار هر سرور سالم از توانش بیشتر میشود |
| ۲. اضافهبار (Overload) | درخواستها سریعتر از تمام شدن کار workerها میرسند | مازاد جایی منتظر میماند: صف، backlog سوکت، حافظه |
| ۳. بالا رفتن تأخیر | تأخیر صف به همهٔ درخواستها اضافه میشود | deadline فراخوانها شروع به انقضا میکند |
| ۴. تقویت با retry | فراخوانهایی که timeout خوردهاند دوباره میفرستند، اغلب در چند لایه | بار ارسالی بالا میرود و کار مفید پایین |
| ۵. تمام شدن poolها | thread، connection، file descriptor و حافظه در دست کارهای کند میمانند | حتی درخواستهای ارزان (و health check) سرویس نمیگیرند |
| ۶. timeout در لایهٔ بالا | فراخوانهای سرویس کند حالا threadهای خودشان را نگه داشتهاند | خرابی در گراف فراخوانی بالا میرود |
| ۷. شکست health check | probe پشت ترافیک واقعی منتظر میماند یا وابستگی کند را چک میکند | load balancer بیرون میاندازد و scheduler سرورهای شلوغ را میکشد |
| ۸. حذف ظرفیت | سرورها کمتر میشوند و آنهایی که برمیگردند cache سرد دارند | سرورهای باقیمانده بار بیشتری میگیرند: برگشت به قدم ۲ |
حلقههای بازخورد مثبت و قطعکنندهٔ ارزان هر کدام.
| حلقه | چه چیزی تقویت میشود | قطعکننده | فصل مالک |
|---|---|---|---|
| Retry storm | تعداد تلاش برای هر درخواست، ضربشده در هر لایه | retry فقط در یک لایه، retry budget (۱۰٪)، full jitter | Timeouts, Retries & Jitter |
| کار محکوم به شکست | سرور درخواستی را پردازش میکند که فراخوانش دیگر منتظر نیست | انتشار deadline، چک deadline پیش از هر مرحله | Deadline |
| رشد صف | صف بیسقف: تأخیر و حافظه بیحد رشد میکنند | صف محدود (حدود ۵۰٪ pool workerها)، 503 سریع | Load Shedding |
| مارپیچ مرگ GC | درخواست در جریان بیشتر، heap بیشتر، GC بیشتر، CPU کمتر | admission control، سقف حافظه، درخواست در جریان کمتر | تمام شدن منابع |
| کشتن با health check | سرور شلوغ مرده فرض و restart میشود | liveness مستقل از بار؛ readiness فقط برای drain | Health check |
| بار failover | ترافیک cluster ازدسترفته به بازماندهها میرود | headroom (N + 2)، اول ترافیک قابلحذف را بریزید | Headroom |
| Cache stampede | cache سرد یا خالی همهٔ درخواستها را به دیتابیس میفرستد | ادغام درخواست، stale-while-revalidate، گرم کردن cache | Caching |
| تأخیر یا سیگنال غلط autoscaler | مقیاسدهی کُند، یا کوچک کردن وقتی threadها منتظر I/O هستند | مقیاس روی saturation، headroom، گرم کردن پیشاپیش | Scaling Strategies |
| کلاینتهای همزمان | retry، cron و انقضای TTL در یک لحظه | jitter روی هر چیز زمانبندیشده | بار همزمان |
| وابستگی کند | threadهای همهٔ فراخوانها پشت یک backend کند | timeout، bulkhead، circuit breaker، fail fast | Circuit Breaker |
آنچه شبیهساز این صفحه اندازه گرفت (۱۰ سرور، ظرفیت ۲٬۰۰۰ درخواست در ثانیه، بار عادی ۱٬۴۰۰، جهش ۲٬۶۰۰ از ثانیهٔ ۲۰ تا ۳۰؛ عدد مدل است، نه عدد production).
| سیستم | goodput در جهش | goodput در ۳۰ تا ۹۰ ثانیه، با بار برگشته به ۷۰٪ | تلاش برای هر درخواست بعد از جهش |
|---|---|---|---|
| سادهلوحانه (timeout پنج ثانیه، سه retry فوری، صف بیسقف، probe داخل صف) | 44.2% | 6.4% و بعد 6.2%: هرگز برنمیگردد | 3.50x |
| سادهلوحانه + فقط retry budget و jitter | 44.2% | 14.0% | 1.08x |
| سادهلوحانه + فقط صف محدود | 76.8% | 100% | 1.01x |
| محافظتشده (deadline، budget، صف محدود، probe فقط liveness) | 76.5% (حدود ۱٬۹۹۰ در ثانیه، یعنی ظرفیت) | 100% | 1.01x |
این تصویر خلاصهٔ کل فصل است: هر جعبه جعبهٔ بعدی را بدتر میکند، و پیکانهایی که حلقه را میبندند («بار بیشتر» و «ظرفیت کمتر») همانهایی هستند که دفاعها قطعشان میکنند. سیستمی که حلقه دارد و قطعکننده ندارد وقتی زمین میخورد بدشانس نبوده؛ فقط منتظر یک ماشه بوده است.
چرا وجود دارد
سیستمهای توزیعشده را دقیقاً با replica و وابستگی میسازیم تا خرابی یک قطعه مهم نباشد. ولی همین ساختار به خرابی راههای زیادی برای حرکت میدهد: بار replica مرده به همتایانش میرود، تأخیر backend به فراخوانهایش میرسد، retry کار را دوباره به جایی میفرستد که همین الان غرق شده، و خودکارسازیهایی که قرار بود درمان کنند (health check، failover، autoscaling، restart) در بدترین لحظه ظرفیت را از سیستم بیرون میکشند. توصیف Nygard از جفتشدگی تنگ (tight coupling) دقیقاً همین است: "A failure in one component causes load to be redistributed to its peers and introduces delays and stress to its callers. This increased stress makes it extremely likely that another component in the system will fail."
| ساختهشده برای حالت پایدار | ساختهشده برای زنده ماندن در اضافهبار |
|---|---|
| retry خطاهای گذرا را پنهان میکند | retry برای هر درخواست و هر کلاینت سقف دارد و فقط در یک لایه انجام میشود |
| timeout سخاوتمندانه تا درخواست کند بالاخره موفق شود | deadline به اندازهٔ صبر کاربر؛ کار محکوم به شکست دور ریخته میشود |
| صفها انفجار را جذب میکنند، تا جایی که حافظه اجازه دهد | صفها کوتاهاند؛ مازاد سریع و ارزان رد میشود |
| health check هر چیزی را که ناسالم به نظر برسد حذف میکند | health check مرده را از شلوغ جدا میکند؛ بیرون انداختن سقف دارد |
| cache سرویس را سریع میکند (و بیصدا بار را حمل میکند) | سرویس با cache خالی زنده میماند یا پیش از ترافیک گرمش میکند |
| autoscaling جای headroom را میگیرد | headroom از دست رفتن یک zone را پوشش میدهد؛ autoscaling خط دوم است |
| همهٔ درخواستها به یک اندازه مهماند | ترافیک criticality دارد؛ کار قابلحذف اول میرود |
| آزمون بار در اوج مورد انتظار متوقف میشود | آزمون بار از زانو میگذرد و صاف ماندن goodput را چک میکند |
تصویر روزمرهای که در کل صفحه به کار میبریم: آشپزخانهٔ یک رستوران شلوغ. سفارشها سریعتر از توان آشپزها میرسند (اضافهبار). ریل سفارش پر میشود (صف بیسقف)، پس هر غذا دیر میرسد (تأخیر). گارسونها چون چیزی بیرون نمیآید همان سفارش را دوباره میفرستند (retry) و ریل بلندتر میشود. مدیر آشپزهایی را که «چیزی تحویل نمیدهند» به خانه میفرستد (کشتن با health check). جایگزینها نمیدانند چیزها کجاست (cache سرد). مدتها بعد از پایان شلوغی، آشپزخانه هنوز دارد غذاهایی را میپزد که کسی منتظرشان نیست. راهحل اول آشپز بیشتر نیست: ده دقیقه سفارش را دمِ در نپذیرید، برگهٔ مشتریهایی را که رفتهاند دور بریزید، به گارسونها بگویید دوباره نفرستند و در را آرام باز کنید.
سه بدفهمی رایج، از همین اول
- «به خاطر ماشه از کار افتاد.» ماشه فقط شروعش میکند. مقالهٔ metastable failures از Bronson و همکاران: "It is common for an outage that involves a metastable failure to be initially blamed on the trigger, but the true root cause is the sustaining effect." در شبیهساز، جهش در ثانیهٔ ۳۰ تمام میشود و سیستم سادهلوحانه در ثانیهٔ ۹۰ هنوز ۶٪ goodput دارد.
- «retry ما را قابلاعتمادتر میکند.» برای خطاهای گذرا و مستقل بله. در اضافهبار سوخت آتش است: کتاب Google SRE نشان میدهد سه لایه با سه retry یک کنش کاربر را به ۶۴ تلاش روی دیتابیس تبدیل میکند، و AWS پنج لایه را ۲۴۳ برابر بار نشان میدهد، "making it unlikely to ever recover."
- «ظرفیت اضافه کنید، خوب میشود.» Google SRE: "if the service has entered a death spiral of some sort, adding more resources may not be sufficient to recover." در شبیهساز، افزودن ۵۰٪ سرور در میانهٔ فروپاشی goodput را برای ده ثانیه از 4.6% به 15.2% برد و بعد به 8% برگرداند؛ بستن ۹۰٪ ترافیک در edge و بازگشایی تدریجی در ۲۰ ثانیه کاملاً درمانش کرد.
از کجا آمده
Year Who / what What it added
1 1994 Floyd & Jacobson (cited by Google SRE as Flo94) Retry ripples scheduled together amplify themselves; randomize
2 2015 Marc Brooker, AWS Architecture Blog "Exponential Backoff And Jitter": Full, Equal, Decorrelated jitter
3 2016 Google SRE book (online edition (c) 2017), ch. 21-22 Overload handling, retry budgets, deadlines, the death spiral
4 2017 AWS S3 us-east-1 summary (Feb 28) Capacity removed too fast; full restarts of index/placement
5 2018 Nygard, Release It! 2nd edition (Jan 2018) Stability antipatterns: Cascading Failures, Chain Reactions, Slow Responses...
6 2018 GitHub, October 21 post-incident analysis 43 s partition, cross-country failover, 24 h 11 min degradation
7 2019 Cloudflare, July 2 outage One regex rule exhausted CPU worldwide for 27 minutes
8 2020 Google, incident 20013 (Dec 14) Quota automation starved the User ID Service: 47 minutes
9 2021 Slack, January 4 outage Saturated AWS Transit Gateways, autoscaling and provisioning loops
10 2021 Bronson et al., HotOS (metastable failures) Trigger vs sustaining effect; stable, vulnerable, metastable statesNygard. کتاب Release It! الگو را از نگاه اپراتور نامگذاری میکند. فصل ضدالگوهای پایداری (stability antipatterns) فهرست Integration Points، Chain Reactions، Cascading Failures، Blocked Threads، Self-Denial Attacks، Scaling Effects، Unbalanced Capacities، Dogpile، Force Multiplier، Slow Responses و Unbounded Result Sets را دارد و الگوهای پایداری پاسخ آنها هستند: Timeouts، Circuit Breaker، Bulkheads، Steady State، Fail Fast، Let It Crash، Handshaking، Test Harnesses، Decoupling Middleware، Shed Load، Create Back Pressure و Governor (فهرست مطالب در صفحهٔ ناشر). گزیدهٔ رایگان کتاب توضیح میدهد چرا کندی حالت خطرناک است: "Clearly, a slow response is a lot worse than no response."
Google SRE. فصل ۲۲ (Mike Ulrich) کالبدشناسی مرجع است: علتها (اضافهبار سرور، تمام شدن منابع، در دسترس نبودن سرویس)، پیشگیری به ترتیب اولویت (آزمون بار تا شکست، پاسخ تنزلیافته، رد کردن در اضافهبار، rate limit در لایههای بالاتر، برنامهریزی ظرفیت)، مدیریت صف، load shedding، retry، deadline، شروع کند و cache سرد، شرایط ماشه، آزمون و قدمهای فوری. فصل ۲۱ (Handling Overload) throttling تطبیقی سمت کلاینت، criticality و retry budget برای هر درخواست و هر کلاینت را اضافه میکند. پانویس ۱۱۰ فصل ۲۲ میگوید "write a simple simulator and see how the amount of useful work the backend can do varies with how much it's overloaded and how many retries are permitted"؛ بخش Go دقیقاً همین کار را میکند.
AWS Builders' Library. مقالهٔ Using load shedding to avoid overload تفاوت goodput و throughput و شکل مطلوب نتیجهٔ آزمون بار را معرفی میکند؛ مقالهٔ Timeouts, retries, and backoff with jitter ضرب ۲۴۳ برابری و محدودیت retry با token bucket را که در ۲۰۱۶ به AWS SDK اضافه شد شرح میدهد.
Metastable failures. Bronson، Charapko، Aghayev و Zhu (HotOS ۲۰۲۱) واژگانی را میدهند که در این صفحه به کار میبریم: "Metastable failures occur in open systems with an uncontrolled source of load where a trigger causes the system to enter a bad state that persists even when the trigger is removed." بیرون آمدن از آن "requires a strong corrective push, such as rebooting the system or dramatically reducing the load."
فهرست مفاهیم
هر بلوک یک ترتیب دارد: به زبان ساده، باور غلط رایج، تعریف، خط زمانی، سناریوی واقعی، آنچه محصولات میدهند، و راهحل. دوازده بلوک اول میگویند آبشار چطور رخ میدهد؛ بقیه میگویند چطور جلویش را بگیریم.
خرابی آبشاری و حلقهٔ بازخورد مثبت حیاتی
به زبان ساده: یک قطعه خراب میشود و همین خرابی احتمال خراب شدن قطعهٔ بعدی را بالا میبرد، و آن هم احتمال بعدی را. دومینو است، با این تفاوت که مهرهها هل میدهند.
بدفهمی رایج: «آبشار یعنی چند خرابی مستقل همزمان.» آبشار یک خرابی است که از راه جفتشدگی پخش میشود. سرور دوم تصادفی خراب نشد؛ خراب شد چون بار سرور اول را گرفت.
تعریف: به تعبیر Google SRE خرابی آبشاری (Cascading Failure) "can occur when a portion of an overall system fails, increasing the probability that other portions of the system fail." موتورش حلقهٔ بازخورد مثبت (Positive Feedback Loop) است: یک خروجی (خطا، تأخیر، ظرفیت از دست رفته) ورودی خودش (بار هر سرور) را بالا میبرد. بازخورد منفی (shedding، backoff، throttling) چیزی است که سیستم را پایدار نگه میدارد.
t Cluster A (capacity 1,000 QPS) Cluster B
1 0 s 1,000 QPS, healthy 1,000 QPS, healthy
2 10 s fails
3 10 s the load balancer sends B's share: 1,200 QPS
4 40 s A runs out of resources: crashes, misses deadlines; useful work falls well below 1,000
5 60 s the global load balancer moves A's traffic to C and D, which overload in turn
6 2 min "service-wide overload failure" (Google SRE: "on the order of a couple minutes")سناریوی واقعی: قطعی یک zone یکسوم ترافیک را روی دو zone که در ۷۰٪ کار میکنند میریزد؛ یک consumer group در Kafka زیر بار rebalance میشود و همهٔ consumerها از offset قدیمیتر دوباره شروع میکنند؛ یک درگاه پرداخت کند میشود و همهٔ threadهای checkout منتظرش میمانند؛ یک cluster کش restart میشود و کل بار خواندن به دیتابیس میرسد.
چه چیزی جفتشدگی (و ترمز) را فراهم میکند:
| جفتشدگی | نمونهٔ محصول | ترمز |
|---|---|---|
| پخش دوبارهٔ بار بین replicaها | AWS ALB، Envoy، upstreamهای NGINX، Kubernetes Service | headroom؛ admission control در هر سرور |
| انتقال تأخیر به فراخوان | هر RPC همزمان: HTTP، gRPC | deadline، bulkhead، circuit breaker |
| تزریق دوبارهٔ retry | کتابخانههای کلاینت، SDKها، proxyها (retry در Envoy)، مرورگر | retry budget (retryThrottling در gRPC، سهمیهٔ AWS SDK) |
| خودکارسازیای که ظرفیت را حذف میکند | liveness probe در Kubernetes، restart در Borg، جایگزینی در ASG | جدا کردن liveness از readiness؛ سقف بیرون انداختن (max_ejection_percent در Envoy) |
| cacheهای مشترک | Redis، Memcached، CDN | latency cache، ادغام درخواست، Cache::flexible |
راهحل / نحوهٔ استفاده: گراف وابستگی را بکشید و هر پیکانی را که بار، تأخیر یا retry میتواند از آن عبور کند علامت بزنید؛ هر پیکان یک ترمز لازم دارد (جدولش در انتخاب است).
اضافهبار، goodput و زانو حیاتی
به زبان ساده: هر سرور یک سقف برای سرعت کار مفید دارد. اگر بیشتر از آن به آن بدهید، سرعت کار مفید صاف نمیماند؛ در بیشتر سرورهای سادهلوحانه پایین میافتد، گاهی تقریباً تا صفر.
بدفهمی رایج: «در ۱۲۰٪ بار، ۱۰۰٪ را سرویس میدهیم و ۲۰٪ اضافه منتظر میماند.» بدون shedding مازاد جلوی همه منتظر میماند، تأخیر همهٔ درخواستها بالا میرود، deadlineها منقضی میشوند و سرعت کار مفید فرو میریزد (Google SRE: در 1,200 QPS "the rate of successfully handled requests in A dips well below 1,000 QPS").
تعریف: گذردهی (Throughput) نرخ درخواستی است که به سرور فرستاده میشود؛ goodput به تعریف AWS "the subset of the throughput that is handled without errors and with low enough latency for the client to make use of the response" است. زانو (Knee) باری است که از آن به بعد goodput دیگر همراه بار ارسالی بالا نمیرود. سرویسِ خوبمحافظتشده در زانو صاف میماند؛ سرویس شکننده از صخره پایین میافتد.
Offered (req/s) Naive goodput Protected goodput (simulator, 2,000 req/s capacity)
1 1,000 1,000 1,000
2 1,800 1,799 1,798
3 2,000 1,713 1,908
4 2,200 236 1,956
5 3,000 108 1,998نمودار بالا همان جدول است: تا ۱٬۸۰۰ درخواست در ثانیه هر دو سیستم همه را سرویس میدهند؛ از ۲٬۰۰۰ به بعد خط سادهلوحانه سقوط میکند و خط محافظتشده نزدیک ظرفیت صاف میماند.
سناریوی واقعی: شروع فروش بلیت در ساعت ۱۰:۰۰:۰۰؛ اشارهٔ یک برنامهٔ تلویزیونی (مثال Shakespeare در کتاب SRE بعد از پخش یک مستند در ژاپن)؛ اولین دوشنبهٔ کاری سال در Slack که "client caches are cold and clients pull down more data than usual on their first connection".
چه چیزی فراهمش میکند:
| محصول | سازوکاری که goodput را صاف نگه میدارد |
|---|---|
| RPC داخلی Google (SRE فصل ۲۱) | سیگنال utilisation هر task («executor load average»)، رد کردن بر اساس criticality |
| Envoy | circuit breaker روی connection، درخواست معلق، درخواست و retry (upstream_rq_pending_overflow) |
| سرویسهای AWS (Builders' Library) | محافظت brownout با هدف نرخ false positive صفر |
| Laravel | middleware throttle برای هر کلاینت، middleware ریختن بر اساس زمان صف (Laravel) |
| Go | middleware پذیرش با صف محدود (Go) |
راهحل / نحوهٔ استفاده: آزمون بار را از زانو رد کنید و بعد ارزانترین مسیر رد کردن را اضافه کنید (سقف ثابت روی درخواست در جریان، صف محدود) تا منحنی صاف شود. الگوریتمها در فصل Load Shedding آمدهاند.
مارپیچ مرگ و خرابی metastable حیاتی
به زبان ساده: سیستم طوری خراب شده که خودش خودش را خراب نگه میدارد. حتی بعد از رفتن مشکل اصلی، واکنشها به آن (retry، restart، cache سرد، کار انباشته) بار را بالاتر از توان ظرفیت باقیمانده نگه میدارند.
بدفهمی رایج: «بار به حالت عادی برگشته، پس خودش خوب میشود.» Google SRE: "if a service was healthy at 10,000 QPS, but started a cascading failure due to crashes at 11,000 QPS, dropping the load to 9,000 QPS will almost certainly not stop the crashes." وقتی فقط ۱۰٪ سرورها سالم باشند، "the request rate would need to drop to about 1,000 QPS in order for the system to stabilize and recover."
تعریف: حالت خرابی metastable (Metastable Failure State) حالتی بد با goodput پایین است که بعد از برداشته شدن ماشه باقی میماند، چون یک اثر نگهدارنده (Sustaining Effect)، یعنی تقویت کار یا افت کارایی، آن را نگه میدارد. Bronson و همکاران سه مرحله را توصیف میکنند: پایدار (stable)، آسیبپذیر (vulnerable؛ سالم، ولی آنقدر کارآمد که یک ماشه میتواند سرنگونش کند؛ "many production systems choose to run in the vulnerable state all the time") و metastable. «مارپیچ مرگ GC» در Google SRE نسخهٔ حافظهای آن است: "less CPU is available, resulting in slower requests, resulting in increased RAM usage, resulting in more GC, resulting in even lower availability of CPU."
t (s) Offered Attempts Good Up Queue What happens (naive run of the simulator)
1 18 1,400 1,400 1,396 10 7 vulnerable but healthy: 70% utilisation
2 20 2,600 2,600 1,955 10 628 trigger: spike to 130%
3 25 2,600 2,600 1,537 10 4,729 queues grow, GC slows every request
4 26 2,600 2,600 765 6 3,527 health checks wait in the queue: 4 servers killed
5 28 2,600 10,377 0 0 0 every attempt times out; retries; no server up
6 30 1,400 12,726 0 0 0 trigger gone, retry wave of 9x
7 32-90 1,400 1,400-13,017 0-252 0-10 ... restarts come back cold, are overloaded, killed againسناریوی واقعی: ناوگان «lame duck» که سرورهایش لحظهٔ برگشتن دوباره health check را رد میکنند؛ سرویس Java در حلقهٔ GC؛ restart شدن Memcached که هر گرهٔ برگشته زیر miss غرق میشود؛ ناوگان consumer صف که روی یک batch سمی کرش میکند، restart میشود و همان batch را دوباره میخواند.
راههای بیرون آمدن (همه «هل اصلاحی قوی»):
| راه خروج | محصول | نکته |
|---|---|---|
| بستن ترافیک در edge و بازگشایی تدریجی | قوانین WAF و rate limit در Cloudflare، AWS WAF، limit_req در NGINX، local rate limit در Envoy | Google SRE: "only allow, say, 1% of the traffic through" |
| قطع retry | feature flag، ارسال پیکربندی به کلاینت، retryThrottling در gRPC | اغلب به push کد یا پیکربندی نیاز دارد |
| غیرفعال کردن health check کُشنده | ویرایش probe در Kubernetes، غیرفعال کردن health check در Borg | Google SRE: "temporarily disabling health checks may permit the system to stabilize" |
| کلید خاموشکنندهٔ سراسری برای قطعهٔ معیوب | «global terminate» در Cloudflare | در قطعی ۲۰۱۹ ساعت 14:07 به کار رفت |
راهحل / نحوهٔ استفاده: طوری طراحی کنید که حالت آسیبپذیر دیده شود (هشدار headroom، آزمون باری که از زانو بگذرد) و هر حلقه قطعکنندهای داشته باشد که خودکار وارد عمل شود؛ یک راه خروج دستی (بستن در edge با بازگشایی تدریجی) آماده و تمرینشده نگه دارید. اجرای شبیهساز در آزمایشگاه است.
در این نمودار خط ضخیم سیستم محافظتشده است که در جهش روی ظرفیت ۲٬۰۰۰ میماند و در ثانیهٔ ۳۰ به ۱٬۴۰۰ برمیگردد؛ خط نقطهخط سیستم سادهلوحانه است که در ثانیهٔ ۲۷ به صفر میرسد و با وجود برگشتن بار به ۷۰٪، تا آخر زیر ۲۶۰ در ثانیه میماند، با موجهای retry هر هشت ثانیه.
Retry storm و تقویت retry حیاتی
به زبان ساده: وقتی همهچیز کند است همه دوباره میپرسند، پس سرویسی که از قبل شلوغ است همان کار را دو، چهار یا شصتوچهار بار دریافت میکند.
بدفهمی رایج: «فقط سه بار retry میکنیم، معقول است.» سه retry در هر یک از سه لایه یعنی 4 × 4 × 4 = 64 تلاش برای هر کلیک. retryها در هر لایه ضرب میشوند، نه جمع.
تعریف: تقویت retry (Retry Amplification) تعداد تلاش برای هر درخواست منطقی در پایین پشته است. مثال Google SRE: backendی با سقف 10,000 QPS که 10,100 QPS میگیرد صدتا را رد میکند، آنها retry میشوند، حالا 10,200 میگیرد، و "The volume of retries grows: 100 QPS of retries in the first second leads to 200 QPS, then to 300 QPS, and so on." طوفان retry (Retry Storm) همان سیل خودنگهدار حاصل است. AWS: "Retries are a way for clients to assert the importance of their request and demand that the service spend more of its resources to handle it."
Layer Attempts per user action (each layer: 3 retries = 4 attempts)
1 JavaScript client 4
2 Frontend 4 x 4 = 16
3 Backend -> DB 4 x 4 x 4 = 64 (Google SRE ch. 22)
4 Five layers, three tries each: 3^5 = 243x (AWS Builders' Library)
5 With retries at one layer only: 4x; with a 10% retry budget: about 1.1x (SRE ch. 21)تصویر همین ضرب را نشان میدهد: یک کلیک در سه لایه به ۶۴ تلاش میرسد، پنج لایه به ۲۴۳ برابر؛ retry فقط در یک لایه بدترین حالت را به ۴ برابر محدود میکند و retry budget دهدرصدی سربار پایدار را نزدیک 1.1 برابر نگه میدارد.
سناریوی واقعی: اپ موبایلی که هر sync ناموفق را فوراً تکرار میکند (کتاب SRE از "an offline sync protocol that retries aggressively" نام میبرد)؛ service meshی که بهصورت پیشفرض retry میکند بهعلاوهٔ retry برنامه؛ failover دیتابیس که در آن همهٔ سرویسها در یک لحظه برای اتصال retry میکنند؛ podهای CrashLoopBackOff در Kubernetes که همان batch را از Kafka دوباره میخوانند.
چه چیزی محافظت میکند:
| محصول | کنترل retry | پیشفرض یا نکته |
|---|---|---|
| gRPC | retryPolicy.maxAttempts، retryThrottling (maxTokens، tokenRatio) | وقتی tokenها از نصف maxTokens کمتر شوند retry متوقف میشود |
| AWS SDKها | سهمیهٔ retry (token bucket) از ۲۰۱۶ | "AWS added this behavior to the AWS SDK in 2016" |
| Envoy | retry_budget یا circuit breaker max_retries | مستندات: "we recommend using retry budgets" |
| HTTP client در Laravel | retry($times, $sleep, $when, throw:) | budget داخلی ندارد؛ RetryBudget این صفحه اضافهاش میکند |
| Go | در net/http چیزی نیست | resilience.Client این صفحه |
راهحل / نحوهٔ استفاده: فقط در یک لایه retry کنید (معمولاً نزدیکترین لایه به کاربر یا لایهای که تضمین idempotency دارد)، تلاش هر درخواست را به ۲ تا ۳ محدود کنید، یک budget دهدرصدی برای کل کلاینت بگذارید، از full jitter استفاده کنید، هرگز روی 4xx یا اضافهبار صریح (429) retry نکنید و در اضافهبار status مشخصی برگردانید. جزئیات در Timeouts, Retries & Jitter و Retry, Backoff & Delayed Delivery.
Slow vs down: چرا کند بدتر است حیاتی
به زبان ساده: وابستگی مرده در یک میلیثانیه «نه» میگوید و شما میروید سراغ کار بعد. وابستگی کند بعد از سی ثانیه «شاید» میگوید و در تمام این مدت شما یک thread، یک connection، مقداری حافظه و یک کاربر را نگه داشتهاید.
بدفهمی رایج: «سرویس کند نیمهکار است و از سرویس از کار افتاده بهتر است.» برای فراخوانها، کندی گرانترین حالت خرابی است: تأخیر را به منبع نگهداشتهشده و منبع نگهداشتهشده را به تمام شدن منابع تبدیل میکند.
تعریف: Nygard: "Fast network failures cause immediate exceptions in the calling code ... Slow failures, such as a dropped ACK, let threads block for minutes before throwing exceptions. The blocked thread can't process other transactions, so overall capacity is reduced. If all threads end up getting blocked, then for all practical purposes, the server is down." تأخیر دوحالته (Bimodal Latency) در Google SRE حالت افراطی آن است: بیشتر درخواستها سریع و چندتایی تا deadline تمام نمیشوند. این همان تمایز slow vs down است.
Frontend: 10 servers x 100 threads = 1,000 threads, 1,000 QPS at 100 ms = 100 threads busy
1 Event: 5% of requests (one unavailable Bigtable key range) never complete
2 Deadline 100 s: those 50 QPS hold 50 x 100 = 5,000 thread-seconds per second
3 Capacity needed: 5,000 + 95 threads; available: 1,000
4 Served: 1,000 / 5,095 = 19.6% of requests; error rate 80.4% (Google SRE)
5 Same event with a fail-fast error after 100 ms: 5% errors, 95% servedسناریوی واقعی: درگاه پرداختی با timeout پیشفرض ۶۰ ثانیه در زمان brownout خودش؛ resolver DNS که بهجای رد کردن، بسته را دور میریزد؛ دیتابیسی که در صف قفل منتظر است؛ لایهٔ وب Slack که در آن packet loss تأخیر تا backendها را بالا برد و "saturated system resources in our web tier".
چه چیزی کند را سریع میکند:
| محصول | تنظیم | پیشفرض (از مستندات) |
|---|---|---|
| HTTP client در Laravel | timeout()، connectTimeout() | ۳۰ ثانیه و ۱۰ ثانیه |
| NGINX | proxy_connect_timeout، proxy_read_timeout | هر کدام 60s |
net/http در Go | http.Client.Timeout، Transport.ResponseHeaderTimeout، deadline در context | هیچ: صفر یعنی بدون timeout |
| PostgreSQL | statement_timeout، lock_timeout، idle_in_transaction_session_timeout | 0 (غیرفعال) |
| probeهای Kubernetes | timeoutSeconds | 1s |
| PHP-FPM | request_terminate_timeout | 0 (خاموش) |
راهحل / نحوهٔ استفاده: هر فراخوانی بیرونی deadlineی بگیرد که از توزیع تأخیر callee (حدود p99.9 آن) اندازه شده و هرگز از وقت باقیماندهٔ فراخوان بیشتر نیست؛ اگر میدانید وابستگی از کار افتاده، فوراً شکست بخورید (circuit breaker)؛ توزیع تأخیر را ببینید، نه میانگین را ("When you see a latency increase, try to look at the distribution of latencies in addition to the averages").
عمق صف، صف بیسقف و head-of-line blocking حیاتی
به زبان ساده: صف «خیلی شلوغم» را به «دیر میرسم» تبدیل میکند. صف کوتاه یک انفجار را جذب میکند؛ صف بلند فقط همه را دیر میکند و برای این کار حافظه هم مصرف میکند.
بدفهمی رایج: «صف بزرگتر یعنی خطای کمتر.» در اضافهبار پایدار هیچ صفی به اندازهٔ کافی بزرگ نیست؛ فقط خطاها را عقب میاندازد و آنها را به timeout تبدیل میکند که از رد کردن گرانتر است.
تعریف: عمق صف (Queue Depth) تعداد درخواستهای منتظر worker است و هزینهاش به زمان برابر است با عمق × زمان سرویس / تعداد worker. Google SRE: "if the queue size is 10x the number of threads, the time to handle the request on a thread is 100 milliseconds. If the queue is full, then a request will take 1.1 seconds to handle, most of which time is spent on the queue." توصیه: "small queue lengths relative to the thread pool size (e.g., 50% or less)"؛ Gmail "often uses queueless servers". صف بیسقف (Unbounded Queue) هیچ حدی ندارد، پس اضافهبار به رشد حافظه و در نهایت کشته شدن با OOM تبدیل میشود. Head-of-line blocking یعنی یک آیتم کند در جلوی صف FIFO همهٔ پشتسریها را معطل کند.
Workers 8, service 40 ms, arrivals 2,600/s vs capacity 200/s per server (one server shown)
1 t=0 queue 0 wait 0 ms
2 t=1 s queue 60 wait 300 ms (60 x 40 / 8)
3 t=5 s queue 300 wait 1.5 s client timeout 1 s: every request now times out
4 t=10 s queue 600 wait 3 s all work served is work nobody waits for
5 bounded queue of 4: wait at most 20 ms; the excess 60/s gets a 503 in under a millisecondسناریوی واقعی: صف Redis در Laravel که در یک قطعی به میلیونها job رسید و ساعتها طول میکشد خالی شود؛ انباشت GitHub از "over five million hook events and 80 thousand Pages builds"؛ سرویس Go که برای هر درخواست بیسقف goroutine میسازد؛ backlog شنود PHP-FPM (پیشفرض 511 در Linux) که درخواستها در kernel منتظر میمانند وقتی همهٔ childها مشغولاند.
چه چیزی سقف میگذارد:
| محصول | صف | سقف / تنظیم |
|---|---|---|
| PHP-FPM | childها و backlog سوکت | pm.max_children، listen.backlog (511 در Linux) |
| Envoy | درخواستهای معلق هر cluster | circuit breaker max_pending_requests |
| Go | goroutine و channel | channel بافردار یا semaphore بهعنوان پذیرش (Go) |
| صفهای Laravel | صف Redis/SQS/database | queue:monitor --max=100 با listener برای QueueBusy؛ pendingSize() |
| Linux | صف accept در TCP | backlog در listen()، net.core.somaxconn |
راهحل / نحوهٔ استفاده: به هر صفی سقف بدهید، اندازهاش را بر حسب زمانِ انفجاری که میخواهید جذب کنید بگذارید (زمان، نه تعداد)، در سقف با 503 سریع رد کنید و ریختن به سبک LIFO یا CoDel را در نظر بگیرید. Google SRE: "Changing the queuing method from the standard first-in, first-out (FIFO) to last-in, first-out (LIFO) or using the controlled delay (CoDel) algorithm ... can reduce load by removing requests that are unlikely to be worth processing."
تمام شدن منابع: CPU، حافظه و GC، thread، file descriptor، connection، ephemeral port حیاتی
به زبان ساده: هر درخواست تا وقتی اجرا میشود مقداری منبع نگه میدارد. وقتی درخواستها طولانیتر اجرا شوند، همزمان از همهچیز بیشتر نگه میدارند و هر منبعی که اول تمام شود همان قطعی میشود.
بدفهمی رایج: «روی CPU هشدار داریم، پس پیش از وقوع میبینیمش.» خیلی از آبشارها چیزی را تمام میکنند که نمودار CPU نشان نمیدهد: threadهایی که منتظر I/O هستند (CPU پایین میآید)، file descriptor، connectionهای pool، ephemeral port، شناسهٔ پردازه.
تعریف: Google SRE اثرها را فهرست میکند. CPU: درخواست در جریان بیشتر، صف بلند، گرسنگی thread، کشته شدن با watchdog، از دست رفتن deadline، افت کارایی cache. حافظه: مردن taskها، "Increased rate of garbage collection (GC) in Java, resulting in increased CPU usage"، افت hit rate. Thread: "Thread starvation can directly cause errors or lead to health check failures"؛ "In extreme cases, thread starvation can also cause you to run out of process IDs". File descriptor: "the inability to initialize network connections, which in turn can cause health checks to fail". این منابع به هم وابستهاند، پس "a service experiencing overload often has a host of secondary symptoms that can look like the root cause". اینها همان GC pressure، thread pool exhaustion، connection pool exhaustion، file descriptor exhaustion و ephemeral port exhaustion هستند.
| منبع | نشانهٔ تمام شدن (عین متن، جایی که استاندارد است) | ماشهٔ معمول | صفحهٔ مالک |
|---|---|---|---|
| CPU | همهٔ درخواستها کندتر، watchdogها فعال | ترکیب درخواست گران، backtracking در regex (Cloudflare 2019) | Latency Budgets |
| حافظه / GC pressure | کشته شدن با OOM، توقف GC، کوچک شدن cache | درخواست در جریان، صف بیسقف | همین صفحه |
| thread / worker | worker برای health check نمانده؛ در PHP-FPM server reached pm.max_children setting | وابستگی کند | همین صفحه |
| file descriptor | accept() با EMFILE ("Too many open files") شکست میخورد | نشت connection، سوکتهای کند زیاد، provision-service در Slack | Ports, Sockets & Connections |
| connectionهای pool | انتظار برای جای خالی pool؛ SQLSTATE 53300 too_many_connections در PostgreSQL | کوئری کند connection نگه میدارد | Connection Pooling |
| ephemeral port | connect() با EADDRNOTAVAIL ("Cannot assign requested address") شکست میخورد | ساختن و بستن مداوم connection بدون keep-alive، انباشت TIME_WAIT | Network Troubleshooting |
| سهمیهها | 429 در API، خطای سهمیهٔ ابر | ساختن انبوه ماشین (Slack به "an AWS quota limit" خورد) | Capacity Planning |
Google SRE's chain: which symptom is the root cause?
1 Java frontend has poorly tuned GC parameters
2 Under high (but expected) load, CPU runs out due to GC
3 Requests complete more slowly -> more in-flight requests -> more RAM in use
4 Less RAM left for the cache -> fewer entries, lower hit rate
5 More cache misses fall through to the backend
6 Backend runs out of CPU or threads
7 Health checks fail: the cascade starts (and the backend team is paged first)سناریوی واقعی: تمام شدن connection pool وقتی یک کوئری کند ۲۰ جای ۲۰ جای pool را نگه داشته؛ تمام شدن thread pool در لایهٔ Tomcat یا PHP-FPM پشت یک شریک کند؛ تمام شدن file descriptor وقتی کلاینتی سوکتها را به یک backend کند باز نگه میدارد؛ تمام شدن ephemeral port روی NAT gateway یا میزبانی که connectionهای کوتاهعمر بدون keep-alive میسازد.
راهحل / نحوهٔ استفاده: برای هر پردازه روی کار در جریان سقف بگذارید (admission control) تا هر منبع حد بالای مشخصی داشته باشد؛ connectionها را دوباره به کار ببرید (پیشفرض ۲ در MaxIdleConnsPerHost در Go تلهای کلاسیک است)؛ ulimit -n و سقف حافظهٔ container را آگاهانه تنظیم کنید؛ برای هر pool معیار saturation (در استفاده / ظرفیت) منتشر کنید.
Health check flapping و حذف ظرفیت حیاتی
به زبان ساده: سیستمی که قرار است شما را از سرورهای خراب محافظت کند سرورهای شلوغ را میبیند، خیال میکند خراباند و حذفشان میکند؛ پس بقیه شلوغتر میشوند و نوبت حذف آنها میرسد.
بدفهمی رایج: «health check عمیق که دیتابیس را هم چک کند صادقتر است.» وقتی دیتابیس کند است، همهٔ podهای وب با هم شکست میخورند و orchestrator کل ناوگان را restart میکند. چک کردن یک وابستگی مشترک در health check یک قطعهٔ کند را به ظرفیت صفر تبدیل میکند.
تعریف: Google SRE بررسی سلامت پردازه (process health checking؛ "is this binary responding at all?") را که به درد scheduler میخورد از بررسی سلامت سرویس (service health checking؛ "is this binary able to respond to this class of requests right now?") که به درد load balancer میخورد جدا میکند و از "a failure mode in which health-checking itself makes the service unhealthy" هشدار میدهد. نوسان health check (Health Check Flapping) یعنی سروری که چون خودِ چک به بار وابسته است مدام بین سالم و ناسالم جابهجا میشود. حذف ظرفیت (Capacity Removal) هر اقدام خودکار یا دستی است که ظرفیت سرویسدهی را بیرون میبرد (بیرون انداختن، کشتن، drain، کوچک کردن).
t Server 3 (busy, alive) Load balancer / scheduler
1 0 s queue wait 2.4 s; probe timeout 2 s probe 1 fails
2 1 s still serving real requests probe 2 fails
3 2 s probe 3 fails: kill and restart
4 2 s its 400 queued requests are lost their clients time out and retry elsewhere
5 7 s comes back, cold cache (3x slower) receives a full share at once
6 9 s queue wait 3 s probes fail again: the flapping loopسناریوی واقعی: liveness probe در Kubernetes که به endpointی اشاره میکند که از PostgreSQL کوئری میگیرد؛ Auto Scaling groupهای AWS که در قطعی یک وابستگی، instanceهایی را که health check ELB را رد میکنند جایگزین میکنند (Slack 2021: instanceها "marked unhealthy by our automation because they couldn't reach the backends that they depended on")؛ outlier detection در Envoy که بیشتر میزبانهای clusterی را که یکنواخت کند است بیرون میاندازد.
آنچه محصولات میدهند:
| محصول | محافظت در برابر حذف ظرفیت | عبارت مستندات |
|---|---|---|
| Envoy | panic threshold (پیشفرض ۵۰٪): وقتی میزبان سالم خیلی کم است بین همه پخش کن | "used to avoid a situation in which host failures cascade throughout the cluster as load increases" |
| Envoy | outlier_detection.max_ejection_percent | اگر از آستانه بالاتر باشد بیرون انداخته نمیشود |
| Kubernetes | livenessProbe، readinessProbe و startupProbe جدا | "The readiness and liveness probes do not depend on each other to succeed" |
| load balancerهای Slack | «panic mode» که "balances requests across all instances when many are failing health checks" | postmortem ۲۰۲۱ Slack |
| Laravel | route داخلی /up: پاسخ 200 "if the application has booted without exceptions" | رویداد DiagnosingHealth برای چکهای بیشتر |
| AWS ALB | slow start در target group (slow_start.duration_seconds) | افزایش خطی برای targetهایی که سالم میشوند |
راهحل / نحوهٔ استفاده: liveness فقط پردازه را چک کند (بدون وابستگی و بدون صف شدن پشت ترافیک: آن را روی مسیر یا listener جدا سرو کنید)؛ readiness فقط هنگام شروع یا drain شکست بخورد؛ saturation را در بدنهٔ پاسخ گزارش کنید بهجای شکست؛ برای بیرون انداختن سقف بگذارید؛ هرگز نگذارید health check چیزی باشد که ۵۰٪ آخر ناوگان را حذف میکند.
Thundering herd و cache stampede مهم
به زبان ساده: تعداد زیادی کلاینت در یک لحظه بیدار میشوند و یک چیز را میخواهند: بعد از restart، وقتی یک کلید cache منقضی میشود، یا وقتی یک وابستگی برمیگردد.
بدفهمی رایج: «cache فقط ما را سریعتر میکند؛ اگر نباشد فقط کندتر میشویم.» Google SRE بین latency cache (سرویس بدون آن زنده میماند) و capacity cache ("a service using a capacity cache cannot sustain its expected load under an empty cache") فرق میگذارد. بیشتر cacheهای جاافتاده بیصدا capacity cache میشوند.
تعریف: هجوم گله (Thundering Herd) انفجاری از درخواستهای همزمانِ کلاینتهای منتظر است؛ cache stampede (در فهرست Nygard: dogpile) حالت خاصی است که یک کلید منقضی یا سرد همهٔ خوانندهها را با هم به منبع اصلی میفرستد. گرم کردن cache (Cache Warming) یعنی پر کردن cache پیش از گرفتن ترافیک.
t Cache Database (capacity 2,000 QPS)
1 0 95% hit rate, 20,000 QPS 1,000 QPS of misses
2 10:00 cache cluster restarted 20,000 QPS: 10x capacity
3 10:00+ every miss is slow, so it holds a connection longer
4 10:01 pool exhausted; app threads wait; health checks fail; cascade
5 Fix: coalesce misses per key, serve stale while one request refreshes, ramp traffic to the new cacheسناریوی واقعی: failover در Redis که cache را خالی میکند؛ منقضی شدن کلید یک محصول پرطرفدار وسط حراج؛ کلاینتهای موبایل که بعد از یک لرزش شبکه با هم وصل میشوند؛ ۴ ژانویهٔ Slack: "client caches are cold"؛ هشدار کتاب SRE دربارهٔ "an externally triggered software update" که "might clear an offline client's cache".
راهحل / نحوهٔ استفاده: missهای همزمان را ادغام کنید (singleflight در Go، Cache::lock یا Cache::flexible در Laravel)، به TTL jitter بدهید، پنجرهٔ stale-while-revalidate نگه دارید، cache را پیش از readiness گرم کنید و گرههای cache را تدریجی برگردانید. الگوریتمها در Caching هستند.
Autoscaler lag و واقعیتهای مقیاسدهی مهم
به زبان ساده: autoscaling به چیزی واکنش نشان میدهد که قبلاً رخ داده، برای رساندن ظرفیت دقیقهها وقت لازم دارد و وقتی معیار دروغ بگوید ممکن است در جهت غلط مقیاس بدهد.
بدفهمی رایج: «autoscaling داریم، پس headroom لازم نیست.» instanceهای جدید باید boot شوند، تدارک ببینند، health check را رد نکنند و cache را گرم کنند؛ در این مدت قدیمیها جهش را حمل میکنند و خود سیستم تدارک هم زیر بار است.
تعریف: تأخیر autoscaler (Autoscaler Lag) فاصلهٔ شروع اضافهبار تا سرویسدهی واقعی ظرفیت جدید است. postmortem Slack دو واقعیت را همزمان نشان میدهد: سیگنال ممکن است وارونه شود ("threads were spending more time waiting, which caused CPU utilization to drop. This drop in CPU utilization initially triggered some automated downscaling") و افزایش مقیاس ممکن است دستگاه خودش را غرق کند ("provision-service hit two separate resource bottlenecks (the most significant one was the Linux open files limit, but we also exceeded an AWS quota limit)").
Slack, Jan 4 2021 (times PST, from the postmortem)
1 ~6:57 99% of messages sent successfully (normally above 99.999%)
2 7:00 hourly mini-peak + packet loss -> web tier saturated
3 7:0x CPU falls (threads wait on the network) -> autoscaler scales DOWN
4 7:01-7:15 thread utilisation rises -> attempt to add 1,200 servers
5 7:xx provision-service hits the open files limit and an AWS quota
6 8:15 provision-service back; 9:15 enough hosts to serve; 10:40 TGW capacity raised by AWSراهحل / نحوهٔ استفاده: برای لایههای I/O-محور روی saturation (utilisation workerها، سن صف) مقیاس بدهید نه فقط CPU؛ headroom ایستا به اندازهٔ از دست رفتن یک zone نگه دارید؛ خود مسیر مقیاسدهی را آزمون بار کنید؛ کوچک کردن خودکار را در حادثه خاموش کنید؛ برای رویدادهای شناختهشده پیشاپیش مقیاس بدهید (Slack: "request a preemptive upscaling of our TGWs at the end of the next holiday season"). ببینید Scaling Strategies.
بار همزمان: cron، TTL در DNS و leader thrash تکمیلی
به زبان ساده: کلاینتهای مستقل، چون یک ساعت، یک تایمر یا یک رویداد مشترک آنها را همخط کرده، در یک ثانیه یک کار را انجام میدهند.
بدفهمی رایج: «رسیدنهای تصادفی میانگین میشوند.» رسیدنها فقط تا وقتی تصادفیاند که چیزی همخطشان نکند: سر ساعت، یک TTL مشترک، یک restart، ارسال یک پیکربندی.
تعریف: Google SRE: اگر retryها "aren't randomly distributed over the retry window, a small perturbation (e.g., a network blip) can cause retry ripples to schedule at the same time, which can then amplify themselves" (با ارجاع به Floyd و Jacobson). گونهها: cron همزمان (Synchronized Cron؛ Slack: "mini-peaks at the top of each hour and half hour ... much of this is external — cronjobs from all over the world")، رکوردهای DNS با TTL یکسان که بعد از failover با هم منقضی میشوند، و leader thrash که در آن انتخاب رهبر زیر بار مدام رهبری را جابهجا میکند و هر جابهجایی اتصال دوباره و بازسازی cache میآورد (Leader Election).
Clients: 10,000, all with retry after exactly 1 s, network blip at t = 0
1 t=0.0 10,000 requests fail together
2 t=1.0 10,000 retries arrive in the same 10 ms
3 t=1.0 overload -> most fail again
4 t=2.0 10,000 retries again (the wave sustains itself)
5 full jitter: retries spread over 0-1 s, then 0-2 s: about 10 per ms instead of 1,000راهحل / نحوهٔ استفاده: به هر زمانبندی jitter بدهید (backoff، شروع cron، TTL، فاصلهٔ health check، تازهسازی cache)، شروع کلاینتها را تصادفی کنید، deploy و lease رهبر را پلکانی کنید و برای اوجهای شناختهشده پیشاپیش مقیاس بدهید. در شبیهساز health checkها برای هر سرور پلکانیاند؛ با این حال اجرای سادهلوحانه هر هشت ثانیه موج retry نشان میدهد، چون timeoutها، restartها و retryهای فوری با هم همخط میشوند.
ماشهها: query of death، rollout، drain، رشد طبیعی مهم
به زبان ساده: چیزی که سیستم آسیبپذیر را سرنگون میکند. معمولاً کوچک است، اغلب یک تغییر، گاهی فقط رشد.
بدفهمی رایج: «ماشه را پیدا کن، درستش کن، تمام.» ماشه زمانبندی را توضیح میدهد ولی حلقه اندازه را. هر دو اقدام لازم دارند.
تعریف: شرایط ماشه در Google SRE: مرگ پردازه (از جمله query of death، "an RPC whose contents trigger a failure in the process")، بهروزرسانی پردازه، rollout جدید، رشد طبیعی، تغییرات برنامهریزیشده، drain یا خاموش کردن، تغییر پروفایل درخواست، و سقف منابع (تکیه بر CPU اضافهٔ cluster مشترک "dangerous" است).
| ماشه | نمونهٔ عمومی | حلقهای که راه انداخت |
|---|---|---|
| فرمان اپراتور با ورودی اشتباه | AWS S3 2017: "a larger set of servers was removed than intended" | restart کامل زیرسیستمهای index و placement |
| ارسال سراسری پیکربندی | Cloudflare 2019: قانون WAF که از طریق Quicksilver "went global in seconds" | تمام شدن CPU روی همهٔ هستههای HTTP |
| قطعی شبکهٔ ۴۳ ثانیهای | GitHub 2018 | failover خودکار بین region و بعد انباشت replication |
| ترافیک فصلی + اشباع شبکهٔ ابر | Slack 2021 | بازخورد autoscaling و تدارک |
| خودکارسازی بر پایهٔ معیار غلط | Google 2020: سهمیه کم شد چون مصرف "incorrectly reported ... as 0" | رهبر Paxos نتوانست بنویسد؛ احراز هویت شکست خورد |
راهحل / نحوهٔ استفاده: هر تغییری، از جمله پیکربندی، را canary و مرحلهای کنید (WAF در Cloudflare فرایند مرحلهای DOG، PIG، Canary خودش را دور میزد "because of the need to respond rapidly to threats")؛ به ابزارهایی که ظرفیت حذف میکنند rate limit بدهید؛ change log نگه دارید تا "check for recent changes and consider reverting them" سریع باشد.
Deadline، انتشار deadline و لغو حیاتی
به زبان ساده: یک بار و در بالای پشته تصمیم بگیرید کاربر چقدر صبر میکند؛ زمان باقیمانده را به همهٔ لایههای پایین بدهید؛ و روی هر چیزی که وقتش تمام شده کار نکنید.
بدفهمی رایج: «timeout طولانی امنتر است چون درخواست کمتری شکست میخورد.» timeout طولانی کار محکوم به شکست را زنده نگه میدارد و منبع نگه میدارد؛ Google SRE: "Having deadlines several orders of magnitude longer than the mean request latency is usually bad."
تعریف: مهلت (Deadline) زمان مطلقی است که بعد از آن نتیجه بیارزش است. انتشار deadline (Deadline Propagation): "a deadline is set high in the stack (e.g., in the frontend). The tree of RPCs emanating from an initial request will all have the same absolute deadline." انتشار لغو (Cancellation Propagation) "fatal errors or timeouts up the stack" را میفرستد و RPCهای همسطح را لغو میکند. سرور باید پیش از هر مرحله deadline را چک کند: "you don't get credit for late assignments with RPCs." timeout (Timeout) حداکثر انتظار برای یک عملیات است و باید از deadline باقیمانده مشتق شود.
Without propagation (Google SRE) With propagation
1 A -> B, deadline 10 s A -> B, deadline 10 s
2 B starts after 8 s, calls C with 20 s B starts after 8 s, calls C with 2 s
3 C dequeues after 5 s, works "with 15 s left" C dequeues after 5 s: deadline passed, drops it
4 A gave up 3 s ago: C's work is wasted C's worker is free for a live requestچه چیزی فراهمش میکند:
| محصول | ابزار | بین hopها منتشر میشود؟ |
|---|---|---|
| gRPC | deadline، هدر grpc-timeout | بله، وقتی context ورودی دوباره استفاده شود |
| Go | context.WithTimeout، context.WithDeadline، context.AfterFunc؛ DeadlineExceeded | درون پردازه بله؛ روی HTTP باید هدر بگذارید (Go) |
| Laravel | Http::timeout() برای هر فراخوانی | نه؛ middleware این صفحه deadline_at را نگه میدارد |
| Envoy | timeout مسیر، per_try_timeout، x-envoy-expected-rq-timeout-ms | درون mesh |
| PostgreSQL | statement_timeout، transaction_timeout | برای هر session از برنامه تنظیم میشود |
راهحل / نحوهٔ استفاده: edge یک بودجه تعیین میکند؛ هر hop مقدار «باقیمانده منهای حاشیه» را میفرستد و آن را به نیاز callee محدود میکند؛ سرورها کار منقضی را پیش از شروع دور میریزند. سازوکار کامل (هدرها، gRPC، بودجهها) در Latency Budgets و Timeouts, Retries & Jitter است.
Retry budget و jitter حیاتی
به زبان ساده: retry را فقط به اندازهٔ کسری کوچک از ترافیک عادی اجازه بدهید و آنها را تصادفی پخش کنید تا با هم نرسند.
بدفهمی رایج: «backoff نمایی کافی است.» backoff بدون jitter کلاینتها را همزمان نگه میدارد (AWS: "there are still clusters of calls") و backoff برای هر درخواست هیچ اثری روی حجم کل retry یک میلیون درخواست ندارد.
تعریف: بودجهٔ retry (Retry Budget) تعداد retry را برای هر کلاینت یا پردازه محدود میکند: Google SRE از "a per-request retry budget of up to three attempts" و "a per-client retry budget ... A request will only be retried as long as this ratio is below 10%" استفاده میکند که رشد بدترین حالت را از "just below 3X" به "just 1.1x" میرساند. لرزش زمانی (Jitter) تأخیر را تصادفی میکند؛ Full Jitter در AWS برابر sleep = random_between(0, min(cap, base * 2 ** attempt)) است و از میان گونهها "Equal Jitter" "the loser" است.
Overloaded backend, every first attempt fails; client sends 1,000 requests/s
1 No limits, 3 retries: up to 4,000 attempts/s
2 Per-request cap only (3 tries): just below 3,000 attempts/s
3 + per-client budget 10%: about 1,100 attempts/s
4 Simulator, 30-60 s: naive 3.50x, naive + budget 1.08x, protected 1.01xراهحل / نحوهٔ استفاده: resilience.RetryBudget و resilience.FullJitter در Go؛ App\Support\RetryBudget همراه Http::retry در Laravel. budget برای هر وابستگی جدا، مشترک بین goroutineها یا workerهای PHP، و منتشرشده بهعنوان معیار (مجاز در برابر ردشده).
Load shedding، admission control، صف محدود و backpressure حیاتی
به زبان ساده: وقتی پر هستید، به بعضی درخواستها فوراً و ارزان «نه» بگویید تا به بقیه درست «بله» بگویید.
بدفهمی رایج: «رد کردن درخواست availability را پایین میآورد.» رد کردن ۲۰٪ یعنی ۸۰٪ سریع میمانند؛ پذیرفتن ۱۰۰٪ میتواند یعنی سرویس به ۰٪. AWS: "Load shedding lets a server maintain its goodput and complete as many requests as it can, even as offered throughput increases."
تعریف: ریختن بار (Load Shedding) یعنی دور ریختن مازاد بار وقتی سرور به اضافهبار نزدیک میشود؛ Google SRE: "return an HTTP 503 (service unavailable) to any incoming request when there are more than a given number of client requests in flight". کنترل پذیرش (Admission Control) نقطهٔ تصمیم است (سقف کار در جریان، token bucket، آستانهٔ utilisation). فشار معکوس (Backpressure) پیام «آهستهتر» را بهجای بافر کردن به بالادست منتقل میکند (channel محدود، پنجرهٔ TCP، lag مصرفکننده در Kafka، flow control در RabbitMQ). throttling سمت کلاینت (Client-Side Throttling؛ adaptive throttling در Google) به کلاینت اجازه میدهد وقتی در دو دقیقهٔ اخیر requests از K برابر accepts بیشتر شد، محلی رد کند.
Simulator, spike 2,600/s against 2,000/s capacity (per second)
1 Naive: accepts all 2,600 -> queue grows -> 1,955, 1,838 ... 765, 0 good
2 Protected: about 2,860 attempts, about 870 shed with a fast 503, about 1,990 good
3 After the spike: protected 1,400 good from the first second; naive never recoversچه چیزی فراهمش میکند:
| محصول | سازوکار |
|---|---|
| Envoy | circuit breakerها (max_connections، max_pending_requests، max_requests، max_retries)؛ شمارندههای overflow |
| NGINX | limit_req، limit_conn؛ max_conns برای هر سرور upstream |
| HAProxy | maxconn برای frontend و سرور با صف و timeout queue |
| Kafka | مدل pull مصرفکننده، max.poll.records؛ backpressure همان lag مصرفکننده است |
| Go | پذیرش با semaphore یا channel بافردار (Go) |
| Laravel | rate limiter throttle، middleware ریختن بر اساس زمان صف، middleware RateLimited برای job |
راهحل / نحوهٔ استفاده: برای اضافهبار سراسری در edge و برای اضافهبار محلی در هر پردازه بریزید؛ مسیر رد کردن تقریباً هیچ هزینهای نداشته باشد (بدون log برای هر رد، بدون فراخوانی دیتابیس)؛ بر اساس criticality اولویت بدهید. الگوریتمها در Load Shedding و Rate Limiting؛ flow control سمت broker در Backpressure & Flow Control.
Circuit breaker، bulkhead، جداسازی وابستگی و fail fast مهم
به زبان ساده: نگذارید یک وابستگی بد همهچیز را مصرف کند: سهم ثابتی از thread و connection به آن بدهید (bulkhead)، وقتی آشکارا شکست میخورد صدایش نزنید (circuit breaker)، و بهجای انتظار سریع «نه» بگویید (fail fast).
بدفهمی رایج: «circuit breaker بهتنهایی آبشار را حل میکند.» فراخوانی یک وابستگی را قطع میکند، ولی AWS هشدار میدهد breakerها "introduce modal behavior into systems that can be difficult to test, and can introduce significant addition time to recovery"؛ AWS token bucket محلی برای retry را ترجیح میدهد. breaker بیشتر برای وابستگیهایی مفید است که سخت شکست میخورند؛ bulkhead برای آنهایی که کند شکست میخورند.
تعریف: جداسازی وابستگی (Dependency Isolation) یعنی شکست یک وابستگی نتواند منابع مشترک را تمام کند. bulkhead منابع را تقسیم میکند (pool برای هر وابستگی، هر tenant، هر criticality)؛ Google SRE برای عدالت پیشنهاد میکند "25% of your threads" برای هر کلاینت. circuit breaker شکستها را دنبال میکند و وقتی باز است فراخوانیها را کوتاه میکند. شکست سریع (Fail Fast): "if a backend is unavailable, it's usually best to immediately return an error for that backend, rather than consuming resources until the backend is available." و «همیشه در پشته پایین بروید»: از فراخوانی درونلایهای که میتواند بنبست توزیعشده بسازد پرهیز کنید.
Product page calls: inventory (critical), recommendations (optional), reviews (optional)
1 Shared pool of 200 threads, recommendations hangs: all 200 wait -> page down
2 Bulkheads: inventory 120, recommendations 40, reviews 40
3 Recommendations hangs: its 40 are busy, its calls fail fast; page renders without it
4 Breaker opens after N failures: calls skipped for 30 s, then a probe requestراهحل / نحوهٔ استفاده: channel Bulkhead در resilience.Client؛ circuit breakerهای Envoy برای هر cluster؛ middleware ThrottlesExceptions در Laravel بهعنوان breaker برای کارهای صف. الگوها بهتفصیل: Circuit Breaker، Bulkheads & Graceful Degradation.
Graceful degradation و criticality مهم
به زبان ساده: وقتی ظرفیت کم است برای هر درخواست کار کمتری بکنید (قابلیت کمتر، پاسخ cache شده، رتبهبندی ارزانتر) و اول درخواستهایی را بریزید که کمترین اهمیت را دارند.
بدفهمی رایج: «حالت تنزلیافته چیز خوبی است که بعداً اضافه میکنیم.» باید ساخته و تمرین شود: "the code path you never use is the code path that (often) doesn't work."
تعریف: تنزل آبرومندانه (Graceful Degradation) در Google SRE: "Graceful degradation takes the concept of load shedding one step further by reducing the amount of work that needs to be performed." اهمیت درخواست (Criticality) برچسبی است (Google از CRITICAL_PLUS، CRITICAL، SHEDDABLE_PLUS، SHEDDABLE استفاده میکند) که خودکار به فراخوانیهای پاییندست منتقل میشود تا backend پرمشغله اول criticalityهای پایینتر را رد کند.
Capacity Product page behaviour
1 100% full page: stock, price, reviews, recommendations, images
2 80% recommendations from a precomputed list; reviews cached
3 60% no reviews, no recommendations; stock "estimate" from the last good value
4 40% static page from CDN, checkout only for logged-in users with a cartراهحل / نحوهٔ استفاده: برای هر قابلیت معلوم کنید «تنزلیافته» یعنی چه، کلیدی بگذارید که سریع عوض شود و دیر بشکند، و مرتباً بخش کوچکی از سرورها را نزدیک اضافهبار اجرا کنید تا این مسیر زنده بماند. مثال Go نسخهٔ کهنه را با X-Degraded سرو میکند؛ مثال Laravel stock_is_estimate برمیگرداند. الگوها در Bulkheads & Graceful Degradation.
Headroom ظرفیت و آزمون بار تا زانو مهم
به زبان ساده: آنقدر ظرفیت اضافه نگه دارید که در اوج بتوانید بزرگترین دامنهٔ خرابیتان را از دست بدهید، و (با آزمون، نه امید) بدانید سیستم کجا میشکند و بعد از آن نقطه چه رفتاری دارد.
بدفهمی رایج: «برنامهریزی ظرفیت جلوی آبشار را میگیرد.» Google SRE: این کار "reduces the probability of triggering a cascading failure, but it is not sufficient to protect the service from cascading failures."
تعریف: فضای اضافه (Headroom) ظرفیت منهای بار اوج است. مثال Google SRE: نقطهٔ شکست ۵٬۰۰۰ QPS برای هر cluster، اوج ۱۹٬۰۰۰ QPS، "approximately six clusters are needed to run the service at N + 2". آزمون بار تا زانو بار را بالا میبرد تا goodput دیگر همراهش نرود و بعد ادامه میدهد: "Load test components until they break"، هر دو الگوی "both gradual and impulse load patterns" را آزمون کنید و برگشت به حالت عادی را هم ("If a couple of servers crash under heavy load, how much does the load need to drop in order for the system to stabilize?").
Peak 19,000 QPS, break point 5,000 QPS per cluster
1 N = 4 clusters: 20,000 capacity, 95% utilisation, one cluster loss = 15,000 -> cascade
2 N + 1 = 5: one loss leaves 20,000 -> survives, barely
3 N + 2 = 6: one loss during maintenance of another leaves 20,000 -> survives
4 Load test result to look for: goodput flat at the knee (AWS), not a cliffراهحل / نحوهٔ استفاده: شکل آزمایشگاه را روی staging و بخش کوچکی از production اجرا کنید (Google SRE فهرست میکند: "Reducing task counts quickly or slowly"، "Rapidly losing a cluster's worth of capacity"، "Blackholing various backends")؛ backendهای غیرحیاتیای را که هرگز پاسخ نمیدهند آزمون کنید؛ روش ظرفیت در Capacity Estimation و Capacity Planning؛ تزریق خطا در Chaos Engineering.
درخواست hedged و محدودیتهایش تکمیلی
به زبان ساده: نسخهٔ دومی از یک درخواست کند را به replica دیگر بفرستید و هر کدام زودتر جواب داد را بردارید. برای دُم تأخیر در ناوگان سالم خوب است؛ در ناوگان پرمشغله خطرناک.
بدفهمی رایج: «hedging ما را مقاومتر میکند.» بار اضافه میکند. وقتی کل ناوگان به خاطر اضافهبار کند است، hedgeها همان retry با اسم دیگرند.
تعریف: درخواست hedged (Hedged Request) نسخهٔ تکراریای است که بعد از یک تأخیر (حدود p95) فرستاده میشود؛ Google SRE یادآوری میکند که به انتشار لغو نیاز دارد تا بازندهها متوقف شوند. فقط با بودجهٔ بار (مثلاً ۵٪ اضافه) و فقط برای خواندن idempotent امن است؛ وقتی saturation بالاست خاموشش کنید.
Healthy fleet, one slow replica Overloaded fleet
1 p95 delay passes, hedge to replica B p95 delay passes, hedge to replica B
2 B answers in 10 ms, A cancelled B is also saturated; now two copies queue
3 tail latency improves, load +2% load +100% on the slowest requests: amplificationراهحل / نحوهٔ استفاده: hedgeها را با token bucket محدود کنید، وقتی retry budget تمام شد خاموششان کنید و بازندهها را لغو کنید. جزئیات در Latency Budgets.
تشخیص: four golden signals، saturation، مصرف latency SLO، نسبت خطا حیاتی
به زبان ساده: ببینید چقدر کند، چقدر زیاد، چند شکست و چقدر پر؛ «پر» همان است که پیش از قرمز شدن بقیه هشدار میدهد.
بدفهمی رایج: «نرخ خطا اولین سیگنال است.» در آبشار، تأخیر و saturation اول تکان میخورند؛ خطاها وقتی میرسند که deadlineها شروع به انقضا کردهاند و تا آن موقع حلقه دارد بسته میشود.
تعریف: Google SRE: "The four golden signals of monitoring are latency, traffic, errors, and saturation." تأخیر خطاها را جدا دنبال کنید ("a slow error is even worse than a fast error"). اشباع (Saturation): "Latency increases are often a leading indicator of saturation. Measuring your 99th percentile response time over some small window (e.g., one minute) can give a very early signal of saturation." مصرف latency SLO (Latency SLO Burn) سرعتی است که درخواستهای کند بودجهٔ خطا را مصرف میکنند (SLAs, SLOs, SLIs & Error Budgets)؛ نسبت خطا (Error Ratio) برابر خطا تقسیم بر درخواست است (و retry تقسیم بر درخواست، که آشکارساز retry storm است).
| سیگنال | معیار | معنا در آبشار |
|---|---|---|
| Latency | p99 هر route، جدا برای خطاها | صف شدن شروع شده |
| Traffic | درخواست در ثانیه، و تلاش در ثانیه در برابر تلاش اول در ثانیه | تقویت retry بالای حدود 1.1 هشدار است |
| Errors | نسبت 5xx، نسبت 503 ریختهشده، timeoutها | deadlineها منقضی میشوند؛ shedding فعال شده |
| Saturation | در جریان / سقف، عمق و سن صف، مصرف pool، تعداد FD، زمان GC | ورودی حلقه، پیش از خطاها |
| Capacity | میزبانهای سالم، بیروناندازی، restart، CrashLoopBackOff | حذف ظرفیت در جریان است |
Typical order in a cascade (watch for it on dashboards)
1 saturation: queue age 0.1 s -> 2 s
2 latency: p99 300 ms -> 5 s
3 traffic: attempts/s 1.0x -> 3x first attempts (retries)
4 errors: timeouts, then 5xx; shed 503s if protected
5 capacity: health-check failures, restarts, ejectionsراهحل / نحوهٔ استفاده: روی سرعت مصرف SLO و روی saturation هشدار بگذارید، ردهای retry budget و شمار ریختهشدهها را منتشر کنید و مانیتورینگ را مستقل از سیستمی که میپاید نگه دارید (داشبوردهای Slack به همان Transit Gatewayها وابسته بودند؛ داشبورد وضعیت AWS به S3). ببینید Observability و Alerting That Works.
بازیابی: ریختن بار، کم کردن retry، مقیاس، restart با slow start، بستن در edge حیاتی
به زبان ساده: اول حلقه را متوقف کنید، بعد ماشه را درست کنید، بعد ترافیک را آرام برگردانید. اگر ترتیب غلط باشد آبشار دوباره راه میافتد.
بدفهمی رایج: «همه را restart کن.» restart همزمان یعنی thundering herd on restart: همهٔ سرورها در یک لحظه سرد برمیگردند و کل ترافیک را میگیرند. در شبیهساز، برگرداندن ۱۰۰٪ ترافیک بهیکباره بعد از ریختن، سیستم را دوباره فروریخت (goodput 8.1% و بعد 4.9%).
تعریف: قدمهای فوری Google SRE: افزایش منابع (در مارپیچ مرگ ممکن است کافی نباشد)، توقف شکست و مرگ با health check، restart سرورها (فقط برای مارپیچ GC، بنبست، درخواستهای بدون deadline؛ "Canary this change, and make it slowly")، ریختن ترافیک ("Reducing load enough so that the crashing stops ... Gradually ramping up the load")، ورود به حالت تنزلیافته، حذف بار دستهای، حذف ترافیک بد. شروع آهسته (Slow Start) به load balancer اجازه میدهد ترافیک را به میزبانهای تازهسالم تدریجی برساند (AWS ALB: "linearly increases the number of requests"؛ slow start mode در Envoy). بازیابی تدریجی (Gradual Recovery) کل این شیب است، از جمله کار انباشته.
Simulator: naive system collapsed; one action at 40 s (goodput by window)
1 do nothing 30-40 s 4.6% 40-50 s 9.0% 50-70 s 5.4% 70-90 s 6.7%
2 scale out +50% (5 cold servers) 4.6% 15.2% 8.2% 7.9%
3 edge 10% for 10 s, ramp over 20 s 4.6% 4.8% 54.6% 100.0%
4 edge 10% for 10 s, then 100% 4.6% 4.8% 8.1% 4.9%سناریوی واقعی: global terminate در WAF کلادفلر و بعد فعال کردن دوباره پس از آزمون "in a single city using a subset of traffic"؛ متوقف کردن webhook و ساخت Pages در GitHub و بعد پردازش انباشت با پاییدن بار شرکا (و کشف payloadهای منقضیشده با TTL)؛ سرویسهای Google Workspace با "a traffic spike following initial recovery".
راهحل / نحوهٔ استفاده: ترتیب دستورالعمل در حل مسئلههای کلاسیک آمده است. قانونهای بستن در edge را آماده نگه دارید (Cloudflare، AWS WAF، limit_req در NGINX)، کلیدی برای خاموش کردن retry و کار دستهای داشته باشید و slow start را روی load balancerها پیکربندی کنید.
Postmortem: بیسرزنش و متمرکز بر حلقهها مهم
به زبان ساده: بعد از حادثه بنویسید چه شد و چرا سیستم اجازه داد بزرگ شود، بدون مقصر دانستن کسی که دکمه را زد.
بدفهمی رایج: «علت ریشهای: خطای انسانی.» در هر مطالعهٔ موردی پایین، یک نفر یا یک ابزار اشتباه کوچکی کرد؛ اندازهٔ قطعی برابر اندازهٔ حلقههایی بود که سیستم داشت.
تعریف: Google SRE دربارهٔ postmortem بیسرزنش (Blameless Postmortem): "For a postmortem to be truly blameless, it must focus on identifying the contributing causes of the incident without indicting any individual or team for bad or inappropriate behavior." postmortem ۲۰۱۹ کلادفلر الگوست: "Getting to a single root cause, while satisfying, may obscure the reality" و بعد فهرست آسیبپذیریهایی که همگرا شدند.
Postmortem sections that matter for cascades
1 Trigger and timeline (with times from the incident channel)
2 Sustaining effect: which loop kept it down, and how long after the trigger
3 Detection: which signal moved first, which alert fired, how late
4 Recovery: what broke the loop, what re-triggered it
5 Action items per loop: breaker, test, alert, runbookراهحل / نحوهٔ استفاده: قالبی با بخش «حلقههای بازخورد»؛ اقدامهایی که شامل آزمون بار فراتر از زانو باشند؛ فرایند در Secure SDLC & Incident Response.
مطالعههای موردی از postmortemهای عمومی
فقط آنچه در postmortem خود شرکتها آمده بهعنوان واقعیت گفته شده است؛ هر چیز دیگر با برچسب استنباط (inference) آمده است.
AWS S3، us-east-1، ۲۸ فوریهٔ ۲۰۱۷ (S3 2017)
| جنبه | از گزارش AWS |
|---|---|
| ماشه | ساعت 9:37AM PST فرمانی "intended to remove a small number of servers" برای زیرسیستم billing؛ "one of the inputs to the command was entered incorrectly and a larger set of servers was removed than intended" |
| چه چیزی به آن وابسته بود | زیرسیستم index ("necessary to serve all GET, LIST, PUT, and DELETE requests") و زیرسیستم placement |
| تقویتکننده | "Removing a significant portion of the capacity caused each of these systems to require a full restart"؛ "we have not completely restarted the index subsystem or the placement subsystem in our larger regions for many years" |
| شعاع انفجار | کنسول S3، راهاندازی instance جدید EC2، volumeهای EBS نیازمند snapshot از S3، AWS Lambda؛ Service Health Dashboard بهروز نمیشد "because of a dependency the SHD administration console has on Amazon S3" |
| بازیابی | GET، LIST، DELETE از 12:26PM؛ کامل در 1:18PM؛ PUT در 1:54PM؛ سرویسهای دیگر "accumulated a backlog of work" |
| اصلاحها | ابزار ظرفیت را "more slowly" حذف میکند با "safeguards to prevent capacity from being removed when it will take any subsystem below its minimum required capacity level"؛ بازیابی سریعتر با «cell»ها |
حلقه در این صفحه: حذف ظرفیت و restart سرد و کند (مارپیچ مرگ). استنباط: بازیابی چندساعته هزینهٔ مسیر restartی بود که در آن مقیاس تمرین نشده بود؛ دقیقاً چیزی که آزمون بار "until failure and beyond" تمرینش میدهد.
Cloudflare، ۲ ژوئیهٔ ۲۰۱۹ (Cloudflare 2019)
| جنبه | از postmortem کلادفلر |
|---|---|
| ماشه | ساعت 13:42 تغییری در WAF Managed Rules برای تشخیص XSS؛ یک عبارت باقاعده "that backtracked enormously and exhausted CPU used for HTTP/HTTPS serving" |
| چرا سراسری بود | قانونها با Quicksilver منتشر میشوند که "can push changes globally in seconds"؛ قانون در حالت "simulate" بود ولی "the rules actually need to execute" |
| قطعکنندهٔ غایب | "A protection that would have helped prevent excessive CPU use by a regular expression was removed by mistake during a refactoring of the WAF weeks prior" |
| اثر بر کاربر | خطای 502 از سرورهای خط اول که "unable to reach the processes that serve HTTP/HTTPS traffic"؛ قطعی ۲۷ دقیقه |
| بازیابی | خاموش کردن سراسری WAF در 14:07؛ ترافیک و CPU عادی در 14:09؛ کُند شد چون "with our Access service down we couldn't authenticate to our internal control panel" |
| اصلاحها | برگرداندن محافظت CPU، بازبینی همهٔ ۳٬۸۶۸ قانون، رفتن به re2 یا موتور regex زبان Rust "which both have run-time guarantees" |
حلقه در این صفحه: تمام شدن CPU بدون deadline برای یک عملیات، بهعلاوهٔ مسیر بازیابیای که به سیستم در حال شکست وابسته بود. استنباط: بودجهٔ CPU برای هر درخواست معادل deadline برای regex است.
GitHub، ۲۱ اکتبر ۲۰۱۸ (GitHub 2018)
| جنبه | از post-incident analysis گیتهاب |
|---|---|
| ماشه | ساعت 22:52 UTC نگهداری تجهیزات نوری اتصال hub ساحل شرقی به مرکز داده را قطع کرد؛ "restored in 43 seconds" |
| خودکارسازی | Orchestrator (روی Raft) clusterها را به US West Coast منتقل کرد؛ بعد "we were unable to fail the primary back over to the US East Coast data center safely" |
| تقویتکننده | تأخیر بینقارهای برای نوشتن؛ replicaها "multiple hours delayed"؛ جبران replication "adhered to a power decay function instead of a linear trajectory" چون کاربران بیدار شدند |
| تنزل آگاهانه | "pausing webhook delivery and GitHub Pages builds"؛ "prioritize data integrity over site usability and time to recovery" |
| بازیابی انباشت | "over five million hook events and 80 thousand Pages builds queued"؛ "~200,000 webhook payloads that had outlived an internal TTL and were dropped" |
| مدت و اصلاحها | "24 hours and 11 minutes of service degradation"؛ پیکربندی Orchestrator "to prevent the promotion of database primaries across regional boundaries" |
حلقه در این صفحه: خودکارسازیای که ظرفیت را جابهجا کرد (حذف ظرفیت) و بازیابی تدریجی یک انباشت. استنباط: مرحلهٔ انباشت خطر اضافهبار دوم و کوچکتری است؛ GitHub صراحتاً آن را در برابر "potentially overloading our ecosystem partners with notifications" سنجید.
Slack، ۴ ژانویهٔ ۲۰۲۱ (Slack 2021)
| جنبه | از postmortem اسلک |
|---|---|
| ماشه | "one of our Transit Gateways became overloaded"؛ اولین روز کاری سال، "client caches are cold" |
| اشباع | اوج کوچک ساعت ۷ صبح PST بهعلاوهٔ packet loss "led to saturation of our web tier" |
| خودکارسازی در جهت غلط | instanceها "marked unhealthy" چون به backendها نمیرسیدند؛ CPU افتاد و "triggered some automated downscaling"؛ بعد تلاش "to add 1,200 servers" بین 7:01 و 7:15 صبح PST |
| تمام شدن منابع خود scaler | provision-service به "the Linux open files limit" و "an AWS quota limit" خورد؛ instanceهای خراب به "autoscaling-group size limits" رسیدند |
| چه کمک کرد | «panic mode» در load balancerها بهعلاوهٔ "retries and circuit breaking"؛ تا 9:15 صبح PST "degraded, not down" |
| اصلاحها | AWS ظرفیت TGW را دستی بالا برد (تا 10:40 صبح PST)؛ مانیتورینگ به همان VPC دیتابیسش منتقل شد؛ آزمون بار provision-service؛ افزایش پیشاپیش TGW بعد از تعطیلات |
حلقه در این صفحه: autoscaler lag، health check flapping، تمام شدن file descriptor و وابستگی مانیتورینگ به قطعهٔ در حال شکست (تشخیص).
Google، ۱۴ دسامبر ۲۰۲۰ (Google 2020، حادثهٔ 20013)
| جنبه | از گزارش حادثهٔ Google Cloud |
|---|---|
| ماشه | مهاجرت سهمیه بخشهایی از سیستم قدیم را باقی گذاشت که "incorrectly reported the usage for the User ID Service as 0"؛ بعد از یک دورهٔ مهلت، خودکارسازی سهمیهاش را کم کرد |
| سازوکار | "the quota for the account database was reduced, which prevented the Paxos leader from writing. Shortly after, the majority of read operations became outdated which resulted in errors on authentication lookups" |
| چک ایمنی غایب | چکهای موجود "did not cover the scenario of zero reported load for a single service" |
| اثر | ۴۷ دقیقه؛ "credential issuance and account metadata lookups for all Google user accounts failed"؛ "5xx errors on virtually all authenticated traffic" |
| دنبالهٔ بازیابی | Calendar و Workspace Admin "served errors up to 05:21 due to a traffic spike following initial recovery"؛ خطاهای Gmail "due to caching of errors from identity services" |
| اصلاحها | "prevent fast implementation of global changes"؛ "Improve resilience of GCP Services to more strictly limit the impact to the data plane during User ID Service failures" |
حلقه در این صفحه: یک وابستگی مشترک (جداسازی وابستگی) بهعلاوهٔ هجوم گله در بازیابی. استنباط: cache کردن خطاهای یک وابستگی قطعی را بعد از سالم شدن آن وابستگی طولانی کرد؛ وارونهٔ fallback از نوع stale-while-revalidate.
سازوکار (Mechanics)
حساب یک آبشار
| کمیت | فرمول | مثال |
|---|---|---|
| workerهای مشغول (Little's law) | نرخ رسیدن × زمان در سیستم | 1,000 QPS × 0.1 s = 100 thread (Google SRE) |
| workerهای لازم وقتی سهمی گیر میکند | نرخ × (سهم × deadline + (1 − سهم) × تأخیر) | 1,000 × (0.05 × 100 + 0.95 × 0.1) = 5,095 |
| سهم سرویسگرفته با W worker | W / workerهای لازم | 1,000 / 5,095 = 19.6% |
| تأخیر صف | عمق صف × زمان سرویس / تعداد worker | 80 × 100 ms / 8 = 1 s |
| تقویت retry، k لایه، a تلاش در هر لایه | a^k | 4^3 = 64؛ 3^5 = 243 |
| سربار retry با budget | 1 + نسبت | 1.1x با budget دهدرصدی |
| بار قابلتحمل برای بازیابی بعد از فروپاشی | بار عادی × سهم سالم | 10,000 QPS با ۱۰٪ سالم: حدود 1,000 QPS (Google SRE) |
| headroom برای N + 2 | ceil(اوج / نقطهٔ شکست) + 2 | ceil(19,000 / 5,000) + 2 = 6 cluster |
تنظیمهایی که تعیین میکنند حلقه بسته شود یا نه
| محصول | تنظیم | پیشفرض / نکته | حلقهای که کنترل میکند |
|---|---|---|---|
net/http در Go | Client.Timeout، Transport.ResponseHeaderTimeout، timeout در DialContext | 0 = هیچ | وابستگی کند |
net/http در Go | Transport.MaxConnsPerHost، MaxIdleConnsPerHost | 0 = بیحد؛ پیشفرض idle برابر 2 | تمام شدن connection و port |
net/http در Go | Server.ReadHeaderTimeout، ReadTimeout، WriteTimeout، IdleTimeout | 0 = هیچ | کلاینت کند goroutine نگه میدارد |
| HTTP client در Laravel | timeout()، connectTimeout()، retry() | ۳۰ و ۱۰ ثانیه | وابستگی کند، retry |
| worker صف Laravel | --timeout، --memory، --max-jobs، --max-time، --tries، retry_after | timeout شصت ثانیه؛ memory برابر 128 MB؛ timeout کمتر از retry_after | job گیرکرده، نشت حافظه، پردازش دوباره |
| Laravel Octane | --workers، --task-workers، --max-requests | یک worker برای هر هستهٔ CPU؛ restart بعد از ۵۰۰ درخواست | نشت حافظه، تمام شدن worker |
| PHP-FPM | pm.max_children، listen.backlog، request_terminate_timeout | backlog برابر 511 در Linux؛ terminate برابر 0 (خاموش) | تمام شدن worker، صف شدن |
| NGINX | proxy_connect_timeout، proxy_read_timeout، proxy_next_upstream_tries | 60s، 60s، 0 (بیحد) | upstream کند، retry در proxy |
| Envoy | circuit breakerها: max_connections، max_pending_requests، max_requests، max_retries | "modest default values, e.g. 1024 connections" | pool، صف، retry |
| Envoy | panic threshold، max_ejection_percent، slow start | panic برابر ۵۰٪ | حذف ظرفیت، میزبان سرد |
| gRPC | retryPolicy.maxAttempts، retryThrottling.maxTokens/tokenRatio، deadline | مثال: ۱۰ token، نسبت 0.1 | retry storm |
| Kubernetes | livenessProbe، readinessProbe، startupProbe، timeoutSeconds | timeout برابر 1s | کشتن با health check |
| AWS ALB | slow_start.duration_seconds، آستانههای health check | slow start بهصورت پیشفرض خاموش | میزبان سرد بعد از بازیابی |
| PostgreSQL | statement_timeout، lock_timeout، idle_in_transaction_session_timeout، transaction_timeout، max_connections | timeoutها 0 = غیرفعال | کوئری کند جای pool را نگه میدارد |
| Linux | ulimit -n، net.ipv4.ip_local_port_range، net.core.somaxconn | پیشفرض توزیع | تمام شدن FD، port، backlog |
پیامهای خطایی که واقعاً میبینید
| منبع | پیام / کد | معنا در آبشار |
|---|---|---|
| Go | context deadline exceeded (context.DeadlineExceeded) | deadline منقضی شد؛ اگر deadline فراخوان بوده retry نکنید |
| Laravel | Illuminate\Http\Client\ConnectionException (cURL error 28) | timeout() یا connectTimeout() رد شد |
| HTTP | 503 Service Unavailable با Retry-After | ریختن عمدی: عقب بکشید |
| HTTP | 429 Too Many Requests | rate limit: در این لایه retry نکنید |
| NGINX | upstream timed out (110: Connection timed out) while reading response header from upstream | به proxy_read_timeout رسید؛ upstream کند |
| NGINX | 502 Bad Gateway | upstream رد یا reset کرد (کاربران Cloudflare 2019 خطای 502 دیدند) |
| PHP-FPM | server reached pm.max_children setting | تمام شدن worker؛ درخواستها حالا در backlog منتظرند |
| Linux | EMFILE "Too many open files"؛ EADDRNOTAVAIL "Cannot assign requested address" | تمام شدن FD؛ تمام شدن ephemeral port |
| PostgreSQL | SQLSTATE 53300 too_many_connections ("sorry, too many clients already") | تمام شدن connection |
| PostgreSQL | SQLSTATE 57014 query_canceled ("canceling statement due to statement timeout") | deadline سمت دیتابیس کار کرد |
| Envoy | شمارندههای upstream_rq_pending_overflow، upstream_rq_retry_overflow، upstream_cx_overflow | circuit breakerها در حال ریختن |
| Kubernetes | Liveness probe failed، CrashLoopBackOff | حذف ظرفیت توسط kubelet |
Go
ماژول academy/cascading-failures فقط از کتابخانهٔ استاندارد استفاده میکند. resilience دفاعها را دارد؛ spiral شبیهساز است؛ cmd/spiral جدولهای همین صفحه را چاپ میکند؛ before و after یک سرویس پیش و پس از اصلاحاند.
Before
حلقهٔ retry سادهلوحانهٔ کتاب SRE به شکل net/http: http.DefaultClient بدون timeout، ده retry فوری، بدون admission control، یک health check عمیق و سروری بدون timeout.
// Command before is the service most cascades start from. Every line is
// common and looks harmless; together they build the death spiral.
package main
import (
"io"
"log"
"net/http"
)
const inventory = "http://inventory.internal/stock" // documentation host
func fetchStock() ([]byte, error) {
var lastErr error
// "Try up to 10 times": the Google SRE book's naive retry example.
// No backoff, no jitter, no budget: an overloaded inventory service
// receives up to 10x the traffic exactly when it can serve the least.
for attempt := 0; attempt < 10; attempt++ {
// http.Get uses http.DefaultClient: no timeout at all. A slow
// inventory pins this goroutine, its socket and its memory forever.
resp, err := http.Get(inventory)
if err != nil {
lastErr = err
continue
}
body, err := io.ReadAll(resp.Body)
resp.Body.Close()
if err == nil && resp.StatusCode == http.StatusOK {
return body, nil
}
lastErr = err
}
return nil, lastErr
}
func main() {
// No admission control: net/http starts one goroutine per connection,
// so the only queue is memory, and it is unbounded.
http.HandleFunc("/product", func(w http.ResponseWriter, r *http.Request) {
stock, err := fetchStock() // ignores r.Context(): no deadline propagation
if err != nil {
http.Error(w, "inventory down", http.StatusInternalServerError) // 500: clients retry
return
}
_, _ = w.Write(stock)
})
// A "deep" health check: if inventory is slow, every product pod fails
// its liveness probe, Kubernetes restarts them all, and capacity
// disappears exactly when load is highest.
http.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
if _, err := fetchStock(); err != nil {
w.WriteHeader(http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusOK)
})
// http.ListenAndServe: no ReadHeaderTimeout, no WriteTimeout, no IdleTimeout.
log.Fatal(http.ListenAndServe(":8080", nil))
}After
Retry budget (token bucket: هر درخواست 0.1 واریز میکند و هر retry یک واحد برمیدارد) و full jitter:
// Package resilience holds the small building blocks that stop a cascade:
// a retry budget, jittered backoff, deadline propagation, admission control
// (bounded concurrency + bounded queue + load shedding) and health endpoints
// that report saturation without removing capacity.
package resilience
import "sync"
// RetryBudget is a token bucket that caps retries to a fraction of first
// attempts, the shape of gRPC retryThrottling (maxTokens, tokenRatio), the
// AWS SDK retry quota and Google SRE's "per-client retry budget" (10%).
//
// Every first attempt deposits Ratio tokens; every retry withdraws one.
// When the bucket is empty, the caller fails instead of retrying, so the
// extra load created by retries can never exceed about Ratio of the traffic.
type RetryBudget struct {
mu sync.Mutex
tokens float64
max float64
ratio float64
retries int64
denied int64
}
// NewRetryBudget returns a budget that allows retries worth ratio of first
// attempts (0.1 = 10%), with burst tokens available up front.
func NewRetryBudget(ratio, burst float64) *RetryBudget {
if burst < 1 {
burst = 1
}
return &RetryBudget{tokens: burst, max: burst, ratio: ratio}
}
// OnRequest records a first attempt and deposits ratio tokens.
func (b *RetryBudget) OnRequest() {
b.mu.Lock()
b.tokens += b.ratio
if b.tokens > b.max {
b.tokens = b.max
}
b.mu.Unlock()
}
// TryRetry withdraws one token. It returns false when the budget is spent:
// the caller must surface the error instead of retrying.
func (b *RetryBudget) TryRetry() bool {
b.mu.Lock()
defer b.mu.Unlock()
if b.tokens >= 1 {
b.tokens--
b.retries++
return true
}
b.denied++
return false
}
// Stats reports granted and denied retries (export them as metrics).
func (b *RetryBudget) Stats() (granted, denied int64) {
b.mu.Lock()
defer b.mu.Unlock()
return b.retries, b.denied
}package resilience
import (
"math/rand/v2"
"time"
)
// FullJitter returns the sleep before retry number attempt (0-based) using
// the "Full Jitter" schedule from the AWS Architecture Blog:
// sleep = random_between(0, min(cap, base * 2^attempt)).
//
// Spreading retries over the whole window is what stops synchronized retry
// waves (a thundering herd) after a blip.
func FullJitter(attempt int, base, maxDelay time.Duration, rnd *rand.Rand) time.Duration {
if attempt < 0 {
attempt = 0
}
ceiling := maxDelay
if attempt < 30 { // avoid overflow of the shift
if d := base << attempt; d > 0 && d < maxDelay {
ceiling = d
}
}
if ceiling <= 0 {
return 0
}
var n int64
if rnd != nil {
n = rnd.Int64N(int64(ceiling))
} else {
n = rand.Int64N(int64(ceiling))
}
return time.Duration(n)
}انتشار deadline همراه با رد کردن فراخوانیهای محکوم به شکست:
package resilience
import (
"context"
"errors"
"net/http"
"strconv"
"time"
)
// HeaderTimeout carries the caller's remaining budget in milliseconds.
// Relative time, not an absolute timestamp, so clock skew between hosts
// does not matter (gRPC's grpc-timeout header works the same way).
const HeaderTimeout = "Request-Timeout-Ms"
// ErrBudgetExhausted means there is not enough time left to do useful work.
var ErrBudgetExhausted = errors.New("resilience: deadline budget exhausted")
// FromRequest derives the request context from the incoming budget header,
// capped by maxBudget. Without a header the server picks maxBudget itself.
func FromRequest(r *http.Request, maxBudget time.Duration) (context.Context, context.CancelFunc) {
budget := maxBudget
if v := r.Header.Get(HeaderTimeout); v != "" {
if ms, err := strconv.Atoi(v); err == nil && ms >= 0 {
if d := time.Duration(ms) * time.Millisecond; d < budget {
budget = d
}
}
}
return context.WithTimeout(r.Context(), budget)
}
// ForHop returns a child context for one downstream call:
// min(hopCap, remaining - margin). It refuses the call (ErrBudgetExhausted)
// when less than minUseful is left: the callee could not finish in time,
// and starting the call would only add load to an overloaded system.
func ForHop(ctx context.Context, hopCap, margin, minUseful time.Duration) (context.Context, context.CancelFunc, error) {
timeout := hopCap
if dl, ok := ctx.Deadline(); ok {
left := time.Until(dl) - margin
if left < minUseful {
return ctx, func() {}, ErrBudgetExhausted
}
if left < timeout {
timeout = left
}
}
c, cancel := context.WithTimeout(ctx, timeout)
return c, cancel, nil
}
// Stamp writes the remaining budget of ctx into the outgoing request.
func Stamp(req *http.Request) {
if dl, ok := req.Context().Deadline(); ok {
ms := time.Until(dl).Milliseconds()
if ms < 0 {
ms = 0
}
req.Header.Set(HeaderTimeout, strconv.FormatInt(ms, 10))
}
}Admission control: همزمانی محدود، صف محدود، انتظار محدود، 503 سریع با Retry-After:
package resilience
import (
"context"
"net/http"
"strconv"
"sync/atomic"
"time"
)
// Admission is admission control for one process: at most MaxInFlight
// requests run, at most MaxQueue wait, and nobody waits longer than MaxWait
// or past its own deadline. Everything else is shed immediately with 503 and
// Retry-After: a fast, cheap "no" instead of a slow "maybe".
//
// It is a bulkhead (a fixed pool that one dependency or client cannot grow),
// a bounded queue and a load shedder in about sixty lines.
type Admission struct {
slots chan struct{}
maxQueue int64
maxWait time.Duration
waiting atomic.Int64
shed atomic.Int64
admitted atomic.Int64
}
// NewAdmission builds an admission controller. Google SRE suggests a queue of
// 50% of the worker pool or less for steady traffic.
func NewAdmission(maxInFlight, maxQueue int, maxWait time.Duration) *Admission {
return &Admission{
slots: make(chan struct{}, maxInFlight),
maxQueue: int64(maxQueue),
maxWait: maxWait,
}
}
// Acquire takes a slot or returns false. The caller must call Release once.
func (a *Admission) Acquire(ctx context.Context) bool {
select {
case a.slots <- struct{}{}:
a.admitted.Add(1)
return true
default:
}
if a.waiting.Add(1) > a.maxQueue {
a.waiting.Add(-1)
a.shed.Add(1)
return false
}
defer a.waiting.Add(-1)
t := time.NewTimer(a.maxWait)
defer t.Stop()
select {
case a.slots <- struct{}{}:
a.admitted.Add(1)
return true
case <-t.C:
case <-ctx.Done():
}
a.shed.Add(1)
return false
}
// Release frees a slot.
func (a *Admission) Release() { <-a.slots }
// Saturation is in-flight / capacity, the "S" of the four golden signals.
type Saturation struct {
InFlight int `json:"in_flight"`
Capacity int `json:"capacity"`
Waiting int64 `json:"waiting"`
Shed int64 `json:"shed_total"`
Admitted int64 `json:"admitted_total"`
Ratio float64 `json:"ratio"`
}
// Stats returns the current saturation.
func (a *Admission) Stats() Saturation {
in, capacity := len(a.slots), cap(a.slots)
return Saturation{
InFlight: in, Capacity: capacity, Waiting: a.waiting.Load(),
Shed: a.shed.Load(), Admitted: a.admitted.Load(),
Ratio: float64(in) / float64(capacity),
}
}
// Middleware sheds load before any expensive work starts.
func (a *Admission) Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !a.Acquire(r.Context()) {
w.Header().Set("Retry-After", strconv.Itoa(1))
http.Error(w, "overloaded, retry later", http.StatusServiceUnavailable)
return
}
defer a.Release()
next.ServeHTTP(w, r)
})
}Health که liveness را از readiness جدا میکند و saturation را بدون شکست گزارش میدهد:
package resilience
import (
"encoding/json"
"net/http"
"sync/atomic"
)
// Health separates the two questions Google SRE says must not be mixed:
// "is this binary responding at all?" (liveness, for the scheduler) and
// "should the load balancer send traffic now?" (readiness).
//
// Neither depends on downstream dependencies or on momentary saturation:
// a liveness probe that fails under load makes Kubernetes restart busy pods,
// which removes capacity exactly when it is needed (the death spiral).
type Health struct {
adm *Admission
ready atomic.Bool // set after warm-up (caches, connections)
draining atomic.Bool // set on SIGTERM
}
// NewHealth wires the probes to the admission controller for reporting.
func NewHealth(adm *Admission) *Health { return &Health{adm: adm} }
// MarkReady ends warm-up; MarkDraining starts graceful shutdown.
func (h *Health) MarkReady() { h.ready.Store(true) }
func (h *Health) MarkDraining() { h.draining.Store(true) }
// Live answers 200 while the process can run a handler at all.
func (h *Health) Live(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("ok\n"))
}
// Ready answers 503 only while warming up or draining. Saturation is
// reported in the body (for dashboards and load-aware balancing) but does
// not flip readiness: shedding happens per request in Admission instead.
func (h *Health) Ready(w http.ResponseWriter, _ *http.Request) {
body := struct {
Ready bool `json:"ready"`
Draining bool `json:"draining"`
Saturation Saturation `json:"saturation"`
}{h.ready.Load(), h.draining.Load(), h.adm.Stats()}
w.Header().Set("Content-Type", "application/json")
if !body.Ready || body.Draining {
w.WriteHeader(http.StatusServiceUnavailable)
}
_ = json.NewEncoder(w).Encode(body)
}کلاینتی که نمیتواند retry storm راه بیندازد (bulkhead، deadline هر hop، budget، jitter، بدون retry روی 429 یا 4xx):
package resilience
import (
"context"
"errors"
"fmt"
"io"
"math/rand/v2"
"net/http"
"time"
)
// Client is an HTTP client that cannot start a retry storm: a per-hop
// deadline taken from the caller's budget, at most MaxAttempts per request,
// a shared RetryBudget, full-jitter backoff, no retry on overload signals
// that mean "the whole fleet is busy", and a bounded number of concurrent
// calls (a bulkhead per dependency).
type Client struct {
HTTP *http.Client
Budget *RetryBudget
Bulkhead chan struct{}
MaxAttempts int
HopCap time.Duration
Margin time.Duration
MinUseful time.Duration
BackoffBase time.Duration
BackoffMax time.Duration
Rand *rand.Rand
}
// ErrBulkheadFull is returned when the dependency's pool is exhausted.
var ErrBulkheadFull = errors.New("resilience: bulkhead full")
// Get performs a budgeted GET and returns the body of a 2xx response.
func (c *Client) Get(ctx context.Context, url string) ([]byte, error) {
select {
case c.Bulkhead <- struct{}{}:
defer func() { <-c.Bulkhead }()
default:
return nil, ErrBulkheadFull // fail fast instead of queueing threads
}
c.Budget.OnRequest()
var lastErr error
for attempt := 0; attempt < c.MaxAttempts; attempt++ {
if attempt > 0 {
if !c.Budget.TryRetry() {
return nil, fmt.Errorf("retry budget spent: %w", lastErr)
}
sleep := FullJitter(attempt-1, c.BackoffBase, c.BackoffMax, c.Rand)
select {
case <-time.After(sleep):
case <-ctx.Done():
return nil, ctx.Err()
}
}
body, retry, err := c.once(ctx, url)
if err == nil {
return body, nil
}
lastErr = err
if !retry {
return nil, err
}
}
return nil, lastErr
}
func (c *Client) once(ctx context.Context, url string) (body []byte, retry bool, err error) {
hop, cancel, err := ForHop(ctx, c.HopCap, c.Margin, c.MinUseful)
if err != nil {
return nil, false, err
}
defer cancel()
req, err := http.NewRequestWithContext(hop, http.MethodGet, url, nil)
if err != nil {
return nil, false, err
}
Stamp(req)
resp, err := c.HTTP.Do(req)
if err != nil {
// The caller's own deadline is gone: retrying cannot help.
if ctx.Err() != nil {
return nil, false, ctx.Err()
}
return nil, true, err // per-hop timeout or connection error
}
defer resp.Body.Close()
b, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
switch {
case err != nil:
return nil, true, err
case resp.StatusCode >= 200 && resp.StatusCode < 300:
return b, false, nil
case resp.StatusCode == http.StatusTooManyRequests:
// Explicit overload signal: back off, do not retry at this layer.
return nil, false, fmt.Errorf("upstream throttled: %d", resp.StatusCode)
case resp.StatusCode >= 500:
return nil, true, fmt.Errorf("upstream %d", resp.StatusCode)
default:
return nil, false, fmt.Errorf("upstream %d", resp.StatusCode) // 4xx never succeeds on retry
}
}package resilience
import (
"context"
"encoding/json"
"errors"
"math/rand/v2"
"net/http"
"net/http/httptest"
"sync"
"sync/atomic"
"testing"
"time"
)
func TestRetryBudgetCapsRetriesToRatio(t *testing.T) {
b := NewRetryBudget(0.1, 10)
granted := 0
for i := 0; i < 1000; i++ {
b.OnRequest()
// every request fails and asks for a retry: the worst case
if b.TryRetry() {
granted++
}
}
// 10 burst tokens + 0.1 * 1000 deposits = about 110 retries, not 1000
if granted < 100 || granted > 111 {
t.Fatalf("granted %d retries, want about 110", granted)
}
}
func TestFullJitterStaysInsideWindow(t *testing.T) {
r := rand.New(rand.NewPCG(1, 2))
base, maxDelay := 50*time.Millisecond, time.Second
for attempt := 0; attempt < 8; attempt++ {
ceiling := base << attempt
if ceiling > maxDelay {
ceiling = maxDelay
}
for i := 0; i < 200; i++ {
d := FullJitter(attempt, base, maxDelay, r)
if d < 0 || d >= ceiling {
t.Fatalf("attempt %d: %v outside [0,%v)", attempt, d, ceiling)
}
}
}
}
func TestForHopRefusesDoomedCalls(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond)
defer cancel()
if _, _, err := ForHop(ctx, time.Second, 10*time.Millisecond, 40*time.Millisecond); !errors.Is(err, ErrBudgetExhausted) {
t.Fatalf("want ErrBudgetExhausted, got %v", err)
}
ctx2, cancel2 := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel2()
hop, c, err := ForHop(ctx2, 300*time.Millisecond, 10*time.Millisecond, 20*time.Millisecond)
if err != nil {
t.Fatal(err)
}
defer c()
dl, _ := hop.Deadline()
if left := time.Until(dl); left > 300*time.Millisecond {
t.Fatalf("hop cap not applied: %v left", left)
}
}
func TestFromRequestHonoursCallerBudget(t *testing.T) {
r := httptest.NewRequest(http.MethodGet, "/", nil)
r.Header.Set(HeaderTimeout, "120")
ctx, cancel := FromRequest(r, 5*time.Second)
defer cancel()
dl, ok := ctx.Deadline()
if !ok || time.Until(dl) > 120*time.Millisecond {
t.Fatalf("deadline not taken from header")
}
}
func TestAdmissionShedsBeyondPoolAndQueue(t *testing.T) {
adm := NewAdmission(2, 1, 50*time.Millisecond)
release := make(chan struct{})
h := adm.Middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
<-release
}))
srv := httptest.NewServer(h)
defer srv.Close()
var ok, shed atomic.Int64
var wg sync.WaitGroup
for i := 0; i < 6; i++ {
wg.Add(1)
go func() {
defer wg.Done()
resp, err := http.Get(srv.URL)
if err != nil {
t.Error(err)
return
}
resp.Body.Close()
if resp.StatusCode == http.StatusServiceUnavailable {
if resp.Header.Get("Retry-After") == "" {
t.Error("503 without Retry-After")
}
shed.Add(1)
} else {
ok.Add(1)
}
}()
}
time.Sleep(150 * time.Millisecond) // the waiting one times out after 50 ms
close(release)
wg.Wait()
if ok.Load() != 2 || shed.Load() != 4 {
t.Fatalf("ok=%d shed=%d, want 2 and 4", ok.Load(), shed.Load())
}
}
func TestReadinessReportsSaturationButStaysReady(t *testing.T) {
adm := NewAdmission(4, 2, time.Millisecond)
h := NewHealth(adm)
rec := httptest.NewRecorder()
h.Ready(rec, httptest.NewRequest(http.MethodGet, "/readyz", nil))
if rec.Code != http.StatusServiceUnavailable {
t.Fatalf("not warmed up yet: want 503, got %d", rec.Code)
}
h.MarkReady()
for i := 0; i < 4; i++ { // fully saturated
adm.Acquire(context.Background())
}
rec = httptest.NewRecorder()
h.Ready(rec, httptest.NewRequest(http.MethodGet, "/readyz", nil))
var body struct {
Saturation Saturation `json:"saturation"`
}
if err := json.NewDecoder(rec.Body).Decode(&body); err != nil {
t.Fatal(err)
}
if rec.Code != http.StatusOK || body.Saturation.Ratio != 1 {
t.Fatalf("saturated pod must stay ready and report ratio 1: code=%d ratio=%v", rec.Code, body.Saturation.Ratio)
}
h.MarkDraining()
rec = httptest.NewRecorder()
h.Ready(rec, httptest.NewRequest(http.MethodGet, "/readyz", nil))
if rec.Code != http.StatusServiceUnavailable {
t.Fatalf("draining: want 503, got %d", rec.Code)
}
}
func TestClientStopsRetryingWhenBudgetIsSpent(t *testing.T) {
var hits atomic.Int64
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hits.Add(1)
http.Error(w, "boom", http.StatusInternalServerError)
}))
defer srv.Close()
c := &Client{
HTTP: srv.Client(), Budget: NewRetryBudget(0.1, 2), Bulkhead: make(chan struct{}, 8),
MaxAttempts: 3, HopCap: time.Second, Margin: time.Millisecond, MinUseful: time.Millisecond,
BackoffBase: time.Millisecond, BackoffMax: 5 * time.Millisecond, Rand: rand.New(rand.NewPCG(3, 4)),
}
for i := 0; i < 50; i++ {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
if _, err := c.Get(ctx, srv.URL); err == nil {
t.Fatal("expected error")
}
cancel()
}
// naive client: 50 * 3 = 150 hits; budgeted: 50 + 2 burst + 50*0.1 = about 57
if n := hits.Load(); n > 60 {
t.Fatalf("%d upstream hits: retry budget did not cap amplification", n)
}
}
func TestClientDoesNotRetry429(t *testing.T) {
var hits atomic.Int64
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hits.Add(1)
w.WriteHeader(http.StatusTooManyRequests)
}))
defer srv.Close()
c := &Client{HTTP: srv.Client(), Budget: NewRetryBudget(1, 10), Bulkhead: make(chan struct{}, 1),
MaxAttempts: 3, HopCap: time.Second, Margin: time.Millisecond, MinUseful: time.Millisecond,
BackoffBase: time.Millisecond, BackoffMax: time.Millisecond}
_, _ = c.Get(context.Background(), srv.URL)
if hits.Load() != 1 {
t.Fatalf("429 retried %d times", hits.Load()-1)
}
}سرویس، اصلاحشده:
// Command after is the same service with the cheap defences that stop a
// cascade: server timeouts, admission control (bounded concurrency, bounded
// queue, fast 503), deadline propagation, a retry budget with full jitter,
// a bulkhead and connection cap per dependency, graceful degradation from a
// stale copy, liveness separated from readiness, warm-up before readiness,
// and draining on shutdown.
package main
import (
"context"
"errors"
"log"
"math/rand/v2"
"net"
"net/http"
"os"
"os/signal"
"sync"
"syscall"
"time"
"academy/cascading-failures/resilience"
)
const inventory = "http://inventory.internal/stock" // documentation host
// staleCache keeps the last good answer for graceful degradation.
type staleCache struct {
mu sync.RWMutex
body []byte
at time.Time
}
func (c *staleCache) put(b []byte) { c.mu.Lock(); c.body, c.at = b, time.Now(); c.mu.Unlock() }
func (c *staleCache) get() ([]byte, time.Time) {
c.mu.RLock()
defer c.mu.RUnlock()
return c.body, c.at
}
func main() {
transport := &http.Transport{
DialContext: (&net.Dialer{Timeout: 200 * time.Millisecond}).DialContext,
MaxConnsPerHost: 64, // bounded connection pool per dependency
MaxIdleConnsPerHost: 64, // default is 2: churn costs handshakes and ports
IdleConnTimeout: 90 * time.Second,
ResponseHeaderTimeout: 800 * time.Millisecond,
}
inv := &resilience.Client{
HTTP: &http.Client{Transport: transport}, // per-call deadlines come from ctx
Budget: resilience.NewRetryBudget(0.1, 10), // retries <= ~10% of calls
Bulkhead: make(chan struct{}, 64), // inventory can hold at most 64 goroutines
MaxAttempts: 3,
HopCap: 300 * time.Millisecond, // about the callee's p99.9
Margin: 20 * time.Millisecond,
MinUseful: 30 * time.Millisecond, // about the callee's p50: less is doomed
BackoffBase: 25 * time.Millisecond,
BackoffMax: 250 * time.Millisecond,
Rand: rand.New(rand.NewPCG(uint64(time.Now().UnixNano()), 1)),
}
stale := &staleCache{}
adm := resilience.NewAdmission(256, 128, 100*time.Millisecond) // queue = 50% of the pool
health := resilience.NewHealth(adm)
mux := http.NewServeMux()
mux.Handle("GET /product", adm.Middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx, cancel := resilience.FromRequest(r, time.Second) // caller's budget, capped at 1 s
defer cancel()
body, err := inv.Get(ctx, inventory)
if err == nil {
stale.put(body)
_, _ = w.Write(body)
return
}
if b, at := stale.get(); b != nil && time.Since(at) < 10*time.Minute {
// graceful degradation: an older answer beats an error page
w.Header().Set("X-Degraded", "stale-inventory")
_, _ = w.Write(b)
return
}
// overload is a 503 with Retry-After, not a 500 that invites retries
log.Printf("product: degraded, no stale copy: %v", err)
w.Header().Set("Retry-After", "1")
http.Error(w, "inventory unavailable", http.StatusServiceUnavailable)
})))
mux.HandleFunc("GET /livez", health.Live) // Kubernetes livenessProbe
mux.HandleFunc("GET /readyz", health.Ready) // Kubernetes readinessProbe / LB health check
srv := &http.Server{
Addr: ":8080",
Handler: mux,
ReadHeaderTimeout: 2 * time.Second, // slow clients cannot pin goroutines
ReadTimeout: 5 * time.Second,
WriteTimeout: 5 * time.Second,
IdleTimeout: 60 * time.Second,
}
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt)
defer stop()
go func() {
warmUp(ctx, inv, stale) // fill caches and connection pools before taking traffic
health.MarkReady()
}()
go func() {
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatal(err)
}
}()
<-ctx.Done()
health.MarkDraining() // readiness fails first so the LB stops sending
time.Sleep(5 * time.Second)
shutdown, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
_ = srv.Shutdown(shutdown)
}
// warmUp primes the stale cache and the connection pool (cache warming).
func warmUp(ctx context.Context, inv *resilience.Client, stale *staleCache) {
for i := 0; i < 3; i++ {
c, cancel := context.WithTimeout(ctx, time.Second)
b, err := inv.Get(c, inventory)
cancel()
if err == nil {
stale.put(b)
return
}
time.Sleep(resilience.FullJitter(i, 200*time.Millisecond, 2*time.Second, nil))
}
}شبیهساز مارپیچ مرگ (گامهای یکمیلیثانیهای، seed قطعی؛ retry، GC pressure، کشتن با health check، OOM، restart سرد، slow start، ریختن در edge و افزایش مقیاس را مدل میکند):
// Package spiral is a deterministic, single-process simulator of the
// cascading-failure death spiral described in Google SRE chapter 22
// (footnote 110 invites exactly this exercise). It runs in 1 ms ticks:
//
// users -> frontend (thread pool) -> load balancer -> N servers (workers + queue)
//
// Positive feedback loops it models: client timeouts and retries amplify load;
// queued work makes requests slower (GC pressure); health checks that wait in
// the same queue fail and the orchestrator kills busy servers (capacity
// removal); restarted servers start with cold caches; unbounded queues grow
// until OOM. Protections it can switch on: per-request deadlines with
// server-side expiry checks, a retry budget with full jitter, bounded queues
// (load shedding) and liveness-only health checks.
package spiral
import (
"math/rand/v2"
"time"
"academy/cascading-failures/resilience"
)
// Config describes one run. All times are in milliseconds.
type Config struct {
Name string
Seed uint64
DurationMs int
// Capacity: Servers * Workers / ServiceMs * 1000 requests per second.
Servers int
Workers int
ServiceMs float64
// Offered load: BaseRPS, and SpikeRPS between SpikeFromMs and SpikeToMs
// (the trigger). After the spike, load returns to BaseRPS.
BaseRPS float64
SpikeRPS float64
SpikeFromMs int
SpikeToMs int
// Client (frontend) behaviour.
FrontendThreads int // 0 = unlimited; each logical request holds one
TimeoutMs int // per-attempt client timeout (the deadline)
MaxAttempts int // 1 = no retries
RetryBudget float64 // 0 = unlimited retries; 0.1 = 10% of first attempts
BackoffBaseMs int // 0 = retry on the next tick (no backoff, no jitter)
BackoffMaxMs int
PatienceMs int // a success later than this is useless to the user
// Server behaviour.
QueueCap int // 0 = unbounded
DropExpired bool // skip work whose client deadline already passed
// Feedback loops.
GCPerQueued float64 // service time grows by this fraction per queued item
MaxSlowdown float64
OOMQueue int // crash when the queue exceeds this (0 = never)
HealthViaQueue bool // health check waits behind requests (naive)
HealthTimeoutMs int
HealthFailures int // consecutive failed checks before a kill
RestartMs int
ColdFactor float64 // service time multiplier right after a restart
ColdMs int // linear warm-up from ColdFactor to 1
SlowStartMs int // LB ramps traffic to a restarted server over this
BucketMs int // stats resolution, default 1000
// Operator actions during an incident.
AddServersAtMs int // scale out: add AddServers cold servers at this time
AddServers int // how many
EdgeShedFromMs int // block traffic at the edge from this time...
EdgeShedMs int // ...for this long, admitting only EdgeAdmit of it,
EdgeAdmit float64 // then ramp linearly back to 100%
EdgeRampMs int // over EdgeRampMs (gradual recovery)
}
// Second is one row of output.
type Second struct {
T int // seconds since start
Offered int // new user requests
Attempts int // attempts sent, including retries
Good int // successes within user patience
Late int // successes after the user gave up
Failed int // final failures seen by users
Shed int // fast rejections (503) at servers or frontend
WastedMs int // worker time spent on attempts nobody waits for
ServersUp int
QueueTotal int
Kills int
InFlight int // frontend threads held
}
// Result is a whole run.
type Result struct {
Config Config
Seconds []Second
}
type request struct {
arrived int
attempts int
done bool
}
type attempt struct {
req *request
sent int
deadline int
finished bool // completed or timed out from the client's view
}
type worker struct {
busyUntil int
att *attempt
startedAt int
}
type server struct {
up bool
upAt int // when it last came up (for cold cache and slow start)
downUntil int
queue []*attempt
head int
workers []worker
fails int
}
func (s *server) qlen() int { return len(s.queue) - s.head }
func (s *server) push(a *attempt) { s.queue = append(s.queue, a) }
func (s *server) pop() *attempt {
a := s.queue[s.head]
s.queue[s.head] = nil
s.head++
if s.head > 1024 && s.head*2 > len(s.queue) {
s.queue = append([]*attempt(nil), s.queue[s.head:]...)
s.head = 0
}
return a
}
type sim struct {
cfg Config
rnd *rand.Rand
budget *resilience.RetryBudget
servers []*server
timeouts [][]*attempt
retries [][]*request
inFlight int
stats []Second
acc float64
}
// Run executes the simulation. It is deterministic for a given Config.
func Run(cfg Config) Result {
if cfg.BucketMs == 0 {
cfg.BucketMs = 1000
}
if cfg.MaxSlowdown == 0 {
cfg.MaxSlowdown = 4
}
s := &sim{cfg: cfg, rnd: rand.New(rand.NewPCG(cfg.Seed, cfg.Seed^0x9e3779b97f4a7c15))}
if cfg.RetryBudget > 0 {
s.budget = resilience.NewRetryBudget(cfg.RetryBudget, 10)
}
horizon := cfg.DurationMs + cfg.TimeoutMs + cfg.BackoffMaxMs + 2
s.timeouts = make([][]*attempt, horizon)
s.retries = make([][]*request, horizon)
for i := 0; i < cfg.Servers; i++ {
s.servers = append(s.servers, &server{up: true, upAt: -1 << 30, workers: make([]worker, cfg.Workers)})
}
s.stats = make([]Second, cfg.DurationMs/cfg.BucketMs+1)
for i := range s.stats {
s.stats[i].T = i * cfg.BucketMs / 1000
}
for t := 0; t < cfg.DurationMs; t++ {
s.tick(t)
}
return Result{Config: cfg, Seconds: s.stats[:cfg.DurationMs/cfg.BucketMs]}
}
func (s *sim) row(t int) *Second { return &s.stats[t/s.cfg.BucketMs] }
func (s *sim) rps(t int) float64 {
if t >= s.cfg.SpikeFromMs && t < s.cfg.SpikeToMs {
return s.cfg.SpikeRPS
}
return s.cfg.BaseRPS
}
func (s *sim) tick(t int) {
c := s.cfg
if c.AddServers > 0 && t == c.AddServersAtMs {
for i := 0; i < c.AddServers; i++ {
s.servers = append(s.servers, &server{up: true, upAt: t, workers: make([]worker, c.Workers)})
}
}
// 1. new user requests
s.acc += s.rps(t) / 1000
admit := s.edgeAdmit(t)
for s.acc >= 1 {
s.acc--
s.row(t).Offered++
if admit < 1 && s.rnd.Float64() >= admit {
s.row(t).Failed++ // blocked at the edge (CDN/WAF/LB rule): cheap
s.row(t).Shed++
continue
}
if c.FrontendThreads > 0 && s.inFlight >= c.FrontendThreads {
s.row(t).Failed++ // thread pool exhausted: the frontend itself refuses
s.row(t).Shed++
continue
}
r := &request{arrived: t}
s.inFlight++
if s.budget != nil {
s.budget.OnRequest()
}
s.send(t, r)
}
// 2. scheduled retries
for _, r := range s.retries[t] {
s.send(t, r)
}
s.retries[t] = nil
// 3. client-side timeouts (the attempt may still sit in a server queue)
for _, a := range s.timeouts[t] {
if !a.finished {
a.finished = true
s.fail(t, a.req)
}
}
s.timeouts[t] = nil
// 4. servers
for _, sv := range s.servers {
s.serve(t, sv)
}
// 5. health checks once per second, staggered per server
for i, sv := range s.servers {
if (t+i*97)%1000 == 0 {
s.healthCheck(t, sv)
}
}
if (t+1)%c.BucketMs == 0 {
row := s.row(t)
for _, sv := range s.servers {
if sv.up {
row.ServersUp++
row.QueueTotal += sv.qlen()
}
}
row.InFlight = s.inFlight
}
}
// edgeAdmit is the share of traffic the edge lets through at time t.
func (s *sim) edgeAdmit(t int) float64 {
c := s.cfg
if c.EdgeShedMs == 0 || t < c.EdgeShedFromMs {
return 1
}
if t < c.EdgeShedFromMs+c.EdgeShedMs {
return c.EdgeAdmit
}
if into := t - c.EdgeShedFromMs - c.EdgeShedMs; c.EdgeRampMs > 0 && into < c.EdgeRampMs {
return c.EdgeAdmit + (1-c.EdgeAdmit)*float64(into)/float64(c.EdgeRampMs)
}
return 1
}
// slowdown is the service-time multiplier: GC pressure from queued work and
// a cold cache after a restart.
func (s *sim) slowdown(t int, sv *server) float64 {
f := 1 + s.cfg.GCPerQueued*float64(sv.qlen())
if s.cfg.ColdMs > 0 && t-sv.upAt < s.cfg.ColdMs {
left := 1 - float64(t-sv.upAt)/float64(s.cfg.ColdMs)
f *= 1 + (s.cfg.ColdFactor-1)*left
}
if f > s.cfg.MaxSlowdown {
f = s.cfg.MaxSlowdown
}
return f
}
func (s *sim) pick(t int) *server {
var up []*server
for _, sv := range s.servers {
if sv.up {
up = append(up, sv)
}
}
for tries := 0; tries < 4 && len(up) > 0; tries++ {
sv := up[s.rnd.IntN(len(up))]
if s.cfg.SlowStartMs > 0 && t-sv.upAt < s.cfg.SlowStartMs {
// slow start: accept a growing share of traffic while warming up
if s.rnd.Float64() > float64(t-sv.upAt)/float64(s.cfg.SlowStartMs) {
continue
}
}
return sv
}
if len(up) == 0 {
return nil
}
return up[s.rnd.IntN(len(up))]
}
func (s *sim) send(t int, r *request) {
r.attempts++
s.row(t).Attempts++
a := &attempt{req: r, sent: t, deadline: t + s.cfg.TimeoutMs}
sv := s.pick(t)
if sv == nil { // connection refused: nobody is up
a.finished = true
s.fail(t, r)
return
}
if s.cfg.QueueCap > 0 && sv.qlen() >= s.cfg.QueueCap && !hasFreeWorker(t, sv) {
a.finished = true // fast 503: cheap for the server, quick for the client
s.row(t).Shed++
s.fail(t, r)
return
}
sv.push(a)
s.timeouts[a.deadline] = append(s.timeouts[a.deadline], a)
}
func hasFreeWorker(t int, sv *server) bool {
for _, w := range sv.workers {
if w.att == nil || w.busyUntil <= t {
return true
}
}
return false
}
// fail decides between a retry and a final error.
func (s *sim) fail(t int, r *request) {
if r.done {
return
}
c := s.cfg
if r.attempts < c.MaxAttempts && (s.budget == nil || s.budget.TryRetry()) {
delay := 1
if c.BackoffBaseMs > 0 {
d := resilience.FullJitter(r.attempts-1, time.Duration(c.BackoffBaseMs)*time.Millisecond,
time.Duration(c.BackoffMaxMs)*time.Millisecond, s.rnd)
delay = 1 + int(d/time.Millisecond)
}
at := t + delay
// a deadline-aware client does not retry past the user's patience
if at < len(s.retries) && (c.PatienceMs == 0 || !c.DropExpired || at-r.arrived < c.PatienceMs) {
s.retries[at] = append(s.retries[at], r)
return
}
}
r.done = true
s.inFlight--
s.row(t).Failed++
}
func (s *sim) serve(t int, sv *server) {
c := s.cfg
if !sv.up {
if t >= sv.downUntil {
sv.up, sv.upAt, sv.fails = true, t, 0
}
return
}
for i := range sv.workers {
w := &sv.workers[i]
if w.att != nil && w.busyUntil <= t {
a := w.att
w.att = nil
if a.finished || a.req.done {
s.row(t).WastedMs += t - w.startedAt // nobody is waiting: wasted work
continue
}
a.finished = true
a.req.done = true
s.inFlight--
if c.PatienceMs > 0 && t-a.req.arrived > c.PatienceMs {
s.row(t).Late++
} else {
s.row(t).Good++
}
}
for w.att == nil && sv.qlen() > 0 {
a := sv.pop()
if c.DropExpired && (a.finished || a.req.done || t >= a.deadline) {
continue // deadline check before work: free
}
svc := int(c.ServiceMs*s.slowdown(t, sv) + 0.5)
if svc < 1 {
svc = 1
}
w.att, w.busyUntil, w.startedAt = a, t+svc, t
}
}
if c.OOMQueue > 0 && sv.qlen() > c.OOMQueue {
s.kill(t, sv) // out of memory
}
}
func (s *sim) healthCheck(t int, sv *server) {
c := s.cfg
if !sv.up || !c.HealthViaQueue {
return // liveness answered on its own path: busy is not dead
}
wait := float64(sv.qlen()) * c.ServiceMs * s.slowdown(t, sv) / float64(c.Workers)
if wait > float64(c.HealthTimeoutMs) {
sv.fails++
if sv.fails >= c.HealthFailures {
s.kill(t, sv)
}
return
}
sv.fails = 0
}
// kill removes a server: queued and running attempts are lost (clients will
// time out), and it comes back after RestartMs with a cold cache.
func (s *sim) kill(t int, sv *server) {
sv.up = false
sv.downUntil = t + s.cfg.RestartMs
sv.queue, sv.head = nil, 0
for i := range sv.workers {
sv.workers[i].att = nil
}
s.row(t).Kills++
}
// Window sums rows with fromS <= T < toS.
func (r Result) Window(fromS, toS int) Second {
var w Second
for _, x := range r.Seconds {
if x.T >= fromS && x.T < toS {
w.Offered += x.Offered
w.Attempts += x.Attempts
w.Good += x.Good
w.Late += x.Late
w.Failed += x.Failed
w.Shed += x.Shed
w.WastedMs += x.WastedMs
w.Kills += x.Kills
}
}
return w
}
// Goodput is good successes / offered requests in a window.
func (r Result) Goodput(fromS, toS int) float64 {
w := r.Window(fromS, toS)
if w.Offered == 0 {
return 0
}
return float64(w.Good) / float64(w.Offered)
}
// Amplification is attempts sent per offered request in a window.
func (r Result) Amplification(fromS, toS int) float64 {
w := r.Window(fromS, toS)
if w.Offered == 0 {
return 0
}
return float64(w.Attempts) / float64(w.Offered)
}package spiral
// The scenario: 10 servers x 8 workers x 40 ms = 2,000 requests/s of
// capacity. Users send 1,400 requests/s (70% utilisation). Between 20 s and
// 30 s a spike of 2,600 requests/s (130%) hits: a marketing email, a
// failover from another region, the first Monday after the holidays.
// The question is what happens at 30 s, when load is back to 70%.
func base(name string) Config {
return Config{
Name: name, Seed: 42, DurationMs: 90_000,
Servers: 10, Workers: 8, ServiceMs: 40,
BaseRPS: 1400, SpikeRPS: 2600, SpikeFromMs: 20_000, SpikeToMs: 30_000,
FrontendThreads: 20_000, PatienceMs: 2_000,
GCPerQueued: 0.0005, MaxSlowdown: 4,
RestartMs: 5_000, ColdFactor: 3, ColdMs: 10_000,
}
}
// Naive is the system most teams ship first: a 5 s client timeout, three
// immediate retries, an unbounded queue that dies of OOM at 6,000 entries,
// a health check that waits in the request queue (2 s timeout, 3 strikes)
// and no deadline check on the server.
func Naive() Config {
c := base("naive")
c.TimeoutMs, c.MaxAttempts = 5_000, 4
c.HealthViaQueue, c.HealthTimeoutMs, c.HealthFailures = true, 2_000, 3
c.OOMQueue = 6_000
return c
}
// Protected adds the four cheap defences: a 1 s deadline that servers check
// before doing work, a 10% retry budget with full-jitter backoff (max 3
// attempts), a bounded queue of 4 per server (50% of the worker pool, the
// SRE book's rule of thumb) and a liveness-only health check.
func Protected() Config {
c := base("protected")
c.TimeoutMs, c.MaxAttempts = 1_000, 3
c.DropExpired = true
c.RetryBudget, c.BackoffBaseMs, c.BackoffMaxMs = 0.1, 50, 1_000
c.QueueCap = 4
c.SlowStartMs = 10_000
return c
}
// Ablations remove one defence at a time from Protected.
func Ablations() []Config {
noDeadline := Protected()
noDeadline.Name, noDeadline.DropExpired, noDeadline.TimeoutMs = "protected - deadlines", false, 5_000
noBudget := Protected()
noBudget.Name, noBudget.RetryBudget, noBudget.BackoffBaseMs, noBudget.MaxAttempts = "protected - retry budget/jitter", 0, 0, 4
unbounded := Protected()
unbounded.Name, unbounded.QueueCap, unbounded.OOMQueue = "protected - bounded queue", 0, 6_000
naiveHealth := Protected()
naiveHealth.Name = "protected + queue-based health check"
naiveHealth.HealthViaQueue, naiveHealth.HealthTimeoutMs, naiveHealth.HealthFailures = true, 2_000, 3
return []Config{Naive(), noDeadline, noBudget, unbounded, naiveHealth, Protected()}
}
// Additions add one defence at a time to Naive.
func Additions() []Config {
deadline := Naive()
deadline.Name, deadline.DropExpired, deadline.TimeoutMs = "naive + deadlines", true, 1_000
budget := Naive()
budget.Name = "naive + retry budget/jitter"
budget.RetryBudget, budget.BackoffBaseMs, budget.BackoffMaxMs, budget.MaxAttempts = 0.1, 50, 1_000, 3
bounded := Naive()
bounded.Name, bounded.QueueCap = "naive + bounded queue", 4
health := Naive()
health.Name, health.HealthViaQueue = "naive + liveness-only health", false
return []Config{Naive(), deadline, budget, bounded, health}
}
// Recoveries start from a collapsed Naive system and apply one operator
// action at 40 s.
func Recoveries() []Config {
nothing := Naive()
nothing.Name = "do nothing"
scale := Naive()
scale.Name, scale.AddServersAtMs, scale.AddServers = "scale out +50% (5 cold servers)", 40_000, 5
edge := Naive()
edge.Name = "edge admits 10% for 10 s, ramp over 20 s"
edge.EdgeShedFromMs, edge.EdgeShedMs, edge.EdgeAdmit, edge.EdgeRampMs = 40_000, 10_000, 0.1, 20_000
snap := Naive()
snap.Name = "edge admits 10% for 10 s, then 100% at once"
snap.EdgeShedFromMs, snap.EdgeShedMs, snap.EdgeAdmit = 40_000, 10_000, 0.1
return []Config{nothing, scale, edge, snap}
}package spiral
import "testing"
func TestNaiveSystemStaysDownAfterTheTriggerEnds(t *testing.T) {
r := Run(Naive())
if g := r.Goodput(0, 20); g < 0.99 {
t.Fatalf("healthy phase goodput %.3f, want >= 0.99", g)
}
// load is back to 70% of capacity, yet the system does not recover:
// a metastable failure sustained by retries, kills and cold restarts
if g := r.Goodput(30, 90); g > 0.2 {
t.Fatalf("naive goodput after the spike %.3f, want collapse (< 0.2)", g)
}
if a := r.Amplification(30, 60); a < 2 {
t.Fatalf("retry amplification %.2fx, want >= 2x", a)
}
if r.Window(20, 90).Kills == 0 {
t.Fatal("expected health-check or OOM kills (capacity removal)")
}
}
func TestProtectedSystemShedsAndRecovers(t *testing.T) {
r := Run(Protected())
// during the 130% spike, goodput stays near capacity: 2,000 of 2,600
if g := r.Goodput(20, 30); g < 0.74 {
t.Fatalf("protected goodput during spike %.3f, want >= 0.74", g)
}
if g := r.Goodput(31, 90); g < 0.99 {
t.Fatalf("protected goodput after spike %.3f, want >= 0.99", g)
}
if a := r.Amplification(20, 30); a > 1.15 {
t.Fatalf("protected amplification %.2fx, want <= 1.15x (10%% budget)", a)
}
if k := r.Window(0, 90).Kills; k != 0 {
t.Fatalf("protected run killed %d servers", k)
}
}
func TestBoundedQueueNeverGrows(t *testing.T) {
c := Protected()
r := Run(c)
for _, x := range r.Seconds {
if x.QueueTotal > c.QueueCap*c.Servers {
t.Fatalf("t=%d queue %d exceeds cap %d", x.T, x.QueueTotal, c.QueueCap*c.Servers)
}
}
}
func TestGradualRecoveryBeatsScaleOutAndSnapBack(t *testing.T) {
rs := Recoveries()
nothing, scale, ramp, snap := Run(rs[0]), Run(rs[1]), Run(rs[2]), Run(rs[3])
if g := ramp.Goodput(70, 90); g < 0.99 {
t.Fatalf("edge shed + ramp: goodput %.3f after ramp, want >= 0.99", g)
}
for name, r := range map[string]Result{"nothing": nothing, "scale": scale, "snap": snap} {
if g := r.Goodput(70, 90); g > 0.3 {
t.Fatalf("%s recovered (%.3f): the death spiral should persist", name, g)
}
}
}
func TestKneeOfTheLoadTest(t *testing.T) {
steady := func(c Config, rps float64) float64 {
c.DurationMs, c.BaseRPS, c.SpikeFromMs, c.SpikeToMs = 30_000, rps, 0, 0
return float64(Run(c).Window(10, 30).Good) / 20
}
// below the knee both are fine; above it naive goodput collapses while
// protected goodput plateaus near capacity (2,000 req/s)
if n, p := steady(Naive(), 1400), steady(Protected(), 1400); n < 1390 || p < 1390 {
t.Fatalf("70%% load: naive %.0f protected %.0f", n, p)
}
if n := steady(Naive(), 2600); n > 500 {
t.Fatalf("naive at 130%%: %.0f req/s, want collapse", n)
}
if p := steady(Protected(), 2600); p < 1900 {
t.Fatalf("protected at 130%%: %.0f req/s, want plateau near 2,000", p)
}
}
func TestDeterministic(t *testing.T) {
a, b := Run(Naive()), Run(Naive())
for i := range a.Seconds {
if a.Seconds[i] != b.Seconds[i] {
t.Fatalf("second %d differs between identical runs", i)
}
}
}// Command spiral prints the tables used on the cascading-failures page.
// It is deterministic (seeded) and finishes in about a second.
package main
import (
"fmt"
"academy/cascading-failures/spiral"
)
func main() {
fmt.Println("1) Timeline: 2,000 req/s capacity, 1,400 req/s load, spike to 2,600 req/s from 20 s to 30 s")
for _, cfg := range []spiral.Config{spiral.Naive(), spiral.Protected()} {
r := spiral.Run(cfg)
fmt.Printf("\n%s\n%4s %7s %8s %6s %6s %6s %6s %5s %7s %6s\n", cfg.Name,
"t(s)", "offered", "attempts", "good", "late", "failed", "shed", "up", "queue", "kills")
for _, x := range r.Seconds {
if x.T%5 == 0 || (x.T >= 18 && x.T <= 40 && x.T%2 == 0) {
fmt.Printf("%4d %7d %8d %6d %6d %6d %6d %5d %7d %6d\n", x.T, x.Offered, x.Attempts,
x.Good, x.Late, x.Failed, x.Shed, x.ServersUp, x.QueueTotal, x.Kills)
}
}
}
fmt.Println("\n2) One defence at a time (goodput = good / offered)")
fmt.Printf("%-38s %8s %8s %8s %8s %9s\n", "config", "0-20s", "20-30s", "30-60s", "60-90s", "ampl30-60")
for _, cfg := range append(spiral.Additions(), spiral.Ablations()[1:]...) {
r := spiral.Run(cfg)
fmt.Printf("%-38s %7.1f%% %7.1f%% %7.1f%% %7.1f%% %8.2fx\n", cfg.Name,
100*r.Goodput(0, 20), 100*r.Goodput(20, 30), 100*r.Goodput(30, 60), 100*r.Goodput(60, 90),
r.Amplification(30, 60))
}
fmt.Println("\n3) Recovering the collapsed naive system with one action at 40 s (goodput)")
fmt.Printf("%-44s %8s %8s %8s %8s\n", "action", "30-40s", "40-50s", "50-70s", "70-90s")
for _, cfg := range spiral.Recoveries() {
r := spiral.Run(cfg)
fmt.Printf("%-44s %7.1f%% %7.1f%% %7.1f%% %7.1f%%\n", cfg.Name,
100*r.Goodput(30, 40), 100*r.Goodput(40, 50), 100*r.Goodput(50, 70), 100*r.Goodput(70, 90))
}
fmt.Println("\n4) Load test to find the knee: steady load for 30 s, goodput in req/s")
fmt.Printf("%8s %10s %12s\n", "offered", "naive", "protected")
for _, rps := range []float64{1000, 1400, 1800, 2000, 2200, 2600, 3000} {
var out [2]float64
for i, cfg := range []spiral.Config{spiral.Naive(), spiral.Protected()} {
cfg.DurationMs, cfg.BaseRPS, cfg.SpikeFromMs, cfg.SpikeToMs = 30_000, rps, 0, 0
r := spiral.Run(cfg)
out[i] = float64(r.Window(10, 30).Good) / 20
}
fmt.Printf("%8.0f %10.0f %12.0f\n", rps, out[0], out[1])
}
}نگاه Go
| قابلیت Go | کاربرد در برابر آبشار | نکته |
|---|---|---|
context.WithTimeout، WithDeadline، ctx.Deadline() | deadline و انتشار آن | DeadlineExceeded همان "the error returned by Context.Err when the context is canceled due to its deadline passing" است |
context.AfterFunc، WithCancelCause، Cause | انتشار لغو همراه با دلیل | «فراخوان منصرف شد» را از «hop زمانش تمام شد» جدا کنید |
http.NewRequestWithContext | لغو فراخوانی در جریان وقتی بودجه تمام میشود | بدون آن، بازندهها ادامه میدهند |
timeoutهای http.Server | کلاینت کند نمیتواند goroutine نگه دارد | ReadHeaderTimeout نگهداشتن به سبک Slowloris را میبندد |
http.Transport.MaxConnsPerHost | connection pool محدود برای هر وابستگی | همراه MaxIdleConnsPerHost برای پرهیز از churn و تمام شدن port |
channel بافردار / golang.org/x/sync/semaphore | admission control و bulkhead | semaphore.Weighted.TryAcquire برای fail fast |
golang.org/x/sync/singleflight | ادغام missهای cache (stampede) | یک fetch برای هر کلید، بقیه منتظر همان |
runtime/debug.SetMemoryLimit، GOMEMLIMIT | جلوگیری از رسیدن heap به سقف container با GC | همراه admission control: سقف جلوی رسیدن کار را نمیگیرد |
math/rand/v2 | jitter بدون قفل مشترک | rand.New(rand.NewPCG(...)) با seed در آزمونها |
net/http/httptest | آزمون اضافهبار و shedding درون پردازه | در resilience_test.go استفاده شده |
Laravel
Before
Http::retry(5, 100) با timeout پیشفرض ۳۰ ثانیه و شکستی که 500 میشود:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Http;
/**
* The controller most cascades start from. Every PHP-FPM child that runs it
* waits up to 30 s (the HTTP client default) per attempt, five attempts with
* a fixed 100 ms pause: a slow inventory service pins every FPM child for
* minutes, NGINX starts answering 502/504, and every caller retries.
*/
class ProductControllerBefore extends Controller
{
public function show(int $id): JsonResponse
{
$stock = Http::retry(5, 100) // no jitter, no budget
->get("http://inventory.internal/stock/{$id}") // default timeout: 30 s
->throw()
->json();
return response()->json(['id' => $id, 'stock' => $stock]); // a failure becomes a 500
}
}After
Retry budget در سطح کل ناوگان در Redis، مشترک بین همهٔ childهای PHP-FPM و workerهای Octane:
<?php
namespace App\Support;
use Illuminate\Support\Facades\Cache;
/**
* A fleet-wide retry budget: retries may be at most $ratio of first attempts
* in the current one-minute window (Google SRE: "per-client retry budget",
* 10%). Counters live in Redis so every PHP-FPM child and Octane worker
* shares them; Cache::increment is atomic on the redis store.
*/
class RetryBudget
{
public function __construct(
private string $dependency,
private float $ratio = 0.1,
private int $minRetriesPerWindow = 10,
) {
}
public function recordRequest(): void
{
$key = $this->key('requests');
Cache::store('redis')->add($key, 0, 120);
Cache::store('redis')->increment($key);
}
public function tryRetry(): bool
{
$store = Cache::store('redis');
$requests = (int) $store->get($this->key('requests'), 0);
$allowed = max($this->minRetriesPerWindow, (int) floor($requests * $this->ratio));
$key = $this->key('retries');
$store->add($key, 0, 120);
return $store->increment($key) <= $allowed;
}
private function key(string $kind): string
{
return sprintf('retry-budget:%s:%s:%s', $this->dependency, $kind, intdiv(time(), 60));
}
}کلاینت موجودی: connect timeout برابر 0.2 ثانیه، timeout پاسخ از deadline درخواست، full jitter، callback به نام when که با budget مشورت میکند، throw: false و fallback کهنه:
<?php
namespace App\Clients;
use App\Support\RetryBudget;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Throwable;
/**
* Inventory client that cannot start a retry storm: tight connect and
* response timeouts, at most two retries with full jitter, a shared retry
* budget, no retry on 429 or 4xx, and a stale fallback (graceful degradation).
*/
class InventoryClient
{
public function __construct(private RetryBudget $budget)
{
}
/**
* @return array{stock: int|null, degraded: bool}
*/
public function stock(int $productId, float $deadlineAt): array
{
$remaining = $deadlineAt - microtime(true) - 0.02; // keep 20 ms for our own work
if ($remaining < 0.03) {
return $this->fallback($productId); // not enough time to succeed: do not call
}
$this->budget->recordRequest();
$response = Http::baseUrl('http://inventory.internal')
->connectTimeout(0.2)
->timeout(min(0.3, $remaining)) // about the callee's p99.9, never past the deadline
->withHeaders(['Request-Timeout-Ms' => (string) (int) ($remaining * 1000)])
->retry(
3,
fn (int $attempt) => random_int(0, 25 * (2 ** $attempt)), // full jitter, ms
function (Throwable $e, PendingRequest $request) use ($deadlineAt): bool {
$transient = $e instanceof ConnectionException
|| ($e instanceof RequestException && $e->response->status() >= 500);
$left = $deadlineAt - microtime(true) - 0.02;
return $transient && $left > 0.03 && $this->budget->tryRetry();
},
throw: false,
)
->get("/stock/{$productId}");
if ($response->successful()) {
$stock = (int) $response->json('stock');
Cache::put("inventory:last:{$productId}", $stock, now()->addMinutes(10));
return ['stock' => $stock, 'degraded' => false];
}
return $this->fallback($productId);
}
/**
* @return array{stock: int|null, degraded: bool}
*/
private function fallback(int $productId): array
{
return ['stock' => Cache::get("inventory:last:{$productId}"), 'degraded' => true];
}
}ریختن بار بر اساس زمان صف: NGINX هدر X-Request-Start را میزند؛ درخواستی که در backlog PHP-FPM بیش از حد منتظر مانده یک 503 ارزان میگیرد:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Load shedding by queue time. NGINX stamps every request on arrival:
* fastcgi_param HTTP_X_REQUEST_START "t=${msec}";
* If a request waited in the PHP-FPM listen backlog (or the Octane queue)
* longer than the budget, the user has probably given up: answer a cheap 503
* instead of doing work nobody will read. Sheddable routes (prefetch,
* recommendations) get a tighter budget than critical ones (checkout).
*/
class ShedQueuedRequests
{
public function handle(Request $request, Closure $next, string $criticality = 'critical'): Response
{
$header = (string) $request->header('X-Request-Start', '');
if (preg_match('/^t=(\d+(?:\.\d+)?)$/', $header, $m) === 1) {
$queuedMs = (microtime(true) - (float) $m[1]) * 1000;
$budgetMs = $criticality === 'sheddable' ? 200 : 1000;
if ($queuedMs > $budgetMs) {
return response('overloaded, retry later', 503, ['Retry-After' => '1']);
}
}
// The absolute deadline for downstream calls, shared by every client.
$request->attributes->set('deadline_at', microtime(true) + 1.0);
return $next($request);
}
}تنزل آبرومندانه با Cache::flexible (stale-while-revalidate در برابر stampede) و پرچم تخمین:
<?php
namespace App\Http\Controllers;
use App\Clients\InventoryClient;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
class ProductController extends Controller
{
public function show(Request $request, int $id, InventoryClient $inventory): JsonResponse
{
$deadlineAt = (float) $request->attributes->get('deadline_at', microtime(true) + 1.0);
// Cache::flexible serves a stale value while one request refreshes it
// in the background: no stampede on the database when an entry expires.
$product = Cache::flexible("product:{$id}", [60, 600], fn () => \App\Models\Product::findOrFail($id)->toArray());
$stock = $inventory->stock($id, $deadlineAt);
return response()
->json([
'product' => $product,
'stock' => $stock['stock'], // null = "check availability at checkout"
'stock_is_estimate' => $stock['degraded'],
])
->header('X-Degraded', $stock['degraded'] ? 'inventory' : 'none');
}
}Readiness که saturation را گزارش میکند (عمق و سن صف از طریق pendingSize، reservedSize و creationTimeOfOldestPendingJob در قرارداد صف) و liveness روی route داخلی /up:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Queue;
/**
* GET /ready reports saturation for dashboards and autoscalers. It never
* fails because a dependency is slow (that would remove capacity during a
* brownout); it fails only during maintenance or draining. Liveness stays on
* Laravel's built-in /up route, which checks only that the app boots.
*/
class ReadinessController extends Controller
{
public function __invoke(): JsonResponse
{
// Cached for 5 s so a burst of probes cannot become load themselves.
$saturation = Cache::remember('ready:saturation', 5, function (): array {
$queue = Queue::connection('redis');
$oldest = $queue->creationTimeOfOldestPendingJob('default');
return [
'queue_pending' => $queue->pendingSize('default'),
'queue_reserved' => $queue->reservedSize('default'),
'queue_oldest_age_s' => $oldest === null ? 0 : time() - $oldest,
'memory_mb' => round(memory_get_usage(true) / 1048576, 1),
];
});
$draining = app()->isDownForMaintenance() || Cache::get('draining:'.gethostname(), false);
return response()->json(['ready' => ! $draining, 'saturation' => $saturation], $draining ? 503 : 200);
}
}<?php
use App\Http\Controllers\ProductController;
use App\Http\Controllers\ReadinessController;
use App\Http\Middleware\ShedQueuedRequests;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Support\Facades\Route;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
commands: __DIR__.'/../routes/console.php',
health: '/up', // liveness: the app boots; no database, no dependencies
then: function () {
Route::get('/ready', ReadinessController::class);
Route::middleware(['throttle:api', 'shed:critical'])
->get('/api/products/{id}', [ProductController::class, 'show']);
},
)
->withMiddleware(function (Middleware $middleware): void {
$middleware->alias(['shed' => ShedQueuedRequests::class]);
$middleware->throttleWithRedis();
})
->withExceptions(function (Exceptions $exceptions): void {
//
})->create();پیشفرضها و عدالت: Http::globalOptions تا هیچ فراخوانی با پیشفرض ۳۰ ثانیه نماند، و RateLimiter::for برای هر کاربر یا IP:
<?php
namespace App\Providers;
use App\Clients\InventoryClient;
use App\Support\RetryBudget;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->app->singleton(InventoryClient::class, fn () => new InventoryClient(new RetryBudget('inventory')));
}
public function boot(): void
{
// Defaults for every outgoing call (Guzzle options): never the 30 s default.
Http::globalOptions([
'connect_timeout' => 1,
'timeout' => 5,
]);
// Per-client fairness: one tenant or crawler cannot take the whole pool.
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(600)
->by($request->user()?->id ?: $request->ip())
->response(fn (Request $request, array $headers) => response('slow down', 429, $headers));
});
// Sheddable traffic gets a much smaller share.
RateLimiter::for('prefetch', fn (Request $request) => Limit::perMinute(60)->by($request->ip()));
}
}Job صفی که نمیتواند به آبشار بپیوندد: #[Timeout(30)]، retryUntil()، backoff() با jitter، ThrottlesExceptions:
<?php
namespace App\Jobs;
use DateTime;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\Timeout;
use Illuminate\Queue\Middleware\ThrottlesExceptions;
use Illuminate\Support\Facades\Http;
/**
* A background job that must not join a cascade: bounded run time (kept
* below the connection's retry_after), a time-based attempt window, jittered
* backoff, and ThrottlesExceptions, which behaves like a circuit breaker for
* jobs: after 10 exceptions further attempts are delayed for 5 minutes instead
* of hammering the failing partner.
*/
#[Timeout(30)]
class SyncInventory implements ShouldQueue
{
use Queueable;
public function __construct(public int $warehouseId)
{
}
public function handle(): void
{
Http::connectTimeout(1)
->timeout(10) // below the job timeout, which is below retry_after
->get("http://warehouse.internal/warehouses/{$this->warehouseId}/stock")
->throw();
}
/**
* Time-based attempts, as the docs recommend with ThrottlesExceptions.
*/
public function retryUntil(): DateTime
{
return now()->addMinutes(30);
}
/**
* Jittered exponential backoff in seconds, so 10,000 failed jobs do not
* come back in the same second.
*/
public function backoff(): int
{
return random_int(0, min(300, 5 * (2 ** $this->attempts())));
}
/**
* @return array<int, object>
*/
public function middleware(): array
{
return [(new ThrottlesExceptions(10, 5 * 60))->backoff(1)];
}
}Workerهایی که خودشان را نو میکنند (برنامهٔ Supervisor با --timeout، --memory، --max-jobs، --max-time):
; Install as /etc/supervisor/conf.d/laravel-worker.conf (Supervisor reads INI syntax).
; Supervisor program for queue workers that recycle themselves before they
; leak memory, never run a job past retry_after, and stop gracefully.
[program:laravel-worker]
command=php /var/www/app/artisan queue:work redis --queue=default --sleep=3 --tries=3 --timeout=60 --max-jobs=1000 --max-time=3600 --memory=256
process_name=%(program_name)s_%(process_num)02d
numprocs=8
autostart=true
autorestart=true
startsecs=5
stopwaitsecs=70
stopasgroup=true
killasgroup=true
user=www-data
redirect_stderr=true
stdout_logfile=/var/www/app/storage/logs/worker.logیک آزمون که ثابت میکند budget تقویت را محدود میکند (۲۲ فراخوانی بهجای ۶۰):
<?php
namespace Tests\Feature;
use App\Clients\InventoryClient;
use App\Support\RetryBudget;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;
class InventoryClientTest extends TestCase
{
public function test_overloaded_dependency_gets_bounded_retries_and_a_stale_answer(): void
{
config(['cache.stores.redis' => ['driver' => 'array']]); // isolated store for the test
Cache::put('inventory:last:7', 3, 600);
Http::fake(['inventory.internal/*' => Http::response('busy', 503)]);
$client = new InventoryClient(new RetryBudget('inventory', ratio: 0.1, minRetriesPerWindow: 2));
for ($i = 0; $i < 20; $i++) {
$result = $client->stock(7, microtime(true) + 1.0);
$this->assertTrue($result['degraded']);
$this->assertSame(3, $result['stock']);
}
// Without the budget: 20 requests x 3 attempts = 60 calls.
// With it: 20 first attempts + about 2 retries.
Http::assertSentCount(22);
}
}نگاه Laravel
| قابلیت Laravel | کاربرد در برابر آبشار | نکته (مستندات Laravel 13) |
|---|---|---|
Http::timeout() / connectTimeout() | کند را سریع کنید | "By default, the HTTP client will timeout after 30 seconds"؛ پیشفرض اتصال ۱۰ ثانیه |
Http::retry($times, $sleep, $when, throw: false) | retry محدود و شرطی | $sleep میتواند closure باشد؛ $when استثنا و PendingRequest را میبیند |
Http::globalOptions([...]) | پیشفرض امن برای هر فراخوانی بیرونی | در AppServiceProvider::boot صدا زده میشود |
RateLimiter::for + Limit::perMinute()->by()->response() | عدالت برای هر کلاینت در route | پیشفرض 429؛ throttleWithRedis() برای Redis |
RateLimiter::attempt، increment، tooManyAttempts، availableIn | rate limit برای هر مسیر کد | increment روی storeهای redis، memcached و database اتمی است |
Cache::flexible($key, [fresh, stale], fn) | stale-while-revalidate: بدون stampede در انقضا | در پسزمینه دوباره محاسبه میشود |
Cache::lock | ادغام بازسازی یک کلید | قفل اتمی بین workerها |
--timeout، --memory، --max-jobs، --max-time در صف | job محدود و workerهای خودنوشونده | --timeout باید "at least several seconds shorter than your retry_after" باشد |
#[Timeout]، #[Tries]، #[Backoff]، #[FailOnTimeout]، retryUntil() | سقف برای هر job | attributeها در Illuminate\Queue\Attributes |
middlewareهای job: ThrottlesExceptions، RateLimited، WithoutOverlapping | breaker، rate limit، انحصار متقابل برای job | ThrottlesExceptions با تلاشهای زمانمحور جفت میشود |
queue:monitor --max= + رویداد QueueBusy | هشدار عمق صف | هر دقیقه زمانبندی شود |
--workers و --max-requests در Octane | همزمانی محدود برای هر سرور؛ کنترل نشت | پیشفرض یک worker برای هر هستهٔ CPU؛ ۵۰۰ درخواست |
route سلامت /up + DiagnosingHealth | liveness | چک وابستگی را از liveness بیرون نگه دارید |
حل مسئلههای کلاسیک
یک لرزش به retry storm تبدیل شد
| راهحل | چطور | مزیت | هزینه / محدودیت |
|---|---|---|---|
| retry فقط در یک لایه | لایههای درونی fail fast میکنند و خطا برمیگردانند | ضرب حذف میشود | به توافق بین تیمها نیاز دارد |
| سقف برای هر درخواست | ۲ تا ۳ تلاش | بدترین حالت هر درخواست محدود است | حجم کل را محدود نمیکند |
| retry budget برای هر کلاینت | token bucket، ۱۰٪ درخواستها | سربار کل حدود 1.1x | در حادثه چند retry مشروع رد میشود |
| Full jitter | random(0, min(cap, base·2^n)) | همزمانی را میشکند | میانگین تأخیر کمی بیشتر |
| status صریح اضافهبار | 503 + Retry-After، 429 | کلاینتها بهجای retry عقب میکشند | کلاینتها باید رعایتش کنند |
یک وابستگی کند همهٔ threadها را گیر انداخته
| راهحل | چطور | مزیت | هزینه / محدودیت |
|---|---|---|---|
| deadline از p99.9 مقصد | Http::timeout(0.3)، ForHop | زمان نگهداشتن محدود | بعضی موفقیتهای کند خطا میشوند |
| bulkhead برای هر وابستگی | pool چهلتایی برای recommendations | بقیه threadهایشان را نگه میدارند | poolها باید اندازهگذاری شوند |
| Circuit breaker | باز شدن بعد از N شکست، probe در حالت نیمهباز | فراخوانیها در میکروثانیه شکست میخورند | رفتار حالتدار؛ تنظیم و آزمون لازم |
| پاسخ تنزلیافته | نسخهٔ کهنه، صفحهٔ ناقص | کاربران همچنان سرویس میگیرند | تصمیم محصول برای هر قابلیت |
همین قاعده درون دیتابیس هم برقرار است. deadline برای هر session در PostgreSQL نمیگذارد یک دستور کند جای pool را برای همیشه بگیرد، و pg_stat_activity نشان میدهد pool در دست sessionهای منتظر است یا طولانی:
-- PostgreSQL: database-side deadlines for an application role
ALTER ROLE app_web SET statement_timeout = '2s'; -- SQLSTATE 57014 when hit
ALTER ROLE app_web SET lock_timeout = '500ms'; -- do not queue behind locks
ALTER ROLE app_web SET idle_in_transaction_session_timeout = '10s'; -- release forgotten transactions
-- Who is holding the connections right now?
SELECT state, wait_event_type, count(*) AS sessions,
max(now() - query_start) AS longest
FROM pg_stat_activity
WHERE datname = current_database()
GROUP BY state, wait_event_type
ORDER BY sessions DESC;
-- Headroom against SQLSTATE 53300 (too_many_connections)
SELECT current_setting('max_connections')::int AS max_connections,
count(*) AS in_use
FROM pg_stat_activity;
-- MySQL equivalent for read queries: per-session SELECT deadline in milliseconds
-- SET SESSION max_execution_time = 2000;health checkها ناوگان شلوغ را میکشند
| راهحل | چطور | مزیت | هزینه / محدودیت |
|---|---|---|---|
| liveness بدون وابستگی | /livez یا /up در Laravel | شلوغ یعنی مرده نیست | پردازهٔ گیرکرده ممکن است بیشتر زنده بماند (watchdog اضافه کنید) |
| readiness برای شروع و drain | 503 فقط هنگام گرم شدن یا drain | بدون flapping زیر بار | saturation بهجایش برای هر درخواست مدیریت میشود |
| سقف بیرون انداختن | max_ejection_percent در Envoy، panic threshold | هرگز بیشتر ناوگان بیرون نمیافتد | بعضی میزبانهای بد ترافیک میگیرند |
| Slow start | AWS ALB، slow start در Envoy | میزبانهای restartشده گرم میشوند | رسیدن به ظرفیت کامل طولانیتر |
پاک شدن یا restart شدن cache همهچیز را به دیتابیس میفرستد
| راهحل | چطور | مزیت | هزینه / محدودیت |
|---|---|---|---|
| ادغام درخواست | singleflight، Cache::lock | یک fetch از منبع برای هر کلید | منتظرها در یک شکست شریکاند |
| Stale-while-revalidate | Cache::flexible، stale-while-revalidate در CDN | انقضای همزمان نداریم | دادهٔ کمی کهنه برای مدتی کوتاه |
| jitter برای TTL | TTL ± ۱۰٪ | انقضاها پخش میشوند | هزینهٔ قابلذکری ندارد |
| گرم کردن پیش از ready | پر کردن cache پیش از قبولی readiness | ترافیک سرد نداریم | شروع کندتر |
| با آن مثل capacity cache رفتار کنید | دیتابیس را برای cache سرد تدارک ببینید یا با shedding محافظتش کنید | برنامهریزی ظرفیت صادقانه | هزینه |
autoscaler در جهت غلط میرود
| راهحل | چطور | مزیت | هزینه / محدودیت |
|---|---|---|---|
| مقیاس روی saturation | utilisation worker، سن صف، در جریان / سقف | جهت درست برای انتظار I/O | معیارهای بیشتر برای انتشار |
| headroom ایستا | N + 1 zone در اوج | پیش از عمل scaler زنده میماند | ظرفیت بیکار پولی |
| خاموش کردن scale-in در حادثه | قدمی در runbook | ظرفیت و نشستهای SSH حفظ میشود | دستی |
| آزمون بار scaler | ده برابر batch معمول را در staging تدارک ببینید | سقف FD و سهمیه را پیدا میکند | زحمت آزمون |
deploy یا ارسال پیکربندی زیر بار
| راهحل | چطور | مزیت | هزینه / محدودیت |
|---|---|---|---|
| مرحلهای کردن هر تغییر، از جمله پیکربندی | DOG، PIG، Canary، Global (فرایند Cloudflare) | شعاع انفجار کوچک | تغییر اضطراری کندتر |
| rollout آگاه از ظرفیت | taskهای کمتری در اوج بهروز شوند | بدون افت ظرفیت در اوج | rollout طولانیتر |
| محافظ منبع برای هر عملیات | موتورهای regex با تضمین زمان اجرا، بودجهٔ CPU برای هر درخواست | یک قانون بد نمیتواند یک هسته را بگیرد | تعویض موتور |
| کلید خاموشکنندهٔ سراسری سریع | «global terminate» در Cloudflare | بازیابی در چند دقیقه | نباید به سیستم در حال شکست وابسته باشد |
بازیابی از فروپاشی
Runbook order (Google SRE immediate steps + the simulator's lesson)
1 Declare the incident; check recent changes and revert those that touch capacity or request profile
2 Stop the loop: block or rate-limit at the edge (admit 1-10%), turn off batch load and retries
3 Stop capacity removal: disable killing health checks and scale-in
4 Fix or paper over the trigger (more memory, rollback, kill switch)
5 Let servers become healthy and warm (caches, connections, JIT)
6 Ramp traffic back gradually (slow start, edge ramp over minutes), watching saturation
7 Drain backlogs at a controlled rate (GitHub: watch partners and TTLs)
8 Re-enable retries and batch work last; write the blameless postmortemانتخاب
از نشانه تا اولین اقدام
| نشانه | اولین اقدام | دفاعی که بعداً اضافه میشود | دلیل |
|---|---|---|---|
| تلاش در ثانیه خیلی بیشتر از تلاش اول در ثانیه | retry را خاموش یا کم کنید؛ rate limit در edge | retry budget، یک لایهٔ retry، jitter | retry storm |
| تأخیر بالا، CPU پایین، threadها مشغول | deadline وابستگی کند را کوتاه کنید | bulkhead، breaker، fail fast | slow vs down |
| سن صف رو به رشد | ریختن در edge یا پردازه | صف محدود، admission control | اضافهبار |
| شکست health check روی میزبانهای شلوغ | چک کُشنده را خاموش کنید، panic mode | جدا کردن liveness/readiness، سقف بیرون انداختن | حذف ظرفیت |
| اشباع دیتابیس بعد از restart شدن cache | خواندنها را بریزید، نسخهٔ کهنه بدهید | ادغام، گرم کردن، برنامهریزی capacity cache | stampede |
| میزبانهای restartشده فوراً میمیرند | بار را پایین نگه دارید، slow start | پیکربندی slow start، گرم شدن پیش از readiness | thundering herd on restart |
| autoscaler در حادثه کوچک میکند | scale-in را منجمد کنید | مقیاس بر اساس saturation، headroom | سیگنال غلط |
| خطاها بعد از رفتن ماشه میمانند | هل اصلاحی قوی: ریختن در edge + بازگشایی تدریجی | آزمون بار فراتر از زانو و برگشت | حالت metastable |
کدام دفاع در کدام لایه
| لایه | دفاع | محصول |
|---|---|---|
| Edge / CDN | rate limit سراسری، بستن ترافیک بد، بازگشایی تدریجی بعد از بازیابی | Cloudflare، AWS WAF، CloudFront، limit_req در NGINX |
| Load balancer / mesh | circuit breaker، outlier detection با سقف، panic threshold، slow start، retry budget | Envoy، Istio، AWS ALB، HAProxy |
| پردازهٔ سرویس | admission control، صف محدود، deadline، liveness/readiness | resilience در Go، middleware در Laravel، تعداد worker در Octane |
| کتابخانهٔ کلاینت | timeout، retry budget، jitter، bulkhead، breaker | resilience.Client، HTTP client در Laravel + RetryBudget، gRPC |
| لایهٔ داده | timeout دستور و قفل، سقف connection، pooler | PostgreSQL، PgBouncer، max_execution_time در MySQL |
| کار ناهمگام | مصرفکنندهٔ محدود، backpressure، backoff با jitter، breaker | صفهای Laravel، Kafka، RabbitMQ |
| سازمان | آزمون بار تا زانو، تمرین chaos، postmortem بیسرزنش | Chaos Engineering |
در معماری: از یک پردازه تا سیستم توزیعشده
Monolith (یکپارچه): یک پردازه، یک دیتابیس
حتی monolith هم درونی آبشار میکند: یک کوئری گزارش کند connectionهای دیتابیس را نگه میدارد، workerهای وب منتظر pool میمانند، health check در load balancer (که از دیتابیس کوئری میگیرد) شکست میخورد و instance جایگزین میشود. سادهترین چیدمان درست: یک pool از PHP-FPM یا Octane با اندازهٔ معلوم، statement_timeout برای نقش وب، timeout برای همهٔ HTTP clientها، routeی برای liveness که به دیتابیس دست نمیزند (/up)، workerهای صف با --timeout و --memory، و نقش یا pool جدا برای گزارشها تا نتوانند connectionهای لایهٔ وب را بگیرند.
Modular monolith: مرز بدون شبکه
ماژولها یک پردازه را شریکاند، پس thread pool، حافظه و connection pool را هم شریکاند؛ وابستگی کند یک ماژول بقیه را گرسنه میگذارد. bulkhead درونپردازهای میشود: نمونههای جدای HTTP client با timeout خودشان، صف جدا برای هر ماژول (workerهای --queue=billing جدا از --queue=emails)، connection pool یا نقش جدا، و برچسب criticality برای هر route. ماژولی که ماژول دیگر را در حلقه بهصورت همزمان صدا میزند نسخهٔ درونپردازهای ارتباط درونلایهای است: در مسیر درخواست از آن پرهیز کنید.
Microservices (میکروسرویسها): هر پیکان مسیری برای بار و تأخیر است
Browser -> API gateway -> product -> inventory -> PostgreSQL
-> pricing -> Redis
-> reviews (optional)
1 inventory slows to 3 s (lock contention)
2 product's threads wait; gateway's connections to product fill
3 gateway retries (3) + product retries (3) = 16 attempts per click on inventory
4 product pods fail liveness (deep check), restart cold; gateway ejects them
5 every page fails, including pages that never call inventory
With the defences: gateway deadline 800 ms, product deadline to inventory 300 ms,
retries only in the gateway with a 10% budget, bulkhead of 40 for reviews,
inventory sheds with 503 above 4 queued per worker, liveness without dependenciesآنچه از مرز سرویس عبور میکند: deadline (به شکل هدر)، criticality، کلید idempotency، status صریح اضافهبار. آنچه عبور نمیکند: حافظهٔ مشترک، تراکنش، و هر فرضی دربارهٔ سریع بودن طرف مقابل. retry در service mesh هم یک لایهٔ retry حساب میشود؛ تصمیم بگیرید کدام لایه مالک آن است (Service Communication، API Gateway & Service Mesh).
داده توزیعشده (Distributed data): replica، cache، region
replicaها از راه تأخیر replication آبشار میکنند (GitHub 2018: replicaهای خواندن ساعتها عقب؛ افزودن replica مصرف هر replica را کم کرد تا replication جبران کند)، از راه خودکارسازی failover (ارتقا بین regionها) و از راه cacheهایی که capacity cache شدهاند. failover منطقهای پخش دوبارهٔ بار در بزرگترین مقیاس است: regionی در ۷۰٪ که ترافیک region دیگر را میگیرد به ۱۴۰٪ میرسد. قاعدهها: headroom برای هر region به اندازهٔ failoverی که برنامهریزی کردهاید، ارتقای بینمنطقهای فقط وقتی برنامه با آن تأخیر زنده میماند، گرم کردن cache پیش از جابهجایی ترافیک، و جدا کردن control planeها (سهمیه، احراز هویت، پیکربندی) از data plane (Google 2020: احراز هویت وابستگی مشترک تقریباً همهچیز بود). سازوکار replication در Replication, Read Replicas & Failover است.
مسیر مقیاس (Scaling path): ۱×، ۱۰×، ۱۰۰×
| مقیاس | آبشار معمول | دفاعهایی که لازم میشوند |
|---|---|---|
| 1x (یک region، چند instance) | کوئری یا شریک کند همهٔ workerها را گیر میاندازد | timeout همه جا، liveness بدون وابستگی، سقف worker |
| 10x (سرویسهای زیاد، autoscaling) | retry storm بین لایهها، کشتن با health check، cache stampede | retry budget، یک لایهٔ retry، صف محدود، bulkhead، slow start، آزمون بار فراتر از زانو |
| 100x (چند region، control plane مشترک) | ارسال سراسری پیکربندی، اضافهبار failover منطقهای، وابستگی به control plane | rollout مرحلهای پیکربندی، cell، انتشار criticality، ریختن در edge با بازگشایی تدریجی، تمرین chaos، مانیتورینگ مستقل |
آزمایشگاه: مارپیچ مرگ و اصلاحها را بازتولید کنید
شبیهساز و آزمونها برنامهٔ Go تکپردازهای هستند و برای این صفحه اجرا شدهاند. بقیه با برچسب «خروجی موردانتظار؛ اجرا نشده» آمدهاند.
cd docs/snippets/system-design/cascading-failures/go
go test ./...
# ? academy/cascading-failures/after [no test files]
# ? academy/cascading-failures/before [no test files]
# ? academy/cascading-failures/cmd/spiral [no test files]
# ok academy/cascading-failures/resilience 0.241s
# ok academy/cascading-failures/spiral 0.371s
go run ./cmd/spiral # deterministic, under a second۱. خط زمانی سیستم سادهلوحانه و محافظتشده (بخشی از خروجی واقعی):
naive
t(s) offered attempts good late failed shed up queue kills
18 1400 1400 1396 0 0 0 10 7 0
20 2600 2600 1955 0 0 0 10 628 0
24 2600 2600 1715 0 0 0 10 3783 0
26 2600 2600 765 660 0 0 6 3527 4
28 2600 10377 0 0 2590 0 0 0 1
30 1400 12726 0 0 3776 0 0 0 0
40 1400 2800 222 202 0 0 9 3586 0
70 1400 13017 0 0 5179 0 0 0 0
protected
20 2600 2858 1968 0 575 839 10 29 0
28 2600 2859 1992 0 608 868 10 28 0
30 1400 1421 1455 0 3 17 10 0 0
40 1400 1408 1396 0 0 9 10 4 0۲. یک دفاع در هر بار (goodput = good / offered؛ تقویت = attempts / offered در ۳۰ تا ۶۰ ثانیه):
config 0-20s 20-30s 30-60s 60-90s ampl30-60
naive 99.8% 44.2% 6.4% 6.2% 3.50x
naive + deadlines 99.8% 25.8% 7.4% 7.2% 2.88x
naive + retry budget/jitter 99.8% 44.2% 14.0% 12.0% 1.08x
naive + bounded queue 99.8% 76.8% 100.2% 100.0% 1.01x
naive + liveness-only health 99.8% 44.2% 4.5% 1.2% 2.83x
protected - bounded queue 99.8% 26.0% 99.5% 100.0% 1.01x
protected 99.8% 76.5% 100.1% 100.0% 1.01xاز این جدول چه بخوانیم: در این مدل صف محدود مهمترین قطعکننده است، چون تأخیر را زیر timeout کلاینت نگه میدارد و در نتیجه timeout و retry اصلاً شروع نمیشوند؛ deadline بهتنهایی وضع را بدتر میکند (timeout کوتاهتر با retry فوری retry بیشتری شلیک میکند، 2.88x)؛ retry budget بهتنهایی تقویت را به 1.08x میرساند ولی جلوی حلقهٔ GC و OOM صف بیسقف را نمیگیرد؛ و probe فقط-liveness بهتنهایی کشتن را حذف میکند ولی حلقهٔ صف را باقی میگذارد. مقدارهای بالای ۱۰۰٪ بعد از جهش، درخواستهای ثانیهٔ قبلیاند که تمام میشوند. اینها نتیجهٔ مدلاند و شکل را نشان میدهند؛ وزنها در سیستم شما فرق دارد و برای همین همین آزمایش را روی سیستم خودتان اجرا میکنید.
۳. اقدامهای بازیابی و ۴. زانو: جدولها در بازیابی و اضافهبار آمدهاند.
۵. ریختن بار در سرویس Go (خروجی موردانتظار؛ اجرا نشده). go run ./after را با یک inventory جعلی روی inventory.internal اجرا کنید (مثلاً یک رکورد در /etc/hosts به یک stub محلی که ۲ ثانیه میخوابد)، بعد:
hey -z 20s -c 600 http://localhost:8080/product # expected, not run
# expected shape: a mix of 200 (stale copy, X-Degraded) and 503 with Retry-After;
# p99 latency stays near the 1 s budget instead of growing; no goroutine growth
curl -s localhost:8080/readyz | jq .saturation # {"in_flight":256,"capacity":256,"waiting":128,...}۶. health checkهایی که میکشند (خروجی موردانتظار؛ اجرا نشده). در یک cluster از kind یا minikube سرویس before را با livenessProbe.httpGet.path: /healthz deploy کنید و inventory را کند کنید:
kubectl get pods -w # expected, not run
# product-7c9 0/1 Running 3 (10s ago)
# product-7c9 0/1 CrashLoopBackOff 4 (5s ago)
kubectl describe pod product-7c9 | grep -i liveness
# Warning Unhealthy Liveness probe failed: HTTP probe failed with statuscode: 503probe را به /livez از after عوض کنید؛ podها بالا میمانند و /readyz saturation را گزارش میکند.
بدفهمیهای رایج
| باور | واقعیت |
|---|---|
| «ماشه علت ریشهای است.» | اثر نگهدارنده علت است؛ ماشه فقط زمانبندی را توضیح میدهد (Bronson و همکاران). |
| «retry قابلیت اعتماد را بالا میبرد.» | در اضافهبار بار را در هر لایه ضرب میکند (64x، 243x)؛ budget و یک لایهٔ retry الزامیاند. |
| «timeout طولانیتر یعنی شکست کمتر.» | یعنی منبع نگهداشتهشدهٔ بیشتر و کار محکوم بیشتر؛ ۵٪ درخواست گیرکرده میتواند ۸۰٪ خطا بسازد. |
| «صف بزرگتر اضافهبار را جذب میکند.» | اضافهبار را به تأخیر و حافظه تبدیل میکند؛ سقف بگذارید و بریزید. |
| «کند بهتر از قطع است.» | برای فراخوانها کند بدتر است: thread، connection و حافظه را گیر میاندازد. |
| «health check عمیق دقیقتر است.» | یک وابستگی کند را به restart کل ناوگان تبدیل میکند؛ برای liveness فقط پردازه را چک کنید. |
| «autoscaling جای headroom را میگیرد.» | دقیقهها عقب است، ممکن است در جهت غلط برود و تدارک خودش را غرق کند. |
| «افزودن ظرفیت مارپیچ مرگ را درمان میکند.» | اغلب نه: سرورهای جدید سرد میرسند و آنها هم غرق میشوند؛ اول بریزید، بعد تدریجی باز کنید. |
| «همه را restart کن تا پاک شود.» | restart همزمان یعنی هجوم سرورهای سرد؛ canary و آهسته restart کنید. |
| «load shedding availability را پایین میآورد.» | goodput را در ظرفیت نگه میدارد؛ پذیرفتن همه میتواند یعنی سرویس به هیچکس. |
| «circuit breaker کافی است.» | برای شکست سخت یک وابستگی کمک میکند؛ شکست کند deadline و bulkhead لازم دارد. |
| «cache ما فقط بهینهسازی است.» | اگر سرویس با cache خالی زنده نمیماند، capacity cache است و باید همینطور برنامهریزی شود. |
| «آزمون بار در اوج مورد انتظار کافی است.» | فراتر از زانو و برگشت به عادی را آزمون کنید؛ آبشارها همانجا زندگی میکنند. |
| «CPU سیگنال saturation است.» | threadهای منتظر I/O مصرف CPU را پایین میآورند؛ کار در جریان، سن صف و مصرف pool را ببینید. |
چکیده
| موضوع | به خاطر بسپارید |
|---|---|
| تعریف | خرابیای که با بازخورد مثبت رشد میکند (Google SRE) |
| مارپیچ مرگ | اضافهبار ← تأخیر ← retry ← تمام شدن منابع ← شکست چکها ← حذف ظرفیت ← اضافهبار بیشتر |
| Metastable | بعد از ماشه هم میماند؛ هل قوی لازم دارد (ریختن و بعد بازگشایی تدریجی) |
| Goodput | پاسخهای مفید و بهموقع؛ در زانو باید صاف بماند، نه سقوط کند |
| Retry | یک لایه، ۲ تا ۳ تلاش، budget دهدرصدی، full jitter، هرگز روی 4xx یا 429 |
| Deadline | یک بار در edge تعیین شود، باقیمانده منتشر شود، کار منقضی پیش از شروع دور ریخته شود |
| صفها | کوتاه (۵۰٪ workerها یا کمتر)، محدود، 503 سریع در سقف؛ LIFO/CoDel را در نظر بگیرید |
| Slow vs down | کندی منبع گیر میاندازد؛ با timeout و fail fast کند را سریع کنید |
| Health check | liveness = فقط پردازه؛ readiness = شروع و drain؛ سقف برای بیرون انداختن |
| Cache | latency cache در برابر capacity cache؛ ادغام miss؛ گرم کردن پیش از ترافیک |
| Autoscaling | عقب است؛ روی saturation مقیاس بدهید؛ headroom از نوع N + 1 یا N + 2 |
| تشخیص | four golden signals؛ saturation و p99 اول تکان میخورند؛ تلاش در برابر تلاش اول |
| بازیابی | برگرداندن تغییر، ریختن در edge، قطع retry و scale-in، اصلاح ماشه، گرم کردن، بازگشایی، تخلیهٔ انباشت |
| Postmortem | بیسرزنش؛ حلقه و قطعکنندهاش را نام ببرید، نه فقط ماشه را |
| شبیهساز | سادهلوحانه ۶٪ goodput بعد از جهش، تقویت 3.5x؛ محافظتشده ۱۰۰٪، 1.01x |
خودآزمایی: پرسش و پاسخ
- حیاتی تقریباً در هر مصاحبه پرسیده میشود
- مهم پرتکرار؛ در سطح senior انتظار میرود
- تکمیلی عمق بیشتر؛ تمایز ایجاد میکند
۱ — یک frontend هزار thread دارد و 1,000 QPS با تأخیر ۱۰۰ میلیثانیه سرویس میدهد. ۵٪ درخواستها تا deadline صدثانیهای گیر میکنند. تقریباً چه سهمی سرویس میگیرد؟ مهم
پاسخ
پاسخ: حدود 19.6%: سهم گیرکرده 50 × 100 = 5,000 thread-ثانیه در هر ثانیه میخواهد بهعلاوهٔ ۹۵ برای بقیه، در برابر ۱٬۰۰۰ موجود (مثال تأخیر دوحالته در Google SRE)؛ یعنی نرخ خطای 80.4% از یک خرابی ۵٪.
۲ — سه لایه هر کدام ۴ تلاش میکنند. یک کلیک در پایین پشته چند تلاش میسازد و دو اصلاح ارزان کداماند؟ حیاتی
پاسخ
پاسخ: 4^3 = 64. retry فقط در یک لایه (بقیه fail fast کنند و خطا را بالا بفرستند) و یک retry budget حدود ۱۰٪ برای هر کلاینت که سربار را نزدیک 1.1x نگه میدارد.
۳ — چرا شبیهساز سادهلوحانه بعد از برگشتن بار به ۷۰٪ در ثانیهٔ ۳۰ فروریخته ماند؟ تکمیلی
پاسخ
پاسخ: یک اثر نگهدارنده: تأخیر بالای timeout کلاینت retry ساخت (3.5x تلاش)، صفهای بیسقف کندی GC و OOM آوردند، health checkهایی که در صف منتظر میماندند سرورها را کشتند و سرورهای restartشده سرد برگشتند و دوباره غرق شدند. ماشه رفته بود؛ حلقهها نه.
۴ — تفاوت بررسی سلامت پردازه و بررسی سلامت سرویس چیست و liveness در Kubernetes کدام را باید به کار ببرد؟ حیاتی
پاسخ
پاسخ: سلامت پردازه میپرسد آیا binary اصلاً پاسخ میدهد و مال scheduler است؛ سلامت سرویس میپرسد آیا الان میتواند این دسته درخواست را سرویس دهد و مال load balancer است. liveness باید فقط سلامت پردازه باشد، بدون چک وابستگی و بدون صف شدن پشت ترافیک.
۵ — چرا autoscaling بر اساس CPU ممکن است در یک حادثهٔ شبکه لایهٔ وب را کوچک کند؟ مهم
پاسخ
پاسخ: threadها منتظر I/O کند میمانند، پس مصرف CPU پایین میآید در حالی که saturation (workerهای مشغول) بالا میرود؛ autoscaler اسلک دقیقاً به همین دلیل اول کوچک کرد. برای لایههای I/O-محور روی utilisation worker یا سن صف مقیاس بدهید.
۶ — یک cluster کش restart میشود و دیتابیس میافتد. «capacity cache» اینجا یعنی چه؟ دو راه کاهش نام ببرید. مهم
پاسخ
پاسخ: سرویس با cache خالی نمیتواند بارش را تحمل کند، پس cache ظرفیت حمل میکند نه فقط تأخیر. راهها: ادغام missها برای هر کلید (singleflight، Cache::lock)، stale-while-revalidate (Cache::flexible)، گرم کردن پیش از ترافیک، تدارک یا shedding برای حالت سرد.
۷ — در فروپاشی، چرا «همه را restart کن» خطرناک است و slow start چه میکند؟ مهم
پاسخ
پاسخ: همهٔ سرورها در یک لحظه سرد برمیگردند و کل ترافیک را میگیرند؛ هجوم گله در restart که اضافهبار را دوباره به راه میاندازد. slow start (AWS ALB، Envoy) سهم ترافیک میزبانهای تازهسالم را تدریجی بالا میبرد تا cache و connectionها اول گرم شوند.
۸ — ترتیب دستورالعمل بازیابی برای یک خرابی metastable را بگویید. مهم
پاسخ
پاسخ: بررسی و برگرداندن تغییرات اخیر؛ ریختن در edge (پذیرفتن درصد کوچکی) و توقف retry و کار دستهای؛ توقف حذف ظرفیت؛ اصلاح ماشه؛ گرم شدن سرورها؛ بازگشایی تدریجی ترافیک؛ تخلیهٔ کنترلشدهٔ انباشت؛ و در آخر فعال کردن دوبارهٔ retry و کار دستهای.
۹ — کدام یک از four golden signals معمولاً اول در آبشار تکان میخورد و چرا ارزش دارد «تلاش برای هر تلاش اول» را رسم کنیم؟ مهم
پاسخ
پاسخ: saturation و latency (Google SRE: افزایش تأخیر اغلب نشانهٔ پیشروی saturation است). نسبت تلاش به تلاش اول بالای حدود 1.1 یک retry storm را پیش از آنکه نرخ خطا توضیحش دهد آشکار میکند.
۱۰ — سازوکار نگهدارنده یا تقویتکننده در S3 2017، Cloudflare 2019 و Google 2020 چه بود؟ تکمیلی
پاسخ
پاسخ: S3: ظرفیت حذفشده restart کامل زیرسیستمهای index و placement را لازم کرد که سالها کامل restart نشده بودند. Cloudflare: یک قانون regex که در چند ثانیه سراسری شد CPU همهٔ هستههای HTTP را تمام کرد و محافظت CPU هم حذف شده بود. Google: خودکارسازی سهمیهٔ User ID Service را کم کرد چون مصرف صفر گزارش شده بود، پس رهبر Paxos نتوانست بنویسد و احراز هویت تقریباً برای همهٔ سرویسها شکست خورد.
۱۱ — چرا timeout کوتاه کلاینت بدون retry budget گاهی از timeout بلند بدتر است؟ حیاتی
پاسخ
پاسخ: timeout کوتاهتر retry را زودتر شلیک میکند، پس retryهای فوری سریعتر میرسند و تقویت بیشتر میشود؛ در شبیهساز «naive + deadlines» از سادهلوحانهٔ خالی بدتر بود (25.8% در جهش، تقویت 2.88x). deadline باید با انضباط retry و چک انقضا در سرور همراه باشد.
واژهنامه
| اصطلاح | معنا |
|---|---|
| خرابی آبشاری (Cascading failure) | خرابیای که با بازخورد مثبت رشد میکند و از یک بخش سیستم به بخشهای دیگر پخش میشود |
| حلقهٔ بازخورد مثبت (Positive feedback loop) | خروجیای (خطا، تأخیر، ظرفیت از دست رفته) که ورودی خودش (بار) را بالا میبرد |
| اضافهبار (Overload) | بار ارسالی بیشتر از نرخی که سرور میتواند کار مفید تمام کند |
| Goodput | پاسخهای درست و بهاندازهٔ کافی سریع برای استفاده؛ گذردهی منهای هدررفت |
| زانو (Knee) | باری که از آن به بعد goodput همراه بار ارسالی بالا نمیرود |
| مارپیچ مرگ (Death spiral) | فروپاشی خودنگهدار: اضافهبار، تأخیر، retry، تمام شدن منابع، حذف ظرفیت، اضافهبار بیشتر |
| خرابی metastable (Metastable failure) | حالت بدی که به خاطر اثر نگهدارنده بعد از برداشتن ماشه باقی میماند |
| حالت آسیبپذیر (Vulnerable state) | سالم ولی آنقدر کارآمد که یک ماشه میتواند آن را به حالت metastable ببرد |
| اثر نگهدارنده (Sustaining effect) | حلقهای (تقویت یا افت کارایی) که خرابی metastable را ادامه میدهد |
| ماشه (Trigger) | رویدادی که آبشار را شروع میکند (جهش، deploy، قطعی شبکه، query of death) |
| Query of death | درخواستی که محتوایش پردازهٔ پردازشکننده را کرش میدهد یا تمام میکند |
| طوفان retry (Retry storm) | سیل خودنگهدار retry علیه یک سرویس پرمشغله |
| تقویت retry (Retry amplification) | تلاش برای هر درخواست منطقی در پایین پشته (a^k در k لایه) |
| بودجهٔ retry (Retry budget) | سقف retry بهصورت سهمی از تلاشهای اول (حدود ۱۰٪)، برای هر کلاینت یا پردازه |
| لرزش زمانی (Jitter) | تأخیر تصادفی که کلاینتها را از همزمانی بازمیدارد؛ Full Jitter: random(0, min(cap, base·2^n)) |
| هجوم گله (Thundering herd) | بیدار شدن و اقدام همزمان کلاینتهای زیاد |
| هجوم گله در restart (Thundering herd on restart) | برگشتن همزمان همهٔ سرورها بهصورت سرد و گرفتن کل ترافیک |
| Cache stampede | miss همزمان خوانندههای زیاد روی یک کلید و هجوم به منبع (dogpile) |
| Latency cache / capacity cache | cacheی که سرویس بدون آن زنده میماند / cacheی که بدون آن بار تحمل نمیشود |
| گرم کردن cache (Cache warming) | پر کردن cache پیش از گرفتن ترافیک |
| تمام شدن connection pool (Connection pool exhaustion) | همهٔ connectionهای pool در دست، کار جدید منتظر میماند یا شکست میخورد |
| تمام شدن thread pool (Thread pool exhaustion) | همهٔ workerها مشغول (اغلب منتظر)، چیزی برای درخواست جدید یا probe نمانده |
| تمام شدن file descriptor (File descriptor exhaustion) | رسیدن به سقف فایل باز هر پردازه؛ EMFILE "Too many open files" |
| تمام شدن ephemeral port (Ephemeral port exhaustion) | نبودن port محلی آزاد برای connection بیرونی جدید؛ EADDRNOTAVAIL |
| فشار GC (GC pressure) | کار garbage collection که با مصرف heap رشد میکند و CPU میدزدد (مارپیچ مرگ GC) |
| عمق صف (Queue depth) | تعداد درخواستهای منتظر worker؛ ضرب در زمان سرویس تقسیم بر worker = انتظار |
| صف بیسقف (Unbounded queue) | صفی بدون حد؛ اضافهبار به رشد حافظه و OOM تبدیل میشود |
| Head-of-line blocking | آیتمهای پشت یک آیتم کند در ترتیب FIFO منتظر آن میمانند |
| Timeout | حداکثر انتظار برای یک عملیات |
| مهلت (Deadline) | زمان مطلقی که بعد از آن نتیجه بیارزش است |
| انتشار deadline (Deadline propagation) | فرستادن همان deadline مطلق (به شکل زمان باقیمانده) به همهٔ فراخوانیهای پاییندست |
| انتشار لغو (Cancellation propagation) | خبر دادن به فراخوانیهای پاییندست برای توقف وقتی درخواست دیگر موفق نمیشود |
| تأخیر دوحالته (Bimodal latency) | بیشتر درخواستها سریع، چندتایی تا deadline گیرکرده؛ منبع را نامتناسب نگه میدارد |
| Slow vs down | شکست کند منبع نگه میدارد و برای فراخوان از شکست سریع بدتر است |
| شکست سریع (Fail fast) | برگرداندن فوری خطا وقتی موفقیت ممکن نیست یا وابستگی قطع است |
| Circuit breaker | کلیدی سمت کلاینت که فراخوانی وابستگی در حال شکست را برای مدتی متوقف میکند |
| Bulkhead | سهم ثابت از منابع برای هر وابستگی، tenant یا criticality |
| جداسازی وابستگی (Dependency isolation) | طراحیای که در آن یک وابستگی نتواند منابع مشترک را تمام کند |
| ریختن بار (Load shedding) | رد ارزان بخشی از بار تا بقیه سریع بماند |
| کنترل پذیرش (Admission control) | تصمیم پذیرفتن یا نپذیرفتن درخواست (سقف در جریان، token bucket، utilisation) |
| فشار معکوس (Backpressure) | سیگنال «آهستهتر» به بالادست بهجای بافر کردن بیحد |
| Throttling سمت کلاینت (Client-side throttling) | کلاینتها وقتی backend زیاد رد میکند محلی رد میکنند (adaptive throttling) |
| اهمیت درخواست (Criticality) | برچسب اهمیت درخواست (CRITICAL_PLUS ... SHEDDABLE) برای ریختن کماهمیتترینها اول |
| تنزل آبرومندانه (Graceful degradation) | کار کمتر برای هر درخواست (نتیجهٔ ارزانتر یا ناقص) در اضافهبار |
| فضای اضافه (Headroom) | ظرفیت بالای بار اوج؛ N + 2 یعنی زنده ماندن با از دست دادن دو واحد |
| تأخیر autoscaler (Autoscaler lag) | فاصلهٔ شروع اضافهبار تا سرویسدهی ظرفیت جدید |
| نوسان health check (Health check flapping) | میزبانی که چون چک به بار وابسته است مدام سالم/ناسالم میشود |
| حذف ظرفیت (Capacity removal) | هر اقدامی که ظرفیت سرویسدهی را بیرون میبرد (بیرون انداختن، کشتن، drain، scale-in) |
| Lame duck | سروری در حال drain که از کلاینتها میخواهد کار جدید نفرستند |
| Panic threshold | رفتار Envoy: نادیده گرفتن وضعیت سلامت وقتی میزبان سالم خیلی کم است (پیشفرض ۵۰٪) |
| شروع آهسته (Slow start) | بالا بردن تدریجی ترافیک میزبانهای تازهسالم توسط load balancer |
| بازیابی تدریجی (Gradual recovery) | برگرداندن پلهپلهٔ ترافیک بعد از فروپاشی، با گرم شدن بین پلهها |
| Four golden signals | latency، traffic، errors، saturation (Google SRE) |
| اشباع (Saturation) | میزان پر بودن سرویس: در جریان / سقف، سن صف، مصرف pool |
| مصرف latency SLO (Latency SLO burn) | سرعت مصرف بودجهٔ خطای تأخیر توسط درخواستهای کند |
| نسبت خطا (Error ratio) | خطا تقسیم بر درخواست؛ retry تقسیم بر تلاش اول طوفان را آشکار میکند |
| Cron همزمان (Synchronized cron) | jobهای زمانبندیشدهٔ کلاینتهای زیاد که در یک لحظه اجرا میشوند |
| Leader thrash | جابهجایی مکرر رهبری زیر بار که هر بار اتصال دوباره و بازسازی میآورد |
| درخواست hedged (Hedged request) | درخواست تکراری بعد از یک تأخیر برای کم کردن دُم تأخیر؛ بار اضافه میکند |
| Postmortem | تحلیل نوشتاری یک حادثه همراه با اقدامها |
| بیسرزنش (Blameless) | متمرکز بر علتهای مشارکتکننده، بدون متهم کردن افراد یا تیمها |
منابع
- Google SRE Book — فصل ۲۲، Addressing Cascading Failures: https://sre.google/sre-book/addressing-cascading-failures/
- Google SRE Book — فصل ۲۱، Handling Overload: https://sre.google/sre-book/handling-overload/
- Google SRE Book — فصل ۶، Monitoring Distributed Systems (four golden signals): https://sre.google/sre-book/monitoring-distributed-systems/
- Google SRE Book — فصل ۱۵، Postmortem Culture: https://sre.google/sre-book/postmortem-culture/
- Google SRE Workbook — Postmortem Culture: https://sre.google/workbook/postmortem-culture/
- Michael Nygard — Release It! Second Edition (صفحهٔ ناشر، فهرست مطالب): https://pragprog.com/titles/mnee2/release-it-second-edition/
- Michael Nygard — گزیدهٔ Stability Antipatterns از Release It!: https://media.pragprog.com/titles/mnee2/antipatterns.pdf
- Bronson، Charapko، Aghayev، Zhu — Metastable Failures in Distributed Systems (HotOS 2021): https://sigops.org/s/conferences/hotos/2021/papers/hotos21-s11-bronson.pdf
- AWS — Summary of the Amazon S3 Service Disruption in the Northern Virginia (US-EAST-1) Region: https://aws.amazon.com/message/41926/
- Cloudflare — Details of the Cloudflare outage on July 2, 2019: https://blog.cloudflare.com/details-of-the-cloudflare-outage-on-july-2-2019/
- GitHub — October 21 post-incident analysis: https://github.blog/news-insights/company-news/oct21-post-incident-analysis/
- Slack Engineering — Slack's Outage on January 4th 2021: https://slack.engineering/slacks-outage-on-january-4th-2021/
- Google Cloud — حادثهٔ 20013 (۱۴ دسامبر ۲۰۲۰): https://status.cloud.google.com/incident/zall/20013
- AWS Architecture Blog — Exponential Backoff And Jitter: https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/
- AWS Builders' Library — Using load shedding to avoid overload: https://aws.amazon.com/builders-library/using-load-shedding-to-avoid-overload/
- AWS Builders' Library — Timeouts, retries, and backoff with jitter: https://aws.amazon.com/builders-library/timeouts-retries-and-backoff-with-jitter/
- AWS — ویژگیهای target group در Application Load Balancer (slow start): https://docs.aws.amazon.com/elasticloadbalancing/latest/application/edit-target-group-attributes.html
- gRPC — Deadlines: https://grpc.io/docs/guides/deadlines/
- gRPC — Retry (retryPolicy، retryThrottling): https://grpc.io/docs/guides/retry/
- Envoy — Circuit breaking: https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/upstream/circuit_breaking
- Envoy — Panic threshold: https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/upstream/load_balancing/panic_threshold
- Envoy — Slow start mode: https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/upstream/load_balancing/slow_start
- Envoy — Outlier detection: https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/upstream/outlier
- Kubernetes — Configure Liveness, Readiness and Startup Probes: https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/
- NGINX — ngx_http_proxy_module: https://nginx.org/en/docs/http/ngx_http_proxy_module.html
- PHP — پیکربندی FPM: https://www.php.net/manual/en/install.fpm.configuration.php
- PostgreSQL — Client connection defaults (statement_timeout، lock_timeout): https://www.postgresql.org/docs/current/runtime-config-client.html
- PostgreSQL — پیوست کدهای خطا: https://www.postgresql.org/docs/current/errcodes-appendix.html
- Linux man-pages — accept(2) (EMFILE، ENFILE): https://man7.org/linux/man-pages/man2/accept.2.html
- Go — پکیج context: https://pkg.go.dev/context
- Go — golang.org/x/sync/semaphore: https://pkg.go.dev/golang.org/x/sync/semaphore
- Laravel 13 — HTTP Client: https://laravel.com/docs/13.x/http-client
- Laravel 13 — Queues: https://laravel.com/docs/13.x/queues
- Laravel 13 — Octane: https://laravel.com/docs/13.x/octane
- Laravel 13 — Rate Limiting: https://laravel.com/docs/13.x/rate-limiting
- Laravel 13 — Routing (rate limiterها، middleware throttle): https://laravel.com/docs/13.x/routing
- Laravel 13 — Cache (flexible، lock): https://laravel.com/docs/13.x/cache
- Laravel 13 — Middleware: https://laravel.com/docs/13.x/middleware
- Laravel 13 — Deployment (route سلامت): https://laravel.com/docs/13.x/deployment
- Laravel framework 13.x — قرارداد صف (pendingSize، creationTimeOfOldestPendingJob): https://raw.githubusercontent.com/laravel/framework/13.x/src/Illuminate/Contracts/Queue/Queue.php