Skip to content

Error & Exception Handling and Fault Tolerance in Design ​

"Values can be programmed, and since errors are values, errors can be programmed." — Rob Pike، Errors are values، The Go Blog، ۱۲ ژانویهٔ ۲۰۱۵

خلاصه (Summary): هر خرابی یکی از سه چیز است: باگ، نتیجهٔ مورد انتظار کسب‌وکار، یا وابستگی‌ای که از کار افتاده. طراحی خوب برای هر کدام type جدا دارد، خطا را فقط یک بار در مرز سیستم مدیریت می‌کند، و هر فراخوانی راه دور را در timeout، retry، circuit breaker و fallback می‌پیچد. تمرکز (Focus): دسته‌بندی خطا، error value در برابر exception در برابر Result<T, E>، خطای sentinel و typed و wrapped، اصل «یک بار مدیریت کن» و ترجمهٔ خطا در مرز لایه‌ها، ضدالگوها، اعتبارسنجی در برابر invariant در برابر assertion، fail-fast، panic و خطای fatal، پاک‌سازی منابع، و الگوهای پایداری (timeout، retry با jitter، idempotency، circuit breaker، bulkhead، fallback، load shedding)، پاسخ RFC 9457، مشاهده‌پذیری و تست، در Go و Laravel. هدف یادگیری (Learning goal): به هر مسیر خرابی نگاه کنید و بگویید این چه نوع خطایی است، کدام لایه آن را می‌سازد و ترجمه و مدیریت می‌کند، retry امن است یا نه، و کاربر چه می‌بیند؛ بعد همین را در Go و Laravel با تست‌هایی که خرابی را عمداً تزریق می‌کنند بسازید.

این فصل مرجع سطح طراحی برای خرابی است. دو چیز را پوشش می‌دهد: اینکه خطا را در کد چطور مدل کنیم (typeها، سلسله‌مراتب، جای مدیریت) و اینکه از خرابی اجزای دیگر چطور جان سالم به در ببریم (الگوهای پایداری). چند صفحهٔ همسایه هر کدام یکی از این الگوها را عمیق‌تر باز می‌کنند و این صفحه به‌جای تکرار، به آن‌ها لینک می‌دهد: Cascading Failures، Timeouts, Retries & Jitter، Circuit Breaker، Bulkheads & Graceful Degradation، Load Shedding، API Idempotency، Dead-Letter Queue، Saga Pattern و Transactional Outbox. فصل‌های هم‌گروه در طراحی هم Distribution of Components (چرا فراخوانی راه دور جور دیگری خراب می‌شود)، Designing for Concurrency و Data Persistence in Design هستند.

نقشهٔ صفحه ​

اگر دنبال این هستیدبروید به
کل موضوع در چند جدولهمه‌چیز در یک دقیقه
چرا طراحی خطا مهم است و چه چیزی را معامله می‌کندچرا وجود دارد
بلاگ Go، Throwable در PHP، Rust، checked exception، Nygard، کتاب SRE، RFC 9457از کجا آمده
باگ در برابر خطای دامنه در برابر خرابی زیرساختدسته‌بندی خطا
error value در برابر exception در برابر Result<T, E>سه مدل خطا
sentinel، typed، wrapped، joined، کد خطاطراحی typeهای خطا
یک بار مدیریت کن، log-and-rethrow، ترجمه بین لایه‌هامدیریت یک‌باره در مرز
گرفتن Throwable، بلعیدن خطا، exception برای کنترل جریانضدالگوها
اعتبارسنجی، invariant، assertion، fail-fast، برنامه‌نویسی تدافعیاعتبارسنجی، Fail-fast
panic/recover، خطای fatal در PHP، defer/finallyPanic، پاک‌سازی
timeout، retry، idempotency، circuit breaker، bulkhead، fallbackالگوهای پایداری
دو ژنرال، at-least-once، DLQ، saga، outboxخرابی جزئی، تراکنش‌ها
RFC 9457، logging، Sentry، error budget، تستخطای API، مشاهده‌پذیری، تست
کد قبل و بعدGo، Laravel
سرویس سفارش در برابر API پرداخت ناپایدار، با تزریق خرابیآزمایشگاه

همه‌چیز در یک دقیقه ​

سه نوع خرابی. هر سطر در فهرست مفهوم‌ها باز می‌شود.

نوعبه زبان سادهمثال کوچکپاسخ درست
باگ برنامه‌نویس (Programmer bug)کد غلط استنوشتن در map نال، TypeError، شکستن invariantfail-fast، 500، گزارش با stack trace، اصلاح کد
نتیجهٔ مورد انتظار دامنه (Domain outcome)دنیا گفت «نه»کارت رد شد، سفارش پیدا نشد، قبلاً ارسال شدهخطای typed یا business exception، 4xx، بدون هشدار
خرابی گذرای زیرساخت (Transient)وابستگی سکسکه کردtimeout، 503، 429، deadlock، قطع اتصالtimeout، retry با backoff و jitter، circuit breaker، fallback
خرابی دائمی زیرساخت (Permanent)وابستگی خودبه‌خود درست نمی‌شودcredential غلط، 400 از شریک، دیسک پرشکست، خبر کردن انسان، dead letter

الگوهای پایداری.

الگودر یک خطGo (این صفحه)Laravel 13
Timeoutهیچ‌وقت تا ابد منتظر نمانcontext.WithTimeout، http.Client.TimeoutHttp::timeout()، connectTimeout()، #[Timeout] روی job
Retry با backoff و jitterبعداً، در زمانی تصادفی، دوباره امتحان کنresilience.DoHttp::retry()، helper retry()، #[Backoff]، retryUntil()
Idempotencyدو بار انجام دادن برابر یک بار استهدر Idempotency-Key و حذف تکرارmiddleware EnsureIdempotency، Cache::lock
Circuit breakerوابستگی از کار افتاده را صدا نزنresilience.BreakerCircuitBreaker روی Cache، ThrottlesExceptions برای job
Bulkheadسهم هر وابستگی را محدود کنresilience.Bulkhead (semaphore)queue و worker جدا، WithoutOverlapping، pool جدای FPM
Fallback / graceful degradationجواب ضعیف‌تر به‌جای هیچ جوابثبت پرداخت برای بعدrescue()، Cache::flexible، job صف‌شده
Load sheddingبخشی از کار را رد کن تا بقیه تمام شود503 و Retry-After زودهنگامrate limiting، 503
Dead letterآنچه مدام شکست می‌خورد را کنار بگذارtopic یا جدول DLQfailed_jobs، failed()، queue:retry

سازوکارهای زبان.

نیازGoPHP 8.4 / Laravel 13Rust (برای مقایسه)
گزارش خطای مورد انتظارreturn ..., errthrow new BusinessExceptionResult<T, E>
تشخیص نوع خطاerrors.Is، errors.As، errors.AsType (Go 1.26)catch (Type $e)، instanceofmatch روی enum خطا
افزودن زمینهfmt.Errorf("...: %w", err)new X(msg, previous: $e)? با From، map_err
چند خطا با همerrors.Joinکیسهٔ errors در ValidationExceptionVec از خطاها
باگ غیرقابل‌بازیابیpanicسلسله‌مراتب Error (TypeError و...)panic!
پاک‌سازی در همهٔ مسیرهاdeferfinallyDrop (RAII)

چرا وجود دارد ​

کدی که فقط مسیر خوش را مدیریت می‌کند نمونهٔ اولیه است، نه محصول. در production در یک ساعت ممکن است هم سرویس پرداخت timeout بدهد، هم دیتابیس deadlock کند، هم کاربری تعداد منفی بفرستد، هم برنامه‌نویسی یک null check را جا انداخته باشد. اگر کد با هر چهار تا یک‌جور رفتار کند (همه را بگیر، log کن، 500 برگردان)، چهار نتیجهٔ بد می‌گیرید: کاربری که فقط اشتباه تایپی داشت «Internal Server Error» می‌بیند، قطعی سرویس لاگ‌ها را پر می‌کند و برای هر درخواست کسی را بیدار می‌کند، باگ واقعی لای هزاران خطای عادی گم می‌شود، و timeout را سه لایه هم‌زمان retry می‌کنند تا سرویس پرداخت کاملاً بخوابد. طراحی خطا یعنی این‌ها را از هم جدا کنیم و برای هر کدام مسیر درست بگذاریم.

مدیریت سرسریمدیریت طراحی‌شده
یک catch (Throwable) در هر controllerخطاهای typed، یک handler در مرز
هر خرابی یعنی 500باگ 500، نتیجهٔ دامنه 4xx، قطعی 503 با Retry-After
در هر لایه log می‌شودیک بار log می‌شود، با کل زنجیره و request id
timeoutهای پیش‌فرض (30 ثانیه در کلاینت Laravel، بی‌نهایت در http.DefaultClient در Go)timeout صریح بر اساس دادهٔ latency و deadline فراخوان
هر چیزی را، هر جا، retry کنفقط خطای گذرا، در یک لایه، با jitter و بودجه
کد اول کار ساده‌ترtypeها و تست‌های بیشتر؛ حادثه‌های خیلی ارزان‌تر
Something failed. What is it?Programmer bugnil map, TypeError, broken invariantfail fast: panic / Error, 500,report with stack, fix the codeExpected domain outcomenot found, declined, invalid statereturn error value / businessexception, 4xx, no alertInfrastructure failuretimeout, 503, refused, deadlockrecoverable? transient orpermanent decides the responseTransienttimeout, retry+jitter,breaker, fallbackPermanentfail, alert,dead letter

این تصویر تصمیمی است که برای هر خرابی می‌گیرید: باگ است، نتیجهٔ مورد انتظار است، یا خرابی زیرساخت؛ و اگر زیرساخت است، گذراست یا دائمی. در شاخهٔ چپ باگ با fail-fast و گزارش همراه با stack trace تمام می‌شود، در وسط نتیجهٔ دامنه به 4xx بی‌صدا می‌رسد، و در راست خرابی زیرساخت به دو شاخهٔ گذرا (timeout، retry، breaker، fallback) و دائمی (شکست، هشدار، dead letter) تقسیم می‌شود.

تشبیهی که در کل صفحه از آن استفاده می‌کنیم: یک شرکت پیک. بسته به سه شکل ممکن است نرسد. نشانی وجود ندارد: این نتیجهٔ دامنه است؛ پیک بسته را با یک یادداشت روشن به فرستنده برمی‌گرداند و کسی به پلیس زنگ نمی‌زند. ون خراب شده: این زیرساخت است؛ بسته صبر می‌کند و بعداً با ون دیگری می‌رود، و اگر همهٔ ون‌های انبار خراب شوند، توزیع‌کننده یک ساعت ون بار نمی‌کند به‌جای اینکه ون‌های بیشتری به جادهٔ خراب بفرستد (circuit breaker). پیک بسته را در دریاچه تحویل داده: این باگ است؛ می‌ایستید و بررسی می‌کنید، چون رانندهٔ چنین کاری را یک بار کرده باز هم می‌کند. انبار قفسه‌ای دارد برای بسته‌هایی که پنج بار شکست خورده‌اند (dead letter) و روی هر بسته شمارهٔ رهگیری می‌زند تا تلاش دوم هرگز دو بار تحویل ندهد (idempotency key).

سه بدفهمی رایج، از همین اول ​

  1. «exception برای خطاست و مقدار بازگشتی برای موفقیت.» خط مفید بین خطا و موفقیت نیست، بین باگ، نتیجهٔ مورد انتظار و زیرساخت است. کارت ردشده نتیجهٔ مورد انتظار است، حتی اگر PHP آن را throw کند.
  2. «گرفتن همه‌چیز سیستم را مقاوم می‌کند.» فقط ساکتش می‌کند. قاعدهٔ Joe Duffy از پروژهٔ Midori دقیقاً برعکس است: "Bugs Aren’t Recoverable Errors!"؛ کدی که به وضعیتی رسیده که نویسنده‌اش انتظارش را نداشت باید بایستد، نه ادامه بدهد.
  3. «retry فراخوانی را قابل‌اعتماد می‌کند.» retry خرابی گذرا را نامرئی می‌کند و اضافه‌بار را بدتر. بدون timeout، jitter، بودجه و idempotency، یک وابستگی کُند را به قطعی کامل تبدیل می‌کند.

از کجا آمده ​

Exception و checked exception. Java کامپایلر را مجبور کرد exceptionهای اعلام‌شده را بررسی کند. قاعدهٔ آموزش رسمی Java این است: "If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception." در ۲۰۰۳ Anders Hejlsberg توضیح داد چرا C# این را کنار گذاشت: "I see two big issues with checked exceptions: scalability and versionability." افزودن یک exception تازه به عبارت throws همهٔ فراخوان‌ها را می‌شکند، و در عمل فراخوان‌ها exceptionها را به "a bottom level exception handler around their message loop" می‌سپارند. این همان ایدهٔ یک بار در مرز مدیریت کن است که از سمت دیگر به آن رسیده‌اند.

Go: خطا به‌عنوان مقدار (۲۰۱۱ تا ۲۰۲۵). مقالهٔ Error handling and Go از Andrew Gerrand (۲۰۱۱) interface داخلی error و fmt.Errorf برای افزودن زمینه را شرح می‌دهد. پست ۲۰۱۵ Rob Pike شعار بالای صفحه را داد. Go 1.13 (۲۰۱۹) wrapping را اضافه کرد: "an error which contains another may implement an Unwrap method"، به‌علاوهٔ errors.Is و errors.As، و هشداری که در مرکز این صفحه است: "wrapping an error makes that error part of your API." در Go 1.20 تابع errors.Join و در Go 1.26 تابع generic errors.AsType آمد. در ۳ ژوئن ۲۰۲۵ Robert Griesemer بحث طولانی دربارهٔ syntax (از جمله پیشنهاد try در issue 32437) را بست: "For the foreseeable future, the Go team will stop pursuing syntactic language changes for error handling."

PHP: یک Throwable، دو سلسله‌مراتب. راهنمای PHP امروز می‌گوید PHP خطاها را از راه "Throwable errors, which are further split into programming errors via the Error class hierarchy and recoverable errors via the Exception class hierarchy" گزارش می‌کند، به‌علاوهٔ خطاهای قدیمی‌تر diagnostic که throw نمی‌شوند (warning، notice). Throwable interface مشترک است (از PHP 7 به بعد) و کلاس‌های کاربر "cannot implement the Throwable interface directly, and must instead extend Exception."

Rust: Result و panic!. کتاب Rust: "Rust groups errors into two major categories: recoverable and unrecoverable errors." and "Rust doesn’t have exceptions. Instead, it has the type Result<T, E> for recoverable errors and the panic! macro that stops execution when the program encounters an unrecoverable error." این همان شکاف Exception/Error در PHP است، با این تفاوت که سیستم type آن را اجبار می‌کند.

Midori: باگ خطا نیست (۲۰۱۶). مقالهٔ The Error Model از Joe Duffy دو طرف را تمیز تعریف می‌کند: "A recoverable error is usually the result of programmatic data validation" و "A bug is a kind of error the programmer didn’t expect." در Midori برای باگ‌ها abandonment (همان fail-fast) و برای بقیه خطای بررسی‌شده به کار می‌رفت.

تحمل خطا (Fault tolerance): Nygard، Fowler، AWS، Google. کتاب Release It! از Michael Nygard (ویرایش دوم ۲۰۱۸) الگوهای پایداری (Stability patterns) را نام‌گذاری کرد: Timeouts، Circuit Breaker، Bulkheads، Steady State، Fail Fast، Let It Crash، Handshaking، Test Harnesses، Decoupling Middleware، Shed Load، Create Back Pressure، Governor (نام‌ها از فهرست مطالب ویرایش دوم است؛ توضیح‌ها در این صفحه خلاصهٔ ماست). مقالهٔ CircuitBreaker از Martin Fowler (۲۰۱۴) اعتبار را به او می‌دهد: "In his excellent book Release It, Michael Nygard popularized the Circuit Breaker pattern to prevent this kind of catastrophic cascade." پست Marc Brooker در AWS با عنوان Exponential Backoff And Jitter (۲۰۱۵) با اندازه‌گیری نشان داد: "The solution isn’t to remove backoff. It’s to add jitter." کتاب Site Reliability Engineering گوگل (نسخهٔ آنلاین © ۲۰۱۷، فصلی از Mike Ulrich) حالت خرابی‌ای را که همهٔ این‌ها جلویش را می‌گیرند تعریف می‌کند: "A cascading failure is a failure that grows over time as a result of positive feedback."

بدنهٔ خطای HTTP. RFC 7807 problem details را تعریف کرد؛ RFC 9457 (ژوئیهٔ ۲۰۲۳) جای آن را گرفت و هدف را نگه داشت: "machine-readable details of errors in HTTP response content to avoid the need to define new error response formats for HTTP APIs."

خرابی جزئی (Partial failure). مسئلهٔ دو ژنرال (two generals) را Akkoyunlu، Ekanadham و Huber در ۱۹۷۵ شرح دادند و Jim Gray در ۱۹۷۸ (Notes on Data Base Operating Systems) نام‌گذاری کرد؛ این تاریخچه را از Wikipedia خواندیم (منبع ثانویه)، که آن را "the first computer communication problem to be proven to be unsolvable" می‌نامد.

فهرست مفهوم‌ها ​

هر بلوک یک ترتیب دارد: به زبان ساده، باور غلط رایج، تعریف دقیق، یک timeline، سناریوهای واقعی، رفتار هر زبان یا محصول، و راه درست.

دسته‌بندی خطا (Error taxonomy): باگ، نتیجهٔ دامنه، زیرساخت حیاتی ​

به زبان ساده: پیش از اینکه catch یا if err != nil بنویسید، تصمیم بگیرید کدام‌یک از این سه اتفاق افتاده: کد غلط است، کسب‌وکار گفت نه، یا چیزی که به آن وابسته‌ایم خراب شد.

بدفهمی رایج: «خطا خطاست؛ همه به یک handler می‌روند.» این سه پاسخ متضاد لازم دارند. باگ باید پرسروصدا باشد (هشدار، stack trace) و نباید retry شود. نتیجهٔ دامنه باید بی‌صدا باشد (بدون هشدار) و به کاربر نشان داده شود. خرابی زیرساخت ممکن است retry شود، ولی فقط اگر گذرا باشد.

تعریف: باگ برنامه‌نویس وضعیتی است که نویسنده پیش‌بینی نکرده (Duffy: "a kind of error the programmer didn’t expect")؛ خطای دامنه (خطای مورد انتظار، خطای کسب‌وکار) نتیجهٔ مستندشدهٔ یک عملیات است؛ خرابی زیرساخت خرابی I/O یا یک جزء دیگر است. خرابی زیرساخت دو دسته دارد: گذرا (Transient؛ ممکن است بعداً موفق شود: timeout، 503، 429، deadlock، انتخاب leader) و دائمی (Permanent؛ بدون تغییر موفق نمی‌شود: 400، 401، host ناشناخته، ناسازگاری schema).

text
     Request: POST /orders/42/pay            Kind                Response
1    order 42 does not exist                 domain              404, no alert
2    order 42 already shipped                domain              409, no alert
3    payment API: 402 card declined          domain              422, no alert, no retry
4    payment API: 503                        infra, transient    retry with jitter, then fallback
5    payment API: 401 bad token              infra, permanent    fail, alert (config is wrong)
6    $order->total_cents is null -> TypeError  bug               500, report with stack, fix code

سناریوی واقعی: checkoutی که برای هر کارت ردشده on-call را بیدار می‌کند؛ jobی که یک 400 از شریک تجاری را ۲۵ بار retry می‌کند؛ یک Error ناشی از غلط تایپی که catch (Throwable) آن را می‌گیرد و به کاربر «پرداخت ناموفق بود» نشان می‌دهد.

زبانباگنتیجهٔ دامنهزیرساخت
Gopanic (runtime یا صریح)error از نوع sentinel یا typederror پیچیده‌شده (*url.Error، *net.OpError، context.DeadlineExceeded)
PHP 8.4زیرکلاس‌های Error: TypeError، ValueError، ArgumentCountError، UnhandledMatchError، DivisionByZeroErrorزیرکلاس‌های Exception خودتانPDOException، QueryException، ConnectionException، RequestException
Rustpanic!Err(DomainError)Err(io::Error)

راه درست: برای هر نوع یک type پایه. در کد این صفحه: برای دامنه sentinelها و *StateError در Go، برای زیرساخت ErrStoreUnavailable، برای باگ panic؛ در Laravel BusinessException (که ShouldntReport را پیاده می‌کند)، PaymentUnavailable (در سطح warning گزارش می‌شود) و خود Error در PHP برای باگ.

سه مدل خطا: مقدار، exception، Result حیاتی ​

به زبان ساده: Go خطا را کنار نتیجه برمی‌گرداند؛ PHP آن را به بالای stack پرتاب می‌کند تا کسی بگیردش؛ Rust مقداری برمی‌گرداند که یا نتیجه است یا خطا، و کامپایلر مجبورتان می‌کند نگاهش کنید.

بدفهمی رایج: «Go exception ندارد، پس نمی‌تواند stack را باز کند (unwind).» Go دستور panic را دارد که stack را باز می‌کند و فراخوانی‌های deferشده را اجرا می‌کند؛ فقط آن را برای باگ نگه می‌دارد. Effective Go: "real library functions should avoid panic." و بلاگ Go: "The convention in the Go libraries is that even when a package uses panic internally, its external API still presents explicit error return values."

تعریف:

