Load Shedding
"Goodput is the subset of the throughput that is handled without errors and with low enough latency for the client to make use of the response." — Amazon Builders' Library، Using load shedding to avoid overload (۵ دسامبر ۲۰۱۹)
خلاصه (Summary): هر سرور ظرفیتی دارد؛ بار بیشتر از آن سرور را «کمی کندتر» نمیکند، بیفایدهاش میکند، چون درخواستهای صفشده وقتی جواب میگیرند که کلاینت دیگر منتظر نیست. حذف عمدی بار (Load Shedding) یعنی بخشی از کار را زود و ارزان رد کنیم تا کارِ پذیرفتهشده بهموقع تمام شود. تمرکز (Focus): فرق goodput و throughput، سیگنالهای overload (زمان انتظار در صف، in-flight، CPU، تأخیر نسبت به SLO، حافظه)، محدودیت concurrency ثابت و تطبیقی (AIMD، Vegas، gradient)، بودجهٔ زمان صف و CoDel، سطوح criticality، سهمیهٔ هر مشتری، 503 در برابر 429 و Retry-After، throttling سمت کلاینت و بودجهٔ retry، TTL و overflow صف، تعامل با autoscaling، تنظیمات Envoy و NGINX و HAProxy و Kubernetes، تست و متریک، با کد Go و Laravel 13 و یک شبیهساز در آزمایشگاه. هدف یادگیری (Learning goal): برای هر سرویس بتوانید سیگنال «overload شدهایم» را نام ببرید، جلوی کار یک محدودکنندهٔ تطبیقی بگذارید، تعیین کنید کدام درخواستها اول رد شوند، به کلاینت بگویید بعد چه کند، و با load test ثابت کنید goodput بهجای سقوط روی یک سطح صاف میماند.
این فصل در گروه Resilience است، بعد از Timeouts, Retries & Jitter و Circuit Breaker و کنار Bulkheads & Graceful Degradation. محدودیت نرخ بر اساس هویت در Rate Limiting است؛ کند کردن تولیدکننده از طریق broker در Backpressure & Flow Control؛ و اینکه یک سرویس overload چطور فراخوانهایش را با خود پایین میکشد در Cascading Failures. اینجا تصمیم «کدام کار را دور بریزیم، کجا، چطور «نه» بگوییم و از کجا بفهمیم کمک کرد» را داریم.
نقشهٔ صفحه
| دنبال چه میگردید | بروید به |
|---|---|
| کل صفحه در سه جدول | همهچیز در یک دقیقه |
| چرا سرور بدتر میشود، نه فقط کندتر | چرا وجود دارد |
| Google SRE، Netflix، AWS، CoDel، Envoy | از کجا آمده |
| Goodput و سقوط | Goodput |
| چه چیزی میگوید «overload است» | سیگنالهای overload |
| محدودیت ثابت و تطبیقی | محدودیت ثابت، محدودیتهای تطبیقی |
| دور ریختن کار کهنه | بودجهٔ زمان صف و CoDel |
| چه کسی اول میبازد | سطوح criticality، سهمیه و هزینه |
| کلاینت چه میبیند | 503، 429، Retry-After، نتیجهٔ جزئی |
| کلاینتی که کمک میکند | همکاری کلاینت |
| Rate limit یا backpressure یا shedding | سه ابزار متفاوت |
| صفها | Shedding در صف |
| Autoscaling | تعامل با autoscaling |
| کدام لایه | کجا shed کنیم |
| اثبات | تست و متریک |
| عددها و knobها | سازوکار |
| کد | Go، Laravel |
| خرابیهای کلاسیک | حل مسئلههای کلاسیک |
| جدول تصمیم | انتخاب |
| از مونولیت تا ناوگان | در معماری |
| اجرای شبیهساز | آزمایشگاه |
| باورهای غلط، چکیده، خودآزمایی، واژهها | بدفهمیها، چکیده، خودآزمایی، واژهنامه |
همهچیز در یک دقیقه
ایدهها.
| ایده | به زبان ساده | مثال کوچک | ریسک اصلی |
|---|---|---|---|
| Load shedding | عمداً بخشی از درخواستها را رد کن تا بقیه بهموقع تمام شوند | وقتی ۲۰ درخواست in-flight است، فوراً 503 بده | رد کردن کاری که میشد انجام داد (false positive) |
| Goodput | پاسخهایی که بهموقع و درست رسیدند | ۱۰۰ درخواست در ثانیه با timeout یکثانیهای کلاینت | اندازهگیری throughput و ندیدن سقوط |
| Concurrency limit | سقف درخواستهای in-flight، نه درخواست در ثانیه | limit = RPS x latency: ۱۰۰ req/s با ۱۰۰ms میشود ۱۰ | عدد ثابتی که بعد از deploy یا scale-out کهنه میشود |
| Adaptive limit | سقف با تأخیر یا خطای اندازهگیریشده جابهجا میشود | Netflix concurrency-limits، Envoy adaptive concurrency | نوسان، مبنای ضعیف minRTT |
| Queue-time budget | درخواستی که زیاد معطل مانده دور ریخته میشود | X-Request-Start قدیمیتر از ۵۰۰ms | اختلاف ساعت proxy و برنامه |
| Criticality tier | برچسبی که تعیین میکند چه کسی اول رد شود | CRITICAL_PLUS، CRITICAL، SHEDDABLE_PLUS، SHEDDABLE | همه خودشان را critical برچسب میزنند |
| همکاری کلاینت | کلاینت وقتی گفته شود آهسته میشود | adaptive throttling، retry budget، رعایت Retry-After | retryهایی که overload را چند برابر میکنند |
سیگنالها، از دیر به زود.
| سیگنال | چه چیزی را میسنجد | چه وقت واکنش نشان میدهد | ضعف |
|---|---|---|---|
| تأخیر نسبت به SLO | زمانی که کاربر میبیند | دیر: آسیب شده | موفقیتهای کند و ردهای سریع در یک histogram قاطی میشوند |
| استفادهٔ CPU | اشباع محاسبه | متوسط | کور نسبت به انتظار I/O و رقابت روی قفل |
| فشار حافظه | استفادهٔ heap یا cgroup | دیر، شبیه پرتگاه | OOM kill پیش از شیب ملایم میرسد |
| درخواستهای in-flight | همزمانی در همین لحظه | زود | به یک limit خوب برای مقایسه نیاز دارد |
| طول صف | اندازهٔ backlog | زود | با تغییر زمان سرویس، یک طول یعنی انتظار متفاوت |
| زمان انتظار در صف | سن قدیمیترین یا بعدی آیتم | زودترین و مستقیمترین | به timestamp در درِ ورودی نیاز دارد |
چه برگردانیم.
| وضعیت | Status | هدرها | کلاینت باید |
|---|---|---|---|
| سرور overload است | 503 Service Unavailable | Retry-After: 1 بهعلاوهٔ jitter | عقب بنشیند، در بودجهاش retry کند |
| این مشتری از سهمیه گذشته | 429 Too Many Requests | Retry-After | فقط همین فراخوان را کند کنید |
| overload است و retry کمکی نمیکند | 503 | نشانهٔ صریح «retry نکن» | خطا را بالا بدهد، retry نکند |
| جواب ارزانتری هست | 200 | Warning یا فیلدی که نتیجه را جزئی علامت بزند | نتیجهٔ degraded را نمایش دهد |
| اتصال در listener رد شده | TCP reset یا بدون پاسخ | ندارد | مثل 503 رفتار کند |
این تصویر خلاصهٔ کل فصل است. زیر ظرفیت، goodput برابر بار ورودی است. بالای ظرفیت، سروری که همه چیز را میپذیرد وقتش را صرف درخواستهایی میکند که کلاینتشان رفته و goodput به صفر نزدیک میشود. سروری که مازاد را رد میکند goodput را روی ظرفیت صاف نگه میدارد. عددهای آزمایشگاه از شبیهساز همین فصل آمدهاند.
چرا وجود دارد
سرور یک صف با چند کارگر است. وقتی بار ورودی از توان کارگرها بیشتر شود صف بیحد رشد میکند، همهٔ درخواستها بیشتر منتظر میمانند و دیر یا زود انتظار از timeout کلاینت میگذرد. از آن لحظه هر پاسخ هدر رفته است: سرور کار را کرد و کسی جوابش را نخواند. Builders' Library این شکل را میگوید: "When a system is given more work than its resources support, it becomes slow. Computers take on work even when they're overloaded, but they spend increasing amounts of their time context switching and become too slow to be useful." و تقویتکننده را نام میبرد: "clients often retry their request. This multiplies the offered load on the system." نتیجه: "an overload creates its own feedback loop that results in overload as a steady state."
| پذیرفتن همه چیز | Shedding عمدی |
|---|---|
| هر درخواست در صف رشدکننده منتظر میماند | مازاد در چند میکروثانیه رد میشود |
| تأخیر همهٔ کاربران بالا میرود | تأخیر پذیرفتهشدهها ثابت میماند |
| کار روی درخواستهای منقضی هدر میرود | کار منقضی نادیده گرفته میشود |
| retryها روی هم انباشته میشوند | به کلاینت با یک راهنما گفته میشود صبر کند |
| فرایند ممکن است حافظه کم بیاورد و restart شود | فرایند بالا میماند و سرویس میدهد |
| برای بهبود باید بار از بین برود | با پایین آمدن بار خودبهخود بهبود مییابد |
| داشبورد throughput بالا و goodput پایین نشان میدهد | داشبورد شمارندهٔ shed دارد که میشود روی آن alarm گذاشت |
تشبیهی که در کل صفحه به کار میبریم: رستوران با آشپزخانهٔ پر. آشپزخانه همزمان ده غذا میپزد. اگر میزبان هر مشتریِ بیرزرو را بنشاند، سفارشها روی هم میماند، همهٔ میزها یک ساعت منتظرند، نصف مهمانها میروند و آشپزخانه هنوز غذای آنها را میپزد. میزبان خوب زمان انتظار میگوید، رزروها و میز منتقد غذا را اول مینشاند، به اتوبوس گردشگران میگوید ساعت سه بیایند و آشپزخانه را روی غذاهایی نگه میدارد که کسی میخورد. نشاندن، admission control است؛ فهرست اولویت، criticality؛ «ساعت سه بیایید»، Retry-After؛ و غذایی که برای میزِ رفته پخته شود، کار هدررفته.
سه بدفهمی رایج، از همین اول
- «Shedding یعنی شکست خوردهایم.» Shedding شکستِ برنامهریزیشدهٔ ارزانترین و کماهمیتترین درخواستهاست تا مهمترینها موفق شوند. AWS اثرش را میگوید: "the requests that the server decided to accept remain available because they were served quickly".
- «سرور overload باید پذیرش ترافیک را متوقف کند.» کتاب SRE گوگل این را اشتباه میداند: "We actually want the backend to continue accepting as much traffic as possible, but to only accept that load as capacity frees up."
- «Autoscaling نیاز به shedding را از بین میبرد.» نمونهٔ جدید دقیقهها طول میکشد؛ overload ثانیهها. AWS اضافه میکند shedding بد پیکربندیشده حتی میتواند "disable reactive automatic scaling". این دو باید با هم طراحی شوند (تعامل با autoscaling).
از کجا آمده
کنترل ازدحام TCP، از ۱۹۸۸. ایدهٔ محدودیتهای تطبیقی از سرویسهای وب قدیمیتر است: تا وقتی همهچیز خوب است پنجره را یکی زیاد کن، با خطا تند کم کن (AIMD)، یا تأخیر را ببین و وقتی صف شکل گرفت آهسته شو (Vegas). README نتفلیکس همین وامگیری را صریح میگوید: "to estimate the limit we borrow from common TCP congestion control algorithms by equating a system's concurrency limit to a TCP congestion window".
Controlled Delay، ۲۰۱۲. CoDel از Nichols و Jacobson (ACM Queue، ۲۰۱۲؛ RFC 8289 در ژانویهٔ ۲۰۱۸ با وضعیت Experimental) اندازه میگیرد هر بسته چقدر در بافر مانده («sojourn time») و فقط وقتی دور میریزد که این تأخیر یک interval کامل بالای هدف بماند، یعنی «صف ایستا» (standing queue)، نه یک جهش کوتاه.
کتاب SRE گوگل، ۲۰۱۶. فصل ۲۱ Handling Overload چهار مقدار criticality، سهمیهٔ هر مشتری بر پایهٔ CPU، adaptive throttling سمت کلاینت و بودجهٔ retry را معرفی کرد و این قاعده را: "a backend task provisioned to serve a certain traffic rate should continue to serve traffic at that rate without any significant impact on latency, regardless of how much excess traffic is thrown at the task".
Netflix concurrency-limits، ۲۰۱۸. کتابخانهٔ نتفلیکس محدودیتهای ثابت درخواست در ثانیه را با محدودیت concurrency که از تأخیر برآورد میشود عوض کرد، چون "in large distributed systems that auto-scale this value quickly goes out of date". Vegas، Gradient2، AIMD و راهبرد اعمال درصدی (partitioned) را دارد.
Amazon Builders' Library، ۲۰۱۹. مقالهٔ Using load shedding to avoid overload واژگان این صفحه را داد (goodput در برابر throughput، حلقههای بازخورد مثبت، کار کراندار، TTL هر درخواست) و قاعدهٔ تست: بهترین نتیجهٔ آزمون overload یعنی "goodput to plateau when the service is close to being fully utilized".
Envoy. Envoy فیلتر HTTP «adaptive concurrency» بر پایهٔ gradient controller و یک overload manager دارد که از روی resource monitorها کارهایی مثل envoy.overload_actions.stop_accepting_requests را فعال میکند.
سال ایده در عمل چه عوض شد
1 1988 TCP congestion avoidance (AIMD) آهسته بالا برو، تند عقب بنشین
2 1995 TCP Vegas (مبتنی بر تأخیر) صف از روی RTT برآورد میشود، بدون نیاز به loss
3 2012 CoDel (Nichols, Jacobson) دور ریختن بر پایهٔ تأخیر پایدار صف، نه طول صف
4 2016 SRE book ch. 21 Criticality، adaptive throttling، retry budget
5 2018 Netflix concurrency-limits محدودیت concurrency جای محدودیت RPS
6 2018 RFC 8289 CoDel مشخص شد (Experimental)
7 2019 AWS Builders' Library Goodput، TTL هر درخواست، تست تا plateau
8 later Envoy adaptive concurrency, overload mgr Shedding در proxy، بدون تغییر برنامهفهرست مفاهیم
هر بلوک ترتیب ثابتی دارد: به زبان ساده، باور غلط رایج، تعریف، یک توالی، سناریوهای واقعی، اینکه محصولات چطور فراهمش میکنند، و راه درست.
Goodput و سقوط زیر overload حیاتی
به زبان ساده: Throughput هر درخواستی را که سرور لمس کرده میشمارد. Goodput فقط پاسخهایی را میشمارد که کسی هنوز میتواند استفاده کند. زیر overload اولی بالا میماند و دومی به صفر میرسد.
بدفهمی رایج: «CPU صد درصد است و درخواست در ثانیه رکورد زده، پس سیستم عالی کار میکند.» این عددها کارِ مربوط به کلاینتهایی را هم دارند که timeout کردهاند. سیستم میتواند بیشینهٔ throughput و صفر goodput داشته باشد.
تعریف: Goodput نرخ درخواستهایی است که موفق و در deadline کلاینت تمام شدهاند. AWS: "Throughput is the total number of requests per second that is being sent to the server. Goodput is the subset of the throughput that is handled without errors and with low enough latency for the client to make use of the response." شکل مسئله از Universal Scalability Law میآید که همین مقاله به آن اشاره میکند: از یک نقطه به بعد، بار بیشتر خروجی مفید را کم میکند.
t رویداد (سرور: ۱۰ کارگر x ۱۰۰ms = ۱۰۰ req/s؛ کلاینتها بعد از ۱ ثانیه timeout میکنند)
1 0.0 بار ورودی به ۳۰۰ req/s میپرد؛ صف با ۲۰۰ req/s رشد میکند
2 1.0 اولین درخواستها بیش از ۱ ثانیه در صف ماندهاند؛ کلاینتشان رفته
3 1.0 سرور هنوز پردازششان میکند: کار هدررفته، کسی پاسخ را نمیخواند
4 2.0 صف ۴۰۰ تایی است؛ هر درخواست جدید ۴ ثانیه منتظر میماند، پس هیچکدام موفق نمیشود
5 2.0 کلاینتها retry میکنند؛ بار الان ۳۰۰ بهعلاوهٔ retryهاست
6 ... Goodput حدود صفر است و CPU روی ۱۰۰٪سناریوهای واقعی: عرضهٔ محصول که سرویس login بعد از رفتن مرورگر جواب میدهد؛ job شبانهٔ نیمهشب که ترافیک روی یک پایگاهداده مشترک را دو برابر میکند؛ deployای که در اوج یکسوم ناوگان را برمیدارد؛ پاک شدن cache که همهٔ خواندنها را به پایگاهداده میفرستد.
چه چیزی فراهمش میکند: مسیر ردِ بسیار ارزانتر از خود کار، و محدودیتی که تأخیر صف را زیر timeout کلاینت نگه دارد.
| محصول | «زود رد کردن» کجا اتفاق میافتد | پاسخ پیشفرض |
|---|---|---|
| NGINX | limit_conn / limit_req | 503 (مقدار پیشفرض limit_conn_status و limit_req_status) |
| HAProxy | timeout queue بعد از رسیدن به maxconn سرور | 503 |
| Envoy | stop_accepting_requests در overload manager؛ فیلتر adaptive concurrency | 503 |
| Kubernetes | eviction کوبلت زیر فشار گره | Pod کشته میشود، پاسخی نیست |
| RabbitMQ | overflow=reject-publish صف | basic.nack به publisher |
| Laravel | middleware خودتان (پایینتر) | 503 + Retry-After |
راه درست: goodput را «۲xx در زمان SLO» تعریف و اندازهگیری کنید، load test بخش تست و متریک را بسازید و یک محدودیت admission جلوی کار بگذارید (Go، Laravel).
سیگنالهای overload حیاتی
به زبان ساده: برای رد کردن کار در لحظهٔ درست عددی لازم است که پیش از آسیب به کاربر بالا برود. عددهای مختلف در زمانهای مختلف بالا میروند.
بدفهمی رایج: «CPU بالای ۸۰٪ یعنی overload.» سرویسی میتواند با ۳۰٪ CPU اشباع باشد (همهٔ threadها منتظر یک پایگاهداده کند) یا با ۹۰٪ سالم (محاسباتی و بدون صف). CPU نماینده است؛ زمان انتظار در صف خودِ مسئله است.
تعریف: سیگنال overload اندازهای است، داخل فرایند یا در درِ ورودی، که وقتی تقاضا از ظرفیت بیشتر شود از آستانه میگذرد. کتاب SRE گوگل حفاظت سطح task را روی «utilization» بنا میکند: "In many cases, the utilization is just a measurement of the CPU rate ... but in some cases we also factor in measurements such as the portion of the memory reserved that is currently being used." عمومیترین سیگنالش executor load average است، شمارش هموارشدهٔ threadهای فعال، "and begin rejecting requests as the number of active threads grows beyond the number of processors available to the task".
زمان In flight انتظار صف CPU p99 سیگنال چه میگوید
1 0 s 8 2 ms 55% 90 ms سالم
2 5 s 12 40 ms 70% 120 ms in flight از تعداد کارگر بیشتر شد: صفکشی شروع شد
3 10 s 20 300 ms 85% 450 ms انتظار صف overload را نشان میدهد؛ CPU هنوز «خوب» است
4 15 s 40 1.5 s 100% 2.5 s تأخیر هم نشان میدهد، کاربران رفتهاندسناریوهای واقعی: سرویسی که منتظر downstream کند است (CPU کم، in-flight روی سقف)؛ JVM پرGC که فشار حافظه اولین نشانه است (گوگل میگوید "in platforms with garbage collection, memory pressure naturally translates into increased CPU consumption")؛ استخر PHP-FPM که همهٔ pm.max_children مشغولاند؛ سرویس Go که goroutineها روی یک mutex تلنبار میشوند.
| سیگنال | NGINX / HAProxy | Envoy | Kubernetes | برنامه |
|---|---|---|---|---|
| In-flight / اتصالها | limit_conn، maxconn سرور | سقف requests در circuit breaker، adaptive concurrency | ندارد | gauge که خودتان نگه میدارید |
| انتظار صف | timeout queue (HAProxy) | breaker درخواستهای pending | ندارد | سنِ X-Request-Start |
| حافظه | ندارد | resource monitorهای fixed_heap و cgroup_memory | سیگنال eviction با نام memory.available | RSS فرایند |
| CPU | ندارد | اقدامهای مبتنی بر CPU با monitor | Allocatable گره، سیگنال eviction برای CPU نیست | utilization، executor load |
| تأخیر نسبت به SLO | ندارد | gradient controller (RTT) | ندارد | histogram، minRTT |
راه درست: یک سیگنال زودرس را محرک کنید (in-flight در برابر limit یا انتظار صف)، CPU و حافظه را پشتیبان نگه دارید و درخواستها را همیشه به تفکیک tier بشمارید. پیشفرض خوب: انتظار صف برای سرویسهای حساس به زمان و in-flight برای بقیه.
محدودیت concurrency ثابت حیاتی
به زبان ساده: تصمیم بگیرید چند درخواست همزمان داخل سرویس باشند؛ درخواست بعدی رد میشود.
بدفهمی رایج: «محدودیت درخواست در ثانیه همین است.» نیست: RPS نمیگوید هر درخواست چقدر یک کارگر را نگه میدارد. README نتفلیکس: "RPS limits are then set somewhere below this tipping point (say 75% of this value) and enforced via a token bucket. However, in large distributed systems that auto-scale this value quickly goes out of date." Concurrency بهخاطر قانون Little ظرفیت را دنبال میکند که README آن را Limit = Average RPS * Average Latency مینویسد.
تعریف: محدودیت ثابت یک مقدار L است. اگر کمتر از L درخواست in-flight باشد پذیرفته میشود، وگرنه فوراً رد. قانون Little نقطهٔ شروع را میدهد: ۱۰۰ req/s با ۱۰۰ms یعنی ۱۰ درخواست in-flight؛ limit برابر ۲۰ صفی تا ۱۰ تایی اجازه میدهد که حداکثر ۱۰۰ms اضافه میکند.
In flight رویداد
1 0..19 درخواست پذیرفته میشود، شمارنده++
2 20 درخواست بعدی رد میشود: 503 + Retry-After، شمارنده ثابت
3 19 یکی تمام میشود، شمارنده--
4 20 درخواست بعدی پذیرفته میشودسناریوهای واقعی: NGINX با limit_conn perserver 100؛ maxconn سرور در HAProxy؛ یک semaphore در Go جلوی endpoint گران؛ pm.max_children در PHP-FPM که ناخواسته limit است و در وبسرور صف میکشد.
| محصول | تنظیم | در سقف چه میشود |
|---|---|---|
| NGINX | limit_conn zone number; | پیشفرض 503 (limit_conn_status) |
| HAProxy | maxconn روی server، timeout queue | در صف میماند، بعد 503 |
| Envoy | circuit breaker شامل max_requests، max_pending_requests، max_connections | 503 و شمارندههای upstream_rq_pending_overflow |
| PHP-FPM | pm.max_children | اتصالها در listen backlog منتظر میمانند |
| Laravel Octane | --workers (پیشفرض: یکی برای هر هستهٔ CPU) | درخواستها در application server صف میکشند |
راه درست: از workers x (1 + صف قابلتحمل) شروع کنید، load test بگیرید و عدد را حدسی بدانید که تاریخ مصرف دارد؛ محدودیتهای تطبیقی حدس زدن را حذف میکنند.
محدودیتهای concurrency تطبیقی: AIMD، Vegas، gradient حیاتی
به زبان ساده: بگذارید سرور محدودیت خودش را پیدا کند، همانطور که TCP پنجرهاش را پیدا میکند: تا وقتی تأخیر صاف است سریعتر، وقتی بالا رفت آهستهتر.
بدفهمی رایج: «تطبیقی یعنی بدون تنظیم.» هنوز الگوریتم، کرانها، پنجره و buffer را شما انتخاب میکنید و باز هم tier و متریک خوب لازم است. آنچه حذف میشود ثابتِ دستیاندازهگیریشده است.
تعریف: محدودیت تطبیقی محدودیتی است که از نمونهها (RTT، تعداد in-flight، drop) دوباره محاسبه میشود. سه خانواده:
| الگوریتم | سیگنال | قاعدهٔ بهروزرسانی | قوت | ضعف |
|---|---|---|---|---|
| AIMD | loss: timeout یا رد | موفقیت و in-flight بالای نصف limit: +1؛ drop: ضرب در backoff مثل 0.9 | ساده، بدون baseline | بعد از آسیب واکنش میدهد؛ دندانهای |
| Vegas | تأخیر | queue = limit x (1 - minRTT/sampleRTT)؛ alpha 2-3، beta 4-6: زیر alpha +1، بالای beta -1 (README نتفلیکس) | پیش از loss واکنش میدهد | یک نمونهٔ سریع استثنایی minRTT را مسموم میکند |
| Gradient / Gradient2 | روند تأخیر | Envoy: gradient = (minRTT + B) / sampleRTT، limit' = gradient x limit + headroom، headroom برابر sqrt(limit)، B = minRTT x buffer | هموار، خودش به بالا کاوش میکند | drift در minRTT؛ اندازهگیری دورهای لازم |
README نتفلیکس توضیح میدهد Gradient2 چه اضافه میکند: "This algorithm attempts to address bias and drift when using minimum latency measurements. To do this the algorithm tracks the measure of divergence between two exponential averages over a long and short time window." کنترلر Envoy همین drift را جور دیگری حل میکند: دورهای minRTT را دوباره میسنجد، با پین کردن concurrency روی min_concurrency، و با jitter تا همهٔ hostها همزمان اندازه نگیرند؛ و مستندات هشدار میدهد: "It is possible that there is a noticeable increase in request 503s during the minRTT measurement window because of the potentially significant drop in the concurrency limit."
حلقهٔ تصویر برای همهٔ الگوریتمها یکی است: تا وقتی in-flight زیر limit است بپذیر، هر درخواست تمامشده را اندازه بگیر، با تأخیر بدونبار مقایسه کن و limit را جابهجا کن.
پنجره avg RTT minRTT gradient (buffer 0.2) limit رویداد
1 1 10 ms 10 ms 1.20 -> 1.0 (سقف) 100 رشد به اندازهٔ sqrt(limit) = +10
2 2 14 ms 10 ms 12/14 = 0.86 96 صفکشی خفیف: کم میشود
3 3 30 ms 10 ms 12/30 = 0.40 -> 0.5 58 clamp، limit تقریباً نصف میشود
4 4 12 ms 10 ms 1.0 65 صف خالی شد: دوباره رشدسناریوهای واقعی: نتفلیکس برای gRPC میگوید روی سرور limiter مبتنی بر تأخیر مثل Vegas و روی کلاینت AIMD یا ترکیبی ("it is recommended to use a dynamic delay based limiter such as the VegasLimit on the server and either a pure loss based (AIMDLimit) or combined loss and delay based limiter on the client")؛ فیلتر adaptive concurrency در Envoy جلوی یک cluster؛ یک gateway Go با limiter از این فصل.
| محصول | محدودیت تطبیقی | نکته |
|---|---|---|
| Netflix concurrency-limits (Java) | VegasLimit، Gradient2Limit، AIMDLimit، WindowedLimit | interceptor برای gRPC، servlet filter (با 429 رد میکند)، executor |
| Envoy | gradient controller در envoy.filters.http.adaptive_concurrency | پیشفرض max_concurrency_limit برابر 1000؛ فیلتر باید همهٔ ترافیک cluster را ببیند |
| NGINX | داخلی ندارد | limit_conn ثابت است |
| HAProxy | داخلی ندارد | maxconn ثابت است؛ پویا فقط از بیرون با runtime API |
| Kubernetes | ندارد | HPA تعداد replica را عوض میکند، نه limit در-پرواز را |
| Laravel Octane | ندارد | workerها ثابتاند؛ از gauge بخش Laravel استفاده کنید |
راه درست: limiter و الگوریتمهای Go: limit.NewGradient، limit.NewVegas، limit.NewAIMD پشت یک interface به نام Algorithm تا تستها بتوانند جایگزینشان کنند.
بودجهٔ زمان صف، queue timeout و CoDel مهم
به زبان ساده: برای کسی که دیگر منتظر نیست کار نکنید. زمان رسیدن درخواست را ثبت کنید؛ اگر بیشتر از ارزشش معطل مانده، ناخوانده دورش بریزید.
بدفهمی رایج: «صف بلندتر امنتر است چون چیزی دور ریخته نمیشود.» صف بلند overload را فقط به تأخیر تبدیل میکند؛ بیشتر محتوایش تا به کارگر برسد منقضی شده است. صف کوتاه و کراندار با بودجهٔ زمان امن است.
تعریف: بودجهٔ زمان صف درخواستی را رد میکند که زمان انتظارش (اکنون منهای زمان ورود، همان «sojourn time») از سقف بیشتر باشد. HAProxy آن را داخلی دارد: "When a server's maxconn is reached, connections are left pending in a queue ... If the timeout is reached, it is considered that the request will almost never be served, so it is dropped and a 503 error is returned to the client." CoDel همین بودجه را تطبیقی میکند: RFC 8289 میگوید TARGET "SHOULD be set to 5 ms for normal Internet traffic" و INTERVAL برابر 100 ms است، و فقط وقتی دور میریزد که تأخیر یک INTERVAL کامل بالای TARGET بماند، که جهش را از صف ایستا جدا میکند. AWS نسخهٔ deadline را میگوید: "we have found it helpful to enforce a 'per-request time-to-live' and throw away doomed requests".
ساعت رویداد
1 12:00:00.000 proxy مقدار X-Request-Start = t=1700000000.000 را میزند
2 12:00:00.400 درخواست به کارگر PHP میرسد (پشت درخواستهای کند صف بوده)
3 12:00:00.401 middleware: ۴۰۱ms منتظر مانده، بودجهٔ tier برابر ۵۰۰ms: سرویس بده
4 12:00:01.200 درخواست بعدی، ۱۲۰۰ms منتظر مانده: از بودجه گذشته -> 503 + Retry-After، بدون هیچ کارسناریوهای واقعی: NGINX جلوی PHP-FPM که listen backlog پر میشود؛ سرویس Go که accept queue اتصالهای کهنه نگه میدارد؛ صف job که job قدیمیتر از ده دقیقه بیمعنی است؛ consumer روی topic با backlog رو به رشد.
| سازوکار | محصول | تنظیم |
|---|---|---|
| Queue timeout | HAProxy | timeout queue، maxqueue سرور |
| TTL هر درخواست | RabbitMQ | x-message-ttl، expiration هر پیام |
| کهنگی job | Laravel queues | retryUntil()، Skip::when() |
| سن درخواست | هر proxy که X-Request-Start بزند | NGINX proxy_set_header X-Request-Start "t=${msec}" |
| دور ریختن صف ایستا | CoDel (RFC 8289) | TARGET 5ms، INTERVAL 100ms برای شبکه؛ صف سرویس مقادیر خودش را میخواهد |
راه درست: shed.ParseRequestStart و QueueBudget در middleware؛ msgqueue.CoDel برای صفهای داخل فرایند؛ ShedLoad برای Laravel. یک احتیاط: بودجه دو ساعت را مقایسه میکند (proxy و برنامه). آنها را با NTP همگام نگه دارید یا فقط روی یک host اندازه بگیرید.
سطوح Criticality (shedding مبتنی بر اولویت) حیاتی
به زبان ساده: وقتی مجبوریم چیزی را رد کنیم، کماهمیتترینها را اول رد کنیم.
بدفهمی رایج: «priority queue مسئله را حل میکند.» Priority queue ترتیب کار منتظر را عوض میکند، نه جلوی رشد صف را میگیرد. Tier باید به یک limit پذیرش گره بخورد: tierهای پایینتر در اشغال کمتری رد میشوند تا جا برای tierهای بالاتر بماند.
تعریف: کتاب SRE گوگل چهار مقدار criticality برای هر درخواست تعریف میکند: CRITICAL_PLUS ("reserved for the most critical requests, those that will result in serious user-visible impact if they fail")، CRITICAL ("the default value for requests sent from production jobs")، SHEDDABLE_PLUS ("traffic for which partial unavailability is expected. This is the default for batch jobs") و SHEDDABLE ("frequent partial unavailability and occasional full unavailability is expected"). قاعدههای فصل: "When a task is itself overloaded, it will reject requests of lower criticalities sooner"، criticality "orthogonal to its latency requirements" است و منتشر میشود: "request B and request C will use the same criticality as request A by default". آن را "as close as possible to the browsers or mobile clients" تعیین کنید.
In flight (limit 20) CRITICAL_PLUS(20) CRITICAL(18) SHEDDABLE_PLUS(14) SHEDDABLE(10)
1 0..9 پذیرش پذیرش پذیرش پذیرش
2 10..13 پذیرش پذیرش پذیرش رد
3 14..17 پذیرش پذیرش رد رد
4 18..19 پذیرش رد رد رد
5 20 رد رد رد ردسناریوهای واقعی: checkout (CRITICAL_PLUS) در برابر تاریخچهٔ سفارش (CRITICAL) در برابر typeahead (SHEDDABLE) در برابر خروجی CSV شبانه (SHEDDABLE_PLUS)؛ ping سلامت که Builders' Library آن را "the most important request that a server will receive" مینامد؛ اعمال درصدی نتفلیکس ("live traffic 100% of the limit during heavy load" و گرسنه ماندن batch، یا "50% of the limit ... to write traffic so writes are never starved")؛ خزندههای موتور جستوجو در amazon.com.
| محصول | سازوکار tier |
|---|---|
| RPC گوگل | criticality بهعنوان فیلد درجهیک، منتشرشده در درخت فراخوانی |
| Netflix concurrency-limits | partitionByHeader(...)، partition("live", 0.9) |
| Envoy | circuit breaker بهازای route و priority؛ انتشار tier داخلی نیست |
| Kubernetes | PriorityClass برای ترتیب eviction؛ API Priority and Fairness برای API server |
| Laravel | پارامتر middleware روی route بهعلاوهٔ هدر X-Priority (این فصل) |
| middleware Go این فصل | Thresholds برابر 1.0 / 0.9 / 0.7 / 0.5 از limit مشترک |
راه درست: tier را بر اساس route و فراخوان تعیین کنید، نه فقط برچسب ارسالی کلاینت (middleware لاراول به کلاینت اجازه میدهد tier خودش را پایین بیاورد، هرگز بالا نبرد). دقیقاً چهار tier نگه دارید: گوگل میگوید مقدارهای بیشتر "would require more resources to operate various criticality-aware systems". ترافیک بدون برچسب را CRITICAL بگیرید.
سهمیهٔ هر مشتری و shedding مبتنی بر هزینه مهم
به زبان ساده: یک مشتری شلوغ نباید برای مشتریان آرام خطا بسازد. به هر مشتری سهمی بدهید و فقط کسی را که از آن گذشته رد کنید.
بدفهمی رایج: «درخواست در ثانیه برای هر مشتری سهمیهٔ منصفانه است.» هزینهٔ درخواستها خیلی فرق دارد. گوگل: "modeling capacity as 'queries per second' ... often makes for a poor metric"؛ هزینه را بهجایش با زمان CPU نرمالشده میسنجد.
تعریف: سهمیهٔ هر مشتری منبعی را که یک فراخوان میتواند مصرف کند محدود میکند. در کتاب SRE سهمیهها CPU-ثانیه بر ثانیهاند ("Gmail is allowed to consume up to 4,000 CPU seconds per second") و "these numbers may add up to more than the 10,000 CPUs allocated"، چون همهٔ مشتریها بهندرت همزمان به اوج میرسند. بالای سهمیه، فقط درخواستهای همان مشتری رد میشود، اول کماهمیتترها. Shedding مبتنی بر هزینه این را تعمیم میدهد: بر پایهٔ هزینهٔ برآوردی یا اندازهگیریشده (ردیفهای اسکنشده، میلیثانیهٔ CPU، token) پذیرش کنید، نه تعداد.
مشتری سهمیه مصرف رویداد
1 A 4000 4600 بالای سهمیه: اول SHEDDABLEهای A رد میشود، بعد CRITICAL
2 B 4000 1200 دستنخورده
3 C 3000 2900 نزدیک سهمیه، هنوز پذیرفته میشود
4 other 500 480 پذیرفته میشودسناریوهای واقعی: tenantی که روی API مشترک scraper اجرا میکند؛ تیم داخلی که job دستهای روی backend مشترک راه میاندازد؛ API عمومی با پلن رایگان و سازمانی؛ پرسوجوهای GraphQL که با پیچیدگی قیمتگذاری میشوند.
| محصول | سازوکار برای هر فراخوان | پاسخ |
|---|---|---|
| NGINX | limit_conn_zone $binary_remote_addr (+ limit_req) | پیشفرض 503؛ limit_conn_status 429 بگذارید |
| Envoy | فیلترهای rate-limit محلی و سراسری | 429 |
| AWS API Gateway، Cloudflare | usage plan برای هر کلید، قاعدهٔ rate | 429 |
| servlet filter نتفلیکس | partitionByUserPrincipal | 429 |
| این فصل | Customer و CustomerMax در middleware Go | 429 + Retry-After |
راه درست: اول سهمیه بر اساس هویت (ارزان، 429 میدهد)، و limit تطبیقی مشترک را برای آنچه سهمیه نمیبیند نگه دارید. الگوریتمهای پشت limit هر هویت در Rate Limiting.
چه برگردانیم: 503، 429، Retry-After حیاتی
به زبان ساده: کد وضعیت به کلاینت میگوید تقصیر کیست و آیا صبر کردن کمک میکند.
بدفهمی رایج: «برای همهٔ shedding از 429 استفاده کن.» RFC 6585 کد 429 را چنین تعریف میکند: "the user has sent too many requests in a given amount of time". این دربارهٔ نرخ یک فراخوان است. overload کل سرور تقصیر فراخوان نیست و 503 است.
تعریف: RFC 9110، 503 را چنین تعریف میکند: "the server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. The server MAY send a Retry-After header field". و اضافه میکند "the existence of the 503 status code does not imply that a server has to use it when becoming overloaded. Some servers might simply refuse the connection." مقدار Retry-After برابر "HTTP-date / delay-seconds" است؛ همراه 503 "indicates how long the service is expected to be unavailable to the client". RFC 6585: پاسخهای 429 "MAY include a Retry-After header" و "MUST NOT be stored by a cache".
| Status | معنی | کی استفاده شود | Retry-After | Retry امن است؟ |
|---|---|---|---|---|
| 503 Service Unavailable | سرور فعلاً نمیتواند | محدودیت concurrency، بودجهٔ صف، overload manager | بله، ثانیه، با jitter | بله، در بودجه |
| 429 Too Many Requests | این فراخوان از نرخ یا سهمیه گذشته | سهمیهٔ هر مشتری | بله | بله، بعد از انتظار |
| 504 Gateway Timeout | proxy از upstream ناامید شد | shedding نیست: نشانهٔ overload پاییندست | خیر | فقط idempotent |
| 500 Internal Server Error | باگ | هرگز برای shedding | خیر | نامعلوم |
gRPC UNAVAILABLE | ردِ limiter نتفلیکس | سرویسهای gRPC | از طریق trailer | بله، با بودجه |
Connection refused / GOAWAY | سطح listener یا اتصال | disable_http_keepalive در Envoy | ندارد | بله |
درخواست پاسخ
1 GET /search/suggest?q=lo (SHEDDABLE) -> 503 Service Unavailable
2 Retry-After: 2
3 X-Shed-Reason: concurrency
4 Cache-Control: no-storeسناریوهای واقعی: limit_conn_status 429 در NGINX برای دانلود بهازای IP و 503 پیشفرض برای محدودیت کل سرور؛ Envoy با stop_accepting_requests که 503 میدهد؛ اپ موبایلی که برای یک درخواست پیشنهاد نباید صفحهٔ خطا نشان دهد.
راه درست: برای overload سراسری 503 و برای فراخوان بالای سهمیهٔ خودش 429 بدهید؛ Retry-After را به ثانیه بفرستید (در ناوگان با ساعتهای ناهمگام هرگز تاریخ)، سمت سرور jitter بیفزایید تا کلاینتهای ردشده با هم برنگردند، Cache-Control: no-store بگذارید و دلیل را برچسب متریک کنید. مسیر ردّ را سبک نگه دارید: بدون log بدنه، بدون پایگاهداده. AWS هشدار میدهد "it's easy to miss an accidental log statement or a socket setting, which might make dropping a request far more expensive than it needs to be".
نتیجهٔ جزئی و degradation ملایم مهم
به زبان ساده: گاهی بهترین «نه»، یک «بله»ی کوچکتر است.
بدفهمی رایج: «پاسخ degraded مشکل را پنهان میکند.» وقتی پاسخ بگوید چه کم است پنهان نیست و کاربر را سر کار نگه میدارد. اولین گزینهٔ کتاب SRE برای overload دقیقاً همین است: "serve degraded responses: responses that are not as accurate as or that contain less data than normal responses, but that are easier to compute".
تعریف: نتیجهٔ جزئی یا degraded پاسخ گران را با پاسخ ارزانتر عوض میکند: جستوجو در بخش کوچکتری از corpus، نمایش نسخهٔ cache، حذف ویجتهای اختیاری، فقط صفحهٔ اول. نوعی shedding داخل خود درخواست است. الگوهای کامل در Bulkheads & Graceful Degradation.
سطح بار پاسخ جستوجو
1 عادی رتبهبندی کامل روی کل index، شخصیسازیشده
2 بالاتر فقط ۱۰۰ کاندیدای برتر، بدون شخصیسازی
3 زیاد نتایج cache یک دقیقهٔ پیش
4 شدید 503 + Retry-After برای SHEDDABLE، cache برای بقیهسناریوهای واقعی: صفحهٔ محصول بدون پیشنهادها؛ feed بدون تبلیغ؛ جستوجو با «ممکن است نتایج ناقص باشد»؛ داشبورد که کندترین پنل را رد میکند.
| محصول | قلاب degradation |
|---|---|
| Envoy | retry/fallback از طریق پیکربندی route، پاسخ سفارشی هنگام overload |
| NGINX | proxy_cache_use_stale هنگام خطا محتوای کهنه میدهد |
| Laravel | Cache::remember با fallback کهنه داخل catch |
| Go | context deadline بهعلاوهٔ تابع fallback |
راه درست: مسیر degraded را مسیر کدی درجهیک با تست خودش کنید، چون دقیقاً وقتی اجرا میشود که بقیه چیز خراب است.
همکاری کلاینت: adaptive throttling، retry budget، backoff حیاتی
به زبان ساده: کلاینتی که رد میشود باید کمتر بفرستد، نه بیشتر.
بدفهمی رایج: «سرور تنهایی از پسش برمیآید.» ردّ کردن مفت نیست: گوگل میگوید "the backend can become overloaded even though the vast majority of its CPU is spent just rejecting requests". و retryهای ساده بار را چند برابر میکنند؛ بدترین حالت کتاب SRE سه تلاش برای هر درخواست است، "somewhere just below 3X".
تعریف: سه ابزار سمت کلاینت. (۱) Adaptive throttling: هر کلاینت requests و accepts دو دقیقهٔ اخیر را نگه میدارد. وقتی requests از K x accepts بیشتر شد، درخواست جدید را با احتمال max(0, (requests - K x accepts) / (requests + 1)) محلی رد میکند؛ کتاب K برابر ۲ را ترجیح میدهد و گزارش میدهد "backends end up rejecting one request for each request they actually process". (۲) Retry budget: سقف سه تلاش برای هر درخواست و سقف برای هر کلاینت ("A request will only be retried as long as this ratio is below 10%") که رشد بدترین حالت را به "just 1.1x" میرساند. (۳) رعایت Retry-After و jitter (Timeouts, Retries & Jitter). فقط لایهٔ درست بالای لایهٔ ردکننده retry کند و وقتی کل ناوگان اشباع است پاسخ «overloaded; don't retry» بدهید: وگرنه "we'd have a combinatorial explosion".
گام کلاینت سرور
1 1 GET /x -> 503 Retry-After: 2 (overload)
2 2 بودجه ok (retries/requests = 4%)
3 3 ۲ ثانیه + jitter صبر، GET /x -> 503
4 4 بودجه: ۳ تلاش خرج شد؛ 503 را به فراخوان برگردان
5 5 درخواستهای بعدی: requests > 2 x accepts -> ۴۰٪ محلی رد میشود، بدون شبکهسناریوهای واقعی: اپ موبایل که بعد از قطعی در لحظهٔ باز شدن retry میکند؛ کلاینت batch با ده worker موازی؛ gateway که 503 را در هر لایه سه بار retry میکند.
| محصول | سازوکار سمت کلاینت |
|---|---|
| Envoy | retry budget و breaker از نوع max_retries ("we recommend using retry budgets") |
| gRPC | سیاست retry با throttling (maxTokens، tokenRatio) در service config |
| Netflix | AIMDLimit سمت کلاینت یا blockOnLimit |
| Go | throttle.Transport این فصل |
| Laravel | Http::retry() با closure خواب که Retry-After را میخواند و closure برای when: پشتیبانیشده با بودجهٔ cache |
راه درست: throttle.Adaptive، throttle.RetryBudget، throttle.Transport. فقط درخواستهای idempotent retry میشوند؛ API Idempotency را ببینید.
Shedding در برابر rate limiting در برابر backpressure حیاتی
به زبان ساده: Rate limiting انصاف را بر پایهٔ یک قول اعمال میکند، backpressure سرعت گیرنده را به فرستنده میرساند، و shedding وقتی بقیه کافی نبودند از گیرنده محافظت میکند.
بدفهمی رایج: «همه یکیاند، یکی را انتخاب کن.» به پرسشهای متفاوت جواب میدهند و روی هم چیده میشوند: rate limit جلوی برداشتن بیش از سهم یک فراخوان را میگیرد، backpressure سرعت گیرنده را به فرستنده منتقل میکند، و shedding آخرین چارهای است که حتی وقتی فرستندهها هیچکدام را رعایت نکنند کار میکند.
تعریف:
| Rate limiting | Backpressure | Load shedding | |
|---|---|---|---|
| پرسش | این فراخوان در نرخ توافقشده است؟ | گیرنده الان میتواند بیشتر بپذیرد؟ | این سرور میتواند کار بیشتری بهموقع تمام کند؟ |
| چه کسی تصمیم میگیرد | سیاست (پلن، سهمیه) | ظرفیت گیرنده | وضعیت خود سرور |
| سیگنال | شمارش بهازای هویت در پنجره | بافر پر، پنجره، credit، lag | in-flight، انتظار صف، تأخیر |
| پاسخ معمول | 429 | block، nack، ack کند، fetch کوچکتر | 503 |
| در برابر چه محافظت میکند | سوءاستفاده، همسایهٔ پرسروصدا | تولیدکنندهٔ سریع، مصرفکنندهٔ کند | موج بار، وابستگی کند، retry |
| نیاز به همکاری | کلاینت هدرها را میخواند | فرستنده سیگنال را رعایت میکند | ندارد: یکجانبه است |
| کجا | لبه، gateway | بین مرحلهها و صفها | هر سرور |
لایه جلوی چه را میگیرد فصل
1 Rate limit یک فراخوان بالای پلنش /system-design/rate-limiting-algorithms
2 Backpressure تولیدکنندهٔ سریعتر از مصرفکننده /messaging/backpressure-flow-control
3 Load shedding تقاضای کل بالای ظرفیت (این فصل)
4 Circuit breaker فراخوانی وابستگی خراب /system-design/circuit-breakerسناریوهای واقعی: API با محدودیت پلن (rate limiting) و limit concurrency که پایگاهداده را حفظ میکند (shedding)؛ consumer کافکا که وقتی بافر حافظهاش پر است partitionها را pause میکند (backpressure) در حالی که جلوی HTTP در لبه shed میشود.
| محصول | Rate limiting | Backpressure | Shedding |
|---|---|---|---|
| NGINX | limit_req | proxy_buffering، limit_rate | limit_conn |
| Envoy | فیلترهای rate-limit | پنجرههای flow-control، بافر watermark | adaptive concurrency، overload manager |
| RabbitMQ | ندارد | publisher confirm، credit flow | overflow=reject-publish، TTL |
| Kafka | سهمیهها (producer_byte_rate) | pull مصرفکننده (max.poll.records) | حذف با retention، رد کردن پیام کهنه در consumer |
| Redis Streams | ندارد | consumer با سرعت خودش میخواند | کوتاه کردن با MAXLEN/MINID |
| Laravel | RateLimiter، middleware throttle | --sleep و --max-jobs worker | middleware ShedLoad (این فصل) |
راه درست: به ترتیب ارزانی روی هم بچینید: rate limit هویتمحور در لبه، limit shedding در هر سرویس، backpressure روی هر صف.
Shedding در صف: TTL، drop-head و reject-publish مهم
به زبان ساده: صف قولی است برای انجام کار «بعداً». اگر بعداً دیر است، پیام را دور بریزید و تصمیم بگیرید قدیمیترین را بریزید یا جدیدترین را.
بدفهمی رایج: «صف هر موجی را جذب میکند، پس هیچچیز گم نمیشود.» صف بیکران کمبود ظرفیت را به کمبود تازگی تبدیل میکند؛ وقتی backlog ساعتها طول دارد consumer روی چیزهایی کار میکند که کسی لازم ندارد و پیامهای جدید و مهم پشت آنها میمانند.
تعریف: سه اهرم. Message TTL: broker یا consumer پیامهای قدیمیتر از سقف را دور میریزد. Drop-head: وقتی صف پر است قدیمیترین را دور بریز؛ پیشفرض مستند RabbitMQ، overflow برابر drop-head ("oldest messages are discarded from the head of the queue"). Reject-publish: وقتی پر است پیام جدید را رد کن؛ RabbitMQ: "the most recently published messages will be discarded" و با publisher confirm "the publisher will be informed of the reject via a basic.nack". reject-publish-dlx پیامهای ردشده را dead-letter هم میکند. Drop-head تازگی را ترجیح میدهد و از تولیدکننده پنهان میکند؛ reject-publish کار قدیمی را نگه میدارد و به تولیدکننده فشار برمیگرداند، که همان backpressure است.
سیاست صف پر است، پیام جدید M میرسد
1 drop-head قدیمیترین دور ریخته میشود (اگر DLX باشد dead-letter)؛ M وارد میشود؛ تولیدکننده موفقیت میبیند
2 reject-publish M رد میشود؛ تولیدکننده nack میگیرد و باید کند شود یا retry کند؛ صف دستنخورده
3 TTL پیامهای قدیمیتر از TTL در head رد میشوند؛ broker یا consumer جا باز میکند
4 CoDel تأخیر پایدار بالای هدف: پیامهای head تا بازگشت تأخیر دور ریخته میشوندسناریوهای واقعی: بهروزرسانی قیمت (فقط آخری مهم است: drop-head)؛ فرمان پرداخت (هرگز بیصدا دور ریخته نمیشود: reject-publish و کند کردن تولیدکننده)؛ خلاصهٔ اعلان (TTL ده دقیقه)؛ telemetry (drop-head، پذیرش از دست رفتن).
| محصول | TTL | Overflow | Dead letter |
|---|---|---|---|
| RabbitMQ | policy x-message-ttl یا expiration هر پیام (کمتر از این دو برنده است)؛ صفهای classic در head منقضی میکنند | x-max-length و x-overflow: drop-head (پیشفرض)، reject-publish، reject-publish-dlx | DLX هنگام انقضا و drop-head |
| Kafka | هر پیام ندارد؛ retention.ms / retention.bytes کل segmentها را حذف میکنند | ندارد: تولیدکننده با max.block.ms یا محدودیت بافر block یا خطا میگیرد | topic خطا سمت consumer |
| Redis Streams | هر entry ندارد | XADD ... MAXLEN / MINID ورودیهای قدیمی را کوتاه میکند | داخلی ندارد |
| SQS | MessageRetentionPeriod (پیشفرض چهار روز) | ندارد: بیکران | redrive به DLQ با maxReceiveCount |
| Laravel queues | retryUntil()، Skip::when()، --max-time | داخلی ندارد | failed_jobs |
راه درست: msgqueue.Queue هر دو حالت overflow، رد TTL و CoDel را با ساعت جعلی مدل میکند؛ job لاراول این فصل با سن منقضی میشود. پیامهای ردشده و منقضی باید به dead-letter queue بروند (Dead Letter Queue) تا از دست رفتن دیده شود.
Shedding و autoscaling مهم
به زبان ساده: Shedding وقت میخرد؛ scaling ظرفیت میخرد. نباید همدیگر را پنهان کنند.
بدفهمی رایج: «اگر shed کنیم CPU پایین میماند و autoscaler کار درست را میکند.» برعکسش ممکن است. AWS: "a service is configured for CPU-based reactive scaling and also has load shedding configured to reject requests at a similar CPU target. In this case, the load shedding system will reduce the number of requests to keep the CPU load low, and reactive scaling will never receive or get a delayed signal to launch new instances."
تعریف: دو کنترلر محرک متفاوت میخواهند. Shedding روی سیگنال سریع و محلی (in-flight، انتظار صف). Scaling روی سیگنالی که تقاضای ردشده را هم بشمارد: نرخ shed، درخواست ورودی در ثانیه یا concurrency شامل تلاشهای ردشده. AWS دربارهٔ ظرفیت Availability Zone هم هشدار میدهد: با shedding، "a fleet might run much closer to the point at which requests would be rejected than system metrics indicate".
t رویداد
1 0 s موج شروع میشود؛ in-flight به limit میرسد؛ shedding آغاز میشود (حلقهٔ سریع، ثانیهها)
2 10 s نرخ shed برابر ۳۰٪ و رو به رشد؛ CPU بهخاطر shedding روی ۷۰٪ صاف است
3 30 s autoscaler نرخ shed را بالای آستانه میبیند (نه CPU): ۴ replica اضافه میخواهد
4 120 s replicaهای جدید readiness را رد میکنند؛ limit ناوگان بالا میرود؛ نرخ shed به ۰ میرسد
5 300 s موج تمام میشود؛ scale-in بعد از cool-downسناریوهای واقعی: HPA کوبرنتیز روی CPU در حالی که limit_conn در NGINX اتصالها را سقف میگذارد؛ سرویس ECS با scaling بر پایهٔ تعداد درخواست پشت ALB؛ Octane با worker ثابت و HPAای که هرگز فعال نمیشود.
| محصول | سیگنال scaling که از shedding جان سالم به در میبرد |
|---|---|
| Kubernetes HPA | متریک سفارشی یا خارجی: شمارندهٔ shed، in-flight، انتظار صف (با metrics adapter) |
| KEDA | scalerهای طول صف یا lag |
| AWS Auto Scaling | RequestCountPerTarget، target tracking روی متریک سفارشی shed |
| Envoy | upstream_rq_pending_overflow و آمار overload manager که به scaler صادر میشود |
| Laravel Horizon | balance: auto تعداد worker را با بار صف تنظیم میکند |
راه درست: شمارندهٔ shed را به تفکیک tier صادر کنید، روی shed_rate > 1% یا انتظار صف scale کنید، و Scaling Strategies را ببینید. همچنین مطمئن شوید از کار افتادن یک AZ به حالت shedding دائمی تبدیل نمیشود.
کجا shed کنیم: لبه، gateway، سرویس، consumer مهم
به زبان ساده: تا جایی که ارزان است زود «نه» بگویید، و در خود سرویس هم «نه» بگویید، چون لایههای اولی کمتر میدانند.
بدفهمی رایج: «یک لایه کافی است، روی gateway بگذار.» Gateway تعداد درخواست و هویت را میبیند، نه CPU، قفل یا سلامت downstream. نتیجهٔ گوگل: "we consider it critical to ensure that individual tasks are protected against overload."
تعریف: هر لایه چیزی میداند و کاری میتواند بکند.
| لایه | چه میداند | چه میتواند بکند | ابزار معمول |
|---|---|---|---|
| Client | نرخ accept اخیر خودش | خودش را throttle کند، عقب بنشیند | adaptive throttling، retry budget |
| Edge / CDN / LB | اتصالها، IP، نرخ درخواست | ارزان رد کند، drain کند | NGINX limit_conn، overload manager در Envoy، ALB |
| API gateway | هویت، route، پلن | سهمیه، 429، برچسب اولویت | Kong، Envoy، AWS API Gateway |
| Service | in-flight، انتظار صف، tier، سلامت downstream | پذیرش tierبندیشده، رد با deadline | middleware این فصل، Envoy adaptive concurrency |
| Queue consumer | سن پیام، backlog | رد با TTL، دور ریختن، dead-letter | TTL در RabbitMQ، Skip در لاراول |
| Database | اتصالها، statementها | max_connections، statement_timeout | PostgreSQL، pooler (Connection Pooling) |
| Orchestrator | حافظه، دیسک، PID گره | pod را evict کند | eviction کوبلت |
لایه تصمیم هزینهٔ رد کردن
1 Client throttle محلی با احتمال ۴۰٪ صفر شبکه
2 Edge 503 با stop_accepting_requests یک hop TCP/TLS
3 Gateway 429 برای tenant بالای سهمیه یک lookup
4 Service 503 برای SHEDDABLE در ۵۰٪ limit مقایسهٔ یک شمارنده
5 Consumer رد job بیستدقیقهای مقایسهٔ یک timestamp
6 Database FATAL: sorry, too many clients already اتصال ناموفق (آخرین چاره)سناریوهای واقعی: overload manager در Envoy در ingress هنگام جهش حافظه؛ limit_conn در NGINX روی مسیر دانلود؛ limit تطبیقی سطح سرویس پشت آن؛ podی که زیر فشار حافظه evict میشود در حالی که بقیه میمانند.
| محصول | تنظیم | اثر |
|---|---|---|
| Envoy overload manager | envoy.overload_actions.stop_accepting_requests با محرک heap برابر ۹۵٪ | "Envoy will immediately respond with a 503 response code to new requests" |
| Envoy overload manager | envoy.overload_actions.disable_http_keepalive در ۹۲٪ | HTTP/2 و HTTP/3 را با GOAWAY drain میکند |
| Envoy load shed point | envoy.load_shed_points.tcp_listener_accept | پذیرش اتصال TCP را متوقف میکند |
| کوبلت Kubernetes | آستانهٔ سخت memory.available<100Mi (پیشفرض Linux) | podها را فوراً میکشد، بدون مهلت |
| کوبلت Kubernetes | condition گره MemoryPressure | taint و توقف زمانبندی podهای بیشتر |
Eviction در کوبرنتیز podها را رتبه میدهد: "whether the pod's resource usage exceeds requests"، بعد Pod Priority، بعد میزان مصرف بالای requests؛ podهای BestEffort و Burstable که از requests گذشتهاند اول میروند. این shedding سطح گره است با کشتن، نه با رد درخواست؛ پس مکمل shedding برنامه است، نه جایگزین آن.
راه درست: یک لایه در لبه برای ردِ ارزان انبوه، یکی در هر سرویس برای درستی، یکی برای هر صف. توپولوژی را در Load Balancing و API Gateway, BFF & Service Mesh ببینید.
تست و متریک حیاتی
به زبان ساده: تا goodput را زیر load test صاف ندیدهاید، load shedding ندارید.
بدفهمی رایج: «load test ما تا اوج ترافیک میرود، خوب است.» آزمون overload باید خیلی فراتر از نقطهٔ شکست برود. AWS: "if they haven't load tested their service to the point where it breaks, and far beyond the point where it breaks, they should assume that the service will fail in the least desirable way possible."
تعریف: آزمون shedding بار را با ترکیب واقعگرایانهٔ اولویتها از ظرفیت میگذراند و goodput، موفقیت هر tier، نرخ shed و تأخیر درخواستهای پذیرفتهشده را میبیند. نتیجهٔ ایدئال plateau است؛ شکست یعنی پرتگاه. گونههای آزمون در همان مقاله: ناوگان ثابت در برابر ناوگان autoscale، و "take an existing load generation test or canary, drive sustained load ... but begin removing servers" تا بار هر نمونه بالا برود.
Ramp ورودی Goodput CRITICAL ok SHEDDABLE ok نرخ shed حکم
1 0.5x 50 /s 50 /s 100% 100% 0% سالم
2 1.0x 100 /s 100 /s 100% 100% 0% در ظرفیت
3 2.0x 200 /s 100 /s 100% ~50% 50% plateau: قبول
4 4.0x 400 /s 100 /s 100% ~25% 75% plateau: قبول
5 4.0x 400 /s 3 /s ~0% ~0% 0% پرتگاه: shedding نداردسناریوهای واقعی: ramp با k6 یا Gatling و ترکیب tier برابر ۵/۱۵/۳۰/۵۰٪؛ برداشتن نمونهها زیر بار ثابت؛ game day که به یک وابستگی تأخیر اضافه میکند (Chaos Engineering).
| متریک | چرا | برچسب |
|---|---|---|
requests_shed_total | ضرری که انتخاب کردهاید | tier، reason (queue_budget، concurrency، quota) |
requests_admitted_total | مخرج | tier |
goodput | ۲xx زیر تأخیر SLO در ثانیه | tier |
concurrency_limit | تصمیم الگوریتم تطبیقی | instance |
inflight | مصرف فعلی | instance، tier |
queue_wait_seconds | زودترین سیگنال | quantile |
| histogram تأخیر پذیرفتهشدهها | ردها را قاطی نکنید | فقط موفق |
دو قاعدهٔ AWS برای این متریکها: نرخ false positive را در حالت پایدار صفر نگه دارید ("when the service gets it wrong and rejects a request although it has capacity")، و "not to pollute our services' latency metrics with failed request latency"، چون shed کردن ۶۰٪ ترافیک میتواند median را عالی نشان دهد. روی نرخ shed به تفکیک tier alarm بگذارید، نه روی وجودش (Alerting That Actually Works، Observability، SLOs).
راه درست: شبیهساز آزمایشگاه نسخهٔ unit-test است؛ production نسخهٔ load-test با وابستگیهای واقعی میخواهد.
سازوکار (Mechanics)
عددها
قانون Little، in-flight = arrival rate x time in system، قطعات را به هم وصل میکند. برای سرویسی با ۱۰ کارگر و ۱۰۰ms کار برای هر درخواست:
| کمیت | مقدار | معنی |
|---|---|---|
| ظرفیت | 10 / 0.1 s = 100 req/s | plateau مربوط به goodput |
| In-flight در ظرفیت | 100 x 0.1 = 10 | برابر تعداد کارگر |
| Limit برابر 20 | ۱۰ در حال اجرا + ۱۰ در صف | بدترین انتظار حدود ۱۰۰ms، تأخیر حدود ۲۰۰ms |
| Limit برابر 200 | ۱۰ در حال اجرا + ۱۹۰ در صف | بدترین انتظار حدود ۱.۹ ثانیه: بالای timeout یکثانیهای کلاینت |
| ورودی 300 req/s بدون shedding | صف با ۲۰۰ در ثانیه رشد میکند | بعد از ۱۰ ثانیه صف ۲۰۰۰ تایی: انتظار ۲۰ ثانیه |
| با shedding در 300 req/s | ۲۰۰ req/s رد میشود | تأخیر پذیرفتهشدهها ۱۰۰ تا ۲۰۰ms میماند |
Knobها به تفکیک محصول
| محصول | تنظیم | پیشفرض | اثر |
|---|---|---|---|
| NGINX | limit_conn zone number | ندارد | بیشینهٔ اتصال همزمان بهازای کلید؛ در HTTP/2 و HTTP/3 هر درخواست یک اتصال حساب میشود |
| NGINX | limit_conn_status | 503 | status درخواستهای ردشده |
| NGINX | limit_conn_dry_run on (1.17.6) | off | مازاد را بشمار بدون رد کردن |
| NGINX | limit_req zone burst= nodelay | ندارد | نرخ بهازای کلید؛ limit_req_status پیشفرض 503 |
| NGINX | limit_conn_zone $binary_remote_addr zone=addr:10m | ندارد | ۴ بایت برای IPv4 و ۱۶ برای IPv6؛ مستندات: یک مگابایت حدود ۳۲ هزار state ۳۲بایتی یا ۱۶ هزار state ۶۴بایتی نگه میدارد و با پر شدن zone "the server will return the error to all further requests" |
| HAProxy | timeout queue | برابر timeout connect اگر تعیین نشود | بیشینهٔ انتظار برای slot سرور، بعد 503 |
| HAProxy | maxconn و maxqueue سرور | ندارد | slotها و طول صف بهازای سرور |
| Envoy | gradient controller در adaptive_concurrency | بدون پیکربندی فعال نیست | concurrency_update_interval، min_concurrency_limit، max_concurrency_limit (1000)، sample_aggregate_percentile، min_rtt_calc_params (interval، request_count، jitter، buffer) |
| Envoy | overload manager شامل refresh_interval، resource_monitors، actions | ندارد | fixed_heap، cgroup_memory؛ اقدامهای stop_accepting_requests، disable_http_keepalive، reduce_timeouts، reset_high_memory_stream |
| Envoy | circuit breakerها | بهازای cluster | حداکثر اتصال، pending، requests، retries |
| Kubernetes | evictionHard | memory.available<100Mi، nodefs.available<10%، imagefs.available<15%، nodefs.inodesFree<5% | عبور از آستانه podها را میکشد |
| Kubernetes | evictionSoft + grace period | ندارد | eviction با مهلت |
| RabbitMQ | x-max-length، x-overflow، x-message-ttl | drop-head | سقف اندازه و سن صف |
| Laravel Octane | --workers، --max-requests (500)، max_execution_time (30) | یک worker برای هر هستهٔ CPU | تعداد worker همان سقف in-flight است |
| Laravel queues | retryUntil()، Skip::when()، retry_after | retry_after برابر 90 در درایور redis | سن و طول عمر job |
پیامها و کدهایی که میبینید
| کجا | متن یا کد | معنی |
|---|---|---|
| HTTP | 503 Service Unavailable با Retry-After | shed شد |
| HTTP | 429 Too Many Requests | فراخوان از سهمیه گذشته |
| لاگ خطای NGINX | limiting connections by zone "addr" (سطح از limit_conn_log_level، پیشفرض error) | limit_conn درخواستی را رد کرد |
| لاگ خطای NGINX | limiting requests, excess: 5.420 by zone "one" | limit_req درخواستی را رد کرد |
| HAProxy | وضعیت پایان sQ | کلاینت در صف منتظر ماند و timeout شد |
| Envoy | شمارندههای upstream_rq_pending_overflow، upstream_rq_active_overflow، upstream_cx_overflow | سرریز circuit breaker |
| Envoy | response flag برابر UO | سرریز upstream |
| AMQP | basic.nack بعد از reject-publish | صف پر است |
| PostgreSQL | FATAL: sorry, too many clients already | max_connections پر شده |
| Kubernetes | condition گره MemoryPressure و taint کوبلت | گره زیر فشار حافظه است و podها را evict میکند |
سه بخش بعدی کد است. هرچه زیر docs/snippets/system-design/load-shedding/ است کامپایل، vet و تست میشود (Go) و php -l را رد میکند (PHP).
Go
مثال: limiter تطبیقی، middleware اولویتدار، throttle کلاینت و شبیهساز
ماژول academy/load-shedding شش پکیج کوچک دارد. اول الگوریتمها: سه برآوردگر limit پشت یک interface.
// Package limit holds concurrency-limit algorithms. Each one answers a single
// question: given what finished recently, how many requests may be in flight?
package limit
import (
"math"
"sync"
"time"
)
// Sample describes one finished request.
type Sample struct {
RTT time.Duration // time from admission to completion, queueing included
Inflight int // requests in flight when this one was admitted
Dropped bool // timeout, 503 from downstream or other loss signal
}
// Algorithm is a pluggable limit estimator.
type Algorithm interface {
Limit() int
OnSample(Sample)
}
func clampInt(v, lo, hi int) int {
if v < lo {
return lo
}
if v > hi {
return hi
}
return v
}
// Fixed never changes: the static concurrency limit.
type Fixed struct{ N int }
func (f Fixed) Limit() int { return f.N }
func (f Fixed) OnSample(Sample) {}
// AIMD is loss based, like TCP: add one on success when the limit is really
// being used, multiply by Backoff when a request is dropped.
type AIMD struct {
mu sync.Mutex
limit float64
Min, Max int
Backoff float64 // for example 0.9
}
func NewAIMD(initial, min, max int, backoff float64) *AIMD {
return &AIMD{limit: float64(initial), Min: min, Max: max, Backoff: backoff}
}
func (a *AIMD) Limit() int {
a.mu.Lock()
defer a.mu.Unlock()
return clampInt(int(a.limit), a.Min, a.Max)
}
func (a *AIMD) OnSample(s Sample) {
a.mu.Lock()
defer a.mu.Unlock()
switch {
case s.Dropped:
a.limit = math.Max(float64(a.Min), a.limit*a.Backoff)
case float64(s.Inflight)*2 >= a.limit:
a.limit = math.Min(float64(a.Max), a.limit+1)
}
}
// window collects RTT samples and releases one summary per N samples.
type window struct {
n, count int
sum time.Duration
maxIn int
dropped bool
}
func (w *window) add(s Sample) (avg time.Duration, maxInflight int, dropped, full bool) {
w.count++
w.sum += s.RTT
if s.Inflight > w.maxIn {
w.maxIn = s.Inflight
}
w.dropped = w.dropped || s.Dropped
if w.count < w.n {
return 0, 0, false, false
}
avg, maxInflight, dropped = w.sum/time.Duration(w.count), w.maxIn, w.dropped
*w = window{n: w.n}
return avg, maxInflight, dropped, true
}
// Vegas is delay based. The estimated queue is limit * (1 - minRTT/sampleRTT).
// Below Alpha the limit grows by one, above Beta it shrinks by one. Netflix's
// README gives alpha 2-3 and beta 4-6 as typical values.
type Vegas struct {
mu sync.Mutex
limit float64
minRTT time.Duration
w window
Min, Max int
Alpha, Beta float64
}
func NewVegas(initial, min, max, windowSize int) *Vegas {
return &Vegas{limit: float64(initial), Min: min, Max: max, Alpha: 3, Beta: 6, w: window{n: windowSize}}
}
func (v *Vegas) Limit() int {
v.mu.Lock()
defer v.mu.Unlock()
return clampInt(int(v.limit), v.Min, v.Max)
}
func (v *Vegas) OnSample(s Sample) {
v.mu.Lock()
defer v.mu.Unlock()
if s.RTT > 0 && (v.minRTT == 0 || s.RTT < v.minRTT) {
v.minRTT = s.RTT
}
avg, maxIn, dropped, full := v.w.add(s)
if !full || avg <= 0 || v.minRTT <= 0 {
return
}
if dropped {
v.limit = math.Max(float64(v.Min), v.limit*0.9)
return
}
queue := v.limit * (1 - float64(v.minRTT)/float64(avg))
switch {
case queue < v.Alpha && float64(maxIn)*2 >= v.limit:
v.limit = math.Min(float64(v.Max), v.limit+1)
case queue > v.Beta:
v.limit = math.Max(float64(v.Min), v.limit-1)
}
}
// Gradient follows Envoy's gradient controller:
// gradient = (minRTT + B) / sampleRTT, limit' = gradient*limit + sqrt(limit),
// where B = minRTT * Buffer. We clamp the gradient to [0.5, 1.0] (our choice)
// so one noisy window cannot halve the limit twice in a row.
type Gradient struct {
mu sync.Mutex
limit float64
minRTT time.Duration
w window
Min, Max int
Buffer float64 // fraction of minRTT tolerated before the gradient drops
}
func NewGradient(initial, min, max, windowSize int, buffer float64) *Gradient {
return &Gradient{limit: float64(initial), Min: min, Max: max, Buffer: buffer, w: window{n: windowSize}}
}
func (g *Gradient) Limit() int {
g.mu.Lock()
defer g.mu.Unlock()
return clampInt(int(g.limit), g.Min, g.Max)
}
// ResetMinRTT forgets the baseline. Envoy re-measures minRTT on a timer
// (min_rtt_calc_params.interval) for the same reason: the "ideal" latency drifts.
func (g *Gradient) ResetMinRTT() {
g.mu.Lock()
g.minRTT = 0
g.mu.Unlock()
}
func (g *Gradient) OnSample(s Sample) {
g.mu.Lock()
defer g.mu.Unlock()
if s.RTT > 0 && (g.minRTT == 0 || s.RTT < g.minRTT) {
g.minRTT = s.RTT
}
avg, maxIn, dropped, full := g.w.add(s)
if !full || avg <= 0 || g.minRTT <= 0 {
return
}
if dropped {
g.limit = math.Max(float64(g.Min), g.limit*0.9)
return
}
b := float64(g.minRTT) * g.Buffer
gradient := (float64(g.minRTT) + b) / float64(avg)
gradient = math.Max(0.5, math.Min(1.0, gradient))
next := gradient*g.limit + math.Sqrt(g.limit)
if gradient == 1.0 && float64(maxIn)*2 < g.limit {
next = g.limit // not using the limit: do not grow it
}
g.limit = math.Max(float64(g.Min), math.Min(float64(g.Max), next))
}Limiter درخواستهای in-flight را میشمارد و تأخیر هر درخواست تمامشده را به الگوریتم برمیگرداند. Acquire(fraction) جایی است که tier به رفتار تبدیل میشود: tier پایینتر کسر کوچکتری میدهد و زودتر به سقف میخورد.
// Package limiter enforces a concurrency limit: it counts requests in flight
// and refuses new ones once the algorithm's current limit is reached.
package limiter
import (
"math"
"sync"
"time"
"academy/load-shedding/clock"
"academy/load-shedding/limit"
)
// Outcome tells the algorithm how a request ended.
type Outcome int
const (
// Success: finished with a useful answer in time.
Success Outcome = iota
// Dropped: timed out or failed because of overload (a loss signal).
Dropped
// Ignore: carries no latency information (client error, cancelled early).
Ignore
)
// Limiter is safe for concurrent use.
type Limiter struct {
alg limit.Algorithm
clk clock.Clock
mu sync.Mutex
inflight int
}
func New(alg limit.Algorithm, clk clock.Clock) *Limiter {
return &Limiter{alg: alg, clk: clk}
}
// Token is the permit for one admitted request. Release it exactly once.
type Token struct {
l *Limiter
start time.Time
inflight int
done bool
}
// Acquire admits a request when inflight is below fraction*limit. Critical
// traffic passes fraction 1.0, sheddable traffic a smaller one, so lower tiers
// are refused first while the shared limit still adapts.
func (l *Limiter) Acquire(fraction float64) (*Token, bool) {
cap := int(math.Ceil(float64(l.alg.Limit()) * fraction))
if cap < 1 {
cap = 1
}
l.mu.Lock()
defer l.mu.Unlock()
if l.inflight >= cap {
return nil, false
}
l.inflight++
return &Token{l: l, start: l.clk.Now(), inflight: l.inflight}, true
}
// Release returns the permit and feeds the measured latency to the algorithm.
func (t *Token) Release(o Outcome) {
if t.done {
return
}
t.done = true
rtt := t.l.clk.Now().Sub(t.start)
t.l.mu.Lock()
t.l.inflight--
t.l.mu.Unlock()
if o != Ignore {
t.l.alg.OnSample(limit.Sample{RTT: rtt, Inflight: t.inflight, Dropped: o == Dropped})
}
}
// Inflight is the current number of admitted requests.
func (l *Limiter) Inflight() int {
l.mu.Lock()
defer l.mu.Unlock()
return l.inflight
}
// Limit is the algorithm's current limit.
func (l *Limiter) Limit() int { return l.alg.Limit() }Tierها و پارس X-Request-Start:
// Package shed is net/http middleware that drops work on purpose: by queue
// age, by priority tier against an adaptive concurrency limit, and by
// per-customer in-flight quota.
package shed
import "strings"
// Tier mirrors the four criticality values in Google's SRE book, chapter 21.
type Tier int
const (
CriticalPlus Tier = iota // user-visible impact if it fails, shed last
Critical // default for production traffic
SheddablePlus // batch: partial unavailability expected
Sheddable // frequent partial unavailability expected
)
var names = [...]string{"CRITICAL_PLUS", "CRITICAL", "SHEDDABLE_PLUS", "SHEDDABLE"}
func (t Tier) String() string {
if t < 0 || int(t) >= len(names) {
return "UNKNOWN"
}
return names[t]
}
// ParseTier reads a header value. Unknown or missing values become Critical,
// the safe default: never shed traffic nobody labelled.
func ParseTier(v string) Tier {
switch strings.ToUpper(strings.TrimSpace(v)) {
case "CRITICAL_PLUS":
return CriticalPlus
case "SHEDDABLE_PLUS":
return SheddablePlus
case "SHEDDABLE":
return Sheddable
default:
return Critical
}
}
// DefaultThresholds is the share of the concurrency limit each tier may use.
var DefaultThresholds = [4]float64{1.0, 0.9, 0.7, 0.5}package shed
import (
"strconv"
"strings"
"time"
)
// ParseRequestStart reads an X-Request-Start value written by a proxy.
// Accepted forms: "t=1700000000.123" (NGINX: "t=$msec"), "1700000000123"
// (Heroku: unix milliseconds) and "t=1700000000123456" (microseconds).
// The unit is guessed from the magnitude; ok is false when it cannot be read.
func ParseRequestStart(v string) (t time.Time, ok bool) {
v = strings.TrimPrefix(strings.TrimSpace(v), "t=")
f, err := strconv.ParseFloat(v, 64)
if err != nil || f <= 0 {
return time.Time{}, false
}
switch {
case f >= 1e15: // microseconds
return time.UnixMicro(int64(f)), true
case f >= 1e11: // milliseconds
return time.UnixMilli(int64(f)), true
default: // seconds with a fraction
sec := int64(f)
return time.Unix(sec, int64((f-float64(sec))*1e9)), true
}
}Middleware سه بررسی را به ترتیب انجام میدهد (بودجهٔ صف، سهمیهٔ مشتری، سهم tier از limit تطبیقی)، با 503 یا 429 و Retry-After جواب میدهد و نتیجه را برمیگرداند:
package shed
import (
"context"
"errors"
"net/http"
"strconv"
"sync"
"sync/atomic"
"time"
"academy/load-shedding/clock"
"academy/load-shedding/limiter"
)
// Reason says why a request was refused. It becomes a metric label.
type Reason string
const (
ReasonQueueBudget Reason = "queue_budget" // waited too long before reaching us
ReasonConcurrency Reason = "concurrency" // tier threshold of the adaptive limit
ReasonQuota Reason = "quota" // per-customer in-flight cap
)
// Config wires the middleware. Zero values are filled by New.
type Config struct {
Limiter *limiter.Limiter
Clock clock.Clock
Thresholds [4]float64 // share of the limit per tier
QueueBudget [4]time.Duration // max age per tier; 0 disables the check
Classify func(*http.Request) Tier
// Customer returns the quota key (API key, tenant id); empty skips the quota.
Customer func(*http.Request) string
CustomerMax int
// RetryAfter is the whole-second hint sent with every refusal. Add jitter
// here in production so refused clients do not return in lockstep.
RetryAfter func(Tier, Reason) time.Duration
}
// Stats counts decisions per tier. Goodput is a separate metric: it is
// "answered in time", which only the client or a latency histogram can tell.
type Stats struct {
admitted [4]atomic.Int64
shed [4][3]atomic.Int64
}
var reasonIndex = map[Reason]int{ReasonQueueBudget: 0, ReasonConcurrency: 1, ReasonQuota: 2}
func (s *Stats) Admitted(t Tier) int64 { return s.admitted[t].Load() }
func (s *Stats) Shed(t Tier, r Reason) int64 { return s.shed[t][reasonIndex[r]].Load() }
// Middleware is the shedding gate.
type Middleware struct {
cfg Config
Stats Stats
mu sync.Mutex
perOwner map[string]int
}
func New(cfg Config) *Middleware {
if cfg.Clock == nil {
cfg.Clock = clock.Real{}
}
if cfg.Thresholds == ([4]float64{}) {
cfg.Thresholds = DefaultThresholds
}
if cfg.Classify == nil {
cfg.Classify = func(r *http.Request) Tier { return ParseTier(r.Header.Get("X-Priority")) }
}
if cfg.RetryAfter == nil {
cfg.RetryAfter = func(Tier, Reason) time.Duration { return time.Second }
}
return &Middleware{cfg: cfg, perOwner: map[string]int{}}
}
// Handler wraps next.
func (m *Middleware) Handler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
tier := m.cfg.Classify(r)
// 1. Queue-time budget: a request that already waited past its budget
// is probably abandoned by the client; serving it is wasted work.
if budget := m.cfg.QueueBudget[tier]; budget > 0 {
if start, ok := ParseRequestStart(r.Header.Get("X-Request-Start")); ok {
if m.cfg.Clock.Now().Sub(start) > budget {
m.refuse(w, tier, ReasonQueueBudget, http.StatusServiceUnavailable)
return
}
}
}
// 2. Per-customer quota: one noisy customer gets 429, others are untouched.
if m.cfg.Customer != nil && m.cfg.CustomerMax > 0 {
if key := m.cfg.Customer(r); key != "" {
if !m.takeQuota(key) {
m.refuse(w, tier, ReasonQuota, http.StatusTooManyRequests)
return
}
defer m.returnQuota(key)
}
}
// 3. Adaptive concurrency limit, with a lower ceiling for lower tiers.
tok, ok := m.cfg.Limiter.Acquire(m.cfg.Thresholds[tier])
if !ok {
m.refuse(w, tier, ReasonConcurrency, http.StatusServiceUnavailable)
return
}
m.Stats.admitted[tier].Add(1)
rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
next.ServeHTTP(rec, r)
switch {
case rec.status == http.StatusServiceUnavailable || rec.status == http.StatusGatewayTimeout ||
errors.Is(r.Context().Err(), context.DeadlineExceeded):
tok.Release(limiter.Dropped)
case rec.status >= 400 && rec.status < 500:
tok.Release(limiter.Ignore) // client errors say nothing about capacity
default:
tok.Release(limiter.Success)
}
})
}
func (m *Middleware) refuse(w http.ResponseWriter, t Tier, why Reason, code int) {
m.Stats.shed[t][reasonIndex[why]].Add(1)
secs := int((m.cfg.RetryAfter(t, why) + time.Second - 1) / time.Second)
if secs < 1 {
secs = 1
}
w.Header().Set("Retry-After", strconv.Itoa(secs))
w.Header().Set("X-Shed-Reason", string(why))
w.Header().Set("Cache-Control", "no-store")
http.Error(w, http.StatusText(code), code)
}
func (m *Middleware) takeQuota(key string) bool {
m.mu.Lock()
defer m.mu.Unlock()
if m.perOwner[key] >= m.cfg.CustomerMax {
return false
}
m.perOwner[key]++
return true
}
func (m *Middleware) returnQuota(key string) {
m.mu.Lock()
defer m.mu.Unlock()
if m.perOwner[key]--; m.perOwner[key] <= 0 {
delete(m.perOwner, key)
}
}
type statusRecorder struct {
http.ResponseWriter
status int
}
func (s *statusRecorder) WriteHeader(code int) {
s.status = code
s.ResponseWriter.WriteHeader(code)
}تستهایش از ساعت جعلی و httptest استفاده میکنند؛ تست tier پنج درخواست را in-flight نگه میدارد و بررسی میکند SHEDDABLE رد میشود در حالی که CRITICAL_PLUS هنوز پذیرفته میشود:
package shed
import (
"net/http"
"net/http/httptest"
"strconv"
"testing"
"time"
"academy/load-shedding/clock"
"academy/load-shedding/limit"
"academy/load-shedding/limiter"
)
func newMW(t *testing.T, limitN int, clk clock.Clock) *Middleware {
t.Helper()
cfg := Config{
Limiter: limiter.New(limit.Fixed{N: limitN}, clk),
Clock: clk,
}
for i := range cfg.QueueBudget {
cfg.QueueBudget[i] = 500 * time.Millisecond
}
return New(cfg)
}
func req(tier string, mutate func(*http.Request)) *http.Request {
r := httptest.NewRequest(http.MethodGet, "/x", nil)
r.Header.Set("X-Priority", tier)
if mutate != nil {
mutate(r)
}
return r
}
func TestStaleRequestIsShedWith503AndRetryAfter(t *testing.T) {
now := time.Unix(1_700_000_000, 0)
clk := clock.NewFake(now)
mw := newMW(t, 10, clk)
called := false
h := mw.Handler(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { called = true }))
stale := strconv.FormatInt(now.Add(-2*time.Second).UnixMilli(), 10) // waited 2s, budget 500ms
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req("CRITICAL", func(r *http.Request) { r.Header.Set("X-Request-Start", stale) }))
if rec.Code != http.StatusServiceUnavailable {
t.Fatalf("status %d, want 503", rec.Code)
}
if rec.Header().Get("Retry-After") != "1" {
t.Fatalf("Retry-After %q, want 1", rec.Header().Get("Retry-After"))
}
if called {
t.Fatal("handler must not run for a stale request")
}
if mw.Stats.Shed(Critical, ReasonQueueBudget) != 1 {
t.Fatal("queue_budget counter not incremented")
}
}
func TestFreshRequestPasses(t *testing.T) {
now := time.Unix(1_700_000_000, 0)
mw := newMW(t, 10, clock.NewFake(now))
h := mw.Handler(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(204) }))
rec := httptest.NewRecorder()
fresh := "t=" + strconv.FormatFloat(float64(now.Add(-50*time.Millisecond).UnixMilli())/1000, 'f', 3, 64)
h.ServeHTTP(rec, req("SHEDDABLE", func(r *http.Request) { r.Header.Set("X-Request-Start", fresh) }))
if rec.Code != 204 {
t.Fatalf("status %d, want 204", rec.Code)
}
}
// With limit 10 and thresholds 1.0/0.9/0.7/0.5, five in-flight requests fill
// the SHEDDABLE share while CRITICAL_PLUS can still use the whole limit.
func TestLowerTiersAreShedFirst(t *testing.T) {
clk := clock.NewFake(time.Unix(1_700_000_000, 0))
mw := newMW(t, 10, clk)
release := make(chan struct{})
entered := make(chan struct{}, 16)
h := mw.Handler(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
entered <- struct{}{}
<-release
}))
for i := 0; i < 5; i++ {
go h.ServeHTTP(httptest.NewRecorder(), req("CRITICAL", nil))
}
for i := 0; i < 5; i++ {
<-entered
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req("SHEDDABLE", nil))
if rec.Code != 503 || rec.Header().Get("X-Shed-Reason") != "concurrency" {
t.Fatalf("SHEDDABLE: %d %q, want 503 concurrency", rec.Code, rec.Header().Get("X-Shed-Reason"))
}
go h.ServeHTTP(httptest.NewRecorder(), req("CRITICAL_PLUS", nil)) // admitted: 5 < 10
<-entered
close(release)
}
func TestPerCustomerQuotaReturns429(t *testing.T) {
clk := clock.NewFake(time.Unix(1_700_000_000, 0))
mw := newMW(t, 100, clk)
mw.cfg.Customer = func(r *http.Request) string { return r.Header.Get("X-Api-Key") }
mw.cfg.CustomerMax = 1
release := make(chan struct{})
entered := make(chan struct{}, 4)
h := mw.Handler(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
entered <- struct{}{}
<-release
}))
withKey := func(k string) *http.Request {
return req("CRITICAL", func(r *http.Request) { r.Header.Set("X-Api-Key", k) })
}
go h.ServeHTTP(httptest.NewRecorder(), withKey("noisy"))
<-entered
rec := httptest.NewRecorder()
h.ServeHTTP(rec, withKey("noisy"))
if rec.Code != http.StatusTooManyRequests {
t.Fatalf("noisy customer: %d, want 429", rec.Code)
}
go h.ServeHTTP(httptest.NewRecorder(), withKey("quiet"))
<-entered // other customers are unaffected
close(release)
}
func TestParseRequestStart(t *testing.T) {
want := time.UnixMilli(1_700_000_000_123)
for _, in := range []string{"1700000000123", "t=1700000000.123", "t=1700000000123000"} {
got, ok := ParseRequestStart(in)
if !ok || got.Sub(want).Abs() > time.Millisecond {
t.Errorf("%q -> %v %v, want %v", in, got, ok, want)
}
}
if _, ok := ParseRequestStart("garbage"); ok {
t.Error("garbage must not parse")
}
}
func TestParseTierDefaultsToCritical(t *testing.T) {
if ParseTier("") != Critical || ParseTier("nonsense") != Critical {
t.Fatal("unlabelled traffic must default to CRITICAL")
}
if ParseTier("sheddable") != Sheddable {
t.Fatal("case-insensitive parse failed")
}
}نیمهٔ کلاینت: adaptive throttling (فرمول کتاب SRE گوگل)، retry budget و یک RoundTripper که Retry-After را رعایت میکند، هرگز POST را retry نمیکند و سر سه تلاش میایستد.
// Package throttle is the client half of load shedding: adaptive throttling
// (Google SRE book, chapter 21) and a retry budget, so a client that is being
// refused backs off by itself instead of adding to the overload.
package throttle
import (
"sync"
"time"
"academy/load-shedding/clock"
)
// counts is a sliding window of per-second buckets.
type counts struct {
mu sync.Mutex
clk clock.Clock
buckets []bucket
}
type bucket struct {
sec int64
requests, accs int64
}
func newCounts(clk clock.Clock, window time.Duration) *counts {
return &counts{clk: clk, buckets: make([]bucket, int(window/time.Second))}
}
func (c *counts) add(requests, accepts int64) {
sec := c.clk.Now().Unix()
c.mu.Lock()
defer c.mu.Unlock()
b := &c.buckets[int(sec%int64(len(c.buckets)))]
if b.sec != sec {
*b = bucket{sec: sec}
}
b.requests += requests
b.accs += accepts
}
func (c *counts) sum() (requests, accepts int64) {
now := c.clk.Now().Unix()
c.mu.Lock()
defer c.mu.Unlock()
for _, b := range c.buckets {
if now-b.sec < int64(len(c.buckets)) && b.sec <= now {
requests += b.requests
accepts += b.accs
}
}
return
}
// Adaptive implements client-side adaptive throttling. Over the last
// Window it counts requests (attempted by the application, including those
// refused locally) and accepts (admitted by the backend). Once requests exceed
// K*accepts the client rejects new requests locally with probability
// max(0, (requests - K*accepts) / (requests + 1)).
type Adaptive struct {
K float64
c *counts
}
// NewAdaptive uses a two-minute window like the SRE book; K=2 is the book's
// preferred multiplier, lower values throttle harder.
func NewAdaptive(clk clock.Clock, k float64) *Adaptive {
return &Adaptive{K: k, c: newCounts(clk, 2*time.Minute)}
}
// RejectProbability is the current local rejection probability.
func (a *Adaptive) RejectProbability() float64 {
req, acc := a.c.sum()
p := (float64(req) - a.K*float64(acc)) / float64(req+1)
if p < 0 {
return 0
}
return p
}
// Allow records an attempt and decides locally. u is a uniform random number
// in [0,1); it is a parameter so tests are deterministic.
func (a *Adaptive) Allow(u float64) bool {
p := a.RejectProbability()
a.c.add(1, 0)
return u >= p
}
// Accepted records that the backend admitted a request.
func (a *Adaptive) Accepted() { a.c.add(0, 1) }
// RetryBudget allows a retry only while retries stay below Ratio of all
// requests in the window (the SRE book uses 10%), plus a small floor so a
// quiet client can still retry its first failures.
type RetryBudget struct {
Ratio float64
Floor int64
c *counts
}
func NewRetryBudget(clk clock.Clock, ratio float64, floor int64) *RetryBudget {
return &RetryBudget{Ratio: ratio, Floor: floor, c: newCounts(clk, time.Minute)}
}
// OnRequest counts a first attempt.
func (b *RetryBudget) OnRequest() { b.c.add(1, 0) }
// TryRetry spends one retry if the budget allows it.
func (b *RetryBudget) TryRetry() bool {
req, retries := b.c.sum()
if retries >= b.Floor && float64(retries+1) > b.Ratio*float64(req) {
return false
}
b.c.add(0, 1)
return true
}package throttle
import (
"context"
"errors"
"net/http"
"strconv"
"time"
)
// ErrThrottled is returned without touching the network.
var ErrThrottled = errors.New("throttle: rejected locally, backend is refusing too much")
// MaxAttempts is the per-request cap (SRE book: up to three attempts).
const MaxAttempts = 3
// Transport wraps a RoundTripper with adaptive throttling, a retry budget and
// Retry-After handling. Only idempotent requests with a replayable body retry.
type Transport struct {
Base http.RoundTripper
Throttle *Adaptive
Budget *RetryBudget
Rand func() float64 // uniform [0,1)
Sleep func(ctx context.Context, d time.Duration) error // injected for tests
MaxWait time.Duration // cap on honouring Retry-After
}
func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
t.Budget.OnRequest()
for attempt := 1; ; attempt++ {
if !t.Throttle.Allow(t.Rand()) {
return nil, ErrThrottled
}
resp, err := t.Base.RoundTrip(req)
refused := err == nil && (resp.StatusCode == http.StatusServiceUnavailable || resp.StatusCode == http.StatusTooManyRequests)
if !refused {
if err == nil {
t.Throttle.Accepted()
}
return resp, err
}
if !retryable(req) || attempt >= MaxAttempts || resp.Header.Get("X-Overloaded-Dont-Retry") != "" || !t.Budget.TryRetry() {
return resp, nil // surface the 503/429 to the caller
}
wait := retryAfter(resp, t.MaxWait)
resp.Body.Close()
if err := t.Sleep(req.Context(), wait); err != nil {
return nil, err
}
if req.GetBody != nil {
body, err := req.GetBody()
if err != nil {
return nil, err
}
req = req.Clone(req.Context())
req.Body = body
}
}
}
func retryable(r *http.Request) bool {
switch r.Method {
case http.MethodGet, http.MethodHead, http.MethodOptions, http.MethodPut, http.MethodDelete:
default:
return false
}
return r.Body == nil || r.Body == http.NoBody || r.GetBody != nil
}
// retryAfter reads the delay-seconds form of Retry-After (RFC 9110, 10.2.3);
// the HTTP-date form is ignored here for brevity.
func retryAfter(resp *http.Response, max time.Duration) time.Duration {
secs, err := strconv.Atoi(resp.Header.Get("Retry-After"))
if err != nil || secs < 0 {
return 0
}
d := time.Duration(secs) * time.Second
if max > 0 && d > max {
return max
}
return d
}یک صف داخل فرایند با هر دو حالت overflow، رد TTL و CoDel سادهشده:
// Package msgqueue is a bounded in-memory queue that sheds on purpose:
// it can reject new messages or drop the oldest when full, expire messages by
// TTL, and drop on persistent queue delay (a simplified CoDel).
package msgqueue
import (
"errors"
"sync"
"time"
"academy/load-shedding/clock"
)
// Overflow is what happens when the queue is full.
type Overflow int
const (
// RejectPublish refuses the new message (RabbitMQ overflow=reject-publish):
// the producer learns about it and can slow down. This is backpressure.
RejectPublish Overflow = iota
// DropHead discards the oldest message to make room (RabbitMQ's default,
// overflow=drop-head): the queue stays fresh, producers never find out.
DropHead
)
// ErrFull is returned by Push under RejectPublish.
var ErrFull = errors.New("msgqueue: full, message rejected")
// Message carries its own enqueue time and TTL.
type Message struct {
ID string
Body []byte
TTL time.Duration // 0 means no expiry
Enqueued time.Time
}
// DeadLetter receives every message the queue discards, with the reason
// ("expired", "dropped_head", "codel"). Wire it to a dead-letter queue or just count.
type DeadLetter func(m Message, reason string)
// Queue is safe for concurrent use.
type Queue struct {
max int
overflow Overflow
clk clock.Clock
dead DeadLetter
codel *CoDel
mu sync.Mutex
msgs []Message
}
func New(max int, overflow Overflow, clk clock.Clock, dead DeadLetter, codel *CoDel) *Queue {
if dead == nil {
dead = func(Message, string) {}
}
return &Queue{max: max, overflow: overflow, clk: clk, dead: dead, codel: codel}
}
// Push enqueues m.
func (q *Queue) Push(m Message) error {
q.mu.Lock()
defer q.mu.Unlock()
if len(q.msgs) >= q.max {
if q.overflow == RejectPublish {
return ErrFull
}
q.dead(q.msgs[0], "dropped_head")
q.msgs = q.msgs[1:]
}
m.Enqueued = q.clk.Now()
q.msgs = append(q.msgs, m)
return nil
}
// Pop returns the next message worth processing. Expired messages and
// messages CoDel decides to drop are dead-lettered and skipped: a consumer
// never wastes time on work the sender has already given up on.
func (q *Queue) Pop() (Message, bool) {
q.mu.Lock()
defer q.mu.Unlock()
for len(q.msgs) > 0 {
m := q.msgs[0]
q.msgs = q.msgs[1:]
now := q.clk.Now()
if m.TTL > 0 && now.Sub(m.Enqueued) > m.TTL {
q.dead(m, "expired")
continue
}
if q.codel != nil && q.codel.ShouldDrop(now, now.Sub(m.Enqueued)) {
q.dead(m, "codel")
continue
}
return m, true
}
return Message{}, false
}
// Len is the number of queued messages.
func (q *Queue) Len() int {
q.mu.Lock()
defer q.mu.Unlock()
return len(q.msgs)
}package msgqueue
import "time"
// CoDel is a simplified controlled-delay gate. RFC 8289 describes the full
// algorithm for network packets: an estimator (sojourn time, the time a unit
// spent in the buffer), a setpoint (TARGET, 5 ms in the RFC) and a control
// loop (INTERVAL, 100 ms in the RFC). We keep the estimator and the setpoint:
// delay above Target that lasts for a whole Interval means a standing queue,
// and from then on every item older than Target is dropped until delay falls
// back under Target. The RFC's drop-rate control law (interval / sqrt(count))
// is left out. For a service queue pick Target near a small multiple of the
// service time, not the RFC's network values.
type CoDel struct {
Target time.Duration
Interval time.Duration
firstAbove time.Time
dropping bool
}
func (c *CoDel) ShouldDrop(now time.Time, sojourn time.Duration) bool {
if sojourn < c.Target {
c.firstAbove = time.Time{}
c.dropping = false
return false
}
if c.firstAbove.IsZero() {
c.firstAbove = now.Add(c.Interval) // start the clock; a burst is allowed
return false
}
if now.Before(c.firstAbove) {
return false
}
c.dropping = true
return true
}و شبیهسازی که عددهای آزمایشگاه را میسازد: ۱۰ سرور، سرویس ۱۰۰ms، timeout کلاینت ۱ ثانیه، پنج سیاست پذیرش، ترکیب tier با seed ثابت.
// Package sim is a deterministic overload simulator: C identical servers,
// fixed service time, a FIFO queue in front, clients that give up after a
// timeout. It shows what the page claims: without shedding goodput collapses
// under overload, with shedding it plateaus.
package sim
import (
"container/heap"
"time"
"academy/load-shedding/clock"
"academy/load-shedding/limit"
"academy/load-shedding/limiter"
"academy/load-shedding/shed"
)
// Mode is the admission policy in front of the queue.
type Mode string
const (
Unbounded Mode = "unbounded" // accept everything
Static Mode = "static-limit" // reject above a fixed in-system count
QueueBudget Mode = "queue-budget" // drop at dequeue when the wait is too long
Tiered Mode = "tiered-static" // per-tier share of a fixed limit
Adaptive Mode = "tiered-adaptive" // per-tier share of a gradient limit
)
// Config describes one run.
type Config struct {
Mode Mode
Servers int
Service time.Duration // time one request takes on one server
ClientTimeout time.Duration // a reply later than this is useless
Offered float64 // multiple of capacity, 2.0 = twice what the servers can do
Duration time.Duration
StaticLimit int // requests allowed in the system (queued + running)
Budget time.Duration // QueueBudget mode
}
// Result counts outcomes per tier.
type Result struct {
Offered, Good, Late, Shed [4]int
Duration time.Duration
}
// Goodput is useful replies per second.
func (r Result) Goodput() float64 {
n := 0
for _, g := range r.Good {
n += g
}
return float64(n) / r.Duration.Seconds()
}
// GoodShare is the fraction of offered requests of tier t answered in time.
func (r Result) GoodShare(t shed.Tier) float64 {
if r.Offered[t] == 0 {
return 0
}
return float64(r.Good[t]) / float64(r.Offered[t])
}
type request struct {
tier shed.Tier
arrive time.Time
tok *limiter.Token
}
type completion struct {
at time.Time
req *request
}
type completions []completion
func (h completions) Len() int { return len(h) }
func (h completions) Less(i, j int) bool { return h[i].at.Before(h[j].at) }
func (h completions) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *completions) Push(x interface{}) { *h = append(*h, x.(completion)) }
func (h *completions) Pop() interface{} {
old := *h
x := old[len(old)-1]
*h = old[:len(old)-1]
return x
}
// tierOf draws from a fixed mix, 5% CRITICAL_PLUS, 15% CRITICAL, 30%
// SHEDDABLE_PLUS and 50% SHEDDABLE, with a seeded generator so runs repeat
// exactly. A repeating pattern would alias with the regular arrival spacing.
func tierOf(state *uint64) shed.Tier {
*state += 0x9e3779b97f4a7c15 // splitmix64
z := *state
z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9
z = (z ^ (z >> 27)) * 0x94d049bb133111eb
z ^= z >> 31
switch k := z % 100; {
case k < 5:
return shed.CriticalPlus
case k < 20:
return shed.Critical
case k < 50:
return shed.SheddablePlus
default:
return shed.Sheddable
}
}
// Run executes one simulation.
func Run(cfg Config) Result {
start := time.Unix(1_700_000_000, 0)
clk := clock.NewFake(start)
capacity := float64(cfg.Servers) / cfg.Service.Seconds()
gap := time.Duration(float64(time.Second) / (capacity * cfg.Offered))
total := int(cfg.Duration / gap)
var lim *limiter.Limiter
switch cfg.Mode {
case Adaptive:
lim = limiter.New(limit.NewGradient(cfg.StaticLimit, cfg.Servers, 4*cfg.StaticLimit, 20, 0.5), clk)
default:
lim = limiter.New(limit.Fixed{N: cfg.StaticLimit}, clk)
}
res := Result{Duration: cfg.Duration}
var queue []*request
var done completions
busy, inSystem := 0, 0
tryStart := func() {
for busy < cfg.Servers && len(queue) > 0 {
r := queue[0]
queue = queue[1:]
if cfg.Mode == QueueBudget && clk.Now().Sub(r.arrive) > cfg.Budget {
res.Shed[r.tier]++
inSystem--
continue
}
busy++
heap.Push(&done, completion{at: clk.Now().Add(cfg.Service), req: r})
}
}
next := 0
seed := uint64(42)
for next < total || done.Len() > 0 {
arrival := start.Add(time.Duration(next) * gap)
if next < total && (done.Len() == 0 || !done[0].at.Before(arrival)) {
clk.Set(arrival)
t := tierOf(&seed)
next++
res.Offered[t]++
r := &request{tier: t, arrive: arrival}
admit := true
switch cfg.Mode {
case Static:
admit = inSystem < cfg.StaticLimit
case Tiered, Adaptive:
r.tok, admit = lim.Acquire(shed.DefaultThresholds[t])
}
if !admit {
res.Shed[t]++
continue
}
inSystem++
queue = append(queue, r)
tryStart()
continue
}
c := heap.Pop(&done).(completion)
clk.Set(c.at)
busy--
inSystem--
lat := c.at.Sub(c.req.arrive)
out := limiter.Success
if lat > cfg.ClientTimeout {
res.Late[c.req.tier]++
out = limiter.Dropped
} else {
res.Good[c.req.tier]++
}
if c.req.tok != nil {
c.req.tok.Release(out)
}
tryStart()
}
return res
}package sim
import (
"testing"
"time"
"academy/load-shedding/shed"
)
func base(mode Mode, offered float64) Config {
return Config{
Mode: mode, Servers: 10, Service: 100 * time.Millisecond,
ClientTimeout: time.Second, Offered: offered, Duration: 60 * time.Second,
StaticLimit: 20, Budget: 300 * time.Millisecond,
}
}
// Capacity is 10 servers / 0.1s = 100 requests per second.
const capacity = 100.0
func TestUnderCapacityEveryModeServesEverything(t *testing.T) {
for _, m := range []Mode{Unbounded, Static, QueueBudget, Tiered, Adaptive} {
r := Run(base(m, 0.5))
if g := r.Goodput(); g < 0.45*capacity {
t.Errorf("%s at 0.5x: goodput %.1f, want about 50", m, g)
}
}
}
func TestOverloadCollapsesWithoutShedding(t *testing.T) {
r := Run(base(Unbounded, 3))
if g := r.Goodput(); g > 0.15*capacity {
t.Fatalf("unbounded queue at 3x: goodput %.1f, want a collapse below 15", g)
}
}
func TestSheddingKeepsGoodputNearCapacity(t *testing.T) {
for _, m := range []Mode{Static, QueueBudget, Tiered, Adaptive} {
r := Run(base(m, 3))
if g := r.Goodput(); g < 0.85*capacity {
t.Errorf("%s at 3x: goodput %.1f, want at least 85", m, g)
}
}
}
func TestTiersProtectCriticalTraffic(t *testing.T) {
for _, m := range []Mode{Tiered, Adaptive} {
r := Run(base(m, 3))
if s := r.GoodShare(shed.CriticalPlus); s < 0.95 {
t.Errorf("%s: CRITICAL_PLUS good share %.2f, want >= 0.95", m, s)
}
if s := r.GoodShare(shed.Critical); s < 0.9 {
t.Errorf("%s: CRITICAL good share %.2f, want >= 0.9", m, s)
}
if r.GoodShare(shed.Sheddable) >= r.GoodShare(shed.Critical) {
t.Errorf("%s: SHEDDABLE must fare worse than CRITICAL", m)
}
}
// Without tiers the unlabelled overload hits everyone alike.
r := Run(base(Static, 3))
if d := r.GoodShare(shed.Critical) - r.GoodShare(shed.Sheddable); d > 0.05 || d < -0.05 {
t.Errorf("static limit is tier-blind, got shares differing by %.2f", d)
}
}
func TestSimulationIsDeterministic(t *testing.T) {
a, b := Run(base(Adaptive, 2)), Run(base(Adaptive, 2))
if a != b {
t.Fatal("same config must give the same result")
}
}
// A static limit tuned for an old, faster fleet is the classic failure:
// 200 in the system on 10 servers means 2 s of queueing, so replies arrive
// after the 1 s client timeout. The adaptive limit starts at the same wrong
// value and walks down to what the servers can really do.
func TestAdaptiveRecoversFromAWrongInitialLimit(t *testing.T) {
static, adaptive := base(Static, 3), base(Adaptive, 3)
static.StaticLimit, adaptive.StaticLimit = 200, 200
s, a := Run(static).Goodput(), Run(adaptive).Goodput()
if s > 0.3*capacity {
t.Fatalf("static limit 200: goodput %.1f, want a collapse below 30", s)
}
if a < 0.8*capacity {
t.Fatalf("adaptive from 200: goodput %.1f, want at least 80", a)
}
}// Command loadsim prints goodput for every admission policy at several
// offered loads. It is deterministic and finishes in well under a second.
package main
import (
"fmt"
"time"
"academy/load-shedding/shed"
"academy/load-shedding/sim"
)
func main() {
modes := []sim.Mode{sim.Unbounded, sim.Static, sim.QueueBudget, sim.Tiered, sim.Adaptive}
loads := []float64{0.5, 1, 2, 4}
fmt.Println("capacity = 100 req/s (10 servers x 100 ms), client timeout 1 s")
fmt.Printf("%-16s", "policy")
for _, l := range loads {
fmt.Printf(" %7.1fx", l)
}
fmt.Println(" (goodput, requests/s)")
for _, m := range modes {
fmt.Printf("%-16s", m)
for _, l := range loads {
r := sim.Run(sim.Config{
Mode: m, Servers: 10, Service: 100 * time.Millisecond, ClientTimeout: time.Second,
Offered: l, Duration: 60 * time.Second, StaticLimit: 20, Budget: 300 * time.Millisecond,
})
fmt.Printf(" %8.1f", r.Goodput())
}
fmt.Println()
}
fmt.Println()
fmt.Println("share of each tier answered in time at 4x offered load")
fmt.Printf("%-16s %13s %9s %14s %10s\n", "policy", "CRITICAL_PLUS", "CRITICAL", "SHEDDABLE_PLUS", "SHEDDABLE")
for _, m := range modes {
r := sim.Run(sim.Config{
Mode: m, Servers: 10, Service: 100 * time.Millisecond, ClientTimeout: time.Second,
Offered: 4, Duration: 60 * time.Second, StaticLimit: 20, Budget: 300 * time.Millisecond,
})
fmt.Printf("%-16s %12.0f%% %8.0f%% %13.0f%% %9.0f%%\n", m,
100*r.GoodShare(shed.CriticalPlus), 100*r.GoodShare(shed.Critical),
100*r.GoodShare(shed.SheddablePlus), 100*r.GoodShare(shed.Sheddable))
}
fmt.Println()
fmt.Println("a limit of 200 is wrong for 10 servers: 60-second average goodput at 3x offered load")
for _, m := range []sim.Mode{sim.Static, sim.Adaptive} {
r := sim.Run(sim.Config{
Mode: m, Servers: 10, Service: 100 * time.Millisecond, ClientTimeout: time.Second,
Offered: 3, Duration: 60 * time.Second, StaticLimit: 200, Budget: 300 * time.Millisecond,
})
fmt.Printf("%-16s goodput %6.1f req/s\n", m, r.Goodput())
}
}زاویهٔ Go
- محدودیت concurrency یک semaphore با حافظه است. کانال بافردار با اندازهٔ
Lهمان limit ثابت است؛ پکیجlimiterهمین ایده باLمتحرک و مسیر بازخورد تأخیر است. با تلاش غیرمسدودکننده پذیرش کنید، نه ارسال مسدودکننده: block کردن یعنی صفکشی و صفکشی همان چیزی است که shedding از آن میپرهیزد. context.Contextهمان deadline است. deadline کلاینت را پایین بدهید (http.ServerهدرX-Request-Startرا نمیخواند؛ middleware شما میخواند) و پیش از گامهای گرانctx.Err()را بررسی کنید تا درخواستهای محکوم زود متوقف شوند (Timeouts, Retries & Jitter).- مسیر ردّ را کمتخصیص نگه دارید.
http.Errorبا بدنهٔ کوتاه، در مسیر داغ فقط افزایش یک شمارنده و لاگ دیگر نه. Builders' Library هشدار میدهد یک خط log اتفاقی میتواند رد کردن را گرانتر از سرویس دادن کند. - ساعت را تزریق کنید. هر پکیج
clock.Clockمیگیرد، پس تستها زمان را دستی جلو میبرند و شبیهساز ۶۰ ثانیهٔ مجازی را در چند میلیثانیه بازپخش میکند. net/httpمحدودیت concurrency داخلی ندارد.http.Server.MaxHeaderBytes،ReadTimeout،IdleTimeoutوgolang.org/x/net/netutil.LimitListenerاتصال را محدود میکنند، نه درخواست in-flight را؛ برای پذیرش بهازای درخواست باید middlewareای مثل بالا بنویسید.- زمانبند Go صفها را پنهان میکند. goroutine ارزان است، پس سرویس Go کمتر صف thread-pool نشان میدهد؛ صف در حافظه، accept backlog و روی قفلهاست. درخواستهای in-flight را ردیابی کنید، نه goroutineها را.
- مراقب retry در
http.Clientباشید.Transportکتابخانهٔ استاندارد برخی درخواستهای idempotent را هنگام خطای استفادهٔ مجدد از اتصال retry میکند؛ برای سیاست overload آن را مثلthrottle.Transportبپوشانید.
Laravel
مثال: shedding بر پایهٔ زمان صف، routeهای tierبندیشده و jobهای منقضیشونده
Laravel 13 قابلیت داخلی load shedding ندارد. middleware throttle و RateLimiter آن rate limiting بهازای هویت است (Rate Limiting). برای overload باید مهر X-Request-Start از proxy، بودجهٔ worker و middleware روی route را ترکیب کنید.
Proxy زمان ورود را مهر میزند (در NGINX متغیر $msec برابر "current time in seconds with the milliseconds resolution" است؛ Heroku هدر X-Request-Start را "unix timestamp (milliseconds) when the request was received by the router" مستند کرده):
location / {
proxy_set_header X-Request-Start "t=${msec}";
proxy_pass http://octane;
}enum مربوط به tier و پارسر هدر PHP سادهاند:
<?php
declare(strict_types=1);
namespace App\Overload;
/**
* The four criticality values from Google's SRE book, chapter 21.
* Lower case value = what clients send in the X-Priority header.
*/
enum Tier: string
{
case CriticalPlus = 'critical_plus';
case Critical = 'critical';
case SheddablePlus = 'sheddable_plus';
case Sheddable = 'sheddable';
/** Unknown or missing labels are CRITICAL: never shed what nobody labelled. */
public static function fromHeader(?string $value): self
{
return self::tryFrom(strtolower(trim((string) $value))) ?? self::Critical;
}
/** Share of the worker budget this tier may use (1.0 = everything). */
public function threshold(): float
{
return match ($this) {
self::CriticalPlus => 1.0,
self::Critical => 0.9,
self::SheddablePlus => 0.7,
self::Sheddable => 0.5,
};
}
}<?php
declare(strict_types=1);
namespace App\Overload;
/**
* Reads the X-Request-Start header a proxy stamps on the request.
* NGINX: proxy_set_header X-Request-Start "t=${msec}"; (seconds, ms resolution)
* Heroku: unix milliseconds. Some APMs use microseconds.
*/
final class RequestStart
{
/** @return float|null unix time in seconds, or null if the header is unusable */
public static function parse(?string $header): ?float
{
if ($header === null) {
return null;
}
$value = preg_replace('/^t=/', '', trim($header)) ?? '';
if (! is_numeric($value) || (float) $value <= 0) {
return null;
}
$number = (float) $value;
return match (true) {
$number >= 1e15 => $number / 1e6, // microseconds
$number >= 1e11 => $number / 1e3, // milliseconds
default => $number, // seconds with a fraction
};
}
/** Seconds the request waited before PHP started working on it. */
public static function queueSeconds(?string $header, ?float $now = null): ?float
{
$start = self::parse($header);
return $start === null ? null : max(0.0, ($now ?? microtime(true)) - $start);
}
}gauge مربوط به in-flight یک interface با پیادهسازی پشتیبانیشده با cache است (برای شمارش سراسری ناوگان store ریدیس را بگیرید). برآورد است، نه قفل:
<?php
declare(strict_types=1);
namespace App\Overload;
/** Counts requests being worked on right now, per host or per fleet. */
interface InflightGauge
{
/** Try to take one slot; false when `$limit` slots are taken. */
public function enter(int $limit): bool;
public function leave(): void;
public function current(): int;
}<?php
declare(strict_types=1);
namespace App\Overload;
use Illuminate\Contracts\Cache\Repository;
/**
* In-flight counter on top of the cache store (use Redis for a fleet-wide
* number, the `array`/`apc` store for one host). The key has a short TTL, so a
* worker that dies between enter() and leave() leaks a slot for at most that
* long. This is an estimate, not a lock: it is meant to drive shedding, not
* to guarantee a hard cap.
*/
final class CacheInflightGauge implements InflightGauge
{
public function __construct(
private readonly Repository $cache,
private readonly string $key = 'shed:inflight',
private readonly int $ttlSeconds = 30,
) {
}
public function enter(int $limit): bool
{
$this->cache->add($this->key, 0, $this->ttlSeconds);
$now = (int) $this->cache->increment($this->key);
if ($now > $limit) {
$this->cache->decrement($this->key);
return false;
}
return true;
}
public function leave(): void
{
if ((int) $this->cache->get($this->key, 0) > 0) {
$this->cache->decrement($this->key);
}
}
public function current(): int
{
return max(0, (int) $this->cache->get($this->key, 0));
}
}<?php
declare(strict_types=1);
namespace App\Providers;
use App\Overload\CacheInflightGauge;
use App\Overload\InflightGauge;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\ServiceProvider;
final class OverloadServiceProvider extends ServiceProvider
{
public function register(): void
{
// Redis gives a fleet-wide count; use Cache::store('array') for one process.
$this->app->bind(InflightGauge::class, fn (): InflightGauge => new CacheInflightGauge(
Cache::store('redis'),
key: 'shed:inflight:' . gethostname(),
));
}
}Middleware بودجهٔ صف و سهم tier را اعمال میکند، با 503 و Retry-After با مقدار jitterدار جواب میدهد و slot را در terminate آزاد میکند. مستندات Laravel میگوید middleware قابلختم مگر بهصورت singleton ثبت شود "a fresh instance of the middleware from the service container" میگیرد؛ برای همین نشانهٔ slot روی request حمل میشود، نه روی instance.
<?php
declare(strict_types=1);
namespace App\Http\Middleware;
use App\Overload\InflightGauge;
use App\Overload\RequestStart;
use App\Overload\Tier;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpFoundation\Response;
/**
* Drops work on purpose to protect goodput.
*
* 1. Queue-time budget: the proxy stamped X-Request-Start; if the request
* already waited longer than its budget, the client has probably given
* up, so answer 503 immediately instead of doing useless work.
* 2. Worker budget: lower tiers may only use a share of the workers.
*
* Usage: Route::get('/search/suggest', ...)->middleware('shed:sheddable');
*/
final class ShedLoad
{
public function __construct(private readonly InflightGauge $gauge)
{
}
public function handle(Request $request, Closure $next, string $tier = 'critical'): Response
{
$routeTier = Tier::fromHeader($tier);
$tier = Tier::fromHeader($request->header('X-Priority', $routeTier->value));
// A client may lower its own priority but never raise it above the route's.
if ($tier->threshold() > $routeTier->threshold()) {
$tier = $routeTier;
}
$budget = (float) config('shedding.queue_budget_seconds.' . $tier->value, 0.0);
$waited = RequestStart::queueSeconds($request->header('X-Request-Start'));
if ($budget > 0 && $waited !== null && $waited > $budget) {
return $this->refuse($tier, 'queue_budget', $waited);
}
$workers = (int) config('shedding.workers', 8);
$slots = max(1, (int) ceil($workers * $tier->threshold()));
if (! $this->gauge->enter($slots)) {
return $this->refuse($tier, 'concurrency', $waited);
}
// Released in terminate() so the slot is held while the response is built.
$request->attributes->set('shed.entered', true);
return $next($request);
}
/** Terminable middleware: runs after the response is sent. */
public function terminate(Request $request, Response $response): void
{
if ($request->attributes->get('shed.entered') === true) {
$this->gauge->leave();
}
}
private function refuse(Tier $tier, string $reason, ?float $waited): Response
{
// Count by tier and reason; never log request bodies or customer data.
Log::info('request shed', ['tier' => $tier->value, 'reason' => $reason, 'queue_seconds' => $waited]);
$retryAfter = random_int(1, 3); // jitter so refused clients do not return together
return response('Service Unavailable', 503, [
'Retry-After' => (string) $retryAfter,
'X-Shed-Reason' => $reason,
'Cache-Control' => 'no-store',
]);
}
}<?php
declare(strict_types=1);
return [
// Octane workers (one request at a time each). Keep equal to --workers.
'workers' => (int) env('SHED_WORKERS', 8),
// Maximum age of a request when PHP picks it up, per tier, in seconds.
'queue_budget_seconds' => [
'critical_plus' => 5.0,
'critical' => 2.0,
'sheddable_plus' => 1.0,
'sheddable' => 0.5,
],
];<?php
declare(strict_types=1);
use App\Http\Middleware\ShedLoad;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Middleware;
return Application::configure(basePath: dirname(__DIR__))
->withMiddleware(function (Middleware $middleware): void {
// Alias so routes can say ->middleware('shed:sheddable').
$middleware->alias(['shed' => ShedLoad::class]);
})
->create();<?php
declare(strict_types=1);
use Illuminate\Support\Facades\Route;
// Checkout is what the business exists for: shed last.
Route::post('/checkout', fn () => response()->json(['ok' => true]))
->middleware('shed:critical_plus');
// Order history: normal production traffic.
Route::get('/orders', fn () => response()->json([]))
->middleware('shed:critical');
// Typeahead and recommendations are nice to have: shed first.
Route::get('/search/suggest', fn () => response()->json([]))
->middleware('shed:sheddable');
// Exports run for minutes and can be retried tomorrow.
Route::get('/reports/export', fn () => response()->streamDownload(fn () => print('id'), 'r.csv'))
->middleware('shed:sheddable_plus');Jobهای صف با سن منقضی میشوند. retryUntil() پنجرهٔ retry را کران میدهد و Skip::when() jobی را که بیش از TTL در صف مانده بدون شمردن بهعنوان شکست حذف میکند:
<?php
declare(strict_types=1);
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\Middleware\Skip;
use Illuminate\Queue\SerializesModels;
/**
* A queued job that is only worth running while it is fresh.
* `retryUntil()` bounds the whole retry window; `Skip::when()` deletes the
* job (no failure, no retry) when it waited in the queue longer than its TTL.
*/
final class SendDigest implements ShouldQueue
{
use Dispatchable;
use InteractsWithQueue;
use Queueable;
use SerializesModels;
/** Seconds a digest stays useful after it was dispatched. */
public const TTL_SECONDS = 600;
public int $enqueuedAt;
public function __construct(public int $userId)
{
$this->enqueuedAt = time();
}
/** @return array<int, object> */
public function middleware(): array
{
return [
Skip::when(fn (): bool => time() - $this->enqueuedAt > self::TTL_SECONDS),
];
}
public function retryUntil(): \DateTimeInterface
{
return now()->addSeconds(self::TTL_SECONDS);
}
public function handle(): void
{
// Build and send the digest for $this->userId.
}
}تست واحد برای پارسر و پیشفرض tier (PHPUnit):
<?php
declare(strict_types=1);
namespace Tests\Unit;
use App\Overload\RequestStart;
use App\Overload\Tier;
use PHPUnit\Framework\TestCase;
final class RequestStartTest extends TestCase
{
public function test_it_reads_seconds_milliseconds_and_microseconds(): void
{
$this->assertEqualsWithDelta(1700000000.123, RequestStart::parse('t=1700000000.123'), 0.001);
$this->assertEqualsWithDelta(1700000000.123, RequestStart::parse('1700000000123'), 0.001);
$this->assertEqualsWithDelta(1700000000.123, RequestStart::parse('t=1700000000123000'), 0.001);
$this->assertNull(RequestStart::parse('garbage'));
$this->assertNull(RequestStart::parse(null));
}
public function test_queue_seconds_is_the_age_of_the_request(): void
{
$this->assertEqualsWithDelta(2.0, RequestStart::queueSeconds('t=1700000000.000', 1700000002.0), 0.0001);
}
public function test_unlabelled_traffic_is_critical(): void
{
$this->assertSame(Tier::Critical, Tier::fromHeader(null));
$this->assertSame(Tier::Sheddable, Tier::fromHeader(' SHEDDABLE '));
}
}زاویهٔ Laravel
- Workerهای Octane همان محدودیت concurrency شما هستند. مستندات: "By default, Octane will start an application request worker for each CPU core provided by your machine"، که با
php artisan octane:start --workers=4عوض میشود. هر worker هر بار یک درخواست پردازش میکند، پس--workersسقف سخت in-flight است و بقیه در application server صف میکشند.shedding.workersرا با آن برابر نگه دارید. Octane پیشفرض worker را بعد از ۵۰۰ درخواست restart میکند (--max-requests) وmax_execution_timeسیثانیهای اعمال میکند. - PHP-FPM همین شکل را دارد.
pm.max_childrenسقف in-flight است؛ اتصالهای اضافه در listen backlog منتظر میمانند، همانجا که سنِX-Request-Startبالا میرود. بودجه را طوری بگذارید که درخواستهای ماندهٔ بیش از timeout کلاینت ناخوانده رد شوند. - Alias و پارامتر route.
$middleware->alias(['shed' => ShedLoad::class])درbootstrap/app.phpو->middleware('shed:sheddable')روی routeها قابلیتهای استاندارد middleware در Laravel 13 هستند (withMiddleware، پارامتر middleware روی route). - برای overload از
throttleاستفاده نکنید.throttle:60,1فراخوان را بدون توجه به وضعیت سرور به ۶۰ درخواست در دقیقه محدود میکند و از انتظار صف یا مصرف worker خبر ندارد. - صفها:
retryUntil()وSkip::when()قابلیتهای مستند صفاند. روی workerها--max-timeو--timeoutهم بگذارید و timeout کارگر را کمتر ازretry_afterنگه دارید، وگرنه job کند به worker دوم داده میشود در حالی که اولی هنوز کار میکند (کار تکراری هنگام overload). - Horizon میتواند workerها را بهازای صف autoscale کند (
balance: auto)؛ با shedding ترکیبش کنید و روی انتظار صف scale کنید، نه CPU. - سمت کلاینت:
Http::retry(3, fn (int $attempt, Exception $e) => ...)closureای میپذیرد که خواب را به میلیثانیه حساب میکند (در فصل HTTP client مستند است)؛ همانجاRetry-Afterرا از پاسخRequestExceptionبخوانید و retry را با آرگومانwhen:و یک بودجهٔ مبتنی بر cache کنترل کنید. فراخوانیهای غیر idempotent را علامت بزنید تا هرگز retry نشوند.
حل مسئلههای کلاسیک
| مسئله | راهحل | چطور | مزیت | هزینه یا حد |
|---|---|---|---|---|
| Goodput در ۲x بار فرو میریزد | محدودیت concurrency | in-flight را سقف بگذار؛ بقیه را رد کن | plateau در ظرفیت | limit باید ظرفیت را دنبال کند |
| محدودیت ثابت بعد از deploy کهنه میشود | محدودیت تطبیقی | gradient یا Vegas از روی تأخیر | بدون تنظیم دستی | کران و minRTT تمیز لازم است |
| درخواستهای قدیمی صف را میگیرند | بودجهٔ زمان صف | X-Request-Start، timeout queue، CoDel | بدون کار برای کلاینت رفته | ساعتها باید هماهنگ باشند |
| job دستهای ترافیک تعاملی را گرسنه میکند | Tierها | SHEDDABLE_PLUS برای batch با سهم ۷۰٪ | تعاملی سریع میماند | برچسب صادقانه لازم است |
| یک tenant API را سیل میکند | سهمیهٔ هر مشتری | سهمیهٔ in-flight یا CPU بهازای کلید، 429 | بقیه آسیب نمیبینند | state بهازای کلید |
| retry storm بعد از brownout | retry budget و adaptive throttling | ۱۰٪ retry، ۳ تلاش، ردّ محلی در کلاینت | تقویت کراندار | کتابخانهٔ کلاینتها باید همکاری کند |
| وابستگی کند همهٔ workerها را گیر میاندازد | limit in-flight بهعلاوهٔ deadline | limit بهازای وابستگی؛ رد با deadline | routeهای دیگر زنده میمانند | Bulkheads را ببینید |
| health check shed میشود، ناوگان کوچک میشود | اولویت دادن به ping | /healthz را از shedding معاف کن | ناوگان در چرخش میماند | سبک نگهش دارید |
| Shedding بار را از autoscaler پنهان میکند | scale روی نرخ shed | شمارندهٔ shed را صادر کن؛ متریک خارجی HPA | ظرفیت تقاضا را دنبال میکند | تأخیر pipeline متریک |
| jobهای کهنه ساعتها دیر پردازش میشوند | TTL برای job | retryUntil()، Skip::when()، TTL در RabbitMQ | کار تازه اول | کار منقضی به DLQ نیاز دارد |
| کل ناوگان اشباع، retryها چند برابر میشوند | نشانهٔ «retry نکن» | هدر روی 503 وقتی histogram retry گسترده نشان میدهد | جلوی انفجار را میگیرد | انتشار شمارندهٔ retry لازم است |
| جهش حافظه podها را میکُشد | overload manager و eviction | Envoy stop_accepting_requests؛ evictionSoft کوبلت | degradation کنترلشده | evict میکند بهجای رد کردن |
retry storm بعد از brownout
کندی ۳۰ثانیهای یک وابستگی 503 میسازد؛ هر کلاینت سه بار retry میکند؛ retryها همزمان با بهبود وابستگی میرسند و دوباره آن را میاندازند. لایهلایه حل کنید: سرور 503 با Retry-After و jitter میدهد، کلاینت از throttle.Transport استفاده میکند (سه تلاش، بودجهٔ ۱۰٪، ردّ محلی) و فقط لایهٔ دقیقاً بالاتر retry میکند. با شبیهساز در ۳x و StaticLimit برابر ۲۰۰ تست کنید (آزمایشگاه).
batch در برابر تعاملی
export شبانه با checkout یک سرویس را شریک است. exportها را SHEDDABLE_PLUS (۷۰٪ limit) و checkout را CRITICAL_PLUS برچسب بزنید. در Laravel Route::get('/reports/export', ...)->middleware('shed:sheddable_plus')؛ در Go X-Priority: SHEDDABLE_PLUS از کلاینت batch یا تابع Classify که route را میخواند. گوگل جلوتر میرود: کلاینتهای batch از یک "batch proxy" رد میشوند که "acts like a fuse".
-- Job table with an explicit expiry, so stale work is never claimed (PostgreSQL).
CREATE TABLE jobs (
id bigserial PRIMARY KEY,
tier smallint NOT NULL, -- 0 critical_plus .. 3 sheddable
payload jsonb NOT NULL,
enqueued_at timestamptz NOT NULL DEFAULT now(),
expires_at timestamptz NOT NULL
);
CREATE INDEX jobs_claim ON jobs (tier, enqueued_at);
-- Claim the best fresh job; expired rows are skipped, not worked.
SELECT id, payload
FROM jobs
WHERE expires_at > now()
ORDER BY tier, enqueued_at
FOR UPDATE SKIP LOCKED
LIMIT 1;
-- Sweep expired work out of the way (dead-letter first if you need an audit).
DELETE FROM jobs WHERE expires_at <= now();
-- Last-line database shedding: fail fast instead of queueing forever.
ALTER ROLE web SET statement_timeout = '3s';
ALTER ROLE web SET lock_timeout = '1s';
ALTER ROLE web CONNECTION LIMIT 50;کوئری claim روی expires_at در WHERE فیلتر میکند (شرط index نمیتواند از now() استفاده کند چون immutable نیست) و DELETE دورهای مانع انباشت ردیفهای منقضی میشود. FOR UPDATE SKIP LOCKED اصطلاح claim صف است که در Locks & Concurrency Control آمده.
انتخاب
| وضعیت | توصیه | تکنیک اضافه | دلیل |
|---|---|---|---|
| سرویس HTTP جدید، یک تیم | limit ثابت = workers x 2، بودجهٔ زمان صف | load test تا ۴x | سادهترین چیزی که plateau میدهد |
| ناوگان autoscale، ظرفیت متغیر | limit تطبیقی (gradient) برای هر نمونه | کران min و max | عددهای ثابت کهنه میشوند |
| ترکیب تعاملی و batch | چهار tier، آستانههای ۱۰۰/۹۰/۷۰/۵۰ | tier را در هدر منتشر کنید | batch اول میبازد |
| API عمومی چندمستاجری | سهمیهٔ هر مشتری بهعلاوهٔ limit مشترک | 429 با Retry-After | جداسازی همسایهٔ پرسروصدا |
| فقط پشت NGINX یا HAProxy | limit_conn، timeout queue، maxconn | اول dry-run | بدون تغییر کد |
| mesh با Envoy یا Istio | فیلتر adaptive concurrency بهعلاوهٔ overload manager | predicate بازگشتی previous_hosts | shedding بدون کد برنامه |
| Laravel روی Octane یا FPM | بودجهٔ X-Request-Start بهعلاوهٔ gauge کارگر | tier بهازای route | با یکدرخواستبهازایهرworker جور است |
| consumerهای صف، داده کهنه بیارزش | TTL و drop-head | dead-letter برای بازبینی | تازگی مهمتر از کامل بودن |
| consumerهای صف، از دست رفتن ناپذیرفتنی | reject-publish و کند کردن تولیدکننده | Backpressure | بدون از دست رفتن |
| فشار حافظهٔ گره کوبرنتیز | requests و PriorityClass را بگذارید | evictionSoft با grace | قربانیهای کنترلشده |
| کلاینتهایی که کنترل دارید | adaptive throttling و retry budget | رعایت Retry-After | جلوی تقویت را میگیرد |
| مسیرهای حیاتی ایمنی | هرگز shed نکنید، ظرفیت اضافه و bulkhead | CRITICAL_PLUS | Shedding برای چیزهایی است که میتوانند شکست بخورند |
در معماری: از یک پردازه تا سیستم توزیعشده
مونولیت (یک پردازه، یک پایگاهداده)
یک برنامهٔ Laravel روی Octane یا PHP-FPM با ۸ worker و یک PostgreSQL. limit in-flight همان تعداد worker است و صف همان accept backlog وبسرور. سادهترین تنظیم درست: limit_conn در NGINX برای IPهای سوءاستفادهگر، middleware shed با بودجهٔ صف، checkout روی critical_plus، پیشنهادهای جستوجو روی sheddable و statement_timeout روی پایگاهداده. health checkها معافاند.
مونولیت ماژولار / چند پایگاهداده
ماژولها workerها را شریکاند ولی اهمیت یکسان ندارند. tier را روی routeهای ماژول بگذارید، به هر ماژول pool پایگاهدادهٔ خودش را بدهید و به ماژولهای batch صف و pool worker جدا بدهید. gauge مشترک in-flight شلوغترین ماژول را نشان میدهد؛ سهم هر ماژول (اعمال Percentage در اصطلاح نتفلیکس) جلوی برداشتن همهٔ workerها توسط ماژول گزارشگیری را میگیرد.
میکروسرویسها
جریان درخواست با criticality منتشرشده از ابتدا تا انتها:
Hop سرویس دریافت انجام
1 1 edge (Envoy) X-Priority از کلاینت اعتبارسنجی، فقط میتواند پایین بیاورد؛ X-Request-Start را مهر میزند
2 2 gateway tier، شناسهٔ مشتری سهمیهٔ هر مشتری -> 429؛ tier را رد میکند
3 3 orders tier=CRITICAL در ۹۰٪ limit تطبیقی خود پذیرش میکند؛ payments را با همان tier صدا میزند
4 4 payments tier=CRITICAL پذیرش؛ اگر بالای limit باشد 503 + Retry-After
5 5 orders 503 از payments یک بار retry میکند (بودجه ok) سپس صفحهٔ سفارش degraded برمیگرداندهر سرویس limit تطبیقی خودش را دارد؛ retry فقط یک لایه بالاتر از سرویس ردکننده رخ میدهد. قاعدهٔ گوگل: "requests should only be retried at the layer immediately above the layer that is rejecting them". Service Communication و Cascading Failures را ببینید. service mesh میتواند بخشی از این را بدون کد انجام دهد (Service Mesh & the Sidecar Pattern).
دادههای توزیعشده (replica، cache، store شاردشده)
Shedding روی لایهٔ stateful دقت بیشتری میخواهد. shard داغ overload شده در حالی که بقیه بیکارند limit بهازای shard میخواهد، نه سراسری (Sharding at System Level). replicaهای خواندنی فقط وقتی خواندنهای shed شده را جذب میکنند که lag کراندار باشد (Replication). پاک شدن cache بار پایگاهداده را چند برابر میکند: stampede guard بگذارید (Caching) و خواندنهای SHEDDABLE را در proxy پایگاهداده shed کنید. Connection pooler (PgBouncer) برای PostgreSQL همان admission control است: pool پر یک صف است و query_wait_timeout یک queue timeout (Connection Pooling). بین منطقهها: پیش از shedding ترافیک را جابهجا کنید (Load Balancing)، همانطور که گوگل میگوید طوری متعادل کنید که "no datacenter receives more traffic than it has the capacity to process".
مسیر مقیاس
| بار | طراحی |
|---|---|
| 1x (صدها req/s) | تعداد worker بهعنوان limit، statement_timeout، health check معاف |
| 10x | بودجهٔ زمان صف، دو tier (critical و sheddable)، limit_conn بهازای IP در NGINX |
| 100x | limit تطبیقی در هر نمونه، چهار tier، سهمیهٔ هر مشتری، autoscale بر پایهٔ نرخ shed، کتابخانههای throttle کلاینت |
| 1000x | انتشار tier بین سرویسها، overload manager در ingress، limit بهازای shard، جداسازی cell-based، game dayهای منظم overload |
آزمایشگاه
شبیهساز قطعی است و کمتر از یک ثانیه اجرا میشود (این خروجی واقعاً با go run ./cmd/loadsim در ماژول snippet تولید شده است).
cd docs/snippets/system-design/load-shedding/go
go test -race ./...
go run ./cmd/loadsimcapacity = 100 req/s (10 servers x 100 ms), client timeout 1 s
policy 0.5x 1.0x 2.0x 4.0x (goodput, requests/s)
unbounded 50.0 100.0 3.2 2.2
static-limit 50.0 100.0 100.2 100.2
queue-budget 50.0 100.0 100.5 100.5
tiered-static 50.0 91.7 99.6 100.1
tiered-adaptive 50.0 100.0 100.2 100.2
share of each tier answered in time at 4x offered load
policy CRITICAL_PLUS CRITICAL SHEDDABLE_PLUS SHEDDABLE
unbounded 0% 0% 1% 1%
static-limit 25% 25% 26% 25%
queue-budget 24% 25% 26% 25%
tiered-static 100% 85% 23% 0%
tiered-adaptive 100% 85% 23% 0%
a limit of 200 is wrong for 10 servers: 60-second average goodput at 3x offered load
static-limit goodput 2.3 req/s
tiered-adaptive goodput 100.1 req/sچطور بخوانیمش، در پنج آزمایش شمارهدار:
- سقوط.
unboundedدر ۲x مقدار 3.2 req/s میدهد در برابر ظرفیت ۱۰۰: سرور مشغول است و بیفایده.Modeرا بهstatic-limitبدهید، همین بار 100.2 میدهد. - Tierها. در ۴x هر سیاستِ کور به tier حدود ۲۵٪ هر tier را سرویس میدهد.
tiered-*به CRITICAL_PLUS صددرصد، به CRITICAL ۸۵٪ و به SHEDDABLE صفر میدهد. CRITICAL زیر ۱۰۰٪ است چون CRITICAL_PLUS بهعلاوهٔ CRITICAL در ۴x برابر ۸۰ req/s است، نزدیک ظرفیت ۱۰۰ req/s، و CRITICAL در ۹۰٪ limit میایستد. - False positive.
tiered-staticدر 1.0x عدد 91.7 را نشان میدهد نه 100: tierهای پایینتر در ۵۰ تا ۹۰٪ limit رد میشوند حتی وقتی سیستم میتوانست حملشان کند. این بهای tierهاست؛ limit تطبیقی آن را جبران میکند چون بالای تعداد worker فضای حرکت دارد. - Limit ثابت اشتباه. با limit برابر 200 روی ۱۰ سرور، صف تا ۱۹۰ درخواست جا دارد، انتظار حدود ۱.۹ ثانیه، بالای timeout یکثانیهای: 2.3 req/s. limit تطبیقی از همان ۲۰۰ شروع میکند و پایین میآید: 100.1 req/s.
- عددها را عوض کنید.
Budgetرا درcmd/loadsim/main.goبه ۱.۵ ثانیه بدهید و ببینیدqueue-budgetدیگر از کلاینت با timeout یک ثانیه محافظت نمیکند؛Serviceرا ۲۰۰ms و limit را ۲۰ بگذارید و ببینید ظرفیت نصف میشود.
بخشهای broker و Laravel آزمایشگاه بهصورت دستور و خروجی موردانتظار نوشته شدهاند (خروجی موردانتظار؛ اجرا نشده):
# RabbitMQ: bounded queue with reject-publish and a 60 s TTL (expected, not run)
rabbitmqctl set_policy shed "^notify\." \
'{"max-length":1000,"overflow":"reject-publish-dlx","message-ttl":60000,"dead-letter-exchange":"dlx"}' \
--apply-to queues
# expected: Setting policy "shed" for pattern "^notify\." to "{...}" with priority "0" for vhost "/" ...
# when the 1001st message arrives, a publisher with confirms gets basic.nack
# Laravel: worker pinned at 2, stale request is shed (expected, not run)
php artisan octane:start --workers=2
curl -i -H 'X-Request-Start: t=1700000000.000' -H 'X-Priority: sheddable' http://127.0.0.1:8000/search/suggest
# expected: HTTP/1.1 503 Service Unavailable
# Retry-After: 2
# X-Shed-Reason: queue_budgetبدفهمیهای رایج
| باور | واقعیت |
|---|---|
| Shedding شکست است | شکست انتخابشدهٔ کنترلشدهٔ کمارزشترین کار است؛ جایگزینش شکست کنترلنشدهٔ همهٔ کارهاست |
| throughput بالا یعنی سلامت | throughput کار مربوط به کلاینتهای timeoutشده را هم دارد؛ فقط goodput میشمارد |
| سرور overload باید پذیرش را متوقف کند | باید آنچه میتواند تمام کند بپذیرد و بقیه را رد کند (کتاب SRE گوگل) |
| CPU روی ۸۰٪ سیگنال overload است | انتظار صف یا شمار in-flight به علت نزدیکتر است؛ CPU نماینده است |
| صف بلندتر امنتر است | صف بلندتر بار را به تأخیر و کار هدررفته تبدیل میکند |
| 429 کد همهٔ shedding است | 429 برای نرخ یک فراخوان است؛ overload کل سرور 503 است |
| priority queue همان load shedding است | کار منتظر را مرتب میکند ولی هیچچیز را رد نمیکند؛ limit پذیرش لازم دارد |
| Autoscaling نیاز را برمیدارد | scaling کندتر از overload است و shedding میتواند بار را از scalerهای مبتنی بر CPU پنهان کند |
| Retry زیر overload سیستم را قابلاعتماد میکند | بدون بودجه بار را تا سه برابر میکند |
| load test تا ترافیک اوج کافی است | خیلی بالاتر از نقطهٔ شکست تست کنید و دنبال plateau باشید |
| برچسب tier کلاینت قابلاعتماد است | کلاینت فقط میتواند tier را پایین بیاورد؛ سقف را route یا gateway تعیین میکند |
| median نشان میدهد shedding کار میکند | ردهای سریع median را پایین میکشند؛ تأخیر پذیرفتهشدهها را جدا بسنجید |
چکیده (Cheat sheet)
| موضوع | چه چیزی را به یاد بسپارید |
|---|---|
| هدف | وقتی بار ورودی بالا میرود goodput روی ظرفیت صاف بماند |
| واحد limit | Concurrency، نه RPS: in-flight = RPS x latency |
| سیگنال زودرس | انتظار صف (سن هنگام برداشتن) و in-flight در برابر limit |
| الگوریتمها | AIMD (loss)، Vegas (تأخیر)، gradient (روند تأخیر)؛ همه کران min و max میخواهند |
| صف | کراندار، با TTL؛ drop-head برای تازگی، reject-publish برای بدوناتلاف |
| Tierها | CRITICAL_PLUS، CRITICAL، SHEDDABLE_PLUS، SHEDDABLE در ۱۰۰/۹۰/۷۰/۵۰٪ limit |
| Status | 503 + Retry-After برای overload سرور؛ 429 برای فراخوان بالای سهمیه |
| مسیر ردّ | ارزانتر از کار، بدون log بدنه، بدون I/O |
| کلاینت | adaptive throttling با K=2، ۳ تلاش، بودجهٔ retry ۱۰٪، رعایت Retry-After |
| لایهها | لبه برای انبوه، سرویس برای حقیقت، صف برای تازگی، پایگاهداده آخرین خط |
| Autoscaling | روی نرخ shed یا انتظار صف scale کنید، نه CPUای که shedding پایین نگه میدارد |
| متریکها | شمارندهٔ shed به تفکیک tier و reason، goodput، limit، تأخیر فقط پذیرفتهشدهها |
| تست | ramp تا ۴x با ترکیب اولویت؛ قبولی یعنی plateau، نه پرتگاه |
| محصولات | NGINX limit_conn، HAProxy timeout queue، Envoy adaptive concurrency و overload manager، RabbitMQ overflow، Octane --workers |
خودآزمایی: پرسش و پاسخ
- حیاتی تقریباً در هر مصاحبه پرسیده میشود
- مهم پرتکرار؛ در سطح senior انتظار میرود
- تکمیلی عمق بیشتر؛ تمایز ایجاد میکند
۱ — فرق throughput و goodput چیست و چرا throughput میتواند بیشینه و goodput صفر باشد؟ حیاتی
پاسخ
پاسخ: Throughput همهٔ درخواستهای پردازششده را میشمارد؛ goodput فقط آنهایی را که موفق و در deadline کلاینت تمام شدهاند. زیر overload سرور روی درخواستهایی کار میکند که کلاینتشان timeout کرده، پس throughput بالا میماند و goodput فرو میریزد.
۲ — چرا limit از نوع concurrency از «درخواست در ثانیه» بهتر است؟ حیاتی
پاسخ
پاسخ: RPS نمیگوید هر درخواست چقدر worker را نگه میدارد و ظرفیت با تأخیر و اندازهٔ ناوگان عوض میشود. قانون Little (in-flight = RPS x latency) نشان میدهد concurrency خودبهخود ظرفیت واقعی را دنبال میکند؛ limit بر پایهٔ RPS کهنه میشود.
۳ — توضیح دهید Vegas و gradient controller چطور تصمیم به پایین آوردن limit میگیرند. تکمیلی
پاسخ
پاسخ: Vegas صف را با limit x (1 - minRTT/sampleRTT) برآورد میکند و وقتی از beta بیشتر شد limit را کم میکند. gradient controller در Envoy مقدار gradient = (minRTT + B) / sampleRTT را حساب و limit' = gradient x limit + sqrt(limit) را اعمال میکند؛ بالا رفتن تأخیر gradient را زیر ۱ میبرد و limit را کوچک میکند.
۴ — سرور کی 503 و کی 429 بدهد؟ حیاتی
پاسخ
پاسخ: 503 برای overload سمت سرور که همه را درگیر میکند (محدودیت concurrency، بودجهٔ صف، overload manager)؛ 429 وقتی یک فراخوان از نرخ یا سهمیهٔ خودش گذشته. هر دو باید Retry-After داشته باشند.
۵ — چهار مقدار criticality گوگل چیست و کدام اول shed میشود؟ تکمیلی
پاسخ
پاسخ: CRITICAL_PLUS، CRITICAL، SHEDDABLE_PLUS، SHEDDABLE. با بالا رفتن utilization، criticalityهای پایینتر زودتر رد میشوند، پس SHEDDABLE اول و CRITICAL_PLUS آخر میرود.
۶ — چرا بودجهٔ زمان صف به timestamp از proxy نیاز دارد؟ مهم
پاسخ
پاسخ: فقط درِ ورودی میداند درخواست واقعاً کی رسیده؛ داخل برنامه درخواست از صف بیرون آمده. X-Request-Start از proxy به برنامه اجازه میدهد انتظار را حساب و درخواستهای رهاشده را دور بریزد.
۷ — retry budget چه میکند و با چه عددهایی؟ مهم
پاسخ
پاسخ: تقویت retry را محدود میکند: حداکثر سه تلاش برای هر درخواست و retry فقط تا وقتی که retryها زیر حدود ۱۰٪ درخواستها باشند، که بدترین رشد را به حدود 1.1x میرساند بهجای 3x.
۸ — drop-head و reject-publish را در RabbitMQ مقایسه کنید. تکمیلی
پاسخ
پاسخ: Drop-head (پیشفرض) وقتی پر است قدیمیترین پیام را دور میریزد، صف را تازه نگه میدارد و از تولیدکننده پنهان میکند. Reject-publish پیام جدید را رد میکند و با publisher confirm basic.nack میفرستد که به تولیدکننده فشار برمیگرداند.
۹ — load shedding چطور میتواند autoscaling مبتنی بر CPU را بشکند؟ مهم
پاسخ
پاسخ: اگر shedding CPU را زیر هدف scaling نگه دارد، autoscaler هرگز تقاضای مازاد را نمیبیند. بهجایش روی نرخ shed، انتظار صف یا concurrency ورودی scale کنید.
۱۰ — چرا متریکهای تأخیر باید درخواستهای shed را کنار بگذارند؟ مهم
پاسخ
پاسخ: ردها بسیار سریعاند؛ اگر ۶۰٪ ترافیک shed شود median عالی به نظر میرسد در حالی که پذیرفتهشدهها ممکن است کند باشند. تأخیر پذیرفتهشدهها را جدا ثبت کنید و shed را به تفکیک tier و reason بشمارید.
۱۱ — آزمون overload چه شکلی دارد و چه نتیجهای قبول است؟ مهم
پاسخ
پاسخ: بار را خیلی بیشتر از ظرفیت با ترکیب واقعی اولویت بالا ببرید، ترجیحاً هم با ناوگان ثابت و هم با برداشتن نمونهها. قبول یعنی plateau در حدود ظرفیت و موفقیت تقریباً کامل tierهای بالا؛ پرتگاه به نزدیک صفر یعنی شکست.
واژهنامه (Glossary)
| واژه | معنی |
|---|---|
| Load shedding (حذف عمدی بار) | رد کردن عمدی بخشی از کار برای حفاظت از کار پذیرفتهشده |
| Goodput | نرخ پاسخهای موفق و بهموقع |
| Throughput | نرخ همهٔ درخواستهای پردازششده، مفید یا نه |
| Overload detection (تشخیص overload) | اندازهگیری سیگنالهایی که نشان میدهند تقاضا از ظرفیت بیشتر است |
| Queue wait time | مدتی که درخواست پیش از شروع کار منتظر ماند (sojourn time) |
| In-flight requests | درخواستهای پذیرفتهشده و هنوز تمامنشده |
| Concurrency limit | بیشینهٔ درخواستهای in-flight |
| Adaptive concurrency limit | limitی که از نمونههای تأخیر یا loss دوباره محاسبه میشود |
| Little's Law (قانون Little) | in-flight = arrival rate x time in system |
| AIMD | افزایش جمعی، کاهش ضربی؛ قاعدهٔ مبتنی بر loss به سبک TCP |
| Vegas | برآورد limit مبتنی بر تأخیر از minRTT و RTT نمونه |
| Gradient | قاعدهٔ limit از نسبت تأخیر بدونبار به تأخیر نمونه (Envoy، Gradient2 نتفلیکس) |
| minRTT | کمترین تأخیر دیدهشده، مبنای بدون صف |
| CoDel | Controlled Delay: دور ریختن بر پایهٔ تأخیر پایدار صف بالای هدف (RFC 8289) |
| Queue timeout | بیشینهٔ زمانی که درخواست میتواند در صف بماند (timeout queue در HAProxy) |
| Admission control (کنترل پذیرش) | تصمیم اینکه درخواست وارد شود یا نه |
| Criticality | برچسب رتبهٔ اهمیت هر درخواست که تعیین میکند چه کسی shed شود |
| Priority tier (سطح اولویت) | یکی از کلاسهای criticality |
| CRITICAL_PLUS | بالاترین criticality؛ شکستش اثر جدی روی کاربر دارد |
| SHEDDABLE | پایینترین criticality؛ عدمدسترسی جزئی قابلانتظار است |
| Per-customer quota (سهمیهٔ هر مشتری) | سقف منبع برای یک فراخوان؛ فقط همان shed میشود |
| Cost-based shedding | پذیرش بر پایهٔ هزینهٔ برآوردی منبع، نه تعداد درخواست |
| 503 Service Unavailable | status مربوط به overload موقت سرور (RFC 9110) |
| 429 Too Many Requests | status مربوط به فراخوان بالای نرخش (RFC 6585) |
| Retry-After | هدر با ثانیه یا تاریخ انتظار پیش از retry |
| Partial results (نتیجهٔ جزئی) | پاسخ ارزانتر و ناقص بهجای خطا |
| Backoff | صبر بیشتر بین retryهای پیاپی |
| Retry budget (بودجهٔ retry) | سقف retry نسبت به درخواستها (حدود ۱۰٪) |
| Adaptive throttling | کلاینت وقتی accepts از requests عقب بماند محلی رد میکند |
| Rate limiting (محدودیت نرخ) | اعمال نرخ توافقشده بهازای هویت |
| Backpressure (فشار برگشتی) | انتقال سرعت گیرنده به فرستنده |
| Message TTL | بیشینهٔ سن پیام در صف |
| Drop-head | هنگام سرریز قدیمیترین پیام را دور بریز |
| Reject-publish | هنگام سرریز پیام جدید را رد کن |
| Dead letter | جایی که پیامهای دورریخته یا منقضی برای بازبینی میروند |
| Autoscaling | افزودن یا کم کردن نمونهها بر پایهٔ متریک |
| Envoy adaptive concurrency | فیلتر HTTP در Envoy با gradient controller |
| Overload manager | زیرسیستم Envoy که فشار منبع را به اقدام نگاشت میکند |
limit_conn | دستور NGINX برای محدودیت اتصال همزمان بهازای کلید |
| Resource pressure (فشار منبع) | کمبود حافظه، دیسک یا PID گره در Kubernetes |
| Eviction | خاتمه دادن کوبلت به podها برای بازپسگیری منابع |
X-Request-Start | هدری که proxy میافزاید و زمان رسیدن درخواست را دارد |
| Shed count | شمارندهٔ درخواستهای ردشده به تفکیک tier و reason |
| Goodput metric | پاسخهای موفق در SLO در ثانیه |
منابع (References)
- Google SRE Book, ch. 21 Handling Overload (criticality, adaptive throttling, retry budgets): https://sre.google/sre-book/handling-overload/
- Google SRE Book, ch. 22 Addressing Cascading Failures: https://sre.google/sre-book/addressing-cascading-failures/
- Amazon Builders' Library, Using load shedding to avoid overload: https://aws.amazon.com/builders-library/using-load-shedding-to-avoid-overload/
- Amazon Builders' Library, Timeouts, retries and backoff with jitter: https://aws.amazon.com/builders-library/timeouts-retries-and-backoff-with-jitter/
- Netflix concurrency-limits README (Vegas, Gradient2, AIMD, enforcement strategies): https://raw.githubusercontent.com/Netflix/concurrency-limits/master/README.md
- Envoy adaptive concurrency filter: https://www.envoyproxy.io/docs/envoy/latest/configuration/http/http_filters/adaptive_concurrency_filter
- Envoy adaptive concurrency API reference: https://www.envoyproxy.io/docs/envoy/latest/api-v3/extensions/filters/http/adaptive_concurrency/v3/adaptive_concurrency.proto
- Envoy overload manager: https://www.envoyproxy.io/docs/envoy/latest/configuration/operations/overload_manager/overload_manager
- Envoy circuit breaking: https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/upstream/circuit_breaking
- RFC 8289 CoDel (Nichols, Jacobson et al.): https://www.rfc-editor.org/rfc/rfc8289.html
- RFC 9110 HTTP Semantics (503, Retry-After): https://www.rfc-editor.org/rfc/rfc9110.html
- RFC 6585 Additional HTTP Status Codes (429): https://www.rfc-editor.org/rfc/rfc6585.html
- NGINX
ngx_http_limit_conn_module: https://nginx.org/en/docs/http/ngx_http_limit_conn_module.html - NGINX
ngx_http_limit_req_module: https://nginx.org/en/docs/http/ngx_http_limit_req_module.html - NGINX core module variables (
$msec): https://nginx.org/en/docs/http/ngx_http_core_module.html - HAProxy configuration manual (
timeout queue,maxconn): https://www.haproxy.com/documentation/haproxy-configuration-manual/latest/ - Heroku HTTP routing (
X-Request-Start): https://devcenter.heroku.com/articles/http-routing - Kubernetes node-pressure eviction: https://kubernetes.io/docs/concepts/scheduling-eviction/node-pressure-eviction/
- RabbitMQ queue length limits and overflow: https://www.rabbitmq.com/docs/maxlength
- RabbitMQ time-to-live: https://www.rabbitmq.com/docs/ttl
- Laravel 13 middleware: https://laravel.com/docs/13.x/middleware
- Laravel 13 Octane: https://laravel.com/docs/13.x/octane
- Laravel 13 queues: https://laravel.com/docs/13.x/queues
- Laravel 13 HTTP client (retries): https://laravel.com/docs/13.x/http-client