مدلخطا از کجا می‌روددر امضای تابع پیداست؟هزینهٔ نادیده‌گرفتنخرابی معمول
Error value (Go)برگردانده و با if err != nil بررسی می‌شودبله (خروجی error)اگر _ = بنویسید بی‌صداپرحرفی، از دست رفتن زمینه
Unchecked exception (PHP، C#، Kotlin)تا یک catch بالا می‌رودنه (فقط docblockهای @throws)به handler سراسری می‌رسدcatch-all، کنترل جریان با exception
Checked exception (Java)بالا می‌رود؛ کامپایلر throws را چک می‌کندبلهخطای کامپایلthrows Exception همه‌جا، نویز wrap-and-rethrow
Result<T, E> (Rust، throws در Swift، Result در Kotlin)برگردانده می‌شود؛ ? منتشرش می‌کندبله، در typeهشدار کامپایلر (#[must_use])enumهای بزرگ خطا، کد تبدیل
text
     Go (values)                         PHP (exceptions)                      Rust (Result)
1    o, err := repo.Find(ctx, id)        $o = $repo->find($id);                let o = repo.find(id)?;
2    if err != nil {                     // throws OrderNotFound,              // `?` returns Err early,
3      return fmt.Errorf("pay: %w", err) // unwinds to the handler             // converting with From
4    }

سناریوی واقعی: سرویسی در Go که defer rows.Close() را فراموش کرده و خطای rows.Err() را هرگز بررسی نمی‌کند؛ controllerی در Laravel که در آن ModelNotFoundException از findOrFail بدون هیچ کدی درست به 404 تبدیل می‌شود؛ کلاینتی در Rust که یک variant تازهٔ خطا همهٔ matchها را مجبور به تغییر می‌کند، که همان نگرانی versioning از Hejlsberg است در شکلی دیگر.

راه درست: در Go هر خطا را بررسی کنید و در هر لایه یک بار زمینه اضافه کنید؛ در PHP exceptionهای مشخص throw کنید و بگذارید تا یک handler سفر کنند؛ در هر دو، نوع خطا را در type نگه دارید، نه در متن پیام.

طراحی typeهای خطا: sentinel، typed، wrapped، joined، کد حیاتی ​

به زبان ساده: فراخوان باید بتواند بپرسد «این همان حالت پیدا نشد است؟» بدون اینکه متن را parse کند. یا یک مقدار برای مقایسه به او بدهید (sentinel)، یا یک type برای بررسی (typed)، یا یک کد پایدار در مرز.

بدفهمی رایج: «همه‌چیز را با %w بپیچ تا فراخوان همهٔ اطلاعات را داشته باشد.» بلاگ Go برعکس هشدار می‌دهد: "Do not wrap an error when doing so would expose implementation details"، چون "wrapping an error makes that error part of your API." repositoryای که sql.ErrNoRows را wrap می‌کند همهٔ فراخوان‌ها را برای همیشه به import کردن database/sql مجبور می‌کند.

تعریف:

شکلGoPHP / Laravelکیهزینه
خطای نگهبان (Sentinel error)var ErrNotFound = errors.New("not found")، تست با errors.Isکلاس exception اختصاصی بدون فیلدفراخوان فقط «کدام حالت» را لازم داردبخشی از API می‌شود؛ داده حمل نمی‌کند
خطای typedtype FieldError struct{...}، تست با errors.As / errors.AsTypeکلاس exception با propertyهای readonlyفراخوان داده لازم دارد (فیلد، سقف، id)typeهای بیشتر
خطای پیچیده (Wrapped)fmt.Errorf("find %s: %w", id, err)، Unwrap() errornew X('msg', previous: $e)، getPrevious()افزودن زمینه با حفظ علت قابل‌بررسیعلت بخشی از API می‌شود
خطای مات (Opaque)fmt.Errorf("...: %v", err)exception تازه بدون previousپنهان کردن جزئیات پیاده‌سازیفراخوان نمی‌تواند رویش شاخه بزند
خطای ترکیبی (Joined)errors.Join(e1, e2)، Unwrap() []errorValidationException با کیسهٔ errorsگزارش چند مشکل با همفراخوان باید درخت را پیمایش کند
کد خطا (Error code)Code(err) string در مرزcode() روی BusinessExceptionکلاینت‌ها، لاگ، داشبورد، ترجمهباید برای همیشه پایدار بماند
متد Is/As سفارشیfunc (e *E) Is(target error) boolنداردیک type باید با sentinel تطبیق بخورداستفادهٔ زیاد غافلگیرکننده است
text
     err := svc.Cancel(ctx, "42")
1    service:    "cancel: %w"                  -> wraps
2    repository: "find order 42: %w"           -> wraps ErrOrderNotFound (translated from sql.ErrNoRows)
3    errors.Is(err, ErrOrderNotFound)  == true   (walks the chain)
4    errors.Is(err, sql.ErrNoRows)     == false  (repository translated, did not wrap the driver error)
5    err.Error() == "cancel: find order 42: order not found"   (text for humans and logs only)

سناریوی واقعی: مرحلهٔ اعتبارسنجی‌ای که باید همهٔ مشکل‌های فیلدها را در یک 422 برگرداند (errors.Join که FieldErrors پیمایشش می‌کند)؛ کلاینت پرداختی که ErrDeclined را عرضه می‌کند ولی پنهان می‌کند از کدام کتابخانهٔ HTTP استفاده می‌کند؛ API عمومی‌ای که سال‌ها قول "code": "insufficient_funds" را می‌دهد در حالی که متن پیام عوض می‌شود.

راه درست: snippet مربوط به errtypes در Go همهٔ شکل‌ها را با یک تست table-driven نشان می‌دهد؛ Exceptions.php یک سلسله‌مراتب Laravel با code()، status و title پایدار برای هر type نشان می‌دهد.

زمینهٔ خطا و stack trace مهم ​

به زبان ساده: پیام خطا باید بگوید چه کاری روی چه چیزی در جریان بود، و رکورد لاگ باید بگوید برای چه کسی. stack trace می‌گوید کجای کد.

بدفهمی رایج: «خطاهای Go بدون stack trace بی‌فایده‌اند.» زنجیره‌ای مثل cancel: find order 42: order store unavailable: dial tcp ...: connection refused اغلب از ۶۰ فریم مفیدتر است، چون هر لایه گفته داشت چه می‌کرد. خطاهای Go به‌طور پیش‌فرض stack ندارند؛ panic یکی چاپ می‌کند و runtime/debug.Stack() هر وقت لازم باشد یکی می‌گیرد. exceptionهای PHP همیشه getTrace() دارند؛ هزینه‌اش این است که trace می‌گوید کجا ولی نمی‌گوید کدام سفارش.

تعریف: زمینهٔ خطا (Error context) داده‌ای است که عملیات را مشخص می‌کند (idها، اندازه‌ها، شمارهٔ تلاش) و در هر لایه یک بار اضافه می‌شود. بلاگ Go: "It is the error implementation’s responsibility to summarize the context." Laravel اجازه می‌دهد exception با متد context() به لاگ زمینه اضافه کند، و زمینهٔ سراسری با $exceptions->context(...) اضافه می‌شود.

سناریوی واقعی: «record not found» در لاگ بدون هیچ id؛ stack traceای که در dispatcher فریم‌ورک تمام می‌شود و tenant id ندارد؛ issueای در Sentry که ۴۰ باگ متفاوت را یکی کرده چون پیام یک id متغیر دارد (راه حل: idها را از پیام بیرون نگه دارید و در فیلدهای زمینه بگذارید).

راه درست: زمینه در پیام به شکل پیشوندهای verb noun id:، شناسه‌ها در فیلدهای ساختاریافته، stack trace فقط برای باگ‌ها (5xx) و هرگز در پاسخ به کلاینت.

یک بار، در مرز مدیریت کن؛ بین لایه‌ها ترجمه کن حیاتی ​

به زبان ساده: هر خرابی باید دقیقاً یک بار log شود و دقیقاً یک بار به پاسخ تبدیل شود، آن هم توسط بیرونی‌ترین لایه‌ای که می‌داند چه کسی پرسیده (HTTP handler، اجراکنندهٔ job، فرمان CLI). لایه‌های داخلی یا زمینه اضافه می‌کنند یا ترجمه؛ log نمی‌کنند.

بدفهمی رایج: «log کردن و دوباره پرتاب کردن (log and rethrow) بی‌خطر است؛ لاگ بیشتر ضرری ندارد.» log کردن در هر لایه یک خرابی را به پنج خط لاگ با پنج زمینهٔ ناقص تبدیل می‌کند، حجم را وسط قطعی چند برابر می‌کند و شمارش خطاها را بی‌معنی. یا مدیریتش کنید (تصمیم بگیرید بعد چه شود) یا بالا بفرستید؛ هر دو با هم همان ضدالگوی log and rethrow است.

تعریف: خطا از سه نوع مرز رد می‌شود. در مرز adapter (repository، کلاینت HTTP) ترجمه می‌شود، از واژگان فناوری به واژگان دامنه (sql.ErrNoRows به ErrOrderNotFound، ConnectionException به PaymentUnavailable). در مرز use case سرویس تصمیم می‌گیرد: شکست، fallback یا جبران. در مرز پروسه handler مدیریت می‌کند: یک بار log با زمینهٔ درخواست، نگاشت به status و بدنه، پنهان کردن جزئیات داخلی. این سمت خطای Dependency Inversion است: دامنه خطاهایی را که portهایش ممکن است برگردانند تعریف می‌کند و adapterها به آن‌ها ترجمه می‌کنند.

InfrastructureRepository / adapterService / use caseBoundarysql.ErrNoRowsconnection refusedtimeout, HTTP 503QueryExceptionTRANSLATEno rows -> ErrOrderNotFounddriver error -> Unavailableadd context, do not logDECIDEdomain rule -> StateErrortransient -> fallback/queueelse wrap and returnHANDLE ONCElog with contextmap to status/codehide internalsClientproblem+jsonBug: panic / uncaught Throwableskips every layer; Recoverer / global handler: 500 + stack to Sentrybug

تصویر جریان را نشان می‌دهد: خطای زیرساخت (مثل sql.ErrNoRows یا timeout) وارد repository می‌شود و آنجا به خطای دامنه ترجمه می‌شود؛ سرویس زمینه اضافه می‌کند یا fallback را انتخاب می‌کند، بی‌آنکه log کند؛ فقط مرز یک بار log می‌کند و پاسخ problem+json به کلاینت می‌دهد. مسیر خط‌چین پایین باگ است: panic یا Throwable گرفته‌نشده از همهٔ لایه‌ها می‌پرد و در middleware بازیابی یا handler سراسری به 500 و گزارش با stack به Sentry ختم می‌شود.

text
     Layer          Receives                         Does                               Logs?
1    pgx driver     network reset                    returns *pgconn error              no
2    repository     *pgconn error                    translate -> ErrStoreUnavailable   no
3    service        ErrStoreUnavailable              add "cancel:" context              no
4    HTTP handler   full chain                       503 + Retry-After, problem+json    YES, once, with request id
5    middleware     (panic only)                     500, stack to Sentry               YES, once

سناریوی واقعی: controllerی در Laravel با try { ... } catch (Throwable $e) { Log::error(...); throw $e; } که هر رویداد Sentry را دوبرابر می‌کند (Laravel برای این نشانه dontReportDuplicates() را دارد)؛ سرویسی در Go که repository، service و handlerاش هر سه روی یک خطا log.Printf صدا می‌زنند.

راه درست: در Go، snippet layers (repository ترجمه می‌کند، service می‌پیچد، handler یک بار log می‌کند و یک تست بررسی می‌کند دقیقاً یک خط لاگ نوشته شده). در Laravel، withExceptions در bootstrap/app.php تنها جای report و render است؛ actionها یا throw می‌کنند یا report() می‌کنند و ادامه می‌دهند، هرگز هر دو. Liskov Substitution را هم ببینید: پیاده‌سازی‌ای که exceptionی پرتاب کند که interfaceاش وعده نداده، هر فراخوانی را که در مرز خطا را مدیریت می‌کند می‌شکند.

سلسله‌مراتب exception و ضدالگوها (Anti-patterns) حیاتی ​

به زبان ساده: سلسله‌مراتب اجازه می‌دهد مرز «همهٔ business exceptionها» را در یک جا بگیرد؛ ضدالگوها عادت‌هایی هستند که باگ را پنهان می‌کنند یا خرابی را پرسروصداتر از لازم می‌کنند.

بدفهمی رایج: «catch (Throwable $e) تدافعی است.» این TypeError و Error را هم می‌گیرد، یعنی باگ‌ها را، و معمولاً آن‌ها را به پیامی دوستانه تبدیل می‌کند که هیچ‌کس پیگیری‌اش نمی‌کند.

تعریف: درخت داخلی PHP این است: Throwable ← Error (باگ‌ها: TypeError، ValueError، ArithmeticError، DivisionByZeroError، ArgumentCountError، UnhandledMatchError، CompileError، ParseError) و Throwable ← Exception (قابل‌بازیابی). SPL شاخهٔ LogicException (باگ در برنامه: InvalidArgumentException، DomainException، LengthException، OutOfRangeException، BadFunctionCallException) و RuntimeException (فقط در زمان اجرا قابل‌تشخیص: UnexpectedValueException، OutOfBoundsException، OverflowException، RangeException، UnderflowException) را اضافه می‌کند. ErrorException خطاهای diagnostic (warning) را به exception تبدیل می‌کند. درخت خودتان را کم‌عمق طراحی کنید: یک پایه برای business exceptionها، یکی دو تا برای زیرساخت.

ضدالگوشکلشچرا آسیب می‌زندبه‌جایش
گرفتن همه‌چیز (Catch-all)catch (Throwable)، recover() همه‌جاباگ را پنهان می‌کند، جواب غلط می‌دهدفقط type مشخصی را بگیرید که از پسش برمی‌آیید
بلعیدن خطا (Swallow)catch (X) {}، _ = f()خرابی ناپدید می‌شودمدیریت کنید، برگردانید، یا report() کنید و ادامه دهید
Log and rethrowLog::error($e); throw $e;لاگ و هشدار تکراریفقط در مرز log کنید
Exception برای کنترل جریانthrow برای خروج از حلقه، panic برای «قبلاً ارسال شده»کُند، جریان نامرئی، قاطی شدن باگ با نتیجهمقدار بازگشتی / نتیجهٔ دامنه
مقایسهٔ رشته‌ایstr_contains($e->getMessage(), 'no rows')با ارتقای driver می‌شکندtype، sentinel، کد
نشت جزئیات داخلیبرگرداندن $e->getMessage() به کلاینتافشای اطلاعات (SQL، hostها)problem details با detail امن
سلسله‌مراتب پوکمونیAppException با ۴۰ زیرکلاس در ۵ سطحهیچ‌کس نمی‌داند کدام را بگیرددرخت کم‌عمق، یک پایه برای هر نوع
exception عمومیthrow new Exception('error')هیچ چیز نمی‌تواند رویش شاخه بزندیک type نام‌دار برای هر نتیجه
text
     Before (catch-all in the controller)             After (typed, handled once)
1    $order = Order::find($id);  // null              $order = Order::findOrFail($id);  // 404 by the handler
2    $order->total_cents         // Error: on null    -- bug cannot happen on this path --
3    catch (Throwable $e)        // caught!           -- no catch in the controller --
4    return 500 "Attempt to read property..."         PaymentDeclined -> 422 problem, no report
5    Sentry: nothing; user: confused                  TypeError (if any) -> 500, Sentry issue with stack

سناریوی واقعی: refactoringی که یک property را تغییر نام می‌دهد؛ Error حاصل را یک catch-all می‌گیرد و یک روز تمام هر checkout می‌گوید «پرداخت ناموفق بود، دوباره تلاش کنید».

راه درست: snippetهای Before.php و before/handler.go این عادت‌ها را فهرست می‌کنند؛ نسخه‌های after حذفشان می‌کنند.

Checked exception و بحث «اعلام کن چه پرتاب می‌کنی» تکمیلی ​

به زبان ساده: آیا کامپایلر باید فراخوان‌ها را مجبور کند با هر خطایی که تابع ممکن است بدهد کنار بیایند؟

بدفهمی رایج: «checked exception شکست خورد، پس typeهای خطا مهم نیستند.» درس Hejlsberg باریک‌تر است: فهرست کردن هر exception سطح پایین در هر امضا مقیاس‌پذیر نیست و نسخه‌پذیر هم نیست. error در Go و Result در Rust هنوز امکان شکست را در امضا نشان می‌دهند؛ فقط تک‌تک typeها را فهرست نمی‌کنند.

تعریف: checked exceptionهای Java بخشی از امضای متدند؛ unchecked‌ها (RuntimeException، Error) نیستند. PHP فقط unchecked exception دارد؛ docblockهای @throws را تحلیلگرهای ایستا (PHPStan، Psalm) می‌خوانند ولی موتور اجرا اجبارشان نمی‌کند. C# و Kotlin checked exception را کنار گذاشتند. موضع Go (۲۰۲۵) این است که بررسی صریح بماند و دنبال syntax تازه نرود.

راه درست: خطاهای دامنه‌ای را که تابع ممکن است برگرداند مستند کنید (توضیح Go مثل "returns an error wrapping ErrNotFound if..."؛ در PHP @throws PaymentDeclined)، و خطاهای زیرساخت را یک دسته ببینید، نه یک فهرست.

اعتبارسنجی، invariant و assertion مهم ​

به زبان ساده: اعتبارسنجی (Validation) ورودی غیرقابل‌اعتماد را بررسی می‌کند و به کاربر می‌گوید چه چیزی را درست کند؛ ناوردا (Invariant) قاعده‌ای است که اشیای خودتان همیشه حفظ می‌کنند؛ assertion چیزی را بررسی می‌کند که فقط وقتی کد باگ داشته باشد غلط درمی‌آید.

بدفهمی رایج: «اعتبارسنجی و assertion یک بررسی‌اند در دو جای مختلف.» مخاطبشان فرق دارد: اعتبارسنجی ناموفق یعنی 422 برای کاربر؛ شکستن invariant در شیء دامنه یا خطای دامنه است (اگر عمل کاربر می‌تواند باعثش شود) یا باگ (اگر یعنی کد شما اعتبارسنجی را جا انداخته).

تعریف:

بررسیکجاچرا شکست می‌خوردپاسخGoLaravel
اعتبارسنجی ورودیلبه (controller، Form Request، handler)کاربر یا کلاینت دادهٔ بد فرستاده422 با خطای همهٔ فیلدهاerrors.Join از *FieldErrorForm Request / validate() که ValidationException پرتاب می‌کند
Invariant دامنهداخل متد aggregateاین عمل الان مجاز نیست409 / 422 خطای کسب‌وکارخطای typed از DebitInvalidOrderState
Assertion / پیش‌شرطهر جا، دربارهٔ کد خودتانباگی در بالادستfail-fast، 500panicassert() (در production با zend.assertions خاموش)، LogicException

سناریوی واقعی: qty برابر صفر که به Wallet.Debit(0) می‌رسد: اعتبارسنجی باید جلویش را می‌گرفت، پس Debit panic می‌کند (باگ)؛ موجودی کم: خطای دامنه، کاربر می‌تواند شارژ کند؛ بدنهٔ JSON با سه فیلد غلط: یک 422 که هر سه را فهرست کند، نه سه رفت‌وبرگشت.

راه درست: در لبه با همهٔ خطاها یک‌جا اعتبارسنجی کنید (Laravel برای ValidationException روی درخواست JSON "a 422 Unprocessable Entity HTTP response" برمی‌گرداند)؛ invariantها را در متد دامنه با خطای typed نگهبانی کنید؛ panic و LogicException را برای «ممکن نیست» نگه دارید.

Fail-fast در برابر fail-safe، و حد برنامه‌نویسی تدافعی مهم ​

به زبان ساده: fail-fast یعنی با اولین نشانهٔ مشکل، نزدیک به علت، بایست. fail-safe یعنی وقتی چیزی خراب شد، سیستم در وضعیت بی‌خطر بماند (در آژیر آتش قفل در باز شود؛ پول برداشته نشود). برنامه‌نویسی تدافعی (Defensive programming) بررسی چیزهایی است که نباید رخ دهند؛ اگر همه‌جا انجام شود، باگ را پنهان می‌کند.

بدفهمی رایج: «fail-fast و fail-safe متضادند.» به دو سؤال متفاوت جواب می‌دهند. fail-fast دربارهٔ تشخیص است (زود بایست، روی وضعیت خراب ادامه نده). fail-safe دربارهٔ وضعیتی است که باقی می‌گذاری (پیش‌فرض رد، rollback، ارسال نکن). طراحی خوب هر دو را دارد: باگ panic می‌کند (fail-fast) و تراکنش rollback می‌شود (fail-safe).

تعریف: الگوی Fail Fast در کتاب Nygard (خلاصهٔ ما): اگر درخواستی قرار است شکست بخورد، مثلاً چون circuit یک وابستگی لازم باز است یا منابع ته کشیده، فوراً ردش کن، نه بعد از اینکه یک thread و یک timeout را مصرف کرد. Duffy نسخهٔ سمت باگ را abandonment می‌نامد. برنامه‌نویسی تدافعی حد دارد: if ($order === null) return; در عمق یک سرویس یک باگ را به از دست رفتن بی‌صدای داده تبدیل می‌کند؛ یک بار در لبه بررسی کنید، داخل اعتماد کنید، بقیه را assert کنید.

text
     Defensive (hides the bug)                        Fail-fast + fail-safe
1    if order == nil { return nil }  // silently ok   if order == nil { panic("BUG: nil order") }
2    -- caller thinks it was cancelled --              -- request gets 500, Sentry issue, tx rolled back --
3    -- refund never issued, customer charged --      -- no money moved; fix deployed same day --

سناریوی واقعی: سرویس feature flag از کار افتاده: پیش‌فرض fail-safe برای قابلیت‌های تازه «خاموش» و برای kill switchها «روشن»؛ بررسی دسترسی‌ای که exception می‌دهد: fail-safe یعنی رد، نه قبول؛ مقدار config که در شروع برنامه نیست: fail-fast در زمان بالا آمدن، نه یک هفته بعد در اولین درخواست.

راه درست: config و وابستگی‌ها را هنگام شروع اعتبارسنجی کنید؛ برای هر تصمیم یک پیش‌فرض امن انتخاب کنید؛ بگذارید باگ درخواست را بخواباند (یا پروسهٔ worker را، به معنای Let It Crash در کتاب Nygard، که یک supervisor آن را دوباره راه می‌اندازد).

Panic، recover و خطاهای fatal در PHP مهم ​

به زبان ساده: panic (در Go) یا Error (در PHP) یعنی «برنامه در وضعیتی است که هیچ‌کس برایش برنامه نداشت». می‌توانید در بیرونی‌ترین لبه بگیریدش تا درخواست‌های دیگر زنده بمانند، ولی نه برای ادامهٔ همین درخواست.

بدفهمی رایج: «recover همان catch در Go است.» بلاگ Go: "Recover is only useful inside deferred functions"، و کتابخانه نباید بگذارد panic از API آن بیرون بزند. جای recover در middleware سطح بالا یا wrapper یک goroutine است، نه دور کد کسب‌وکار.

تعریف:

وضعیتGoPHP 8.4
باگی که runtime تشخیص می‌دهدpanic زمان اجرا (map نال، index خارج از بازه)پرتاب زیرکلاسی از Error
«ممکن نیست» صریحpanic("...")throw new LogicException
گرفتن در لبهdefer func(){ if v := recover(); ... }() در middlewarehandler سراسری (set_exception_handler، handler لاراول)
panic در goroutine دیگراگر همان goroutine بازیابی نکند کل پروسه را می‌خواباندندارد (هر worker یک درخواست)
واقعاً fatalfatal error: concurrent map writes، کمبود حافظه (قابل‌بازیابی نیست)سقف حافظه، سقف زمان اجرا: Throwable نیستند؛ فقط register_shutdown_function با error_get_last() می‌بیندشان
قطع عمدیpanic(http.ErrAbortHandler) پاسخ را بی‌صدا قطع می‌کندabort(404) یک HttpException پرتاب می‌کند
text
     Go net/http server, one request panics
1    goroutine for request A: nil map write -> panic
2    Recoverer middleware: recover() -> log stack -> 500 problem+json for A
3    requests B, C, D on other goroutines: unaffected
4    BUT: a goroutine started by A with `go work()` panics -> no recover there -> whole process exits

راه درست: Recoverer در snippet لایه‌ها (http.ErrAbortHandler را دوباره panic می‌کند و debug.Stack() را log می‌کند)؛ هر go func() که در سرور راه می‌اندازید recover خودش را دارد یا از errgroup استفاده می‌کند. در PHP به handler لاراول تکیه کنید (که Illuminate\Foundation\Bootstrap\HandleExceptions ثبتش می‌کند)؛ اسکریپت‌های ساده هر دو handler را مثل Cleanup.php ثبت می‌کنند.

پاک‌سازی منابع (Resource cleanup): defer، finally، RAII مهم ​

به زبان ساده: هر چه باز، قفل یا شروع می‌کنید، باید در همهٔ مسیرها ببندید، آزاد کنید یا تمام کنید: موفقیت، خطا و panic.

بدفهمی رایج: «defer f.Close() کافی است.» برای فایلی که نوشته‌اید، Close ممکن است خطای واقعی را برگرداند (داده به دیسک نرسید)؛ نادیده‌گرفتنش نوشتن را بی‌صدا از دست می‌دهد. و «finally فقط وقت خطا اجرا می‌شود»: در موفقیت، در return و در throw هم اجرا می‌شود؛ راهنمای PHP: "All finally blocks it encounters along the way will be executed."

تعریف: defer در Go وقتی تابع برمی‌گردد (یا panic می‌کند) اجرا می‌شود، به ترتیب آخر-وارد-اول-خارج؛ آرگومان‌های deferشده "are evaluated when the defer statement is evaluated" و توابع deferشده "may read and assign to the returning function’s named return values"، و همین راهی است که خطای Close به نتیجه join می‌شود. finally در PHP بعد از try/catch اجرا می‌شود. C++ و Rust از RAII (Drop) استفاده می‌کنند: پاک‌سازی گره‌خورده به scope. Laravel موارد رایج را پوشش می‌دهد: DB::transaction() روی هر exception rollback می‌کند و دوباره پرتاب می‌کند، و $lock->release() در finally.

text
     InTx(ctx, db, fn)
1    BEGIN
2    fn(tx) returns ErrInsufficientFunds   -> deferred: ROLLBACK, return the error
3    fn(tx) panics (bug)                    -> deferred: ROLLBACK, re-panic
4    fn(tx) ok, COMMIT fails (40001)        -> deferred: return "commit: ..." (retryable at a higher level)

راه درست: cleanup.go (errors.Join(err, f.Close())، InTx) و Cleanup.php (finally، DB::transaction(..., attempts: 3)).

Timeout و deadline حیاتی ​

به زبان ساده: هر فراخوانی که از پروسه بیرون می‌رود باید سقف انتظار داشته باشد. timeout نداشتن یک وابستگی کُند را به فراخوان گیرکرده، و بعد به سیستم گیرکرده تبدیل می‌کند.

بدفهمی رایج: «timeout پیش‌فرض کافی است.» مستندات http.Client در Go: "A Timeout of zero means no timeout"، و http.DefaultClient هیچ timeoutی ندارد. کلاینت HTTP لاراول به‌طور پیش‌فرض بعد از ۳۰ ثانیه timeout می‌دهد، که از صبر بیشتر کاربران طولانی‌تر است و برای پر کردن همهٔ workerهای PHP-FPM در یک حادثه کافی است.

تعریف: timeout یک عملیات را محدود می‌کند؛ deadline زمان مطلق برای کل یک درخواست است که همهٔ فراخوانی‌های پایین‌دست به ارث می‌برند. مستندات context در Go: "Incoming requests to a server should create a Context, and outgoing calls to servers should accept a Context." قاعدهٔ کتاب SRE انتشار deadline (deadline propagation) است: "Rather than inventing a deadline when sending RPCs to backends, servers should employ deadline propagation." راهنمای AWS برای انتخاب عدد: "start with the latency metrics of the downstream service" و یک صدک بالا انتخاب کنید (مثالشان p99.9 است)، نه حدس.

text
     Edge deadline 2s ----------------------------------------------------------|
1    t=0      API receives request, ctx deadline t+2s
2    t=10ms   orders -> payments, per-attempt timeout 300ms (min(300ms, remaining))
3    t=310ms  attempt 1 times out (context.DeadlineExceeded)
4    t=350ms  attempt 2 ok
5    t=1.9s   if attempts were still failing: do not start one that cannot finish before 2s
تنظیمGoLaravel 13 / PHP
کل درخواستhttp.Client{Timeout: ...} یا context.WithTimeoutHttp::timeout(3) (پیش‌فرض 30 ثانیه)
فقط اتصالnet.Dialer{Timeout: ...}Http::connectTimeout(1) (پیش‌فرض 10 ثانیه)
deadline فراخوانctx که پایین داده می‌شودانتشار داخلی ندارد؛ deadline را صریح پاس بدهید
job صف‌شدهcontext سطح worker#[Timeout(120)]، --timeout؛ باید کمتر از retry_after باشد
دیتابیسctx روی QueryContext، statement_timeoutstatement_timeout / max_execution_time در config دیتابیس

راه درست: context.WithTimeout برای هر تلاش داخل حلقهٔ retry و یک deadline فراخوان بیرون آن (آزمایشگاه)؛ در Laravel connectTimeout(1)->timeout(3) در PaymentGateway.php. جزئیات: Timeouts, Retries & Jitter.

Retry با exponential backoff و jitter حیاتی ​

به زبان ساده: اگر فراخوانی به دلیلی گذرا شکست خورد، کمی صبر کنید و دوباره امتحان کنید؛ هر بار بیشتر صبر کنید؛ و زمان صبر را تصادفی انتخاب کنید تا هزار کلاینت در یک میلی‌ثانیه برنگردند.

بدفهمی رایج: «سه بار retry، همه‌جا.» حساب کتاب SRE: اگر دیتابیس زیر بار است و "the backend, frontend, and JavaScript layers all issue 3 retries (4 attempts), then a single user action may create 64 attempts (4^3) on the database." این همان طوفان retry (retry storm) است.

تعریف: exponential backoff به اندازهٔ base × 2^n (با سقف) صبر می‌کند؛ full jitter مقداری تصادفی در [0, min(cap, base × 2^n)) صبر می‌کند. اندازه‌گیری‌های Brooker نشان داد full jitter کمترین کار کل را دارد. قاعده‌های کتاب SRE: "Always use randomized exponential backoff when scheduling retries"، "Limit retries per request"، "Consider having a server-wide retry budget" (مثالشان: "only allow 60 retries per minute in a process")، و "Don’t retry permanent errors or malformed requests in a client, because neither will ever succeed." AWS retry را "selfish" می‌نامد و توصیه می‌کند "retry at a single point in the stack" انجام شود. پس بودجهٔ retry (retry budget) و retry در یک لایه دو قاعدهٔ اصلی‌اند.

attempt 1timeout 80msceiling 100attempt 2503ceiling 200attempt 3503ceiling 400attempt 4200 OKcaller deadlinedashed box = backoff ceiling min(cap, base x 2^n); dot = random wait chosen by full jitterevery attempt sends the SAME Idempotency-Key; 4xx and domain errors are never retriedno jitter: 1,000 clients retry at the same instants and knock the recovering server over again

در تصویر، هر تلاش timeout خودش را دارد؛ بین تلاش‌ها سقف backoff از 100 به 200 و 400 میلی‌ثانیه دو برابر می‌شود و نقطه‌ها زمان تصادفی‌ای هستند که full jitter زیر آن سقف انتخاب کرده؛ خط‌چین سمت راست deadline فراخوان است که بعد از آن تلاشی شروع نمی‌شود.

خطاRetry؟چرا
Timeout، قطع یا رد اتصالبله، اگر عملیات idempotent باشدگذراست؛ شاید سرور کار را انجام داده، شاید نه
HTTP 503، 502، 504بله؛ Retry-After را رعایت کنیدبه تعریف گذراست
HTTP 429بله، بعد از Retry-Afterrate limit شده‌اید
HTTP 500شاید (فقط idempotent)ممکن است باگ باشد؛ تعداد را محدود کنید
HTTP 400، 401، 403، 404، 409، 422نههمان درخواست، همان جواب
PostgreSQL 40001 (serialization)، 40P01 (deadlock)؛ MySQL 1213بله، کل تراکنشDeadlocks را ببینید
Circuit باز، bulkhead پرنه (در همین فراخوانی)retry حفاظت را بی‌اثر می‌کند
خطای دامنه (رد شد، پیدا نشد)هرگزخرابی سیستم نیست

راه درست: در Go resilience.Do (دسته‌بندی با interface Retryable، full jitter، آگاه از deadline، sleep قابل‌تزریق)؛ در Laravel Http::retry(3, fn ($attempt) => random_int(...), fn ($e) => transient)، helper retry() با callback when، و برای job #[Backoff([10, 30, 60])] همراه retryUntil(). Http::retry در Laravel "the maximum number of times the request should be attempted" و مکث بر حسب میلی‌ثانیه یا یک closure را می‌گیرد. جزئیات: Timeouts, Retries & Jitter، Retry, Backoff & Delayed Delivery.

Idempotency حیاتی ​

به زبان ساده: عملیاتی idempotent است که دو بار انجامش همان اثر یک بار را داشته باشد. retry فقط برای عملیات idempotent امن است، پس عملیات غیر idempotent (کسر پول، ساخت سفارش، فرستادن ایمیل) را با یک کلید idempotent می‌کنید.

بدفهمی رایج: «timeout یعنی فراخوانی شکست خورد.» timeout یعنی نمی‌دانید. شاید سرور کارت را شارژ کرده و پاسخ گم شده. retry بدون کلید دو بار پول کم می‌کند؛ این دقیقاً سناریوی B' در آزمایشگاه است.

تعریف: کلاینت برای هر عملیات منطقی یک کلید idempotency (idempotency key) می‌سازد و در هر تلاش می‌فرستد (هدر Idempotency-Key)؛ سرور کلید را با نتیجه ذخیره می‌کند و دوباره پخشش می‌کند. مستندات Stripe: "A client generates an idempotency key, which is a unique key that the server uses to recognize subsequent retries of the same request"، "Retries with the same key return the saved response, including 500 errors"، و سرور "compares incoming parameters to those of the original request and errors if they’re not the same". کلیدها را می‌توان بعد از "at least 24 hours" حذف کرد.

text
     Client (orders)                           Payment API
1    POST /charges  Idempotency-Key: order-1002-payment
2                                              charge created ch_2, response is slow
3    timeout after 100ms (unknown outcome)
4    POST /charges  Idempotency-Key: order-1002-payment   (same key!)
5                                              key seen -> replay ch_2, no new charge
6    paid ch_2                                 charges created: 1
sql
-- PostgreSQL: server-side idempotency store for our own POST endpoints.
CREATE TABLE idempotency_keys (
    scope        text        NOT NULL,           -- tenant or user id
    key          text        NOT NULL,
    fingerprint  text        NOT NULL,           -- hash of method + path + body
    status_code  int,                            -- NULL while in progress
    response     jsonb,
    created_at   timestamptz NOT NULL DEFAULT now(),
    PRIMARY KEY (scope, key)
);
-- Claim the key atomically; 0 rows inserted means "seen before": replay or 409.
INSERT INTO idempotency_keys (scope, key, fingerprint)
VALUES ($1, $2, $3) ON CONFLICT (scope, key) DO NOTHING;
DELETE FROM idempotency_keys WHERE created_at < now() - interval '24 hours';

راه درست: کلید را از عملیات کسب‌وکار بسازید (order-{id}-payment)، نه از شمارهٔ تلاش، و همان را در مسیر fallback و در job صف‌شده هم استفاده کنید. در Laravel: EnsureIdempotency.php (پخش دوباره، 422 برای کلید تکراری با بدنهٔ متفاوت، 409 در حین پردازش، آزاد کردن قفل در finally). مصرف‌کنندهٔ پیام هم همین ویژگی را لازم دارد: Idempotent Consumers & the Inbox Pattern؛ برای API: API Idempotency.

Circuit breaker حیاتی ​

به زبان ساده: بعد از تعداد کافی شکست پشت‌سرهم، مدتی وابستگی خراب را صدا نزنید و فوراً شکست بدهید؛ بعد یک فراخوانی آزمایشی را رد کنید تا ببینید درست شده یا نه.

بدفهمی رایج: «breaker فراخوانی‌ها را موفق می‌کند.» آن‌ها را زودتر شکست می‌دهد، تا فراخوان‌ها threadها، socketها و وقت کاربر را نگه دارند و وابستگی فرصت بازیابی داشته باشد. باید با یک fallback جفت شود، وگرنه کاربر فقط زودتر خطا می‌بیند.

تعریف: Fowler: "Once the failures reach a certain threshold, the circuit breaker trips, and all further calls to the circuit breaker return with an error, without the protected call being made at all." حالت سوم "half open - meaning the circuit is ready to make a real call as trial to see if the problem is fixed." است (در این صفحه half-open می‌نویسیم). و: "Not all errors should trip the circuit, some should reflect normal failures and be dealt with as part of regular logic." تنظیم‌ها (با نام‌های sony/gobreaker): MaxRequests ("the maximum number of requests allowed to pass through when the CircuitBreaker is half-open")، Interval (کی شمارش‌ها در حالت بسته صفر می‌شوند)، Timeout ("the period of the open state")، ReadyToTrip (قاعدهٔ قطع، مثلاً ۵ شکست پشت‌سرهم یا نرخ شکست ۵۰٪).

CLOSEDcalls pass throughcount failuresOPENfail fast: ErrOpenno call is madeHALF-OPENallow N trial callsfailures >= threshold (e.g. 5 in a row, or 50% in a window)only 5xx / timeouts / connection errors count, never 4xx or domain errorsopen timeout elapsed(e.g. 30 s)trial failstrial succeedssuccess resets count

تصویر ماشین حالت را نشان می‌دهد: در حالت بسته (Closed) فراخوانی‌ها رد می‌شوند و شکست‌ها شمرده می‌شوند؛ وقتی به آستانه رسید به باز (Open) می‌رود و فراخوانی‌ها بدون تماس با وابستگی شکست می‌خورند؛ بعد از پایان زمان باز به نیمه‌باز (half-open) می‌رود و چند فراخوانی آزمایشی را راه می‌دهد؛ آزمایش موفق آن را می‌بندد و آزمایش ناموفق دوباره بازش می‌کند.

انتخابگزینهٔ الفگزینهٔ ب
قاعدهٔ قطعشکست‌های پشت‌سرهم (ساده، همین صفحه)نرخ شکست روی پنجرهٔ لغزان با حداقل حجم
جایگاهداخل حلقهٔ retry (هر تلاش را می‌شمارد؛ آزمایشگاه Go)بیرون آن (هر فراخوانی منطقی را می‌شمارد؛ gateway در Laravel)
محل نگهداری حالتحافظهٔ پروسه (Go، worker در Octane)cache مشترک (PHP-FPM: Redis، چون workerها هیچ چیز مشترک ندارند)
چه چیزی حساب می‌شود5xx، timeout، خطای اتصالهرگز 4xx یا خطای دامنه
کتابخانه‌هاsony/gobreaker (Go)، Resilience4j (Java)، Polly (.NET)outlier detection در Envoy/Istio (سطح mesh)

راه درست: در Go resilience.Breaker (ماشین حالت با ساعت تزریقی و predicate IsFailure، که گذار به گذار تست شده)؛ در Laravel CircuitBreaker.php روی Cache با Cache::add اتمیک برای آزمایش half-open، و ThrottlesExceptions به‌عنوان معادل سمت صف ("all further attempts to execute the job are delayed until a specified time interval lapses"). جزئیات: Circuit Breaker.

Bulkhead مهم ​

به زبان ساده: به هر وابستگی pool محدود خودش را بدهید، تا یک وابستگی کُند فقط محفظهٔ خودش را مصرف کند، نه همهٔ workerهایتان را.

بدفهمی رایج: «timeoutها از ما محافظت می‌کنند.» timeout سه‌ثانیه‌ای با ۱۰۰ درخواست در ثانیه به یک وابستگی گیرکرده هنوز ۳۰۰ worker هم‌زمان را درگیر می‌کند. bulkhead این عدد را سقف می‌گذارد.

تعریف: صفحهٔ الگو در Azure: "This pattern is named after the sectioned partitions (bulkheads) of a ship's hull." پیاده‌سازی‌ها: یک semaphore برای هر وابستگی، connection pool جدا، queue و گروه worker جدا، pool جدای PHP-FPM، یا instanceهای جدای سرویس ("Partition service instances into different groups based on consumer load and availability requirements").

text
     Shared pool of 50 workers               Bulkheads: payments 10, search 10, rest 30
1    payments hangs, 50 workers wait          payments hangs, 10 workers wait, 11th gets ErrBulkheadFull fast
2    search and login also time out           search and login keep working

راه درست: در Go resilience.Bulkhead (کانال بافردار به‌عنوان semaphore، با انتظار محدود)؛ در Laravel یک queue اختصاصی payments با پروسه‌های queue:work خودش، WithoutOverlapping، و pool جدای FPM برای routeهای کُند. جزئیات: Bulkheads & Graceful Degradation.

Fallback، تنزل آبرومندانه (graceful degradation) و load shedding مهم ​

به زبان ساده: وقتی نمی‌توانید جواب کامل بدهید، جواب کوچک‌تری بدهید (قیمت cacheشده، «پرداخت در انتظار»، بدون پیشنهاد)؛ وقتی کار بیشتر از ظرفیت دارید، بخشی را زود رد کنید تا بقیه تمام شود.

بدفهمی رایج: «fallback یعنی یک catch که مقدار پیش‌فرض برمی‌گرداند.» fallback یک تصمیم محصول است: «سفارش را بپذیر و بعداً پول را کسر کن» باید با کسب‌وکار توافق شود، idempotent باشد و دیده شود (metric)، وگرنه بی‌صدا به مسیر عادی تبدیل می‌شود.

تعریف: کتاب SRE: "Load shedding drops some proportion of load by dropping traffic as the server approaches overload conditions"؛ "Graceful degradation takes the concept of load shedding one step further by reducing the amount of work that needs to be performed." حذف بار می‌تواند "indiscriminate" یا گزینشی باشد، مثلاً "drop requests for low-priority operations like background synchronization, but keep serving interactive user sessions". statusی برگردانید که به کلاینت بگوید عقب بکشد: "Return a specific status when overloaded so that clients and other layers back off and do not retry" (503 با Retry-After طبق RFC 9110).

Fallbackکی درست استریسک
مقدار cacheشده / کهنهخواندن (قیمت، کاتالوگ)دادهٔ کهنه؛ برچسب بزنید
مقدار پیش‌فرضقابلیت‌های غیرحیاتی (پیشنهادها، آواتار)قابلیت خراب را پنهان می‌کند؛ روی نرخش هشدار بگذارید
ثبت برای بعدنوشتن‌هایی که می‌توانند ناهمگام باشند (کسر پول، ایمیل)idempotency و dead letter لازم دارد
ارائه‌دهندهٔ جایگزینپرداخت، پیامک، نقشهدو یکپارچه‌سازی برای نگهداری
شکست با پیام روشنچیزی امن برای جایگزینی نیستکاربر دوباره تلاش می‌کند؛ Retry-After بدهید

راه درست: در آزمایشگاه Go متد OrderService.Checkout وضعیت payment_pending برمی‌گرداند و id سفارش را در صف می‌گذارد؛ در Laravel action Checkout خطای PaymentUnavailable را می‌گیرد، payment_pending را ثبت می‌کند و بعد از commit ChargePendingPayment را dispatch می‌کند؛ rescue() برای فراخوانی‌های اختیاری ("All exceptions that are caught will be sent to your exception handler; however, the request will continue processing")؛ Cache::flexible برای خواندن stale-while-revalidate. جزئیات: Load Shedding، Cascading Failures (خرابی آبشاری، cascading failure).

خرابی جزئی: دو ژنرال، at-least-once، dead letter، saga مهم ​

به زبان ساده: در سیستم توزیع‌شده یک فراخوانی ممکن است بعد از انجام کارش شکست بخورد و همیشه نمی‌توانید بفهمید. پس به‌جای «یا انجام شد یا نشد» برای «ممکن است صفر بار یا بیشتر انجام شده باشد» طراحی می‌کنید.

بدفهمی رایج: «با تأییدیه‌های کافی می‌توانیم مطمئن شویم دو طرف توافق دارند.» مسئلهٔ دو ژنرال (two generals) نشان می‌دهد هیچ تعداد پیامی روی کانال غیرقابل‌اعتماد قطعیت نمی‌دهد؛ به همین دلیل تحویل exactly-once از تحویل at-least-once به‌علاوهٔ پردازش idempotent ساخته می‌شود.

تعریف: خرابی جزئی: بخشی از عملیات موفق شد و بخشی نه (پول کسر شد، به‌روزرسانی سفارش شکست خورد). At-least-once: فرستنده تا تأیید retry می‌کند، پس تکرار ممکن است و گیرنده باید idempotent باشد. صف یا جدول dead letter کارهایی را نگه می‌دارد که دائماً شکست خورده‌اند یا retryهایشان ته کشیده (در Laravel: "it will be inserted into the failed_jobs database table"). Saga یک تراکنش توزیع‌شده را با گام‌های محلی و جبران‌ها (compensation) جایگزین می‌کند (بازپرداخت به‌جای rollback).

text
     orders                          payments                 shipping
1    charge (key order-7-payment) ->  ok ch_9
2    reserve stock ------------------------------------------>  503, retries exhausted
3    saga: compensate                 refund ch_9 (key order-7-refund)
4    order status: cancelled_out_of_stock; customer notified

راه درست: کلید idempotency برای هر گام و هر جبران؛ DLQ با مالک و هشدار؛ لینک‌ها: Delivery Guarantees، Dead-Letter Queue، Saga Pattern.

تراکنش و خطا: rollback و outbox مهم ​

به زبان ساده: داخل یک دیتابیس، تراکنش «نیمه‌کاره» را غیرممکن می‌کند: هر خطا همه‌چیز را rollback می‌کند. لحظه‌ای که یک API را هم صدا بزنید یا پیامی منتشر کنید، تراکنش دیگر آن را پوشش نمی‌دهد و به outbox نیاز دارید.

بدفهمی رایج: «job را داخل تراکنش dispatch کن؛ اگر شکست خورد job هم rollback می‌شود.» صف داخل دیتابیس نیست. اگر تراکنش بعد از dispatch rollback شود، job برای سفارشی اجرا می‌شود که وجود ندارد؛ اگر بعد از commit dispatch کنید و پروسه وسط کار بمیرد، job گم می‌شود.

تعریف: DB::transaction(): "If an exception is thrown within the transaction closure, the transaction will automatically be rolled back and the exception is re-thrown." آرگومان دومش "the number of times a transaction should be retried when a deadlock occurs" است. ->afterCommit() dispatch را تا commit تراکنش بیرونی عقب می‌اندازد. Transactional outbox پیام را در همان تراکنش در یک جدول می‌نویسد و یک relay آن را at-least-once منتشر می‌کند.

sql
BEGIN;
UPDATE orders SET status = 'payment_pending' WHERE id = 1005 AND status = 'placed';
INSERT INTO outbox (aggregate_id, type, payload)
VALUES (1005, 'ChargePendingPayment', '{"order_id":1005,"key":"order-1005-payment"}');
COMMIT;  -- both rows or neither; a relay publishes outbox rows and marks them sent

راه درست: فراخوانی‌های بیرونی را بیرون از تراکنش دیتابیس نگه دارید (فراخوانی HTTP سه‌ثانیه‌ای داخل تراکنش قفل سطرها را سه ثانیه نگه می‌دارد)؛ برای کار بعدی از afterCommit() یا outbox استفاده کنید. ACID & Transactions را ببینید.

پاسخ خطای API: problem details در RFC 9457 حیاتی ​

به زبان ساده: کلاینت‌ها یک قالب خطای ماشین‌خوان لازم دارند که در همهٔ endpointها یکی باشد: یک type برای شاخه زدن، یک title برای انسان، status، و جزئیات اختیاری.

بدفهمی رایج: «پیام exception را در پاسخ بگذار.» RFC 9457: "Problem details are not a debugging tool for the underlying implementation; rather, they are a way to expose greater detail about the HTTP interface itself"، همراه با هشدار دربارهٔ "exposing implementation internals through error messages".

تعریف: media type application/problem+json؛ عضوها: type (یک URI؛ "Consumers MUST use the "type" URI (after resolution, if necessary) as the problem type's primary identifier."؛ پیش‌فرض about:blank)، title، status ("only advisory")، detail، instance، به‌علاوهٔ extension memberها (این صفحه code و errors را اضافه می‌کند). RFC 9457 جایگزین RFC 7807 است.

text
     HTTP/1.1 422 Unprocessable Content
     Content-Type: application/problem+json
     {"type":"https://example.com/probs/validation-failed","title":"Your request is not valid.",
      "status":422,"instance":"/api/orders","code":"validation_failed",
      "errors":{"qty":["The qty field must be at least 1."]}}
خطاStatusslug در typeاضافه
اعتبارسنجی422validation-failederrors برای هر فیلد
پیدا نشد404order-not-foundندارد
وضعیت نامعتبر409invalid-stateندارد
پرداخت رد شد422 (یا 402)payment-declinedندارد
rate limit429about:blankRetry-After
وابستگی از کار افتاده503unavailableRetry-After
باگ500about:blankهیچ چیز داخلی؛ یک request id

راه درست: در Go تابع writeProblem در layers؛ در Laravel Problem::response() که از $exceptions->render(...) در bootstrap-app.php صدا زده می‌شود. قاعده‌های طراحی API: REST API Design.

مشاهده‌پذیری خطا (Observability) مهم ​

به زبان ساده: چیزی را که نمی‌بینید نمی‌توانید درست کنید، و اگر هر 404 مورد انتظار کسی را بیدار کند هیچ چیز نمی‌بینید. یک بار و ساختاریافته log کنید، باگ‌ها را به error tracker بفرستید، و همه‌چیز را به‌شکل metric بشمارید.

بدفهمی رایج: «هر exception باید به Sentry برود.» business exceptionها باگ نیستند؛ ShouldntReport و dontReport در Laravel بیرونشان نگه می‌دارند، و فریم‌ورک به‌طور پیش‌فرض 404ها و بعضی پاسخ‌های 403/419 را نادیده می‌گیرد.

تعریف: لاگ ساختاریافته (structured logging) فیلدهای کلید/مقدار می‌نویسد (log/slog در Go، channelهای Monolog در Laravel با context())؛ error tracker (Sentry، Flare، Laravel Nightwatch که همه در مستندات Laravel نام برده شده‌اند) exceptionها را با stack و نسخهٔ release در issueها گروه می‌کند؛ metricها خطاها را بر اساس نوع می‌شمارند و SLO را تغذیه می‌کنند. بودجهٔ خطا (error budget) مقدار خرابی‌ای است که SLO اجازه می‌دهد؛ مصرف آن تعیین می‌کند کی ساختن قابلیت را متوقف کنیم و پایداری را درست کنیم (صاحبش صفحهٔ SLAs, SLOs, SLIs & Error Budgets است).

سیگنالباگنتیجهٔ دامنهزیرساخت
سطح لاگerrorinfo/debug (یا هیچ)warning؛ error وقتی بودجه می‌سوزد
Error trackerبله، با stackنه (ShouldntReport)نمونه‌گیری/throttle ($exceptions->throttle، Limit::perMinute)
Metricerrors_total{kind="bug"}outcomes_total{code=...}dependency_errors_total{dep=...}، وضعیت breaker
هشدارروی issue تازه / نرخهشدار کسب‌وکاری اگر نرخ جهش کندروی نرخ سوختن SLO، breaker باز

راه درست: در Laravel level(PaymentUnavailable::class, LogLevel::WARNING)، throttle(...)، context(...)، dontReportDuplicates()؛ Sentry برای Laravel با Integration::handles($exceptions) داخل withExceptions ثبت می‌شود. در Go: slog در مرز با request id، path، status، code و زنجیرهٔ خطا. جزئیات: Observability.

تست مسیرهای خطا حیاتی ​

به زبان ساده: مسیرهای خطا همان کدی‌اند که وسط حادثه اجرا می‌شوند، پس بیشتر از مسیر خوش به تست نیاز دارند. خرابی را عمداً بسازید (تزریق خطا، fault injection) و روی نوع خطا و اثرهای جانبی assert کنید.

بدفهمی رایج: «روی پیام خطا assert کن.» پیام برای انسان است و عوض می‌شود؛ با errors.Is/errors.As یا expectException(Type::class) assert کنید، و اثرهای جانبی را هم (پول دو بار کم نشده، دقیقاً یک خط لاگ، موجودی تغییر نکرده).

تعریف: تست table-driven برای هر حالت خرابی یک سطر دارد (عادت Go، و #[DataProvider] در PHPUnit)؛ تزریق خطا (fault injection) یک وابستگی را با نسخه‌ای جایگزین می‌کند که طبق برنامه شکست می‌خورد (httptest.Server با فهرست خرابی‌ها، Http::fake در Laravel با Http::sequence()->pushStatus(503) و Http::failedConnection())؛ زمان قطعی ساعت، sleep و منبع تصادف را تزریق می‌کند؛ Chaos Engineering همین کار را در محیط شبیه production انجام می‌دهد.

text
     Row                         Inject                         Assert
1    503 then ok                 sequence 503, 200              ch_1, 2 requests, same Idempotency-Key
2    declined                    402                            PaymentDeclined, 1 request, breaker untouched
3    our bug                     400                            RequestException surfaces, not hidden as "unavailable"
4    outage                      503 forever                    PaymentUnavailable, 3 requests
5    breaker open                503 x2 calls                   3rd call sends 0 requests

راه درست: تست‌های Go در errtypes، layers و resilience (با go test -race ./...)؛ در Laravel PaymentGatewayTest.php با Http::fake، Http::assertSentCount و Http::assertSent روی هدر.

نگاه هر زبان و فریم‌ورک ​

زبان / فریم‌ورکخطای مورد انتظارباگپاک‌سازیابزار retry / breaker
Goمقدار error؛ errors.Is/As/AsType/Join، %wpanic؛ recover فقط در middlewaredeferفقط stdlib (این صفحه)، sony/gobreaker، cenkalti/backoff
PHP 8.4زیرکلاس‌های Exceptionزیرکلاس‌های Error؛ ErrorException برای warningfinallyداخلی ندارد
Laravel 13exception همراه report/render در withExceptions، ShouldntReport، abort()handler سراسری، Sentry/Flare/NightwatchDB::transaction، قفل‌هاHttp::retry، retry()، #[Tries]، #[Backoff]، retryUntil، ThrottlesExceptions، failed()
RustResult<T, E>، ?panic!Dropcrateها (پوشش داده نشده)
Javachecked و unchecked exceptionError، RuntimeExceptiontry-with-resourcesResilience4j
C# / .NETunchecked exceptionهمانusing / IDisposablePolly

سازوکار (Mechanics) ​

Go: درخت خطا مهم ​

fmt.Errorf با یک %w خطایی برمی‌گرداند که Unwrap() error آن مقدار پیچیده‌شده را می‌دهد؛ با چند %w (Go 1.20 به بعد) یا با errors.Join، نتیجه Unwrap() []error را پیاده می‌کند. errors.Is این درخت را عمق‌اول پیمایش می‌کند و با == یا متد سفارشی Is(error) bool مقایسه می‌کند؛ errors.As اولین مقداری را که به type هدف قابل‌انتساب است پیدا می‌کند؛ errors.AsType[E] (Go 1.26) همین کار را با generic انجام می‌دهد: "For most uses, prefer AsType." توجه: errors.Unwrap "does not unwrap errors returned by Join"؛ از errors.Is/As استفاده کنید یا Unwrap() []error را پیمایش کنید (همان کاری که FieldErrors می‌کند). snippetها از errors.As استفاده می‌کنند تا module با go 1.24 build شود.

PHP: باز شدن stack و آخرین خط‌های دفاع مهم ​

یک Throwable پرتاب‌شده "will unwind the call stack until it is caught by a catch block or the global scope is reached" و در مسیر هر finally را اجرا می‌کند. اگر گرفته نشود به handlerی می‌رود که با set_exception_handler() ثبت شده، "otherwise, the program is terminated with a fatal error"؛ و بعد از آن handler، "the script terminates once the handler returns". خطاهای fatal موتور (حافظه، زمان اجرا) throwable نیستند؛ register_shutdown_function همراه error_get_last() تنها قلاب است. Laravel همهٔ این‌ها را در HandleExceptions نصب می‌کند و throwableها را از مسیر report (channelهای لاگ، trackerها) و render (پاسخ) عبور می‌دهد.

Laravel: خط لولهٔ exception حیاتی ​

text
     throw / uncaught Throwable
1    report:  ShouldntReport / dontReport / dontReportWhen?  -> skip
2             dontReportDuplicates (same instance)            -> skip
3             throttle (Lottery / Limit)                      -> sample
4             $exceptions->report(fn (Type $e) ...) ->stop()? -> custom reporter, else log at level()
5             + context() of the exception + global context()
6    render:  exception's own render()  -> response?
7             $exceptions->render(fn (Type $e, Request $r))  -> first non-null wins
8             defaults: ValidationException -> 422 JSON / redirect; HttpException -> status page; else 500
9             respond(fn (Response $r))  -> last chance to change the response

APP_DEBUG در production باید false باشد: "If the value is set to true in production, you risk exposing sensitive configuration values to your application's end users."

مرجع خطا و status حیاتی ​

کجاخطامعنیRetry؟
Gocontext.DeadlineExceededdeadline گذشتهمان تلاش، اگر deadline فراخوان اجازه دهد
Gocontext.Canceledفراخوان منصرف شدنه
Gosql.ErrNoRowsسطری نیست؛ به not-found دامنه ترجمه کنیدنه
Go*url.Error / net.Error با Timeout()خرابی شبکهبله (idempotent)
Goio.EOFپایان عادی ورودی، خرابی نیست—
LaravelConnectionExceptiontimeout / DNS / رد اتصالبله
LaravelRequestException (->response->status())4xx/5xx بعد از throw() یا retry تمام‌شده5xx/429 بله، 4xx نه
LaravelValidationException422 با خطاهانه
LaravelModelNotFoundExceptionبه 404 تبدیل می‌شودنه
LaravelAuthorizationException / AuthenticationException403 / 401نه
LaravelQueryException با SQLSTATE 40001، 40P01، MySQL 1213شکست serialization / deadlockبله، کل تراکنش
LaravelMaxAttemptsExceededException، TimeoutExceededException (نام کلاس از سورس فریم‌ورک، نه صفحهٔ مستندات)تلاش یا زمان job تمام شدنه؛ failed() اجرا می‌شود
HTTP408، 429، 502، 503، 504گذرابله، Retry-After را رعایت کنید

تنظیم‌هایی که باید بشناسید تکمیلی ​

تنظیمپیش‌فرضتوصیه
Http::timeout / connectTimeout در Laravel30 ثانیه / 10 ثانیهاز p99 پایین‌دست؛ اتصال 1 ثانیه، کل 2 تا 5 ثانیه
--tries صف Laravel1 تلاشبرای هر job #[Tries] یا retryUntil() بگذارید
--backoff در Laravel0 (فوری)#[Backoff([10, 30, 60])]
#[Timeout] روی job60 ثانیهکمتر از retry_after اتصال (پیش‌فرض 90)
پیام RequestExceptionکوتاه‌شده تا 120 کاراکترtruncateAt() / dontTruncate()
http.Client.Timeout در Go0 (هیچ)همیشه بگذارید، یا همیشه ctx با deadline پاس بدهید
آستانهٔ breaker / زمان باز—۵ شکست یا ۵۰٪ روی حداقل ۲۰ فراخوانی؛ ۱۰ تا ۶۰ ثانیه باز
تعداد retry—جمعاً ۳ در یک لایه؛ یک بودجه برای هر پروسه

Go ​

قبل ​

پنج عادت در یک فایل: log-and-return در repository، مقایسهٔ رشته‌ای روی "no rows"، نشت پیام driver به کلاینت، خطای encode بلعیده‌شده، و panic برای یک قاعدهٔ کسب‌وکار.

go
// Package before shows four error-handling habits that compile, pass review
// on a busy day, and hurt in production. Compare with the layers package.
package before

import (
	"database/sql"
	"encoding/json"
	"errors"
	"log"
	"net/http"
	"strings"
)

type Order struct {
	ID     string `json:"id"`
	Status string `json:"status"`
}

type Repo struct{ DB *sql.DB }

// Find logs AND returns the error: the same failure is logged again by every
// caller up the stack (log-and-rethrow), with no context about which order.
func (r *Repo) Find(id string) (Order, error) {
	var o Order
	err := r.DB.QueryRow(`SELECT id, status FROM orders WHERE id = $1`, id).Scan(&o.ID, &o.Status)
	if err != nil {
		log.Printf("error: %v", err)
		return Order{}, err // leaks sql.ErrNoRows into the domain and the HTTP layer
	}
	return o, nil
}

type Handler struct{ Repo *Repo }

func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	o, err := h.Repo.Find(r.PathValue("id"))
	if err != nil {
		log.Printf("handler error: %v", err) // logged a second time
		// String matching: breaks when the driver changes its message.
		if strings.Contains(err.Error(), "no rows") {
			http.Error(w, err.Error(), http.StatusNotFound)
			return
		}
		// Leaks internals (driver text, SQL) to the client, and every failure is a 500.
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	// Swallowed error: if encoding fails, nobody will ever know.
	_ = json.NewEncoder(w).Encode(o)
}

// Cancel uses a panic for an expected business outcome (control flow by panic).
func Cancel(o *Order) {
	if o.Status == "shipped" {
		panic(errors.New("cannot cancel a shipped order"))
	}
	o.Status = "cancelled"
}

بعد ​

شکل‌های خطا و تست table-driven آن‌ها:

go
// Package errtypes shows the shapes a Go error can take: sentinel, typed,
// wrapped and joined, plus a stable machine-readable code for the boundary.
package errtypes

import (
	"errors"
	"fmt"
	"strings"
)

// Sentinel errors: the identity of the value is the contract.
// Callers compare with errors.Is, never with == or by string.
var (
	ErrNotFound          = errors.New("not found")
	ErrInsufficientFunds = errors.New("insufficient funds")
	ErrConflict          = errors.New("conflict")
)

// FieldError is a typed error: callers read its fields with errors.As.
type FieldError struct {
	Field string
	Rule  string
}

func (e *FieldError) Error() string { return e.Field + ": " + e.Rule }

// ValidateOrder reports every problem at once with errors.Join.
// It returns nil when there is nothing to report.
func ValidateOrder(sku string, qty int) error {
	var errs []error
	if strings.TrimSpace(sku) == "" {
		errs = append(errs, &FieldError{Field: "sku", Rule: "required"})
	}
	if qty < 1 {
		errs = append(errs, &FieldError{Field: "qty", Rule: "must be >= 1"})
	}
	return errors.Join(errs...)
}

// Wallet is a tiny aggregate with one invariant: the balance never goes negative.
type Wallet struct {
	ID           string
	BalanceCents int64
}

// Debit returns an expected domain error, wrapped with context, when funds are short.
// A non-positive amount is a programmer bug (the caller should have validated),
// so it panics instead of returning an error: fail fast.
func (w *Wallet) Debit(amount int64) error {
	if amount <= 0 {
		panic(fmt.Sprintf("errtypes: Debit called with non-positive amount %d", amount))
	}
	if w.BalanceCents < amount {
		return fmt.Errorf("wallet %s: debit %d with balance %d: %w",
			w.ID, amount, w.BalanceCents, ErrInsufficientFunds)
	}
	w.BalanceCents -= amount
	return nil
}

// Code maps any error to a stable code. Only the boundary (HTTP, CLI, job runner)
// calls it; inner layers keep returning rich errors.
func Code(err error) string {
	var fe *FieldError
	switch {
	case err == nil:
		return ""
	case errors.As(err, &fe):
		return "validation_failed"
	case errors.Is(err, ErrNotFound):
		return "not_found"
	case errors.Is(err, ErrInsufficientFunds):
		return "insufficient_funds"
	case errors.Is(err, ErrConflict):
		return "conflict"
	default:
		return "internal"
	}
}

// FieldErrors walks the whole error tree (single and multi Unwrap)
// and collects every *FieldError, e.g. to build a 422 response body.
func FieldErrors(err error) []*FieldError {
	if err == nil {
		return nil
	}
	if fe, ok := err.(*FieldError); ok {
		return []*FieldError{fe}
	}
	switch u := err.(type) {
	case interface{ Unwrap() []error }:
		var out []*FieldError
		for _, e := range u.Unwrap() {
			out = append(out, FieldErrors(e)...)
		}
		return out
	case interface{ Unwrap() error }:
		return FieldErrors(u.Unwrap())
	}
	return nil
}
go
package errtypes

import (
	"errors"
	"fmt"
	"testing"
)

// Table-driven error tests: one row per error path, asserting identity, not text.
func TestCode(t *testing.T) {
	wallet := &Wallet{ID: "w1", BalanceCents: 100}
	tests := []struct {
		name       string
		err        error
		wantCode   string
		wantFields int
	}{
		{"no error", nil, "", 0},
		{"two invalid fields joined", ValidateOrder("", 0), "validation_failed", 2},
		{"one invalid field", ValidateOrder("SKU-1", 0), "validation_failed", 1},
		{"domain error wrapped with context", wallet.Debit(500), "insufficient_funds", 0},
		{"sentinel wrapped twice", fmt.Errorf("service: %w", fmt.Errorf("repo: %w", ErrNotFound)), "not_found", 0},
		{"%v hides the sentinel on purpose", fmt.Errorf("repo: %v", ErrNotFound), "internal", 0},
		{"unknown error", errors.New("boom"), "internal", 0},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if got := Code(tt.err); got != tt.wantCode {
				t.Fatalf("Code() = %q, want %q (err: %v)", got, tt.wantCode, tt.err)
			}
			if got := len(FieldErrors(tt.err)); got != tt.wantFields {
				t.Fatalf("FieldErrors() = %d, want %d", got, tt.wantFields)
			}
		})
	}
}

func TestDebitPanicsOnProgrammerError(t *testing.T) {
	defer func() {
		if recover() == nil {
			t.Fatal("expected a panic for a non-positive amount")
		}
	}()
	(&Wallet{ID: "w1", BalanceCents: 100}).Debit(0)
}

func TestDebitKeepsInvariantOnError(t *testing.T) {
	w := &Wallet{ID: "w1", BalanceCents: 100}
	err := w.Debit(150)
	if !errors.Is(err, ErrInsufficientFunds) {
		t.Fatalf("want ErrInsufficientFunds, got %v", err)
	}
	if w.BalanceCents != 100 {
		t.Fatalf("balance changed on a failed debit: %d", w.BalanceCents)
	}
}

لایه‌ها: repository ترجمه می‌کند، service تصمیم می‌گیرد، handler یک بار log می‌کند و problem details می‌نویسد؛ Recoverer یک panic را برای همان یک درخواست به 500 تبدیل می‌کند.

go
// Package layers shows where errors are created, translated and handled:
// repository (infrastructure) -> service (domain) -> HTTP boundary.
// Each layer adds context or translates; only the boundary logs and responds.
package layers

import (
	"context"
	"database/sql"
	"encoding/json"
	"errors"
	"fmt"
	"log/slog"
	"net/http"
	"runtime/debug"
	"strconv"
	"time"
)

// ---------- domain errors (owned by the service layer) ----------

var (
	ErrOrderNotFound    = errors.New("order not found")
	ErrStoreUnavailable = errors.New("order store unavailable")
)

// StateError is a typed domain error: a rule of the order life cycle was broken.
type StateError struct {
	OrderID string
	From    string
	Action  string
}

func (e *StateError) Error() string {
	return fmt.Sprintf("order %s: cannot %s an order that is %s", e.OrderID, e.Action, e.From)
}

type Order struct {
	ID     string
	Status string
}

// ---------- repository: translate driver errors into domain errors ----------

// QueryFunc stands in for a database/sql or pgx call so the example runs without a database.
type QueryFunc func(ctx context.Context, id string) (Order, error)

type Repo struct{ Query QueryFunc }

func (r *Repo) Find(ctx context.Context, id string) (Order, error) {
	o, err := r.Query(ctx, id)
	switch {
	case err == nil:
		return o, nil
	case errors.Is(err, sql.ErrNoRows):
		// Translate: callers depend on ErrOrderNotFound, not on database/sql.
		return Order{}, fmt.Errorf("find order %s: %w", id, ErrOrderNotFound)
	default:
		// Wrap the domain-level sentinel; keep the driver text for logs only (%v, not %w),
		// so the driver error does not become part of this package's API.
		return Order{}, fmt.Errorf("find order %s: %w: %v", id, ErrStoreUnavailable, err)
	}
}

// ---------- service: business rules, no HTTP, no logging ----------

type Service struct{ Repo *Repo }

func (s *Service) Cancel(ctx context.Context, id string) (Order, error) {
	o, err := s.Repo.Find(ctx, id)
	if err != nil {
		return Order{}, fmt.Errorf("cancel: %w", err) // add context, do not log
	}
	if o.Status == "shipped" {
		return Order{}, &StateError{OrderID: id, From: o.Status, Action: "cancel"}
	}
	o.Status = "cancelled"
	return o, nil
}

// ---------- HTTP boundary: handle once (log + respond) ----------

// Problem is an RFC 9457 problem details object.
type Problem struct {
	Type     string `json:"type"`
	Title    string `json:"title"`
	Status   int    `json:"status"`
	Detail   string `json:"detail,omitempty"`
	Instance string `json:"instance,omitempty"`
	Code     string `json:"code"` // extension member: stable machine code
}

type Handler struct {
	Svc *Service
	Log *slog.Logger
}

func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	o, err := h.Svc.Cancel(r.Context(), r.PathValue("id"))
	if err != nil {
		h.writeError(w, r, err)
		return
	}
	w.Header().Set("Content-Type", "application/json")
	if err := json.NewEncoder(w).Encode(map[string]string{"id": o.ID, "status": o.Status}); err != nil {
		h.Log.Warn("write response", "err", err) // the client went away; nothing else to do
	}
}

func (h *Handler) writeError(w http.ResponseWriter, r *http.Request, err error) {
	p := Problem{Instance: r.URL.Path}
	var se *StateError
	switch {
	case errors.Is(err, ErrOrderNotFound):
		p.Type, p.Title, p.Status, p.Code = "https://example.com/probs/order-not-found", "Order not found", 404, "order_not_found"
	case errors.As(err, &se):
		p.Type, p.Title, p.Status, p.Code = "https://example.com/probs/invalid-state", "Order state does not allow this", 409, "invalid_state"
		p.Detail = se.Error() // safe: written for humans, no internals
	case errors.Is(err, ErrStoreUnavailable):
		p.Type, p.Title, p.Status, p.Code = "https://example.com/probs/unavailable", "Temporarily unavailable", 503, "unavailable"
		w.Header().Set("Retry-After", strconv.Itoa(int((2 * time.Second).Seconds())))
	default:
		p.Type, p.Title, p.Status, p.Code = "about:blank", "Internal Server Error", 500, "internal"
	}
	// The single place this failure is logged, with the full chain and request context.
	level := slog.LevelInfo
	if p.Status >= 500 {
		level = slog.LevelError
	}
	h.Log.Log(r.Context(), level, "request failed", "path", r.URL.Path, "status", p.Status, "code", p.Code, "err", err)
	writeProblem(w, p)
}

func writeProblem(w http.ResponseWriter, p Problem) {
	w.Header().Set("Content-Type", "application/problem+json")
	w.WriteHeader(p.Status)
	_ = json.NewEncoder(w).Encode(p) // headers are sent; an encode error cannot be reported to the client
}

// Recoverer turns a panic (a bug) into a logged 500 for this request only.
// It does not "handle" the bug: the stack goes to logs and error tracking.
func Recoverer(log *slog.Logger, next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		defer func() {
			if v := recover(); v != nil {
				if v == http.ErrAbortHandler {
					panic(v) // net/http uses this panic to abort a response on purpose
				}
				log.Error("panic", "path", r.URL.Path, "panic", v, "stack", string(debug.Stack()))
				writeProblem(w, Problem{Type: "about:blank", Title: "Internal Server Error", Status: 500, Code: "internal"})
			}
		}()
		next.ServeHTTP(w, r)
	})
}
go
package layers

import (
	"bytes"
	"context"
	"database/sql"
	"encoding/json"
	"errors"
	"log/slog"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
)

func newServer(q QueryFunc, logs *bytes.Buffer) http.Handler {
	log := slog.New(slog.NewJSONHandler(logs, nil))
	mux := http.NewServeMux()
	mux.Handle("POST /orders/{id}/cancel", &Handler{Svc: &Service{Repo: &Repo{Query: q}}, Log: log})
	mux.HandleFunc("GET /boom", func(http.ResponseWriter, *http.Request) {
		var m map[string]int
		m["x"]++ // nil map write: a programmer bug
	})
	return Recoverer(log, mux)
}

func TestErrorPathsAcrossLayers(t *testing.T) {
	tests := []struct {
		name       string
		path       string
		query      QueryFunc
		wantStatus int
		wantCode   string
		leakCheck  string // text that must NOT reach the client
	}{
		{"ok", "/orders/1/cancel", func(context.Context, string) (Order, error) { return Order{ID: "1", Status: "paid"}, nil }, 200, "", ""},
		{"no rows -> 404", "/orders/2/cancel", func(context.Context, string) (Order, error) { return Order{}, sql.ErrNoRows }, 404, "order_not_found", "sql:"},
		{"domain rule -> 409", "/orders/3/cancel", func(context.Context, string) (Order, error) { return Order{ID: "3", Status: "shipped"}, nil }, 409, "invalid_state", ""},
		{"driver down -> 503", "/orders/4/cancel", func(context.Context, string) (Order, error) {
			return Order{}, errors.New("dial tcp 10.0.0.5:5432: connection refused")
		}, 503, "unavailable", "10.0.0.5"},
		{"panic -> 500", "/boom", nil, 500, "internal", "nil map"},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			var logs bytes.Buffer
			method := http.MethodPost
			if tt.path == "/boom" {
				method = http.MethodGet
			}
			rec := httptest.NewRecorder()
			newServer(tt.query, &logs).ServeHTTP(rec, httptest.NewRequest(method, tt.path, nil))
			if rec.Code != tt.wantStatus {
				t.Fatalf("status = %d, want %d; body %s", rec.Code, tt.wantStatus, rec.Body)
			}
			if tt.wantCode == "" {
				return
			}
			if ct := rec.Header().Get("Content-Type"); ct != "application/problem+json" {
				t.Fatalf("content-type = %q", ct)
			}
			var p Problem
			if err := json.Unmarshal(rec.Body.Bytes(), &p); err != nil || p.Code != tt.wantCode {
				t.Fatalf("problem = %+v, err = %v", p, err)
			}
			if tt.leakCheck != "" && strings.Contains(rec.Body.String(), tt.leakCheck) {
				t.Fatalf("internal detail %q leaked to the client: %s", tt.leakCheck, rec.Body)
			}
			if n := strings.Count(logs.String(), "\n"); n != 1 {
				t.Fatalf("want the failure logged exactly once, got %d lines", n)
			}
		})
	}
}

پاک‌سازی با defer:

go
// Package cleanup shows resource cleanup on every path with defer, including
// the error that Close itself can return, and a transaction that always ends.
package cleanup

import (
	"context"
	"database/sql"
	"errors"
	"fmt"
	"os"
)

// WriteReport never leaks the file handle and never loses the Close error:
// for a written file, Close is where a full disk is often reported.
func WriteReport(path string, lines []string) (err error) {
	f, err := os.Create(path)
	if err != nil {
		return fmt.Errorf("write report: %w", err)
	}
	defer func() {
		err = errors.Join(err, f.Close()) // keep both the write error and the close error
	}()
	for _, l := range lines {
		if _, err := fmt.Fprintln(f, l); err != nil {
			return fmt.Errorf("write report %s: %w", path, err)
		}
	}
	return nil
}

// InTx runs fn in a transaction. Any error or panic rolls back; a panic is
// re-raised after the rollback because it is a bug, not an outcome.
func InTx(ctx context.Context, db *sql.DB, fn func(*sql.Tx) error) (err error) {
	tx, err := db.BeginTx(ctx, nil)
	if err != nil {
		return fmt.Errorf("begin: %w", err)
	}
	defer func() {
		if p := recover(); p != nil {
			_ = tx.Rollback()
			panic(p)
		}
		if err != nil {
			if rbErr := tx.Rollback(); rbErr != nil && !errors.Is(rbErr, sql.ErrTxDone) {
				err = errors.Join(err, fmt.Errorf("rollback: %w", rbErr))
			}
			return
		}
		if cerr := tx.Commit(); cerr != nil {
			err = fmt.Errorf("commit: %w", cerr) // commit can fail too (serialization, lost connection)
		}
	}()
	return fn(tx)
}

الگوهای پایداری، فقط با کتابخانهٔ استاندارد:

go
// Package resilience implements the stability patterns on this page with the
// standard library only: retry with backoff and full jitter, a circuit breaker
// and a bulkhead. Clocks, sleeps and randomness are injectable for tests.
package resilience

import (
	"context"
	"errors"
	"fmt"
	"math/rand/v2"
	"time"
)

// Retryable is implemented by errors that know whether a new attempt can succeed
// (for example a 503 or a 429 from an HTTP API).
type Retryable interface{ Retryable() bool }

// IsTransient is the default classification: per-attempt timeouts and errors that
// say they are retryable. Everything else (validation, 4xx, domain rules, an open
// breaker) is permanent: retrying cannot change the answer.
func IsTransient(err error) bool {
	if errors.Is(err, ErrOpen) || errors.Is(err, ErrBulkheadFull) {
		return false
	}
	if errors.Is(err, context.DeadlineExceeded) {
		return true
	}
	var r Retryable
	return errors.As(err, &r) && r.Retryable()
}

type Policy struct {
	MaxAttempts int           // total attempts, including the first
	Base        time.Duration // first backoff ceiling
	Cap         time.Duration // maximum backoff ceiling
	Rand        func() float64
	Sleep       func(ctx context.Context, d time.Duration) error
	Retryable   func(error) bool
	OnRetry     func(attempt int, wait time.Duration, err error)
}

// Backoff is "full jitter": a random wait in [0, min(Cap, Base*2^(attempt-1))).
func (p Policy) Backoff(attempt int) time.Duration {
	ceiling := p.Base << (attempt - 1)
	if ceiling > p.Cap || ceiling <= 0 {
		ceiling = p.Cap
	}
	r := rand.Float64
	if p.Rand != nil {
		r = p.Rand
	}
	return time.Duration(r() * float64(ceiling))
}

// SleepCtx waits for d or until ctx is done, whichever comes first.
func SleepCtx(ctx context.Context, d time.Duration) error {
	t := time.NewTimer(d)
	defer t.Stop()
	select {
	case <-ctx.Done():
		return ctx.Err()
	case <-t.C:
		return nil
	}
}

// Do runs op until it succeeds, fails permanently, runs out of attempts, or the
// caller's deadline cannot fit another wait. Retry in ONE layer only.
func Do[T any](ctx context.Context, p Policy, op func(ctx context.Context, attempt int) (T, error)) (T, error) {
	var zero T
	retryable, sleep := p.Retryable, p.Sleep
	if retryable == nil {
		retryable = IsTransient
	}
	if sleep == nil {
		sleep = SleepCtx
	}
	for attempt := 1; ; attempt++ {
		v, err := op(ctx, attempt)
		if err == nil {
			return v, nil
		}
		if ctx.Err() != nil {
			return zero, fmt.Errorf("attempt %d: %w", attempt, errors.Join(err, ctx.Err()))
		}
		if !retryable(err) {
			return zero, err // permanent: return as is, the caller decides
		}
		if attempt >= p.MaxAttempts {
			return zero, fmt.Errorf("gave up after %d attempts: %w", attempt, err)
		}
		wait := p.Backoff(attempt)
		if dl, ok := ctx.Deadline(); ok && time.Until(dl) < wait {
			return zero, fmt.Errorf("deadline leaves no room for attempt %d: %w", attempt+1, err)
		}
		if p.OnRetry != nil {
			p.OnRetry(attempt, wait, err)
		}
		if serr := sleep(ctx, wait); serr != nil {
			return zero, errors.Join(err, serr)
		}
	}
}
go
package resilience

import (
	"errors"
	"sync"
	"time"
)

// ErrOpen is returned without calling the dependency while the breaker is open.
var ErrOpen = errors.New("circuit breaker is open")

type State int

const (
	Closed State = iota
	Open
	HalfOpen
)

func (s State) String() string {
	return [...]string{"closed", "open", "half-open"}[s]
}

// Breaker is a consecutive-failure circuit breaker (Nygard, Release It!).
// Closed: calls pass, failures are counted. Open: calls fail fast with ErrOpen.
// Half-open: after OpenFor, a limited number of trial calls decide the next state.
type Breaker struct {
	Threshold      int           // consecutive failures that trip the breaker
	OpenFor        time.Duration // how long to stay open before a trial
	HalfOpenProbes int           // concurrent trial calls allowed in half-open
	Now            func() time.Time
	IsFailure      func(error) bool // which errors count; 4xx and domain errors should not
	OnStateChange  func(from, to State)

	mu       sync.Mutex
	state    State
	failures int
	openedAt time.Time
	inFlight int
}

func (b *Breaker) now() time.Time {
	if b.Now != nil {
		return b.Now()
	}
	return time.Now()
}

func (b *Breaker) setState(to State) {
	from := b.state
	b.state, b.failures, b.inFlight = to, 0, 0
	if to == Open {
		b.openedAt = b.now()
	}
	if b.OnStateChange != nil && from != to {
		b.OnStateChange(from, to)
	}
}

// State reports the current state, moving open -> half-open when OpenFor has passed.
func (b *Breaker) State() State {
	b.mu.Lock()
	defer b.mu.Unlock()
	if b.state == Open && b.now().Sub(b.openedAt) >= b.OpenFor {
		b.setState(HalfOpen)
	}
	return b.state
}

func (b *Breaker) allow() error {
	b.mu.Lock()
	defer b.mu.Unlock()
	if b.state == Open && b.now().Sub(b.openedAt) >= b.OpenFor {
		b.setState(HalfOpen)
	}
	switch b.state {
	case Open:
		return ErrOpen
	case HalfOpen:
		limit := max(b.HalfOpenProbes, 1)
		if b.inFlight >= limit {
			return ErrOpen
		}
		b.inFlight++
	}
	return nil
}

func (b *Breaker) record(err error) {
	b.mu.Lock()
	defer b.mu.Unlock()
	failed := err != nil
	if failed && b.IsFailure != nil {
		failed = b.IsFailure(err)
	}
	switch b.state {
	case HalfOpen:
		if failed {
			b.setState(Open)
		} else {
			b.setState(Closed)
		}
	case Closed:
		if !failed {
			b.failures = 0
			return
		}
		b.failures++
		if b.failures >= b.Threshold {
			b.setState(Open)
		}
	}
}

// Call runs fn through the breaker.
func Call[T any](b *Breaker, fn func() (T, error)) (T, error) {
	var zero T
	if err := b.allow(); err != nil {
		return zero, err
	}
	v, err := fn()
	b.record(err)
	return v, err
}
go
package resilience

import (
	"context"
	"errors"
	"time"
)

// ErrBulkheadFull means the compartment for this dependency is saturated.
// Rejecting fast keeps the caller's goroutines, sockets and memory free for
// work that does not need the slow dependency.
var ErrBulkheadFull = errors.New("bulkhead full")

// Bulkhead caps concurrent calls to one dependency with a semaphore.
type Bulkhead struct{ slots chan struct{} }

func NewBulkhead(maxConcurrent int) *Bulkhead {
	return &Bulkhead{slots: make(chan struct{}, maxConcurrent)}
}

// Do waits at most maxWait for a slot, then runs fn.
func (b *Bulkhead) Do(ctx context.Context, maxWait time.Duration, fn func(context.Context) error) error {
	t := time.NewTimer(maxWait)
	defer t.Stop()
	select {
	case b.slots <- struct{}{}:
	case <-t.C:
		return ErrBulkheadFull
	case <-ctx.Done():
		return ctx.Err()
	}
	defer func() { <-b.slots }()
	return fn(ctx)
}
go
package resilience

import (
	"context"
	"errors"
	"fmt"
	"sync"
	"testing"
	"time"
)

type statusErr int

func (s statusErr) Error() string   { return fmt.Sprintf("http status %d", int(s)) }
func (s statusErr) Retryable() bool { return s == 429 || s >= 500 }

func noSleep(context.Context, time.Duration) error { return nil }

func TestRetryClassification(t *testing.T) {
	tests := []struct {
		name         string
		failures     []error // errors returned by attempts 1..n, then success
		wantAttempts int
		wantErr      bool
	}{
		{"succeeds first time", nil, 1, false},
		{"503 then success", []error{statusErr(503)}, 2, false},
		{"timeout twice then success", []error{context.DeadlineExceeded, context.DeadlineExceeded}, 3, false},
		{"422 is permanent", []error{statusErr(422)}, 1, true},
		{"open breaker is not retried", []error{ErrOpen}, 1, true},
		{"gives up after max attempts", []error{statusErr(503), statusErr(503), statusErr(503), statusErr(503)}, 3, true},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			p := Policy{MaxAttempts: 3, Base: 10 * time.Millisecond, Cap: time.Second, Sleep: noSleep}
			calls := 0
			_, err := Do(context.Background(), p, func(context.Context, int) (string, error) {
				calls++
				if calls <= len(tt.failures) {
					return "", tt.failures[calls-1]
				}
				return "ok", nil
			})
			if calls != tt.wantAttempts || (err != nil) != tt.wantErr {
				t.Fatalf("attempts = %d (want %d), err = %v (want error: %v)", calls, tt.wantAttempts, err, tt.wantErr)
			}
		})
	}
}

func TestFullJitterStaysUnderCeiling(t *testing.T) {
	p := Policy{Base: 100 * time.Millisecond, Cap: time.Second, Rand: func() float64 { return 0.999999 }}
	for attempt, ceiling := range map[int]time.Duration{1: 100 * time.Millisecond, 2: 200 * time.Millisecond, 4: 800 * time.Millisecond, 10: time.Second} {
		if got := p.Backoff(attempt); got >= ceiling || got < ceiling*99/100 {
			t.Fatalf("attempt %d: backoff %v, ceiling %v", attempt, got, ceiling)
		}
	}
}

func TestRetryRespectsDeadline(t *testing.T) {
	ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
	defer cancel()
	p := Policy{MaxAttempts: 10, Base: time.Second, Cap: time.Second, Rand: func() float64 { return 0.5 }}
	calls := 0
	_, err := Do(ctx, p, func(context.Context, int) (int, error) { calls++; return 0, statusErr(503) })
	if calls != 1 || err == nil {
		t.Fatalf("a 500ms wait cannot fit a 20ms deadline: calls = %d, err = %v", calls, err)
	}
}

func TestBreakerStateMachine(t *testing.T) {
	now := time.Unix(0, 0)
	var transitions []string
	b := &Breaker{
		Threshold: 3, OpenFor: 10 * time.Second, HalfOpenProbes: 1,
		Now:           func() time.Time { return now },
		IsFailure:     func(err error) bool { return !errors.Is(err, errDeclined) },
		OnStateChange: func(from, to State) { transitions = append(transitions, from.String()+"->"+to.String()) },
	}
	fail := func() (int, error) { return 0, statusErr(503) }
	ok := func() (int, error) { return 1, nil }
	declined := func() (int, error) { return 0, errDeclined }

	for range 5 {
		_, _ = Call(b, declined) // business errors never trip the breaker
	}
	for range 3 {
		_, _ = Call(b, fail)
	}
	if _, err := Call(b, ok); !errors.Is(err, ErrOpen) {
		t.Fatalf("want fail-fast ErrOpen while open, got %v", err)
	}
	now = now.Add(10 * time.Second) // open -> half-open
	_, _ = Call(b, fail)            // trial fails -> open again
	now = now.Add(10 * time.Second)
	if _, err := Call(b, ok); err != nil { // trial succeeds -> closed
		t.Fatal(err)
	}
	want := []string{"closed->open", "open->half-open", "half-open->open", "open->half-open", "half-open->closed"}
	if len(transitions) != len(want) {
		t.Fatalf("transitions = %v, want %v", transitions, want)
	}
	for i := range want {
		if transitions[i] != want[i] {
			t.Fatalf("transitions = %v, want %v", transitions, want)
		}
	}
}

var errDeclined = errors.New("card declined")

func TestBulkheadRejectsWhenFull(t *testing.T) {
	b := NewBulkhead(2)
	release := make(chan struct{})
	var wg sync.WaitGroup
	for range 2 {
		wg.Add(1)
		go func() {
			defer wg.Done()
			_ = b.Do(context.Background(), time.Second, func(context.Context) error { <-release; return nil })
		}()
	}
	time.Sleep(20 * time.Millisecond) // let both goroutines take a slot
	err := b.Do(context.Background(), 10*time.Millisecond, func(context.Context) error { return nil })
	close(release)
	wg.Wait()
	if !errors.Is(err, ErrBulkheadFull) {
		t.Fatalf("want ErrBulkheadFull, got %v", err)
	}
}

نگاه Go ​

  • بررسی کن، یک بار بپیچ، یک بار مدیریت کن. هر لایه یک پیشوند اضافه می‌کند ("cancel: %w")؛ فقط مرز log می‌کند. linterهایی مثل errcheck و errorlint (در golangci-lint) خطاهای نادیده‌گرفته و مقایسهٔ == روی خطای پیچیده‌شده را پیدا می‌کنند.
  • %w در برابر %v یک تصمیم API است. چیزی را بپیچید که فراخوان‌ها ممکن است به آن تکیه کنند؛ بقیه را format کنید.
  • Context همه‌جا. ctx اولین پارامتر هر چیزی است که I/O انجام می‌دهد؛ context.WithTimeout برای هر تلاش، context.WithTimeoutCause وقتی علت سفارشی می‌خواهید؛ context را هرگز در struct نگه ندارید.
  • panic داخل می‌ماند. recover فقط در middleware HTTP و wrapperهای goroutine؛ کتابخانه خطا برمی‌گرداند.
  • sentinel را در هر فراخوانی تازه نسازید. sentinelها متغیرهای سطح package هستند؛ ساختن نمونهٔ تازه در هر فراخوانی errors.Is را می‌شکند.
  • اکوسیستم. golang.org/x/sync/errgroup (اولین خطا گروه را لغو می‌کند)، sony/gobreaker، cenkalti/backoff، log/slog برای لاگ ساختاریافته، net/http/httptest برای fakeهایی که خطا تزریق می‌کنند.

Laravel ​

قبل ​

controllerی بدون timeout، بدون کلید idempotency، با مقایسهٔ رشته‌ای روی بدنه، با catch-allی که باگ‌ها را پنهان و پیام‌ها را افشا می‌کند، و حلقه‌ای که خرابی‌ها را می‌بلعد.

php
<?php

// app/Http/Controllers/CheckoutController.php — the habits this page removes.
namespace App\Http\Controllers;

use App\Models\Order;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Throwable;

class CheckoutController extends Controller
{
    public function store(int $orderId): JsonResponse
    {
        try {
            $order = Order::find($orderId);

            // No timeout: the default HTTP client timeout is 30 seconds, so one slow
            // provider can hold every PHP-FPM worker for 30 seconds.
            // No idempotency key: a retry after a lost response charges twice.
            $response = Http::post('https://payments.example/charges', [
                'amount' => $order->total_cents, // null order -> Error, caught below as if it were a payment problem
            ]);

            if (str_contains($response->body(), 'declined')) { // string matching on a body
                return response()->json(['error' => 'declined'], 400);
            }

            $order->update(['status' => 'paid', 'charge_id' => $response->json('id')]);

            return response()->json($order);
        } catch (Throwable $e) {
            // Catches bugs (TypeError, Error) and outages alike, logs, then...
            Log::error($e->getMessage());

            // ...leaks the internal message to the client, always as a 500.
            // The global handler will not report it, so Sentry never sees the bug.
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }

    public function retryAll(): void
    {
        foreach (Order::where('status', 'pending')->get() as $order) {
            try {
                $this->store($order->id);
            } catch (Throwable) {
                // Swallowed: the loop "succeeds" and nobody learns that half the orders failed.
            }
        }
    }
}

بعد ​

سلسله‌مراتب و helper مربوط به problem details:

php
<?php

// app/Exceptions/Problem.php — one helper that renders RFC 9457 problem details.
namespace App\Exceptions;

use Illuminate\Http\JsonResponse;

final class Problem
{
    /**
     * @param  array<string, mixed>  $extensions
     * @param  array<string, string>  $headers
     */
    public static function response(
        string $type,
        string $title,
        int $status,
        ?string $detail = null,
        ?string $instance = null,
        array $extensions = [],
        array $headers = [],
    ): JsonResponse {
        $body = array_filter(
            ['type' => $type, 'title' => $title, 'status' => $status, 'detail' => $detail, 'instance' => $instance],
            fn ($value) => $value !== null,
        ) + $extensions;

        return response()->json($body, $status, ['Content-Type' => 'application/problem+json'] + $headers);
    }
}

// app/Exceptions/BusinessException.php — base class for EXPECTED domain outcomes.
// They are part of the API (stable type URI + code), are not bugs, and are never
// reported to the error tracker (ShouldntReport).
namespace App\Exceptions;

use Exception;
use Illuminate\Contracts\Debug\ShouldntReport;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

abstract class BusinessException extends Exception implements ShouldntReport
{
    abstract public function code(): string;   // stable machine code, e.g. "invalid_state"

    abstract public function status(): int;    // HTTP status at the boundary

    abstract public function title(): string;  // short, human, constant per type

    public function toProblem(Request $request): JsonResponse
    {
        return Problem::response(
            type: 'https://example.com/probs/'.str_replace('_', '-', $this->code()),
            title: $this->title(),
            status: $this->status(),
            detail: $this->getMessage(),          // written for the client: no internals
            instance: '/'.$request->path(),
            extensions: ['code' => $this->code()],
        );
    }
}

namespace App\Exceptions;

final class OrderNotFound extends BusinessException
{
    public static function withId(int $id): self
    {
        return new self("Order {$id} does not exist.");
    }

    public function code(): string { return 'order_not_found'; }
    public function status(): int { return 404; }
    public function title(): string { return 'Order not found'; }
}

namespace App\Exceptions;

final class InvalidOrderState extends BusinessException
{
    public function __construct(public readonly int $orderId, public readonly string $from, string $action)
    {
        parent::__construct("Order {$orderId} is {$from} and cannot be {$action}.");
    }

    /** Extra fields for the log entry if this is ever reported (Laravel reads context()). */
    public function context(): array
    {
        return ['order_id' => $this->orderId, 'from' => $this->from];
    }

    public function code(): string { return 'invalid_state'; }
    public function status(): int { return 409; }
    public function title(): string { return 'Order state does not allow this'; }
}

namespace App\Exceptions;

final class PaymentDeclined extends BusinessException
{
    public function code(): string { return 'payment_declined'; }
    public function status(): int { return 422; }
    public function title(): string { return 'Payment declined'; }
}

// Infrastructure failures are NOT business exceptions: they are reported (at warning),
// they may be retried, and the client only sees a generic 503.
namespace App\Exceptions;

use RuntimeException;

class PaymentUnavailable extends RuntimeException {}

final class CircuitOpenException extends RuntimeException {}

تنها جای گزارش و render:

php
<?php

// bootstrap/app.php — the ONE place exceptions are reported and rendered (handle once).
use App\Exceptions\BusinessException;
use App\Exceptions\PaymentDeclined;
use App\Exceptions\PaymentUnavailable;
use App\Exceptions\Problem;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Psr\Log\LogLevel;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        api: __DIR__.'/../routes/api.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {
        //
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        // Reporting: who hears about what.
        $exceptions->context(fn () => ['request_id' => request()->header('X-Request-Id')]);
        $exceptions->level(PaymentUnavailable::class, LogLevel::WARNING);
        $exceptions->throttle(fn (Throwable $e) => $e instanceof PaymentUnavailable
            ? Limit::perMinute(60)            // an outage must not flood Sentry
            : Limit::none());
        $exceptions->dontReportDuplicates();

        // Queued jobs: a declined card will never succeed, so do not retry it.
        $exceptions->dontRetry([PaymentDeclined::class]);

        // Rendering: translate to RFC 9457 at the HTTP boundary. ONE predicate for every
        // callback, so a request the catch-all renders is never one the others skipped.
        $isApi = fn (Request $request): bool => $request->expectsJson() || $request->is('api/*');

        $exceptions->render(function (BusinessException $e, Request $request) use ($isApi) {
            return $isApi($request) ? $e->toProblem($request) : null;
        });

        $exceptions->render(function (ValidationException $e, Request $request) use ($isApi) {
            if (! $isApi($request)) {
                return null;
            }

            return Problem::response(
                type: 'https://example.com/probs/validation-failed',
                title: 'Your request is not valid.',
                status: 422,
                instance: '/'.$request->path(),
                extensions: ['code' => 'validation_failed', 'errors' => $e->errors()],
            );
        });

        $exceptions->render(function (PaymentUnavailable $e, Request $request) use ($isApi) {
            return $isApi($request)
                ? Problem::response('https://example.com/probs/unavailable', 'Temporarily unavailable', 503,
                    instance: '/'.$request->path(), extensions: ['code' => 'unavailable'], headers: ['Retry-After' => '30'])
                : null;
        });

        // Everything else on API routes: a generic problem, never the internal message.
        $exceptions->render(function (Throwable $e, Request $request) use ($isApi) {
            if (! $isApi($request) || config('app.debug')
                || $e instanceof HttpResponseException || $e instanceof AuthenticationException) {
                return null; // let Laravel's default rendering run
            }
            $status = $e instanceof HttpExceptionInterface ? $e->getStatusCode() : 500;

            return Problem::response('about:blank', Response::$statusTexts[$status] ?? 'Error', $status,
                instance: '/'.$request->path());
        });
    })->create();

circuit breaker، gatewayی که timeout و retry و breaker و کلید idempotency را اعمال می‌کند، و use case همراه job مربوط به fallback:

php
<?php

// app/Support/CircuitBreaker.php — a consecutive-failure breaker whose state lives in
// the cache (Redis in production), because PHP-FPM workers share no memory: a breaker
// held in a PHP variable would be forgotten at the end of every request.
namespace App\Support;

use App\Exceptions\CircuitOpenException;
use Closure;
use Illuminate\Support\Facades\Cache;
use Throwable;

final class CircuitBreaker
{
    public function __construct(
        private readonly string $name,
        private readonly int $threshold = 5,      // consecutive failures that trip it
        private readonly int $openSeconds = 30,   // open period before one trial call
    ) {}

    /**
     * @template T
     *
     * @param  Closure(): T  $call
     * @param  (Closure(Throwable): bool)|null  $isFailure  which exceptions count (not 4xx/domain)
     * @return T
     *
     * @throws CircuitOpenException
     */
    public function call(Closure $call, ?Closure $isFailure = null): mixed
    {
        if ($this->rejects()) {
            throw new CircuitOpenException("circuit {$this->name} is open");
        }

        try {
            $result = $call();
        } catch (Throwable $e) {
            if ($isFailure === null || $isFailure($e)) {
                $this->recordFailure();
            } else {
                $this->recordSuccess(); // the dependency answered; it is healthy
            }
            throw $e;
        }

        $this->recordSuccess();

        return $result;
    }

    public function state(): string
    {
        $openUntil = Cache::get($this->key('open_until'));

        return match (true) {
            $openUntil === null => 'closed',
            now()->getTimestamp() < $openUntil => 'open',
            default => 'half-open',
        };
    }

    private function rejects(): bool
    {
        return match ($this->state()) {
            'closed' => false,
            'open' => true,
            // half-open: Cache::add is atomic, so exactly one caller wins the trial call
            'half-open' => ! Cache::add($this->key('probe'), true, $this->openSeconds),
        };
    }

    private function recordFailure(): void
    {
        Cache::add($this->key('failures'), 0, 60);
        $failures = Cache::increment($this->key('failures'));

        if ($this->state() === 'half-open' || $failures >= $this->threshold) {
            Cache::put($this->key('open_until'), now()->getTimestamp() + $this->openSeconds, $this->openSeconds * 10);
            Cache::forget($this->key('failures'));
            Cache::forget($this->key('probe'));
        }
    }

    private function recordSuccess(): void
    {
        Cache::forget($this->key('failures'));
        Cache::forget($this->key('open_until'));
        Cache::forget($this->key('probe'));
    }

    private function key(string $suffix): string
    {
        return "circuit:{$this->name}:{$suffix}";
    }
}
php
<?php

// app/Payments/PaymentGateway.php — the ONLY class that knows the provider's HTTP API.
// It applies timeout + retry (full jitter) + circuit breaker + idempotency key, and
// translates transport errors into two domain-level outcomes: declined or unavailable.
namespace App\Payments;

use App\Exceptions\CircuitOpenException;
use App\Exceptions\PaymentDeclined;
use App\Exceptions\PaymentUnavailable;
use App\Support\CircuitBreaker;
use Exception;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Http;
use Throwable;

final class PaymentGateway
{
    public function __construct(
        private readonly CircuitBreaker $breaker,
        private readonly int $baseBackoffMs = 100,
        private readonly int $maxBackoffMs = 2000,
    ) {}

    /**
     * @throws PaymentDeclined     permanent: the customer must use another card
     * @throws PaymentUnavailable  transient: the caller may degrade or retry later
     */
    public function charge(string $idempotencyKey, int $amountCents): string
    {
        try {
            return $this->breaker->call(
                fn () => $this->send($idempotencyKey, $amountCents),
                isFailure: fn (Throwable $e) => self::isTransient($e), // 402/4xx never trip it
            );
        } catch (CircuitOpenException|ConnectionException $e) {
            throw new PaymentUnavailable('payment provider unreachable', previous: $e);
        } catch (RequestException $e) {
            if (! self::isTransient($e)) {
                throw $e; // any other 4xx is OUR bug (bad payload, bad token): report it, do not hide it
            }
            throw new PaymentUnavailable("payment provider answered {$e->response->status()}", previous: $e);
        }
    }

    /** Network errors, 5xx and 429 can succeed on a later attempt; nothing else can. */
    private static function isTransient(Throwable $e): bool
    {
        return $e instanceof ConnectionException
            || ($e instanceof RequestException && ($e->response->serverError() || $e->response->status() === 429));
    }

    private function send(string $idempotencyKey, int $amountCents): string
    {
        try {
            $response = Http::baseUrl(config('services.payments.url'))
                ->withToken(config('services.payments.key'))
                ->withHeaders(['Idempotency-Key' => $idempotencyKey]) // same key on every attempt
                ->acceptJson()
                ->connectTimeout(1)   // seconds to establish the connection
                ->timeout(3)          // seconds for the whole response
                ->retry(
                    3,
                    // full jitter: random wait in [0, min(cap, base * 2^attempt)]
                    fn (int $attempt, Exception $exception) => random_int(0, min($this->maxBackoffMs, $this->baseBackoffMs * 2 ** $attempt)),
                    // retry only what can succeed next time
                    fn (Throwable $e) => self::isTransient($e),
                )
                ->post('/charges', ['amount' => $amountCents, 'currency' => 'EUR']);
        } catch (RequestException $e) {
            if ($e->response->status() === 402) {
                throw new PaymentDeclined('The card was declined.', previous: $e);
            }
            throw $e;
        }

        return (string) $response->json('charge_id');
    }
}
php
<?php

// app/Actions/Checkout.php — the use case decides what a failure MEANS for the business.
namespace App\Actions;

use App\Exceptions\InvalidOrderState;
use App\Exceptions\PaymentDeclined;
use App\Exceptions\PaymentUnavailable;
use App\Jobs\ChargePendingPayment;
use App\Models\Order;
use App\Payments\PaymentGateway;
use Illuminate\Support\Facades\DB;

final class Checkout
{
    public function __construct(private readonly PaymentGateway $payments) {}

    public function __invoke(Order $order): Order
    {
        if ($order->status !== 'placed') {
            throw new InvalidOrderState($order->id, $order->status, 'paid'); // rendered as 409
        }

        $key = "order-{$order->id}-payment"; // derived from the order: stable across retries and jobs

        try {
            $chargeId = $this->payments->charge($key, $order->total_cents);
            $order->update(['status' => 'paid', 'charge_id' => $chargeId]);
        } catch (PaymentDeclined $e) {
            $order->update(['status' => 'payment_declined']);
            throw $e; // the boundary renders a 422 problem; not reported (ShouldntReport)
        } catch (PaymentUnavailable $e) {
            // Graceful degradation: accept the order, charge later with the SAME key.
            // afterCommit(): the job is pushed only if the status change commits. It is NOT
            // atomic with it (a crash between commit and push loses the job); use an outbox for that.
            DB::transaction(function () use ($order, $key) {
                $order->update(['status' => 'payment_pending']);
                ChargePendingPayment::dispatch($order->id, $key)->afterCommit();
            });
            report($e); // handled here, still visible in logs and Sentry
        }

        return $order;
    }
}

// app/Jobs/ChargePendingPayment.php — the asynchronous retry path with its own budget.
namespace App\Jobs;

use App\Models\Order;
use App\Payments\PaymentGateway;
use DateTime;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use App\Exceptions\PaymentDeclined;
use App\Exceptions\PaymentUnavailable;
use Illuminate\Queue\Attributes\Timeout;
use Illuminate\Queue\Middleware\FailOnException;
use Illuminate\Queue\Middleware\ThrottlesExceptions;
use Illuminate\Queue\Middleware\WithoutOverlapping;
use Throwable;

#[Timeout(20)]
final class ChargePendingPayment implements ShouldQueue
{
    use Queueable;

    public function __construct(public int $orderId, public string $idempotencyKey) {}

    /** @return array<int, object> */
    public function middleware(): array
    {
        return [
            // A declined card will never succeed: fail at once, failed() runs.
            new FailOnException([PaymentDeclined::class]),
            new WithoutOverlapping($this->orderId),
            // A queue-side breaker for provider outages only: after 5 exceptions, pause every
            // job in the 'payments-provider' bucket for 5 minutes; below the threshold, wait
            // 1 minute between attempts (without backoff() it would retry immediately).
            (new ThrottlesExceptions(5, 5 * 60))
                ->by('payments-provider')
                ->when(fn (Throwable $e) => $e instanceof PaymentUnavailable)
                ->backoff(1),
        ];
    }

    public function retryUntil(): DateTime
    {
        return now()->plus(hours: 2); // time budget instead of an attempt count
    }

    public function handle(PaymentGateway $payments): void
    {
        $order = Order::findOrFail($this->orderId);

        if ($order->status !== 'payment_pending') {
            return; // idempotent consumer: a duplicate delivery does nothing
        }

        // PaymentUnavailable: ThrottlesExceptions releases the job (spaced, budgeted by retryUntil).
        // PaymentDeclined: FailOnException fails the job at once and failed() runs.
        $chargeId = $payments->charge($this->idempotencyKey, $order->total_cents);
        $order->update(['status' => 'paid', 'charge_id' => $chargeId]);
    }

    public function failed(?Throwable $exception): void
    {
        // Budget exhausted or permanent error: compensate and tell a human.
        // The payload stays in failed_jobs (Laravel's dead-letter table) for queue:retry.
        Order::whereKey($this->orderId)->update(['status' => 'payment_failed']);
    }
}

idempotency برای endpointهای خودمان، پاک‌سازی، و تست تزریق خطا:

php
<?php

// app/Http/Middleware/EnsureIdempotency.php — makes OUR POST endpoints safe to retry.
// Same key + same payload -> the saved response is replayed; same key + different
// payload -> 422; a request with the same key still running -> 409.
namespace App\Http\Middleware;

use App\Exceptions\Problem;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Symfony\Component\HttpFoundation\Response;

final class EnsureIdempotency
{
    public function handle(Request $request, Closure $next): Response
    {
        $key = $request->header('Idempotency-Key');
        if ($key === null) {
            return Problem::response('https://example.com/probs/idempotency-key-required',
                'Idempotency-Key header is required', 400, instance: '/'.$request->path());
        }

        $scope = 'idem:'.($request->user()?->getAuthIdentifier() ?? 'guest').':'.$key;
        $fingerprint = hash('sha256', $request->method().' '.$request->path().' '.$request->getContent());

        if (is_array($saved = Cache::get($scope))) {
            if ($saved['fingerprint'] !== $fingerprint) {
                return Problem::response('https://example.com/probs/idempotency-key-reused',
                    'Idempotency-Key was used with a different request', 422, instance: '/'.$request->path());
            }

            return response($saved['body'], $saved['status'], $saved['headers'] + ['Idempotent-Replayed' => 'true']);
        }

        $lock = Cache::lock($scope.':lock', 30);
        if (! $lock->get()) {
            return Problem::response('https://example.com/probs/request-in-progress',
                'A request with this Idempotency-Key is still being processed', 409,
                instance: '/'.$request->path(), headers: ['Retry-After' => '1']);
        }

        try {
            // Re-check under the lock: a request that just finished may have saved the answer
            // between our first Cache::get and acquiring the lock.
            if (is_array($saved = Cache::get($scope)) && $saved['fingerprint'] === $fingerprint) {
                return response($saved['body'], $saved['status'], $saved['headers'] + ['Idempotent-Replayed' => 'true']);
            }

            $response = $next($request);

            // Save final answers only. A 5xx is not saved, so the client's retry runs again;
            // that is safe because the downstream calls carry their own idempotency keys.
            if ($response->getStatusCode() < 500) {
                Cache::put($scope, [
                    'fingerprint' => $fingerprint,
                    'status' => $response->getStatusCode(),
                    'headers' => ['Content-Type' => (string) $response->headers->get('Content-Type')],
                    'body' => $response->getContent(),
                ], now()->plus(hours: 24));
            }

            return $response;
        } finally {
            $lock->release(); // runs on success, on exception and on early return
        }
    }
}
php
<?php

// app/Reports/ReportWriter.php — cleanup on every path with finally.
namespace App\Reports;

use Illuminate\Support\Facades\DB;
use RuntimeException;

final class ReportWriter
{
    /** @param list<string> $lines */
    public function write(string $path, array $lines): void
    {
        $handle = fopen($path, 'wb');
        if ($handle === false) {
            throw new RuntimeException("cannot open {$path}"); // fopen returns false, it does not throw
        }

        try {
            foreach ($lines as $line) {
                if (fwrite($handle, $line.PHP_EOL) === false) {
                    throw new RuntimeException("cannot write {$path}");
                }
            }
        } finally {
            fclose($handle); // runs after return, after throw, after success
        }
    }

    public function moveStock(int $from, int $to, int $qty): void
    {
        // DB::transaction rolls back on ANY Throwable and rethrows it;
        // the second argument retries the whole closure on a deadlock.
        DB::transaction(function () use ($from, $to, $qty) {
            DB::table('stock')->where('warehouse_id', $from)->decrement('qty', $qty);
            DB::table('stock')->where('warehouse_id', $to)->increment('qty', $qty);
        }, attempts: 3);
    }
}

// Outside Laravel (a plain CLI script), the last lines of defence look like this.
// Laravel registers its own equivalents in Illuminate\Foundation\Bootstrap\HandleExceptions.
namespace Scripts;

set_exception_handler(function (\Throwable $e): void {
    // Uncaught Throwable: log it with the stack; the script ends after this handler returns.
    error_log(sprintf('uncaught %s: %s at %s:%d', $e::class, $e->getMessage(), $e->getFile(), $e->getLine()));
    exit(1);
});

register_shutdown_function(function (): void {
    // Fatal errors (out of memory, max execution time) are not Throwables: only this sees them.
    $error = error_get_last();
    if ($error !== null && in_array($error['type'], [E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR], true)) {
        error_log('fatal: '.$error['message']);
    }
});
php
<?php

// tests/Feature/PaymentGatewayTest.php — fault injection with Http::fake.
namespace Tests\Feature;

use App\Exceptions\PaymentDeclined;
use App\Exceptions\PaymentUnavailable;
use App\Payments\PaymentGateway;
use App\Support\CircuitBreaker;
use Illuminate\Http\Client\Request;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Http;
use PHPUnit\Framework\Attributes\DataProvider;
use Tests\TestCase;

class PaymentGatewayTest extends TestCase
{
    private function gateway(int $threshold = 5): PaymentGateway
    {
        config(['services.payments.url' => 'https://payments.test', 'cache.default' => 'array']);

        // baseBackoffMs = 0: random_int(0, 0) keeps the test fast and deterministic.
        return new PaymentGateway(new CircuitBreaker('payments', $threshold, 30), baseBackoffMs: 0);
    }

    /** One row per failure mode: what the provider does -> what the domain sees. */
    public static function faults(): array
    {
        return [
            '503 then ok' => [fn () => Http::sequence()->pushStatus(503)->push(['charge_id' => 'ch_1']), 'ch_1', null, 2],
            '429 then ok' => [fn () => Http::sequence()->pushStatus(429)->push(['charge_id' => 'ch_2']), 'ch_2', null, 2],
            'declined: no retry' => [fn () => Http::response(['error' => 'card_declined'], 402), null, PaymentDeclined::class, 1],
            'bad request: our bug, no retry' => [fn () => Http::response([], 400), null, RequestException::class, 1],
            'outage: 3 attempts' => [fn () => Http::response([], 503), null, PaymentUnavailable::class, 3],
            // null: we do not assert how many failed connections the fake records
            'connection refused' => [fn () => Http::failedConnection(), null, PaymentUnavailable::class, null],
        ];
    }

    #[DataProvider('faults')]
    public function test_failure_modes(callable $fake, ?string $chargeId, ?string $exception, ?int $attempts): void
    {
        Http::fake(['payments.test/*' => $fake()]);

        if ($exception !== null) {
            $this->expectException($exception);
        }

        try {
            $this->assertSame($chargeId, $this->gateway()->charge('order-1-payment', 4999));
        } finally {
            if ($attempts !== null) {
                Http::assertSentCount($attempts);
                Http::assertSent(fn (Request $r) => $r->hasHeader('Idempotency-Key', 'order-1-payment'));
            }
        }
    }

    public function test_breaker_opens_and_fails_fast(): void
    {
        Http::fake(['payments.test/*' => Http::response([], 503)]);
        $gateway = $this->gateway(threshold: 2);

        foreach (range(1, 2) as $_) {
            try {
                $gateway->charge('order-2-payment', 100);
            } catch (PaymentUnavailable) {
            }
        }
        Http::assertSentCount(6); // 2 logical calls x 3 attempts

        $this->expectException(PaymentUnavailable::class);
        try {
            $gateway->charge('order-3-payment', 100); // open: no request leaves the process
        } finally {
            Http::assertSentCount(6);
        }
    }
}

نگاه Laravel ​

  • withExceptions همان مرز است. report، render، level، dontReport، throttle، context، dontReportDuplicates، respond، و برای jobها dontRetry/dontRetryWhen، همه در bootstrap/app.php.
  • exception می‌تواند خودش را render کند. متد render(Request $request) روی exception (برگرداندن false به رفتار پیش‌فرض برمی‌گردد) و report()؛ context() فیلدهای لاگ اضافه می‌کند.
  • report($e) در برابر throw. report() از مسیر handler لاگ می‌کند و می‌گذارد درخواست ادامه پیدا کند (مسیر fallback)؛ throw تصمیم را به مرز می‌سپارد؛ rescue() یعنی «امتحان کن، گزارش بده، مقدار پیش‌فرض برگردان».
  • abort(404) / abort_if یک HttpException پرتاب می‌کنند که handler آن را render می‌کند؛ در controller استفاده کنید، نه در کد دامنه.
  • کلاینت HTTP روی 4xx/5xx پرتاب نمی‌کند ("Unlike Guzzle's default behavior")؛ throw() را صدا بزنید، یا از retry() استفاده کنید که وقتی همهٔ تلاش‌ها شکست خوردند RequestException پرتاب می‌کند، مگر throw: false بدهید.
  • Jobها. #[Tries]، #[Backoff]، #[MaxExceptions]، #[Timeout]، #[FailOnTimeout]، retryUntil()/#[RetryFor]، failed(?Throwable $e)، ThrottlesExceptions، WithoutOverlapping، failed_jobs و queue:retry. "If both retryUntil and tries are defined, Laravel gives precedence to the retryUntil method."
  • PHP-FPM هیچ چیز مشترک ندارد. وضعیت breaker، بودجهٔ retry و رکوردهای idempotency باید در Redis یا دیتابیس باشند؛ زیر Octane، حالت درون‌حافظه‌ای برای هر worker جداست.

حل مسئله‌های کلاسیک ​

مسئلهراه‌حلچطورمزیتهزینه / محدودیت
طوفان retry وسط قطعیretry در یک لایه + jitter + بودجه + breakerresilience.Do، Http::retry با closure، breakerوابستگی فرصت بازیابی داردبعضی درخواست‌ها به‌جای انتظار شکست می‌خورند
کسر دوبارهٔ پول بعد از timeoutکلید idempotency برای هر عملیاتIdempotency-Key: order-{id}-paymentretry امن می‌شودذخیرهٔ کلید، TTL، اثرانگشت payload
workerهای گیرکردهtimeout + bulkheadctx برای هر تلاش، Http::timeout، queueهای جداخرابی محلی می‌ماندتنظیم بر اساس دادهٔ latency
باگ پنهان پشت «پرداخت ناموفق»خطای typed، بدون catch-allBusinessException در برابر Errorباگ به Sentry می‌رسدکلاس‌های بیشتر
نویز لاگ و هشداریک بار مدیریت، ShouldntReport، throttlewithExceptionsسیگنال بر نویزانضباط در code review
نشت جزئیات داخلی در پاسخRFC 9457 + APP_DEBUG=falseProblem::responseخطای امن و یکدستیک قالب دیگر برای مستندسازی
پیام سمی که بی‌نهایت retry می‌شودسقف تلاش + DLQ + failed()retryUntil، failed_jobs، topic DLQصف حرکت می‌کندکسی باید مالک DLQ باشد
کار نیمه‌تمام بین سرویس‌هاsaga با جبرانبازپرداخت وقتی گام بعدی شکست خوردنتیجهٔ سازگارنهایی، نه اتمیک
job برای سطری که rollback شدafterCommit() / outboxهمان تراکنشکار شبح‌وار نداریمrelay برای نگهداری (outbox)

طوفان retry ​

نشانه‌اش وابستگی‌ای است که چند ثانیه بهبود پیدا می‌کند و دوباره می‌افتد، در حالی که نرخ درخواست به آن چند برابر نرخ کاربران است. retry را از همهٔ لایه‌ها جز یکی حذف کنید (معمولاً کلاینتی که به وابستگی نزدیک‌تر است)، به full jitter بروید، یک بودجهٔ retry در سطح پروسه بگذارید، و breaker را جلو بگذارید تا circuit باز retry را کاملاً متوقف کند. آزمایشگاه نشان می‌دهد تلاش ۴ بعد از باز شدن breaker به‌صورت محلی رد شد.

کسر دوبارهٔ پول ​

نشانه‌اش دو کسر با فاصلهٔ چند صد میلی‌ثانیه برای یک سفارش است. راه درست یک کلید برای هر عملیات کسب‌وکار است که در هر تلاش، در مسیر fallback و در job ناهمگام دوباره استفاده می‌شود؛ ارائه‌دهنده (یا EnsureIdempotency خودتان) نتیجهٔ اول را دوباره پخش می‌کند. سناریوی B' آزمایشگاه باگ را بازتولید می‌کند: ۲ کسر برای یک سفارش.

باگ‌های پنهان ​

نشانه‌اش نرخ خطایی است که هرگز به tracker نمی‌رسد. catch-allها را از کد کسب‌وکار حذف کنید، بگذارید Error و panic به مرز برسند، ShouldntReport را فقط برای business exceptionها نگه دارید، و تستی اضافه کنید که بررسی کند باگ به 500 با دقیقاً یک رکورد لاگ تبدیل می‌شود (تست layers در Go همین کار را می‌کند).

انتخاب ​

وضعیتتوصیهتکنیک اضافهدلیل
«نه»ی مورد انتظار کسب‌وکارخطای typed / business exception، 4xxcode پایدار، بدون هشدارنتیجه است، نه خرابی
باگ تشخیص داده شدfail-fast: panic / بگذارید Error بالا برودrecover فقط در لبهادامه روی وضعیت خراب بدتر است
خواندن از وابستگی ناپایدارtimeout + retry (idempotent) + breaker + fallback از cacheCache::flexible، برچسب کهنگیخواندن تکرارپذیر است
نوشتن در وابستگی ناپایدارtimeout + retry با کلید idempotency + breaker + ثبت برای بعدoutbox / afterCommittimeout یعنی نتیجهٔ نامعلوم
وابستگی کُند، نه خرابbulkhead + timeout تنگload shedding در بالادستاز ظرفیت محافظت می‌کند
job ناهمگام که API صدا می‌زندretryUntil + #[Backoff] + ThrottlesExceptionsfailed() + مالک DLQبودجهٔ زمانی، breaker سمت صف
چند مشکل اعتبارسنجیهمه را جمع کن، یک 422errors.Join، Form Requestیک رفت‌وبرگشت برای کاربر
گردش‌کار چندسرویسیsaga با جبرانگام‌های idempotentتراکنش توزیع‌شده نداریم
اضافه‌بارکار کم‌اولویت را رد کن، 503 + Retry-Afterاولویت‌هابخشی از کار به‌جای هیچ

در معماری: از یک پروسه تا سیستم توزیع‌شده ​

سؤال «چه کسی این خرابی را مدیریت می‌کند، و چطور؟» در هر اندازه‌ای یک جواب دارد: در مرزها ترجمه کن، یک بار در بیرونی‌ترین مرز مدیریت کن، و هر فراخوانی راه دور را چیزی بدان که می‌تواند شکست بخورد، کُند باشد، یا موفق شود بی‌آنکه خبرت کند.

Monolith (مونولیت): یک پروسه، یک دیتابیس ​

چطور دیده می‌شود: exception و error value داخل یک call stack، یک handler سراسری، یک تراکنش دیتابیس برای هر use case. خرابی‌ها بیشتر باگ، اعتبارسنجی و خطای دیتابیس‌اند.

ساده‌ترین استفادهٔ درست: درخت exception کم‌عمق، withExceptions (یا یک middleware در Go) به‌عنوان تنها جای log، DB::transaction برای اتمیک بودن، timeout روی چند فراخوانی بیرونی (پرداخت، ایمیل، نقشه).

مثال (ساده): یک وبلاگ: ValidationException به 422، ModelNotFoundException به 404، بقیه 500 و Sentry.

مثال (پیچیده): monolith یک فروشگاه که سرویس پرداخت را صدا می‌زند: PaymentGateway تنها کلاسی است که ارائه‌دهنده را می‌شناسد، به PaymentDeclined/PaymentUnavailable ترجمه می‌کند، و checkout به payment_pending و یک job صف‌شده عقب‌نشینی می‌کند.

Modular monolith و چند دیتابیس ​

چطور دیده می‌شود: ماژول‌ها داخل پروسه همدیگر را صدا می‌زنند، ولی هر ماژول مالک خطاهای خودش است. API عمومی هر ماژول خطاهای دامنهٔ خودش را عرضه می‌کند، نه خطای ماژول دیگر یا ORM را.

قاعده‌ها: در facade ماژول ترجمه کنید (ChargeOrder در Billing خطای Billing\PaymentDeclined پرتاب می‌کند، نه exception مربوط به Stripe را)؛ هیچ ماژولی typeهای exception داخلی ماژول دیگر را نگیرد (architecture test)؛ اگر ماژول‌ها دیتابیس جدا دارند، فراخوانی بین آن‌ها دیگر اتمیک نیست: حتی داخل پروسه از رویدادهای afterCommit یا outbox استفاده کنید.

Microservices (میکروسرویس): خطا از روی مرز شبکه ​

چه چیزی می‌ماند: خطاهای typed دامنه به قرارداد تبدیل می‌شوند: URIهای type و codeها در مشخصات API (OpenAPI) مستند و بین نسخه‌ها پایدارند. چه چیزی می‌شکند: exception از روی سیم رد نمی‌شود؛ stack trace نباید رد شود؛ timeout یعنی نتیجهٔ نامعلوم؛ retry در هر hop ضرب می‌شود.

text
     gateway -> orders -> payments -> bank
1    gateway: deadline 3s, no retries (clients retry with backoff)
2    orders:  per-call timeout 800ms, 1 retry layer, breaker on payments, Idempotency-Key per order
3    payments: retries the bank once with the SAME bank idempotency key; maps bank 5xx -> 503 problem
4    payments down: orders' breaker opens -> fallback "payment_pending" + outbox event ChargeRequested
5    later: payments consumes ChargeRequested at-least-once, dedups by key, publishes PaymentCaptured

مثال: checkout در فروشگاه میکروسرویسی: saga کسر پول، رزرو و ارسال را انجام می‌دهد؛ هر گام و هر جبران کلید دارد؛ خرابی‌هایی که retryشان ته کشیده در یک DLQ با تیم مالک می‌نشینند.

داده‌های توزیع‌شده: replica، cache و partition ​

جایی که مدیریت خطا عوض می‌شود: خواندن از replica عقب‌مانده دادهٔ کهنه برمی‌گرداند بدون هیچ خطایی؛ cache می‌تواند مقدار کهنه را به‌عنوان fallback بدهد (خوب) یا یک قطعی را تا پایان TTL پنهان کند (بد)؛ failover چند ثانیه نوشتن‌ها را به خطای اتصال تبدیل می‌کند (خطای گذرا را روی کل تراکنش retry کنید)؛ partition شبکه یعنی بعضی nodeها یک وابستگی را سالم می‌بینند و بعضی خراب (breakerهای هر instance با هم اختلاف دارند، و این اشکالی ندارد). Replication & Failover را ببینید.

پادزهرها: 40001/40P01/خطای failover را در سطح تراکنش retryپذیر بدانید، پاسخ‌های fallback را کهنه علامت بزنید، روی باز بودن breaker و رشد DLQ هشدار بگذارید، و برای partitionها آزمایش chaos اجرا کنید.

مسیر مقیاس‌پذیری: 1×، 10×، 100× ​

مقیاسساختارروش خطا و تحمل خرابی
1× (یک اپ، یک تیم)Monolithخطای typed، یک handler، timeout روی هر فراخوانی بیرونی، Sentry
10× (چند تیم، صف‌ها)Modular monolith + workerهاقرارداد problem details، کلید idempotency، retryUntil/failed() برای job، breaker برای هر ارائه‌دهنده، queueهای bulkhead
100× (سرویس‌های زیاد، چند region)Microservicesانتشار deadline، بودجهٔ retry، outlier detection در mesh، load shedding بر اساس اولویت، هشدار مبتنی بر SLO و error budget، game day

آزمایشگاه: سرویس سفارش در برابر API پرداخت ناپایدار ​

یک سرویس سفارش را در برابر یک ارائه‌دهندهٔ پرداخت جعلی اجرا می‌کنید که طبق برنامه خرابی تزریق می‌کند: یک 503، یک پاسخ کُند (ارائه‌دهنده پول را کسر می‌کند، کلاینت timeout می‌خورد)، همان پاسخ کُند بدون کلید idempotency، یک کارت ردشده، یک قطعی کامل، و بازیابی. همه‌چیز آفلاین اجرا می‌شود.

آماده‌سازی.

bash
cd docs/snippets/design/error-handling-fault-tolerance/go
gofmt -l . && go vet ./... && go test -race ./...   # all clean, all ok
go run ./lab
go
// Command lab runs an order service against a flaky payment API and injects
// faults: 503s, a slow response, a declined card and a full outage. The client
// uses a per-attempt timeout, retries with full jitter, a circuit breaker,
// an idempotency key and a fallback (queue the payment for later).
package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"math/rand/v2"
	"net/http"
	"net/http/httptest"
	"strings"
	"sync"
	"time"

	"academy/error-handling-fault-tolerance/resilience"
)

// ---------- fake payment provider with a fault schedule ----------

type provider struct {
	mu       sync.Mutex
	schedule []string          // next faults: "ok", "503", "slow", "402"
	requests int               // every HTTP request that arrived
	charges  map[string]string // idempotency key -> charge id
	created  int               // charges actually created (money moved)
}

func (p *provider) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	p.mu.Lock()
	p.requests++
	fault := "ok"
	if len(p.schedule) > 0 {
		fault, p.schedule = p.schedule[0], p.schedule[1:]
	}
	p.mu.Unlock()

	switch fault {
	case "503":
		w.Header().Set("Retry-After", "1")
		http.Error(w, `{"error":"unavailable"}`, http.StatusServiceUnavailable)
		return
	case "402":
		w.WriteHeader(http.StatusPaymentRequired)
		_, _ = w.Write([]byte(`{"error":"card_declined"}`))
		return
	}
	id := p.charge(r.Header.Get("Idempotency-Key")) // the work is done...
	if fault == "slow" {
		time.Sleep(250 * time.Millisecond) // ...but the answer arrives after the client gave up
	}
	_ = json.NewEncoder(w).Encode(map[string]string{"charge_id": id})
}

func (p *provider) charge(key string) string {
	p.mu.Lock()
	defer p.mu.Unlock()
	if id, ok := p.charges[key]; ok && key != "" {
		return id // replay: same key, same result, no second charge
	}
	p.created++
	id := fmt.Sprintf("ch_%d", p.created)
	if key != "" {
		p.charges[key] = id
	}
	return id
}

// ---------- payment client: timeout + retry + breaker ----------

var ErrDeclined = errors.New("card declined")

type StatusError struct{ Code int }

func (e *StatusError) Error() string   { return fmt.Sprintf("payment api: http %d", e.Code) }
func (e *StatusError) Retryable() bool { return e.Code == 408 || e.Code == 429 || e.Code >= 500 }

type PaymentClient struct {
	URL            string
	HTTP           *http.Client
	Breaker        *resilience.Breaker
	Retry          resilience.Policy
	AttemptTimeout time.Duration
	SendKey        bool
}

func (c *PaymentClient) Charge(ctx context.Context, key string, cents int64) (string, error) {
	return resilience.Do(ctx, c.Retry, func(ctx context.Context, attempt int) (string, error) {
		id, err := resilience.Call(c.Breaker, func() (string, error) {
			actx, cancel := context.WithTimeout(ctx, c.AttemptTimeout)
			defer cancel()
			return c.once(actx, key, cents)
		})
		fmt.Printf("    attempt %d: %s\n", attempt, outcome(id, err))
		return id, err
	})
}

func (c *PaymentClient) once(ctx context.Context, key string, cents int64) (string, error) {
	body := strings.NewReader(fmt.Sprintf(`{"amount":%d,"currency":"EUR"}`, cents))
	req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.URL+"/charges", body)
	if err != nil {
		return "", err
	}
	if c.SendKey {
		req.Header.Set("Idempotency-Key", key)
	}
	resp, err := c.HTTP.Do(req)
	if err != nil {
		return "", fmt.Errorf("payment api: %w", err) // *url.Error unwraps to context.DeadlineExceeded
	}
	defer resp.Body.Close()
	switch {
	case resp.StatusCode == http.StatusPaymentRequired:
		return "", ErrDeclined
	case resp.StatusCode >= 400:
		return "", &StatusError{Code: resp.StatusCode}
	}
	var out struct {
		ChargeID string `json:"charge_id"`
	}
	if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
		return "", fmt.Errorf("payment api: decode: %w", err)
	}
	return out.ChargeID, nil
}

func outcome(id string, err error) string {
	switch {
	case err == nil:
		return "ok " + id
	case errors.Is(err, resilience.ErrOpen):
		return "rejected locally: circuit open (no request sent)"
	case errors.Is(err, context.DeadlineExceeded):
		return "timeout after 100ms"
	default:
		return err.Error()
	}
}

// ---------- order service: classify the final error, degrade gracefully ----------

type OrderService struct {
	Pay     *PaymentClient
	Pending []string // payments to retry later with the SAME key (fallback)
}

func (s *OrderService) Checkout(orderID string, cents int64) string {
	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
	defer cancel()
	id, err := s.Pay.Charge(ctx, "order-"+orderID+"-payment", cents)
	switch {
	case err == nil:
		return "paid " + id
	case errors.Is(err, ErrDeclined):
		return "rejected: card declined (permanent, not retried)"
	default:
		s.Pending = append(s.Pending, orderID)
		return "payment_pending: accepted, will charge later (" + short(err) + ")"
	}
}

func short(err error) string {
	if errors.Is(err, resilience.ErrOpen) {
		return "circuit open"
	}
	return "retries exhausted"
}

func main() {
	p := &provider{charges: map[string]string{}}
	srv := httptest.NewServer(p)
	defer srv.Close()

	now := time.Unix(0, 0) // the breaker's clock; advanced by hand below
	rng := rand.New(rand.NewPCG(42, 1))
	breaker := &resilience.Breaker{
		Threshold: 3, OpenFor: 30 * time.Second, HalfOpenProbes: 1,
		Now:       func() time.Time { return now },
		IsFailure: func(err error) bool { return !errors.Is(err, ErrDeclined) },
		OnStateChange: func(from, to resilience.State) {
			fmt.Printf("    breaker: %s -> %s\n", from, to)
		},
	}
	client := &PaymentClient{
		URL: srv.URL, HTTP: &http.Client{}, Breaker: breaker, AttemptTimeout: 100 * time.Millisecond, SendKey: true,
		Retry: resilience.Policy{
			MaxAttempts: 4, Base: 20 * time.Millisecond, Cap: 200 * time.Millisecond, Rand: rng.Float64,
			OnRetry: func(attempt int, wait time.Duration, err error) {
				fmt.Printf("    backoff before attempt %d: %dms\n", attempt+1, wait.Milliseconds())
			},
		},
	}
	orders := &OrderService{Pay: client}

	run := func(title, orderID string, faults ...string) {
		p.mu.Lock()
		p.schedule = faults
		p.mu.Unlock()
		fmt.Printf("%s\n", title)
		fmt.Printf("  => order %s: %s\n", orderID, orders.Checkout(orderID, 4999))
		p.mu.Lock()
		fmt.Printf("  provider so far: %d requests, %d charges\n", p.requests, p.created)
		p.mu.Unlock()
	}

	run("A. one 503, then healthy", "1001", "503")
	run("B. slow response: provider charged, client timed out, retry with same key", "1002", "slow")
	client.SendKey = false
	run("B'. same fault WITHOUT an idempotency key", "1003", "slow")
	client.SendKey = true
	run("C. card declined (402)", "1004", "402")
	run("D. outage: every call returns 503", "1005", "503", "503", "503", "503", "503")
	run("E. still down, breaker open", "1006", "503", "503")

	now = now.Add(31 * time.Second)
	fmt.Println("F. 31s later, provider healthy: drain the pending queue with the same keys")
	p.mu.Lock()
	p.schedule = nil
	p.mu.Unlock()
	pending := orders.Pending
	orders.Pending = nil
	for _, id := range pending {
		fmt.Printf("  => order %s: %s\n", id, orders.Checkout(id, 4999))
	}

	time.Sleep(300 * time.Millisecond) // let the slow handlers finish before counting
	p.mu.Lock()
	defer p.mu.Unlock()
	fmt.Printf("provider: %d requests received, %d charges created, breaker %s\n", p.requests, p.created, breaker.State())
}

خروجی واقعی (قطعی است: منبع jitter با seed ثابت ساخته شده و ساعت breaker دستی جلو برده می‌شود):

text
A. one 503, then healthy
    attempt 1: payment api: http 503
    backoff before attempt 2: 16ms
    attempt 2: ok ch_1
  => order 1001: paid ch_1
  provider so far: 2 requests, 1 charges
B. slow response: provider charged, client timed out, retry with same key
    attempt 1: timeout after 100ms
    backoff before attempt 2: 1ms
    attempt 2: ok ch_2
  => order 1002: paid ch_2
  provider so far: 4 requests, 2 charges
B'. same fault WITHOUT an idempotency key
    attempt 1: timeout after 100ms
    backoff before attempt 2: 6ms
    attempt 2: ok ch_4
  => order 1003: paid ch_4
  provider so far: 6 requests, 4 charges
C. card declined (402)
    attempt 1: card declined
  => order 1004: rejected: card declined (permanent, not retried)
  provider so far: 7 requests, 4 charges
D. outage: every call returns 503
    attempt 1: payment api: http 503
    backoff before attempt 2: 17ms
    attempt 2: payment api: http 503
    backoff before attempt 3: 4ms
    breaker: closed -> open
    attempt 3: payment api: http 503
    backoff before attempt 4: 76ms
    attempt 4: rejected locally: circuit open (no request sent)
  => order 1005: payment_pending: accepted, will charge later (circuit open)
  provider so far: 10 requests, 4 charges
E. still down, breaker open
    attempt 1: rejected locally: circuit open (no request sent)
  => order 1006: payment_pending: accepted, will charge later (circuit open)
  provider so far: 10 requests, 4 charges
F. 31s later, provider healthy: drain the pending queue with the same keys
    breaker: open -> half-open
    breaker: half-open -> closed
    attempt 1: ok ch_5
  => order 1005: paid ch_5
    attempt 1: ok ch_6
  => order 1006: paid ch_6
provider: 12 requests received, 6 charges created, breaker closed

گام ۱: سناریوها را بخوانید. A: یک 503 گذرا برای کاربر نامرئی است. B: timeout یک نتیجهٔ نامعلوم بود؛ retry با همان کلید همان ch_2 را می‌گیرد، یک کسر. B': همان خرابی بدون کلید برای یک سفارش ch_3 و ch_4 می‌سازد: کسر دوباره. C: یک 402 نتیجهٔ دامنه است: یک تلاش، و breaker آن را نمی‌شمارد. D: سومین 503 breaker را قطع می‌کند، پس تلاش ۴ هرگز از پروسه بیرون نمی‌رود؛ سفارش به payment_pending تنزل پیدا می‌کند. E: fail-fast، صفر درخواست. F: بعد از دورهٔ باز، یک فراخوانی آزمایشی breaker را می‌بندد و صف با کلیدهای اصلی خالی می‌شود.

گام ۲: دسته‌بندی را خراب کنید. در lab/main.go مقدار IsFailure را nil کنید (هر خطایی حساب می‌شود). دوباره اجرا کنید (ما اجرا کردیم): کارت ردشده در C حالا به آستانه اضافه می‌شود، پس در D breaker بعد از تلاش ۲ باز می‌شود نه تلاش ۳، و D به‌جای ۳ درخواست ۲ درخواست می‌فرستد (provider so far: 9 requests). برگردانیدش.

گام ۳: یک لایهٔ retry دوم (اول روی کاغذ). اگر OrderService.Checkout فراخوانی Charge را در یک resilience.Do دیگر با ۳ تلاش می‌پیچید و breaker وجود نداشت، یک سفارش در D می‌توانست به‌جای ۴ درخواست، 3 × 4 = 12 درخواست به ارائه‌دهنده بفرستد: همان ضرب کتاب SRE. با وجود breaker، لایهٔ داخلی ErrOpen برمی‌گرداند که IsTransient آن را دائمی می‌داند، پس لایهٔ بیرونی زود می‌ایستد: یک دلیل دیگر برای retryناپذیر نگه داشتن ErrOpen و retry فقط در یک لایه.

گام ۴: jitter را بردارید. Rand: rng.Float64 را با Rand: func() float64 { return 1 } عوض کنید و rng := ... را به _ = ... تغییر دهید. دوباره اجرا کنید (ما اجرا کردیم): هر انتظار برابر کل سقف می‌شود، 20، 40، 80 میلی‌ثانیه، برای همهٔ کلاینت‌ها یکسان: retryهای هم‌زمان.

گام ۵: Laravel. فایل‌های PaymentGateway.php، CircuitBreaker.php و PaymentGatewayTest.php را در یک اپ Laravel 13 کپی کنید و php artisan test --filter=PaymentGatewayTest را اجرا کنید. خروجی مورد انتظار (اینجا اجرا نشده؛ روی ماشینی که این صفحه را نوشت PHP نصب نیست):

text
   PASS  Tests\Feature\PaymentGatewayTest
  ✓ failure modes with data set "503 then ok"
  ✓ failure modes with data set "429 then ok"
  ✓ failure modes with data set "declined: no retry"
  ✓ failure modes with data set "bad request: our bug, no retry"
  ✓ failure modes with data set "outage: 3 attempts"
  ✓ failure modes with data set "connection refused"
  ✓ breaker opens and fails fast

بدفهمی‌های رایج ​

باورواقعیت
گرفتن Throwable همه‌جا اپ را مقاوم می‌کندباگ‌ها (TypeError، Error) را پشت پیام‌های دوستانه پنهان می‌کند
timeout یعنی عملیات شکست خوردیعنی نتیجه نامعلوم است؛ فقط idempotency retry را امن می‌کند
retry بیشتر یعنی اطمینان بیشترretry در چند لایه بار را ضرب می‌کند و طوفان retry می‌سازد
هر خطا باید همان جا که رخ داده log شودیک بار در مرز log کنید؛ لایه‌های داخلی زمینه اضافه می‌کنند
پیچیدن با %w همیشه خوب استwrapping علت را بخشی از API شما می‌کند
خطاهای کسب‌وکار باید on-call را خبر کنندنتیجه‌اند؛ بشمارید، page نکنید
circuit breaker وابستگی را درست می‌کندزود شکست می‌دهد و به وابستگی فرصت می‌دهد؛ هنوز fallback لازم دارید
پاسخ‌های 4xx باید breaker را قطع کنندفقط 5xx، timeout و خطای اتصال نشانهٔ ناسالم بودن وابستگی‌اند
recover همان catch در Go استفقط برای بیرونی‌ترین لبه؛ کتابخانه‌ها خطا برمی‌گردانند
finally فقط وقتی چیزی خراب شود اجرا می‌شوددر همهٔ مسیرها اجرا می‌شود
لایهٔ انتقال می‌تواند تحویل exactly-once را تضمین کنداثر exactly-once از at-least-once + پردازش idempotent ساخته می‌شود
پیام exception را برگردان تا کلاینت debug کندproblem details رابط HTTP را توصیف می‌کند، نه جزئیات داخلی را
null check تدافعی همه‌جا بی‌خطر استباگ را به نتیجهٔ غلط بی‌صدا تبدیل می‌کند؛ در لبه اعتبارسنجی، داخل assert

چکیده ​

موضوعبه خاطر بسپارید
دسته‌بندیباگ ← fail-fast؛ دامنه ← خطای typed، 4xx؛ زیرساخت ← گذرا (retry) یا دائمی (هشدار)
شکل‌ها در Gosentinel + errors.Is؛ typed + errors.As/AsType؛ %w می‌پیچد، %v پنهان می‌کند؛ errors.Join برای چندتا
شکل‌ها در PHPError = باگ، Exception = قابل‌بازیابی؛ یک پایهٔ BusinessException با code()
یک بار مدیریتترجمه در adapter، تصمیم در service، log و پاسخ در مرز
مرز در LaravelwithExceptions: report، render، level، dontReport، throttle، context، dontRetry
Timeoutهمیشه صریح؛ برای هر تلاش داخل deadline فراخوان؛ پیش‌فرض Go هیچ، Laravel 30 ثانیه
Retryفقط گذرا، یک لایه، exponential backoff + full jitter، بودجه، رعایت Retry-After
Idempotencyیک کلید برای هر عملیات کسب‌وکار، در retry و fallback و job دوباره استفاده می‌شود
Circuit breakerبسته ← باز با رسیدن به آستانه ← half-open بعد از timeout ← آزمایش تصمیم می‌گیرد؛ فقط 5xx/timeout حساب می‌شود
Bulkheadpool/queue جدا برای هر وابستگی
تنزلfallback تصمیم محصول است؛ بار کم‌اولویت را با 503 + Retry-After رد کنید
خطای APIRFC 9457 با application/problem+json: type، title، status، detail، instance، code
پاک‌سازیdefer + join خطای Close؛ finally؛ فراخوانی HTTP داخل تراکنش دیتابیس نه
تستtable-driven، تزریق خطا (httptest، Http::fake)، assert روی نوع و اثر جانبی

خودآزمایی: پرسش و پاسخ ​

نمایش:
  • حیاتی تقریباً در هر مصاحبه پرسیده می‌شود
  • مهم پرتکرار؛ در سطح senior انتظار می‌رود
  • تکمیلی عمق بیشتر؛ تمایز ایجاد می‌کند

۱ — یک action در Laravel Throwable را می‌گیرد، log می‌کند و null برمی‌گرداند. دو مشکل مشخص نام ببرید. حیاتی ​

پاسخ

پاسخ: باگ‌ها (TypeError، Error) را که باید به tracker برسند پنهان می‌کند، و فراخوان نمی‌تواند نبودِ نتیجه را از شکست تشخیص دهد، پس خرابی ناپدید می‌شود. فقط business exception یا exception زیرساختی‌ای را بگیرید که از پسش برمی‌آیید؛ بگذارید بقیه به مرز برسند.

۲ — repository شما fmt.Errorf("find: %w", err) برمی‌گرداند که err از pgx است. همین الان چه قولی به فراخوان‌ها دادید؟ مهم ​

پاسخ

پاسخ: اینکه خطاهای pgx بخشی از API شماست: فراخوان‌ها حالا می‌توانند با errors.As به *pgconn.PgError برسند و شما بدون شکستن آن‌ها نمی‌توانید driver را عوض کنید. به sentinel دامنه (ErrOrderNotFound، ErrStoreUnavailable) ترجمه کنید و متن driver را با %v نگه دارید. طراحی typeهای خطا را ببینید.

۳ — فراخوانی پرداخت timeout خورد. retry امن است؟ حیاتی ​

پاسخ

پاسخ: فقط اگر درخواست کلید idempotencyای داشته باشد که ارائه‌دهنده رعایتش کند. timeout نتیجهٔ نامعلوم است: شاید پول کسر شده باشد. سناریوی B' آزمایشگاه کسر دوباره بدون کلید را نشان می‌دهد.

۴ — سه لایه هر کدام ۳ بار retry می‌کنند (۴ تلاش). یک عمل کاربر در پایین‌ترین لایه حداکثر چند تلاش می‌سازد؟ حیاتی ​

پاسخ

پاسخ: 4 × 4 × 4 = 64، مثال کتاب SRE. فقط در یک لایه retry کنید و بودجه بگذارید.

۵ — کدام خطاها باید circuit breaker یک API پرداخت را قطع کنند؟ مهم ​

پاسخ

پاسخ: timeout، خطای اتصال و 5xx (و شاید 429). هرگز 402/4xx یا خطای دامنه: هیچ چیزی دربارهٔ سلامت ارائه‌دهنده نمی‌گویند.

۶ — فرق fail-fast و fail-safe چیست؟ برای هر کدام یک مثال بزنید. حیاتی ​

پاسخ

پاسخ: fail-fast زود تشخیص می‌دهد و می‌ایستد (panic روی سفارش nil؛ رد فوری وقتی breaker باز است). fail-safe وضعیت بی‌خطر باقی می‌گذارد (rollback تراکنش؛ رد دسترسی وقتی سرویس مجوز از کار افتاده).

۷ — چرا circuit breaker در PHP وضعیتش را در Redis نگه می‌دارد نه در یک property ایستا؟ مهم ​

پاسخ

پاسخ: workerهای PHP-FPM حافظهٔ مشترک ندارند و بعد از هر درخواست همه‌چیز را فراموش می‌کنند، پس property ایستا هر بار صفر می‌شود. زیر Octane هم برای هر worker جدا می‌بود.

۸ — handler HTTP شما در Go یک go sendEmail() راه می‌اندازد که panic می‌کند. middleware Recoverer سرور را نجات می‌دهد؟ مهم ​

پاسخ

پاسخ: نه. recover فقط در همان goroutineی کار می‌کند که panic کرده؛ panic در goroutine بدون recover پروسه را تمام می‌کند. داخل همان goroutine recover کنید یا از errgroup استفاده کنید. Panic را ببینید.

۹ — در پاسخ RFC 9457 برای قطعی دیتابیس چه چیزی می‌آید و چه چیزی نباید بیاید؟ مهم ​

پاسخ

پاسخ: status 503، یک type مثل .../unavailable، یک title کوتاه، instance، یک code و هدر Retry-After. نه پیام driver، نه نام hostها، نه SQL، نه stack trace.

۱۰ — یک job صف‌شده یک API ناپایدار را صدا می‌زند. کدام قابلیت‌های Laravel به آن بودجهٔ زمانی، retry با فاصله، breaker سمت صف و dead letter می‌دهند؟ مهم ​

پاسخ

پاسخ: retryUntil() (یا #[RetryFor])، #[Backoff([...])]، middleware ThrottlesExceptions، و failed() همراه جدول failed_jobs؛ و dontRetry() برای خطاهای دائمی.

۱۱ — چرا فراخوانی HTTP بیرونی نباید داخل DB::transaction اجرا شود؟ حیاتی ​

پاسخ

پاسخ: تراکنش در تمام مدت فراخوانی قفل‌ها را نگه می‌دارد (وسط حادثه چند ثانیه)، و rollback نمی‌تواند اثر جانبی سمت دیگر را برگرداند. بیرون فراخوانی کنید، بعد نتیجه را ثبت کنید؛ برای کار بعدی afterCommit() یا outbox.

واژه‌نامه ​

اصطلاحمعنی
باگ برنامه‌نویس (Programmer bug)وضعیتی که نویسنده پیش‌بینی نکرده؛ fail-fast و اصلاح
خطای دامنه (Domain error / expected error)نتیجهٔ مستندشدهٔ کسب‌وکار مثل «رد شد» یا «پیدا نشد»
خرابی زیرساخت (Infrastructure failure)خرابی I/O یا جزء دیگر؛ گذرا یا دائمی
خطای گذرا (Transient error)ممکن است با retry بعدی موفق شود (timeout، 503، 429، deadlock)
قابل‌بازیابی و غیرقابل‌بازیابی (Recoverable vs unrecoverable)شکاف Rust و PHP: Result/Exception در برابر panic!/Error
خطای نگهبان (Sentinel error)مقدار خطای سطح package که با errors.Is مقایسه می‌شود
خطای typed (Typed error)type خطا با فیلد، که با errors.As/errors.AsType بررسی می‌شود
پیچیدن (Wrapping، %w، Unwrap)افزودن زمینه با حفظ علت قابل‌بررسی؛ آن را API می‌کند
errors.Joinچند خطا را با Unwrap() []error یکی می‌کند
کد خطا (Error code)شناسهٔ پایدار ماشین‌خوان در مرز
Throwableinterface پایهٔ PHP برای Error و Exception
ErrorExceptionexception در PHP برای تبدیل خطاهای diagnostic به throwable
Checked exceptionexceptionی که کامپایلر فراخوان را مجبور به مدیریت یا اعلامش می‌کند (Java)
Result<T, E>type در Rust که یا مقدار دارد یا خطا
یک بار مدیریت (Handle once)log و پاسخ در یک جا، بیرونی‌ترین مرز
Log and rethrowضدالگو: log کردن و بالا فرستادن همان خطا
بلعیدن (Swallowing)گرفتن خطا و هیچ کاری با آن نکردن
ناوردا (Invariant)قاعده‌ای که شیء همیشه حفظ می‌کند؛ شکستنش خطای دامنه یا باگ است
Assertionبررسی‌ای که فقط وقتی کد باگ دارد شکست می‌خورد
Fail-fastبا اولین نشانهٔ مشکل بایست (در Nygard: زود رد کن)
Fail-safeدر وضعیت بی‌خطر شکست بخور (رد، rollback)
برنامه‌نویسی تدافعی (Defensive programming)نگهبانی در برابر وضعیت‌های ناممکن؛ محدود، چون باگ را پنهان می‌کند
panic / recoverباز کردن stack در Go برای باگ و گرفتنش فقط در لبه
defer / finally / RAIIپاک‌سازی‌ای که در همهٔ مسیرها اجرا می‌شود
Timeout / deadlineسقف زمان یک عملیات / زمان مطلق کل درخواست
انتشار deadline (Deadline propagation)پاس دادن deadline فراخوان به همهٔ فراخوانی‌های پایین‌دست
Exponential backoffصبر طولانی‌تر بعد از هر شکست
Full jitterانتظار تصادفی در [0, ceiling) برای ناهم‌زمان کردن کلاینت‌ها
طوفان retry (Retry storm)تشدید بار از retry در لایه‌ها یا کلاینت‌های زیاد
بودجهٔ retry (Retry budget)سقف retry برای هر پروسه یا بازهٔ زمانی
کلید idempotency (Idempotency key)شناسه‌ای که کلاینت می‌سازد تا سرور به‌جای تکرار، نتیجه را دوباره پخش کند
Circuit breakerنگهبان بسته/باز/نیمه‌باز که وقتی وابستگی از کار افتاده زود شکست می‌دهد
Half-openحالتی از breaker که فراخوانی‌های آزمایشی محدود را راه می‌دهد
Bulkheadpool منابع جدا برای هر وابستگی
Fallbackجواب ضعیف‌تری که وقتی جواب اصلی شکست خورد استفاده می‌شود
تنزل آبرومندانه (Graceful degradation)کم کردن کار یا کیفیت به‌جای شکست
Load sheddingرد زودهنگام بخشی از درخواست‌ها در اضافه‌بار
خرابی آبشاری (Cascading failure)"a failure that grows over time as a result of positive feedback" (کتاب SRE)
Steady stateالگوی Nygard: سیستم بدون پاک‌سازی انسانی (لاگ، حذف داده) به کار ادامه می‌دهد
Let It Crashالگوی Nygard: جزء خراب را دوباره راه بینداز به‌جای تعمیر وضعیتش
خرابی جزئی (Partial failure)بخشی از عملیات توزیع‌شده موفق شد و بخشی نه
مسئلهٔ دو ژنرال (Two generals problem)اثبات اینکه توافق روی کانال غیرقابل‌اعتماد تضمین‌پذیر نیست
At-least-onceتحویل با retry؛ تکرار ممکن است، گیرنده باید idempotent باشد
Dead letter (DLQ، failed_jobs)محل نگهداری کاری که دائماً شکست خورده یا retryاش تمام شده
Saga / جبران (Compensation)گام‌های محلی و عمل‌های برگشتی به‌جای تراکنش توزیع‌شده
Outboxنوشتن پیام در همان تراکنش دیتابیسی که وضعیت را تغییر می‌دهد
RFC 9457 / application/problem+jsonبدنهٔ استاندارد خطای HTTP: type، title، status، detail، instance
Retry-Afterهدر HTTP که می‌گوید کلاینت چقدر صبر کند (RFC 9110)
لاگ ساختاریافته (Structured logging)لاگ به‌شکل فیلدهای کلید/مقدار (log/slog، context در Monolog)
Sentryerror trackerی که exceptionها را در issueها گروه می‌کند
بودجهٔ خطا (Error budget)مقدار ناپایداری مجاز زیر یک SLO
تزریق خطا (Fault injection)خراب کردن عمدی وابستگی‌ها در تست یا آزمایش
تست table-drivenیک تست، چند سطر ورودی و خطای مورد انتظار
Http::fakefake کلاینت HTTP در Laravel برای تزریق پاسخ و خرابی

منابع ​

ساخته‌شده توسط Morteza Negahi