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, 12 January 2015

Summary: Every failure is one of three things: a bug, an expected business outcome, or a failing dependency. Good design gives each its own type, handles it once at the boundary, and wraps every remote call in timeouts, retries, a circuit breaker and a fallback. Focus: Error taxonomy, error values vs exceptions vs Result<T, E>, sentinel/typed/wrapped errors, handle-once and translation at layer boundaries, anti-patterns, validation vs invariants vs assertions, fail-fast, panics and fatal errors, cleanup, and the stability patterns (timeout, retry with jitter, idempotency, circuit breaker, bulkhead, fallback, load shedding), RFC 9457 responses, observability and testing, in Go and Laravel. Learning goal: Look at any failure path and say what kind of error it is, which layer creates, translates and handles it, whether a retry is safe, and what the user sees, then build it in Go and Laravel with tests that inject the fault.

This chapter is the design-level reference for failure. It covers how to model errors in code (types, hierarchies, where they are handled) and how to survive failures of other components (the stability patterns). Several neighbours go deeper on one pattern each, and this page links to them instead of repeating them: Cascading Failures, Timeouts, Retries & Jitter, Circuit Breaker, Bulkheads & Graceful Degradation, Load Shedding, API Idempotency, Dead-Letter Queue, Saga Pattern and Transactional Outbox. The design siblings in this group are Distribution of Components (why remote calls fail differently), Designing for Concurrency and Data Persistence in Design.

Page map ​

If you are looking forGo to
The whole topic in a few tablesEverything in one minute
Why error design matters and what it tradesWhy it exists
Go blog, PHP Throwable, Rust, checked exceptions, Nygard, SRE book, RFC 9457Where it comes from
Bug vs domain error vs infrastructure failureError taxonomy
Error values vs exceptions vs Result<T, E>Three error models
Sentinel, typed, wrapped, joined errors, error codesDesigning error types
Handle once, log-and-rethrow, translation between layersHandle once at the boundary
Catching Throwable, swallowing, exceptions for control flowAnti-patterns
Validation, invariants, assertions, fail-fast, defensive programmingValidation, Fail-fast
panic/recover, PHP fatal errors, defer/finallyPanics, Cleanup
Timeouts, retries, idempotency, circuit breaker, bulkhead, fallbackStability patterns
Two generals, at-least-once, DLQ, sagas, outboxPartial failure, Transactions
RFC 9457 problem details, logging, Sentry, error budgets, testsAPI errors, Observability, Testing
Before/after codeGo, Laravel
Order service vs a flaky payment API, with fault injectionLab

Everything in one minute ​

The three kinds of failure. Every row is unpacked in the catalogue.

KindIn plain wordsTiny exampleRight response
Programmer bugThe code is wrongnil map write, TypeError, broken invariantFail fast, 500, report with stack trace, fix the code
Expected domain outcomeThe world said "no"card declined, order not found, already shippedReturn a typed error / business exception, 4xx, no alert
Infrastructure failure, transientA dependency hiccupedtimeout, 503, 429, deadlock, connection resetTimeout, retry with backoff and jitter, circuit breaker, fallback
Infrastructure failure, permanentA dependency will not recover by itselfwrong credentials, 400 from a partner, disk fullFail, alert a human, dead-letter the work

The stability patterns.

PatternOne lineGo (this page)Laravel 13
TimeoutNever wait forevercontext.WithTimeout, http.Client.TimeoutHttp::timeout(), connectTimeout(), #[Timeout] on jobs
Retry with backoff + jitterTry again later, at a random timeresilience.DoHttp::retry(), retry() helper, #[Backoff], retryUntil()
IdempotencyDoing it twice equals doing it onceIdempotency-Key header + dedupEnsureIdempotency middleware, Cache::lock
Circuit breakerStop calling a dependency that is downresilience.BreakerCache-backed CircuitBreaker, ThrottlesExceptions for jobs
BulkheadCap what one dependency can consumeresilience.Bulkhead (semaphore)Separate queues/workers, WithoutOverlapping, FPM pools
Fallback / graceful degradationGive a worse answer instead of nonequeue the payment for laterrescue(), Cache::flexible, queued job
Load sheddingRefuse some work to finish the rest503 + Retry-After earlyrate limiting middleware, 503
Dead letterPark what keeps failingDLQ topic / tablefailed_jobs, failed(), queue:retry

The language mechanisms.

NeedGoPHP 8.4 / Laravel 13Rust (comparison)
Report an expected errorreturn ..., errthrow new BusinessExceptionResult<T, E>
Test the kind of errorerrors.Is, errors.As, errors.AsType (Go 1.26)catch (Type $e), instanceofmatch on the error enum
Add contextfmt.Errorf("...: %w", err)new X(msg, previous: $e)? with From, map_err
Several errors at onceerrors.JoinValidationException errors baga Vec of errors
Unrecoverable bugpanicError hierarchy (TypeError...)panic!
Cleanup on every pathdeferfinallyDrop (RAII)

Why it exists ​

Code that only handles the happy path is a prototype. In production, the payment provider times out, the database deadlocks, a user submits a negative quantity and a developer forgets a null check, all in the same hour. If the code treats all four the same way (catch everything, log, return 500), you get four bad outcomes: the user with the typo sees "Internal Server Error", the outage floods the logs and pages someone for every request, the bug hides among thousands of expected errors, and the timeout gets retried by three layers at once until the provider falls over. Error design is the discipline of telling these apart and giving each the right path.

Ad-hoc handlingDesigned handling
One catch (Throwable) per controllerTyped errors, one handler at the boundary
Every failure is a 500Bugs 500, domain outcomes 4xx, outages 503 + Retry-After
Logged in every layerLogged once, with the full chain and request id
Default timeouts (30 s in Laravel's client, none in Go's http.DefaultClient)Explicit timeouts from latency data and a caller deadline
Retry anything, anywhereRetry transient errors, in one layer, with jitter and a budget
Simpler code at firstMore types and tests; much cheaper incidents
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

The picture is the decision you make for every failure: is it a bug, an expected outcome, or an infrastructure failure, and if infrastructure, transient or permanent.

The analogy we reuse on this page: a courier company. A parcel can fail in three ways. The address does not exist: that is a domain outcome, the courier returns it to the sender with a clear note, nobody calls the police. The van breaks down: that is infrastructure, the parcel waits and goes out with another van later, and if every van in the depot breaks the dispatcher stops loading vans for an hour instead of sending more onto the broken road (circuit breaker). The courier delivers the parcel into a lake: that is a bug, you stop and investigate, because a driver who does that once will do it again. The depot keeps a shelf for parcels that failed five times (dead letter), and stamps every parcel with a tracking number so a second delivery attempt never delivers twice (idempotency key).

Three common misunderstandings, up front ​

  1. "Exceptions are for errors, return values are for success." The useful line is not error vs success but bug vs expected outcome vs infrastructure. A declined card is an expected outcome even if PHP throws it.
  2. "Catching everything makes the system robust." It makes it quiet. Joe Duffy's rule from Midori, "Bugs Aren’t Recoverable Errors!", is the opposite: code that met a situation its author did not expect should stop, not carry on.
  3. "Retries make calls reliable." Retries make transient failures invisible and make overload worse. Without timeouts, jitter, a budget and idempotency they turn a slow dependency into an outage.

Where it comes from ​

Exceptions and checked exceptions. Java made the compiler check declared exceptions. The Java tutorial's rule is "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." In 2003 Anders Hejlsberg explained why C# left them out: "I see two big issues with checked exceptions: scalability and versionability." Adding a new exception to a throws clause breaks every caller, and in practice callers let exceptions pass to "a bottom level exception handler around their message loop". That is the handle once at the boundary idea, arrived at from the other side.

Go: errors as values (2011–2025). Andrew Gerrand's Error handling and Go (2011) describes the built-in error interface and fmt.Errorf for context. Rob Pike's 2015 post gives the slogan quoted at the top. Go 1.13 (2019) added wrapping: "an error which contains another may implement an Unwrap method", plus errors.Is and errors.As, and a warning that is central to this page: "wrapping an error makes that error part of your API." Go 1.20 added errors.Join; Go 1.26 added the generic errors.AsType. On 3 June 2025 Robert Griesemer closed the long syntax debate (the try proposal, issue 32437, among others): "For the foreseeable future, the Go team will stop pursuing syntactic language changes for error handling."

PHP: one Throwable, two hierarchies. The PHP manual today says PHP reports errors through "Throwable errors, which are further split into programming errors via the Error class hierarchy and recoverable errors via the Exception class hierarchy", plus older non-throwing diagnostic errors (warnings, notices). Throwable is the common interface (PHP 7 onward) and user classes "cannot implement the Throwable interface directly, and must instead extend Exception."

Rust: Result and panic!. The Rust book: "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." This is the same split as PHP's Exception/Error, enforced by the type system.

Midori: bugs are not errors (2016). Joe Duffy's The Error Model defines the two sides cleanly: "A recoverable error is usually the result of programmatic data validation" and "A bug is a kind of error the programmer didn’t expect." Midori used abandonment (fail-fast) for bugs and checked errors for the rest.

Fault tolerance: Nygard, Fowler, AWS, Google. Michael Nygard's Release It! (second edition 2018) named the stability patterns: Timeouts, Circuit Breaker, Bulkheads, Steady State, Fail Fast, Let It Crash, Handshaking, Test Harnesses, Decoupling Middleware, Shed Load, Create Back Pressure, Governor (names from the second edition's table of contents; descriptions on this page are our summary). Martin Fowler's CircuitBreaker (2014) credits him: "In his excellent book Release It, Michael Nygard popularized the Circuit Breaker pattern to prevent this kind of catastrophic cascade." Marc Brooker's AWS post Exponential Backoff And Jitter (2015) measured why "The solution isn’t to remove backoff. It’s to add jitter." Google's Site Reliability Engineering book (© 2017 on the online edition, chapter by Mike Ulrich) defines the failure mode all of this prevents: "A cascading failure is a failure that grows over time as a result of positive feedback."

HTTP error bodies. RFC 7807 defined problem details; RFC 9457 (July 2023) obsoletes it and keeps the purpose: "machine-readable details of errors in HTTP response content to avoid the need to define new error response formats for HTTP APIs."

Partial failure. The two generals problem was described by Akkoyunlu, Ekanadham and Huber in 1975 and named by Jim Gray in 1978 (Notes on Data Base Operating Systems); we read this history on Wikipedia (secondary source), which calls it "the first computer communication problem to be proven to be unsolvable."

The concept catalogue ​

Each block follows the same order: plain words, the usual wrong belief, a precise definition, a timeline, real scenarios, what each language or product does, and the fix.

Error taxonomy: bug, domain outcome, infrastructure Must-know ​

In plain words: before you write catch or if err != nil, decide which of three things happened: the code is wrong, the business said no, or something we depend on failed.

Common misunderstanding: "An error is an error; they all go to the same handler." They need opposite responses. A bug must be loud (alert, stack trace) and must not be retried. A domain outcome must be quiet (no alert) and shown to the user. An infrastructure failure may be retried, but only if it is transient.

Definition: a programmer bug is a state the author did not anticipate (Duffy: "a kind of error the programmer didn’t expect"); a domain error (expected error, business error) is a documented outcome of an operation; an infrastructure failure is a failure of I/O or of another component. Infrastructure failures split into transient (may succeed later: timeout, 503, 429, deadlock, leader election) and permanent (will not succeed without a change: 400, 401, unknown host, schema mismatch).

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

Real scenario: a checkout that pages on-call for every declined card; a job that retries a 400 from a partner 25 times; an Error from a typo caught by catch (Throwable) and shown to users as "payment failed".

LanguageBugDomain outcomeInfrastructure
Gopanic (runtime or explicit)sentinel or typed errorwrapped error (*url.Error, *net.OpError, context.DeadlineExceeded)
PHP 8.4Error subclasses: TypeError, ValueError, ArgumentCountError, UnhandledMatchError, DivisionByZeroErroryour Exception subclassesPDOException, QueryException, ConnectionException, RequestException
Rustpanic!Err(DomainError)Err(io::Error)

Fix: one base type per kind. In this page's code: Go sentinels and *StateError for the domain, ErrStoreUnavailable for infrastructure, panic for bugs; Laravel BusinessException (implements ShouldntReport), PaymentUnavailable (reported at warning) and PHP's own Error for bugs.

Three error models: values, exceptions, Result Must-know ​

In plain words: Go returns the error next to the result; PHP throws it up the stack until someone catches it; Rust returns a value that is either the result or the error, and the compiler makes you look.

Common misunderstanding: "Go has no exceptions, so it cannot unwind." Go has panic, which unwinds and runs deferred calls; it just reserves it for bugs. Effective Go: "real library functions should avoid panic." And the Go blog: "The convention in the Go libraries is that even when a package uses panic internally, its external API still presents explicit error return values."

Definition:

ModelWhere the error travelsVisible in the signature?Cost of ignoring itTypical failure
Error values (Go)Returned, checked with if err != nilYes (error result)Silent if you write _ =Verbose, easy to drop context
Unchecked exceptions (PHP, C#, Kotlin)Unwinds until a catchNo (only @throws docblocks)Bubbles to the global handlerCatch-all handlers, control flow by exception
Checked exceptions (Java)Unwinds; compiler checks throwsYesCompile errorthrows Exception everywhere, wrap-and-rethrow noise
Result<T, E> (Rust, Swift throws, Kotlin Result)Returned; ? propagatesYes, in the typeCompiler warning (#[must_use])Large error enums, conversion boilerplate
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    }

Real scenario: a Go service where defer rows.Close() is forgotten and the error from rows.Err() is never checked; a Laravel controller where a ModelNotFoundException from findOrFail correctly becomes a 404 without any code; a Rust client where a new error variant forces every match to be updated, which is exactly Hejlsberg's versioning concern in a different form.

Fix: in Go, check every error and add context once per layer; in PHP, throw specific exceptions and let them travel to one handler; in both, keep the kind of the error in its type, not in its message.

Designing error types: sentinel, typed, wrapped, joined, codes Must-know ​

In plain words: callers need to ask "is this the not-found case?" without parsing text. Give them a value to compare (sentinel), a type to inspect (typed), or a stable code at the boundary.

Common misunderstanding: "Wrap everything with %w so callers have all the information." The Go blog warns the opposite: "Do not wrap an error when doing so would expose implementation details", because "wrapping an error makes that error part of your API." A repository that wraps sql.ErrNoRows forces every caller to import database/sql forever.

Definition:

ShapeGoPHP / LaravelUse whenCost
Sentinel errorvar ErrNotFound = errors.New("not found"), test with errors.Isa dedicated exception class with no fieldsThe caller only needs "which case"Becomes public API; cannot carry data
Typed errortype FieldError struct{...}, test with errors.As / errors.AsTypeexception class with readonly propertiesThe caller needs data (field, limit, id)More types
Wrapped errorfmt.Errorf("find %s: %w", id, err), Unwrap() errornew X('msg', previous: $e), getPrevious()Add context, keep the cause inspectableExposes the cause as API
Opaque errorfmt.Errorf("...: %v", err)new exception without previousHide an implementation detailCallers cannot branch on it
Joined errorerrors.Join(e1, e2), Unwrap() []errorValidationException with an errors bagReport several problems at onceCallers must walk a tree
Error codeCode(err) string at the boundarycode() on BusinessExceptionClients, logs, dashboards, i18nMust stay stable forever
Custom Is/As methodfunc (e *E) Is(target error) booln/aA type should match a sentinelSurprising if overused
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)

Real scenario: a validation step that must return all field problems in one 422 (errors.Join, walked by FieldErrors); a payment client that exposes ErrDeclined but hides which HTTP library it uses; a public API that promises "code": "insufficient_funds" for years while the message text changes.

Fix: the Go errtypes snippet shows all shapes with a table-driven test; Exceptions.php shows a Laravel hierarchy with a stable code(), status and title per type.

Error context and stack traces Important ​

In plain words: an error message should say what was being done, to what, and the log entry should say for whom. A stack trace says where in the code.

Common misunderstanding: "Go errors are useless without stack traces." A wrapped chain like cancel: find order 42: order store unavailable: dial tcp ...: connection refused is often more useful than 60 frames, because each layer says what it was doing. Go errors carry no stack by default; panics print one, and runtime/debug.Stack() captures one when you need it. PHP exceptions always carry getTrace(); the cost is that the trace says where but not which order.

Definition: error context is the data that identifies the operation (ids, sizes, attempt numbers), added once per layer. The Go blog: "It is the error implementation’s responsibility to summarize the context." Laravel lets an exception add log context with a context() method, and adds global context with $exceptions->context(...).

Real scenario: "record not found" in a log with no id; a stack trace that ends in a framework dispatcher with no tenant id; a Sentry issue that groups 40 different bugs because the message contains a variable id (fix: keep ids out of the message, put them in context fields).

Fix: context in the message as verb noun id: prefixes, identifiers in structured fields, stack traces only for bugs (5xx), never in client responses.

Handle once, at the boundary; translate between layers Must-know ​

In plain words: each failure should be logged exactly once and turned into a response exactly once, by the outermost layer that knows who is asking (the HTTP handler, the job runner, the CLI command). Inner layers either add context or translate; they do not log.

Common misunderstanding: "Log and rethrow is safe: more logs can't hurt." Logging in every layer turns one failure into five log lines with five partial contexts, multiplies volume during an outage, and makes error counts meaningless. Either handle it (decide what happens next) or pass it up; doing both is the log and rethrow anti-pattern.

Definition: an error crosses three kinds of boundary. At an adapter boundary (repository, HTTP client) it is translated from the technology's vocabulary to the domain's (sql.ErrNoRows to ErrOrderNotFound, ConnectionException to PaymentUnavailable). At a use-case boundary the service decides: fail, fall back, or compensate. At the process boundary the handler handles: log once with request context, map to a status and a body, hide internals. This is the error-side of Dependency Inversion: the domain defines the errors its ports may return, adapters translate into them.

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
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

Real scenario: a Laravel controller with try { ... } catch (Throwable $e) { Log::error(...); throw $e; } that doubles every Sentry event (Laravel offers dontReportDuplicates() for the symptom); a Go service whose repository, service and handler each call log.Printf on the same error.

Fix: Go: the layers snippet (repository translates, service wraps, handler logs once, a test asserts exactly one log line). Laravel: bootstrap/app.php withExceptions is the single place for report and render; actions throw or report() and continue, never both. Also see Liskov Substitution: an implementation that throws exceptions its interface does not promise breaks every caller that handles errors at the boundary.

Exception hierarchies and anti-patterns Must-know ​

In plain words: a hierarchy lets the boundary catch "all business exceptions" in one place; anti-patterns are the habits that hide bugs or make failures louder than they need to be.

Common misunderstanding: "catch (Throwable $e) is defensive." It also catches TypeError and Error, i.e. bugs, and usually turns them into a friendly message that nobody investigates.

Definition: PHP's built-in tree is Throwable → Error (bugs: TypeError, ValueError, ArithmeticError, DivisionByZeroError, ArgumentCountError, UnhandledMatchError, CompileError, ParseError) and Throwable → Exception (recoverable). SPL adds LogicException (bug in the program: InvalidArgumentException, DomainException, LengthException, OutOfRangeException, BadFunctionCallException) and RuntimeException (detectable only at run time: UnexpectedValueException, OutOfBoundsException, OverflowException, RangeException, UnderflowException). ErrorException turns diagnostic errors (warnings) into exceptions. Design your own tree shallow: one base for business exceptions, one or two for infrastructure.

Anti-patternLooks likeWhy it hurtsInstead
Catch-allcatch (Throwable), recover() everywhereHides bugs, returns wrong answersCatch the specific type you can handle
Swallowcatch (X) {}, _ = f()Failure disappearsHandle, return, or report() and continue
Log and rethrowLog::error($e); throw $e;Duplicate logs and alertsLog at the boundary only
Exceptions for control flowthrow to exit a loop, panic for "already shipped"Slow, invisible flow, bugs mixed with outcomesReturn values / domain results
String matchingstr_contains($e->getMessage(), 'no rows')Breaks on a driver upgradeTypes, sentinels, codes
Leaking internalsreturning $e->getMessage() to the clientInformation disclosure (SQL, hosts)Problem details with safe detail
Pokemon hierarchyAppException with 40 subclasses 5 levels deepNobody knows which to catchShallow tree, one base per kind
Generic exceptionsthrow new Exception('error')Nothing can branch on itA named type per outcome
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

Real scenario: a refactoring that renames a property; the resulting Error is caught by a catch-all and every checkout says "payment failed, try again" for a day.

Fix: the Before.php and before/handler.go snippets list these habits; the after versions remove them.

Checked exceptions and the "declare what you throw" debate Good to know ​

In plain words: should the compiler force callers to deal with every error a function can raise?

Common misunderstanding: "Checked exceptions failed, so error types do not matter." The lesson from Hejlsberg is narrower: listing every low-level exception in every signature does not scale or version. Go's error and Rust's Result still make failure possible visible in the signature; they just do not list each type.

Definition: Java checked exceptions are part of the method signature; unchecked ones (RuntimeException, Error) are not. PHP has only unchecked exceptions; @throws docblocks are read by static analysers (PHPStan, Psalm) but not enforced by the engine. C# and Kotlin dropped checked exceptions. Go's position (2025) is to keep explicit checks and stop pursuing new syntax.

Fix: document the domain errors a function can return (Go doc comment "returns an error wrapping ErrNotFound if..."; PHP @throws PaymentDeclined), and treat infrastructure errors as a category, not a list.

Validation, invariants and assertions Important ​

In plain words: validation checks untrusted input and tells the user what to fix; an invariant is a rule your own objects always keep; an assertion checks something that can only be false if your code has a bug.

Common misunderstanding: "Validation and assertions are the same check in different places." They have different audiences: a failed validation is a 422 for the user; a broken invariant inside a domain object is either a domain error (if a user action could cause it) or a bug (if it means your code skipped validation).

Definition:

CheckWhereFails becauseResponseGoLaravel
Input validationEdge (controller, Form Request, handler)User or client sent bad data422 with every field errorerrors.Join of *FieldErrorForm Request / validate() throws ValidationException
Domain invariantInside the aggregate methodThe action is not allowed now409 / 422 business errortyped error from DebitInvalidOrderState
Assertion / preconditionAnywhere, about your own codeA bug upstreamFail fast, 500panicassert() (off in production by zend.assertions), LogicException

Real scenario: a qty of 0 reaching Wallet.Debit(0): validation should have stopped it, so Debit panics (bug); a balance that is too low: domain error, the user can top up; a JSON body with three wrong fields: one 422 listing all three, not three round trips.

Fix: validate at the edge with all errors at once (Laravel returns "a 422 Unprocessable Entity HTTP response" for ValidationException on JSON requests); guard invariants in the domain method with typed errors; reserve panics/LogicException for "cannot happen".

Fail-fast vs fail-safe, and the limits of defensive programming Important ​

In plain words: fail-fast means stop at the first sign that something is wrong, close to the cause. Fail-safe means that when something fails, the system ends in a harmless state (the door unlocks during a fire alarm; the payment is not taken). Defensive programming is checking for things that should not happen; done everywhere, it hides bugs.

Common misunderstanding: "Fail-fast and fail-safe are opposites." They answer different questions. Fail-fast is about detection (stop early, do not continue on corrupted state). Fail-safe is about the state you leave behind (default deny, roll back, do not ship). A good design does both: a bug panics (fail-fast), the transaction rolls back (fail-safe).

Definition: Nygard's Fail Fast pattern (our summary): if a request is going to fail, for example because a needed dependency's circuit is open or resources are exhausted, reject it immediately instead of after consuming a thread and a timeout. Duffy calls the bug-side version abandonment. Defensive programming has limits: if ($order === null) return; deep in a service turns a bug into silent data loss; check once at the edge, trust inside, assert the rest.

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 --

Real scenario: a feature flag service that is down: fail-safe default "off" for new features, "on" for kill switches; a permissions check that throws: fail-safe is deny, not allow; a config value missing at startup: fail-fast at boot, not at the first request a week later.

Fix: validate config and dependencies at startup; choose a safe default per decision; let bugs crash the request (or the worker process, in Nygard's Let It Crash sense, where a supervisor restarts it).

Panics, recover and PHP fatal errors Important ​

In plain words: a panic (Go) or an Error (PHP) means "the program is in a state nobody planned for". You may catch it at the outermost edge to keep other requests alive, but not to continue this one.

Common misunderstanding: "recover is Go's catch." The Go blog: "Recover is only useful inside deferred functions", and a library should not let a panic escape its API. recover belongs in a top-level middleware or goroutine wrapper, not around business code.

Definition:

SituationGoPHP 8.4
Bug detected by the runtimeruntime panic (nil map, index out of range)Error subclass thrown
Explicit "cannot happen"panic("...")throw new LogicException
Catch at the edgedefer func(){ if v := recover(); ... }() in middlewareglobal handler (set_exception_handler, Laravel's handler)
Panic in another goroutinecrashes the whole process unless that goroutine recoversn/a (one request per worker)
Truly fatalfatal error: concurrent map writes, out of memory (cannot be recovered)memory limit, max execution time: not a Throwable; only register_shutdown_function + error_get_last() sees it
Deliberate abortpanic(http.ErrAbortHandler) aborts a response quietlyabort(404) throws an 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

Fix: the Recoverer in the layers snippet (re-panics http.ErrAbortHandler, logs debug.Stack()); every go func() you start in a server gets its own recover or uses an errgroup. PHP: rely on Laravel's handler (registered by Illuminate\Foundation\Bootstrap\HandleExceptions); plain scripts register both handlers as in Cleanup.php.

Resource cleanup: defer, finally, RAII Important ​

In plain words: whatever you open, lock or begin, you must close, release or end on every path: success, error, and panic.

Common misunderstanding: "defer f.Close() is enough." For a file you wrote, Close can return the real error (the data did not reach the disk); ignoring it loses writes silently. And "finally runs only on errors": it runs on success, on return and on throw; the PHP manual: "All finally blocks it encounters along the way will be executed."

Definition: Go defer runs when the function returns (or panics), last-in first-out; deferred arguments "are evaluated when the defer statement is evaluated" and deferred functions "may read and assign to the returning function’s named return values", which is how a Close error is joined into the result. PHP finally runs after try/catch. C++ and Rust use RAII (Drop): cleanup tied to scope. Laravel wraps the common cases: DB::transaction() rolls back on any exception and rethrows, Cache::lock(...)->block(...) and $lock->release() in 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)

Fix: cleanup.go (errors.Join(err, f.Close()), InTx) and Cleanup.php (finally, DB::transaction(..., attempts: 3)).

Timeouts and deadlines Must-know ​

In plain words: every call that leaves the process must have a maximum wait. A missing timeout turns a slow dependency into a stuck caller, then into a stuck system.

Common misunderstanding: "The default timeout is fine." Go's http.Client doc: "A Timeout of zero means no timeout", and http.DefaultClient has none. Laravel's HTTP client times out after 30 seconds by default, which is longer than most users wait and long enough to exhaust every PHP-FPM worker during an incident.

Definition: a timeout bounds one operation; a deadline is an absolute time for a whole request that every downstream call inherits. Go's context docs: "Incoming requests to a server should create a Context, and outgoing calls to servers should accept a Context." The SRE book's rule is deadline propagation: "Rather than inventing a deadline when sending RPCs to backends, servers should employ deadline propagation." AWS's guidance for choosing a value: "start with the latency metrics of the downstream service" and pick a high percentile (their example uses p99.9), not a guess.

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
KnobGoLaravel 13 / PHP
Whole requesthttp.Client{Timeout: ...} or context.WithTimeoutHttp::timeout(3) (default 30 s)
Connect onlynet.Dialer{Timeout: ...}Http::connectTimeout(1) (default 10 s)
Caller deadlinectx passed down(no built-in propagation; pass a deadline explicitly)
Queued jobworker-level context#[Timeout(120)], --timeout; must be less than retry_after
Databasectx on QueryContext, statement_timeoutstatement_timeout / max_execution_time in DB config

Fix: per-attempt context.WithTimeout inside the retry loop and a caller deadline outside it (lab); Laravel connectTimeout(1)->timeout(3) in PaymentGateway.php. Details: Timeouts, Retries & Jitter.

Retry with exponential backoff and jitter Must-know ​

In plain words: if a call failed for a transient reason, wait a bit and try again; wait longer each time; and pick the wait at random so a thousand clients do not all come back at the same millisecond.

Common misunderstanding: "Retry three times, everywhere." The SRE book's arithmetic: if the database is overloaded and "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." That is a retry storm.

Definition: exponential backoff waits base × 2^n (capped); full jitter waits a random value in [0, min(cap, base × 2^n)). Brooker's measurements found full jitter does the least total work. Rules from the SRE book: "Always use randomized exponential backoff when scheduling retries", "Limit retries per request", "Consider having a server-wide retry budget" (their example: "only allow 60 retries per minute in a process"), and "Don’t retry permanent errors or malformed requests in a client, because neither will ever succeed." AWS calls retries "selfish" and recommends retrying "at a single point in the stack".

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
ErrorRetry?Why
Timeout, connection reset/refusedYes, if the operation is idempotentTransient; the server may or may not have done the work
HTTP 503, 502, 504Yes; honour Retry-AfterTransient by definition
HTTP 429Yes, after Retry-AfterYou are being rate limited
HTTP 500Maybe (idempotent only)Could be a bug; cap attempts
HTTP 400, 401, 403, 404, 409, 422NoSame request, same answer
PostgreSQL 40001 (serialization), 40P01 (deadlock); MySQL 1213Yes, the whole transactionSee Deadlocks
Circuit open, bulkhead fullNo (in this call)Retrying defeats the protection
Domain errors (declined, not found)NeverNot a failure of the system

Fix: Go resilience.Do (classification via a Retryable interface, full jitter, deadline-aware, injectable sleep); Laravel Http::retry(3, fn ($attempt) => random_int(...), fn ($e) => transient), the retry() helper with a when callback, and for jobs #[Backoff([10, 30, 60])] plus retryUntil(). Laravel's Http::retry accepts "the maximum number of times the request should be attempted" and the sleep in milliseconds or a closure. Deep dive: Timeouts, Retries & Jitter, Retry, Backoff & Delayed Delivery.

Idempotency Must-know ​

In plain words: an operation is idempotent if doing it twice has the same effect as doing it once. Retries are only safe for idempotent operations, so you make non-idempotent ones (charge, create order, send email) idempotent with a key.

Common misunderstanding: "A timeout means the call failed." A timeout means you do not know. The server may have charged the card and the response got lost. Retrying without a key charges twice; that is exactly scenario B' in the lab.

Definition: the client generates an idempotency key per logical operation and sends it on every attempt (Idempotency-Key header); the server stores the key with the result and replays it. Stripe's documentation: "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", and the server "compares incoming parameters to those of the original request and errors if they’re not the same". Keys may be removed after "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';

Fix: derive the key from the business operation (order-{id}-payment), not from the attempt, and reuse it on the fallback path and in the queued job. Laravel: EnsureIdempotency.php (replay, 422 on a reused key with a different body, 409 while in progress, finally releases the lock). Consumers of messages need the same property: Idempotent Consumers & the Inbox Pattern; APIs: API Idempotency.

Circuit breaker Must-know ​

In plain words: after enough failures in a row, stop calling the broken dependency for a while and fail immediately; then let one trial call through to see if it recovered.

Common misunderstanding: "A breaker makes calls succeed." It makes them fail faster, so callers keep their threads, sockets and users' time, and the dependency gets room to recover. It must be paired with a fallback, or users just see errors sooner.

Definition: 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." The third state is "half open - meaning the circuit is ready to make a real call as trial to see if the problem is fixed." And: "Not all errors should trip the circuit, some should reflect normal failures and be dealt with as part of regular logic." Knobs (named as in sony/gobreaker): MaxRequests ("the maximum number of requests allowed to pass through when the CircuitBreaker is half-open"), Interval (when closed counts reset), Timeout ("the period of the open state"), ReadyToTrip (the trip rule, e.g. 5 consecutive failures or a 50% failure rate).

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
ChoiceOption AOption B
Trip ruleConsecutive failures (simple, this page)Failure rate over a sliding window with a minimum volume
PositionInside the retry loop (counts each attempt; Go lab)Outside it (counts each logical call; Laravel gateway)
State storageIn process memory (Go, Octane worker)Shared cache (PHP-FPM: Redis, since workers share nothing)
What counts5xx, timeouts, connection errorsNever 4xx or domain errors
Librariessony/gobreaker (Go), Resilience4j (Java), Polly (.NET)Envoy/Istio outlier detection (mesh level)

Fix: Go resilience.Breaker (state machine with an injected clock and an IsFailure predicate, tested transition by transition); Laravel CircuitBreaker.php on Cache with an atomic Cache::add for the half-open probe, and ThrottlesExceptions as the queue-side equivalent ("all further attempts to execute the job are delayed until a specified time interval lapses"). Deep dive: Circuit Breaker.

Bulkhead Important ​

In plain words: give each dependency its own limited pool, so one slow dependency can use up only its own compartment, not every worker you have.

Common misunderstanding: "Timeouts already protect us." A 3 s timeout with 100 requests per second to a hung dependency still ties up 300 concurrent workers. A bulkhead caps that number.

Definition: the Azure pattern page: "This pattern is named after the sectioned partitions (bulkheads) of a ship's hull." Implementations: a semaphore per dependency, a separate connection pool, a separate queue and worker group, a separate PHP-FPM pool, or separate service instances ("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

Fix: Go resilience.Bulkhead (buffered channel as semaphore, bounded wait); Laravel: a dedicated payments queue with its own queue:work processes, WithoutOverlapping, and a separate FPM pool for slow routes. Deep dive: Bulkheads & Graceful Degradation.

Fallback, graceful degradation and load shedding Important ​

In plain words: when you cannot give the full answer, give a smaller one (cached prices, "payment pending", no recommendations); when you have more work than capacity, refuse some early so you can finish the rest.

Common misunderstanding: "A fallback is a catch that returns a default." A fallback is a product decision: "accept the order and charge later" must be agreed with the business, must be idempotent, and must be visible (metrics), or it silently becomes the normal path.

Definition: SRE book: "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." Shedding can be "indiscriminate" or selective, e.g. "drop requests for low-priority operations like background synchronization, but keep serving interactive user sessions". Return a status that tells clients to back off: "Return a specific status when overloaded so that clients and other layers back off and do not retry" (503 with Retry-After, RFC 9110).

FallbackWhen it is rightRisk
Cached / stale valueReads (prices, catalogue)Stale data; label it
Default valueNon-critical features (recommendations, avatars)Hides a broken feature; alert on rate
Queue for laterWrites that can be asynchronous (payment capture, email)Needs idempotency and a dead letter
Alternative providerPayments, SMS, mapsTwo integrations to maintain
Fail with a clear messageNothing safe to substituteUser retries; give Retry-After

Fix: Go lab OrderService.Checkout returns payment_pending and queues the order id; Laravel Checkout action catches PaymentUnavailable, sets payment_pending and dispatches ChargePendingPayment after commit; rescue() for optional calls ("All exceptions that are caught will be sent to your exception handler; however, the request will continue processing"); Cache::flexible for stale-while-revalidate reads. Deep dives: Load Shedding, Cascading Failures.

Partial failure: two generals, at-least-once, dead letters, sagas Important ​

In plain words: in a distributed system, a call can fail after it did its work, and you cannot always find out. So you design for "it may have happened zero or more times" instead of "it happened or it did not".

Common misunderstanding: "With enough acknowledgements we can be sure both sides agree." The two generals problem shows that no number of messages over an unreliable channel gives certainty; this is why exactly-once delivery is built from at-least-once delivery plus idempotent processing.

Definition: partial failure: part of an operation succeeded and part did not (the charge succeeded, the order update failed). At-least-once: the sender retries until acknowledged, so duplicates are possible and receivers must be idempotent. A dead letter queue/table holds work that failed permanently or exhausted its retries (Laravel: "it will be inserted into the failed_jobs database table"). A saga replaces one distributed transaction with local steps plus compensations (refund instead of 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

Fix: idempotency keys on every step and every compensation; DLQ with an owner and an alert; links: Delivery Guarantees, Dead-Letter Queue, Saga Pattern.

Transactions and errors: rollback and outbox Important ​

In plain words: inside one database, a transaction makes "half done" impossible: any error rolls everything back. The moment you also call an API or publish a message, the transaction cannot cover it, and you need the outbox.

Common misunderstanding: "Dispatch the job inside the transaction; if it fails, the job is rolled back too." The queue is not in the database. If the transaction rolls back after the dispatch, the job runs for an order that does not exist; if you dispatch after commit and the process dies in between, the job is lost.

Definition: DB::transaction(): "If an exception is thrown within the transaction closure, the transaction will automatically be rolled back and the exception is re-thrown." Its second argument is "the number of times a transaction should be retried when a deadlock occurs". ->afterCommit() delays dispatch until the surrounding transaction commits. The transactional outbox writes the message to a table in the same transaction, and a relay publishes it 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

Fix: keep external calls outside database transactions (a 3 s HTTP call inside a transaction holds row locks for 3 s); use afterCommit() or an outbox for the follow-up. See ACID & Transactions.

Error responses for APIs: RFC 9457 problem details Must-know ​

In plain words: clients need a machine-readable error format that is the same on every endpoint: a type to branch on, a title for humans, the status, and optional details.

Common misunderstanding: "Put the exception message in the response." 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", with a warning about "exposing implementation internals through error messages".

Definition: media type application/problem+json; members type (a URI; "Consumers MUST use the "type" URI (after resolution, if necessary) as the problem type's primary identifier."; default about:blank), title, status ("only advisory"), detail, instance, plus extension members (this page adds code and errors). RFC 9457 obsoletes 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."]}}
ErrorStatustype slugExtra
Validation422validation-failederrors per field
Not found404order-not-foundnone
Invalid state409invalid-statenone
Payment declined422 (or 402)payment-declinednone
Rate limited429about:blankRetry-After
Dependency down503unavailableRetry-After
Bug500about:blanknothing internal; a request id

Fix: Go writeProblem in layers; Laravel Problem::response() called from $exceptions->render(...) in bootstrap-app.php. API design rules: REST API Design.

Observability of errors Important ​

In plain words: you cannot fix what you cannot see, and you cannot see anything if every expected 404 pages someone. Log once with structure, send bugs to an error tracker, count everything as metrics.

Common misunderstanding: "Every exception should go to Sentry." Business exceptions are not bugs; Laravel's ShouldntReport and dontReport keep them out, and the framework already ignores 404s and some 403/419 responses by default.

Definition: structured logging writes key/value fields (Go log/slog, Laravel's Monolog channels with context()); an error tracker (Sentry, Flare, Laravel Nightwatch, all named in the Laravel docs) groups exceptions into issues with stacks and releases; metrics count errors by kind and feed the SLO. An error budget is the amount of failure the SLO allows; spending it decides when to stop shipping features and fix reliability (owned by SLAs, SLOs, SLIs & Error Budgets).

SignalBugDomain outcomeInfrastructure
Log levelerrorinfo/debug (or none)warning, error when budget burns
Error trackeryes, with stackno (ShouldntReport)sampled/throttled ($exceptions->throttle, Limit::perMinute)
Metricerrors_total{kind="bug"}outcomes_total{code=...}dependency_errors_total{dep=...}, breaker state
Alerton new issue / ratebusiness alert if rate spikeson SLO burn rate, breaker open

Fix: Laravel level(PaymentUnavailable::class, LogLevel::WARNING), throttle(...), context(...), dontReportDuplicates(); Sentry for Laravel registers via Integration::handles($exceptions) inside withExceptions. Go: slog at the boundary with request id, path, status, code and the error chain. Deep dive: Observability.

Testing error paths Must-know ​

In plain words: the error paths are the code that runs during incidents, so they need tests more than the happy path. Make failures happen on purpose (fault injection) and assert on the kind of error and on side effects.

Common misunderstanding: "Assert on the error message." Messages are for humans and change; assert with errors.Is/errors.As or expectException(Type::class), and assert side effects (no double charge, exactly one log line, balance unchanged).

Definition: table-driven tests list one row per failure mode (Go idiom, PHPUnit #[DataProvider]); fault injection replaces a dependency with one that fails on schedule (httptest.Server with a fault list, Laravel Http::fake with Http::sequence()->pushStatus(503), Http::failedConnection()); deterministic time injects clocks, sleeps and random sources; Chaos Engineering does the same in production-like environments.

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

Fix: Go tests in errtypes, layers and resilience (run with go test -race ./...); Laravel PaymentGatewayTest.php with Http::fake, Http::assertSentCount and Http::assertSent on the header.

Per-language and per-framework view ​

Language / frameworkExpected errorsBugsCleanupRetry / breaker tooling
Goerror values; errors.Is/As/AsType/Join, %wpanic; recover in middleware onlydeferstdlib only (this page), sony/gobreaker, cenkalti/backoff
PHP 8.4Exception subclassesError subclasses; ErrorException for warningsfinallynone built in
Laravel 13Exceptions + withExceptions report/render, ShouldntReport, abort()Global handler, Sentry/Flare/NightwatchDB::transaction, locksHttp::retry, retry(), #[Tries], #[Backoff], retryUntil, ThrottlesExceptions, failed()
RustResult<T, E>, ?panic!Dropcrates (not covered)
Javachecked + unchecked exceptionsError, RuntimeExceptiontry-with-resourcesResilience4j
C# / .NETunchecked exceptionssameusing / IDisposablePolly

Mechanics ​

Go: the error tree Important ​

fmt.Errorf with one %w returns an error whose Unwrap() error returns the wrapped value; with several %w (Go 1.20+) or with errors.Join, the result implements Unwrap() []error. errors.Is walks this tree depth-first comparing with == or a custom Is(error) bool method; errors.As finds the first value assignable to the target type; errors.AsType[E] (Go 1.26) does the same with generics: "For most uses, prefer AsType." Note: errors.Unwrap "does not unwrap errors returned by Join"; use errors.Is/As or walk Unwrap() []error (as FieldErrors does). The snippets use errors.As so the module builds with go 1.24.

PHP: unwinding and the last lines of defence Important ​

A thrown Throwable "will unwind the call stack until it is caught by a catch block or the global scope is reached", running every finally on the way. Uncaught, it goes to the handler from set_exception_handler(), "otherwise, the program is terminated with a fatal error"; after that handler "the script terminates once the handler returns". Engine-fatal errors (memory, execution time) are not throwables; register_shutdown_function plus error_get_last() is the only hook. Laravel installs all of these in HandleExceptions and routes throwables through report (log channels, trackers) and render (response).

Laravel: the exception pipeline Must-know ​

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 must be false in production: "If the value is set to true in production, you risk exposing sensitive configuration values to your application's end users."

Error and status reference Must-know ​

WhereErrorMeaningRetry?
Gocontext.DeadlineExceededthe deadline passedthe attempt, if the caller's deadline allows
Gocontext.Canceledthe caller gave upno
Gosql.ErrNoRowsno row; translate to a domain not-foundno
Go*url.Error / net.Error with Timeout()network failureyes (idempotent)
Goio.EOFnormal end of input, not a failuren/a
LaravelConnectionExceptiontimeout / DNS / refusedyes
LaravelRequestException (->response->status())4xx/5xx after throw() or exhausted retry5xx/429 yes, 4xx no
LaravelValidationException422 with errorsno
LaravelModelNotFoundExceptionbecomes 404no
LaravelAuthorizationException / AuthenticationException403 / 401no
LaravelQueryException SQLSTATE 40001, 40P01, MySQL 1213serialization failure / deadlockyes, whole transaction
LaravelMaxAttemptsExceededException, TimeoutExceededException (class names from the framework source, not the docs page)job out of attempts / timeno; failed() runs
HTTP408, 429, 502, 503, 504transientyes, honour Retry-After

Knobs worth knowing Good to know ​

KnobDefaultRecommendation
Laravel Http::timeout / connectTimeout30 s / 10 sfrom downstream p99; 1 s connect, 2–5 s total
Laravel queue --tries1 attemptset #[Tries] or retryUntil() per job
Laravel --backoff0 (immediate)#[Backoff([10, 30, 60])]
Laravel job #[Timeout]60 sless than the connection's retry_after (default 90)
Laravel RequestException messagetruncated to 120 charstruncateAt() / dontTruncate()
Go http.Client.Timeout0 (none)always set, or always pass a ctx with a deadline
Breaker threshold / open timen/a5 failures or 50% over ≥20 calls; 10–60 s open
Retry attemptsn/a3 total at one layer; a budget per process

Go ​

Before ​

Five habits in one file: log-and-return in the repository, string matching on "no rows", leaking the driver message to the client, a swallowed encode error, and a panic used for a business rule.

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"
}

After ​

Error shapes and their table-driven test:

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)
	}
}

Layers: the repository translates, the service decides, the handler logs once and writes problem details; Recoverer turns a panic into a 500 for one request.

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)
			}
		})
	}
}

Cleanup with 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)
}

The stability patterns, standard library only:

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)
	}
}

The Go angle ​

  • Check, wrap once, handle once. Each layer adds one prefix ("cancel: %w"); only the boundary logs. Linters such as errcheck and errorlint (in golangci-lint) catch ignored errors and == comparisons on wrapped errors.
  • %w vs %v is an API decision. Wrap what callers may rely on; format the rest.
  • Context everywhere. ctx is the first parameter of anything that does I/O; context.WithTimeout per attempt, context.WithTimeoutCause when you want a custom cause; never store a context in a struct.
  • Panics stay inside. recover in HTTP middleware and in goroutine wrappers only; a library returns errors.
  • No errors.New in hot loops for sentinel checks. Sentinels are package-level variables; creating new ones per call breaks errors.Is.
  • Ecosystem. golang.org/x/sync/errgroup (first error cancels the group), sony/gobreaker, cenkalti/backoff, log/slog for structured logs, net/http/httptest for fault-injecting fakes.

Laravel ​

Before ​

A controller with no timeout, no idempotency key, string matching on the body, a catch-all that hides bugs and leaks messages, and a loop that swallows failures.

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.
            }
        }
    }
}

After ​

The hierarchy and the problem details helper:

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 {}

The single place for reporting and rendering:

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();

The circuit breaker, the gateway that applies timeout + retry + breaker + idempotency key, and the use case with its fallback job:

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 for our own endpoints, cleanup, and the fault-injection test:

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);
        }
    }
}

The Laravel angle ​

  • withExceptions is the boundary. report, render, level, dontReport, throttle, context, dontReportDuplicates, respond, and for jobs dontRetry/dontRetryWhen, all in bootstrap/app.php.
  • Exceptions can render themselves. A render(Request $request) method on the exception (returning false falls back to the default) and report(); context() adds log fields.
  • report($e) vs throw. report() logs through the handler and lets the request continue (the fallback path); throw lets the boundary decide; rescue() is "try, report, return a default".
  • abort(404) / abort_if throw HttpExceptions that the handler renders; use them in controllers, not in domain code.
  • The HTTP client does not throw on 4xx/5xx ("Unlike Guzzle's default behavior"); call throw(), or use retry(), which throws RequestException when all attempts fail unless throw: false.
  • Jobs. #[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 shares nothing. Breaker state, retry budgets and idempotency records must live in Redis or the database; under Octane, in-memory state is per worker.

Solving the classic problems ​

ProblemSolutionHowAdvantageCost / limitation
Retry storm during an outageRetry at one layer + jitter + budget + breakerresilience.Do, Http::retry with closure, breakerDependency can recoverSome requests fail instead of waiting
Double charge after a timeoutIdempotency key per operationIdempotency-Key: order-{id}-paymentRetries become safeKey storage, TTL, payload fingerprint
Hung workersTimeouts + bulkheadper-attempt ctx, Http::timeout, separate queuesFailure stays localTuning from latency data
Bugs hidden as "payment failed"Typed errors, no catch-allBusinessException vs ErrorBugs reach SentryMore classes
Log and alert noiseHandle once, ShouldntReport, throttlewithExceptionsSignal over noiseDiscipline in reviews
Internals leaked in responsesRFC 9457 + APP_DEBUG=falseProblem::responseSafe, uniform errorsOne more format to document
Poison message retried foreverMax attempts + DLQ + failed()retryUntil, failed_jobs, DLQ topicQueue keeps movingSomeone must own the DLQ
Half-done cross-service workSaga with compensationsrefund on later-step failureConsistent outcomeEventual, not atomic
Job dispatched for a rolled-back rowafterCommit() / outboxsame transactionNo phantom workRelay to operate (outbox)

Retry storm ​

The symptom is a dependency that recovers for seconds and falls over again, with request rate to it several times the user rate. Remove retries from every layer but one (usually the client closest to the dependency), switch to full jitter, add a process-wide retry budget, and put the breaker in front so an open circuit stops retries entirely. The lab shows attempt 4 rejected locally once the breaker opened.

Double charge ​

The symptom is two charges a few hundred milliseconds apart for one order. The fix is a key per business operation, reused on every attempt, the fallback path and the async job; the provider (or your own EnsureIdempotency) replays the first result. Scenario B' of the lab reproduces the bug: 2 charges for one order.

Hidden bugs ​

The symptom is an error rate that never reaches the tracker. Delete catch-alls in business code, let Error/panics reach the boundary, keep ShouldntReport for business exceptions only, and add a test that asserts a bug becomes a 500 with exactly one log entry (the Go layers test does).

Choosing ​

SituationRecommendationExtra techniqueReason
Expected business "no"Typed error / business exception, 4xxStable code, no alertIt is an outcome, not a failure
Bug detectedFail fast: panic / let Error propagateRecover only at the edgeContinuing on bad state is worse
Read from a flaky dependencyTimeout + retry (idempotent) + breaker + cached fallbackCache::flexible, stale labelReads are safe to repeat
Write to a flaky dependencyTimeout + retry with idempotency key + breaker + queue-for-laterOutbox / afterCommitA timeout is an unknown outcome
Slow, not failing, dependencyBulkhead + tight timeoutLoad shedding upstreamProtects capacity
Async job calling an APIretryUntil + #[Backoff] + ThrottlesExceptionsfailed() + DLQ ownerTime budget, queue-side breaker
Many validation problemsCollect all, one 422errors.Join, Form RequestOne round trip for the user
Multi-service workflowSaga with compensationsIdempotent stepsNo distributed transaction
OverloadShed low-priority work, 503 + Retry-AfterPrioritiesFinish some work instead of none

In architecture: from a single process to a distributed system ​

The question "who handles this failure, and how?" has the same answer at every size: translate at boundaries, handle once at the outermost boundary, and treat every remote call as able to fail, be slow, or succeed without telling you.

Monolith: one process, one database ​

How it shows up: exceptions and error values inside one call stack, one global handler, one database transaction per use case. Failures are mostly bugs, validation and database errors.

Simplest correct usage: a shallow exception tree, withExceptions (or one Go middleware) as the only logger, DB::transaction for atomicity, timeouts on the few external calls (payment, email, maps).

Example (simple): a blog: ValidationException to 422, ModelNotFoundException to 404, everything else 500 + Sentry.

Example (complex): a shop monolith calling a payment provider: PaymentGateway is the only class that knows the provider, translates to PaymentDeclined/PaymentUnavailable, and the checkout falls back to payment_pending + a queued job.

Modular monolith and multiple databases ​

How it shows up: modules call each other in-process, but each owns its errors. A module's public API exposes its domain errors, never another module's or the ORM's.

Rules: translate at module facades (Billing's ChargeOrder throws Billing\PaymentDeclined, not a Stripe exception); no catch of another module's internal exception types (architecture tests); if modules have separate databases, a call across them is no longer atomic: use afterCommit events or an outbox even in-process.

Microservices: errors across a network boundary ​

What survives: typed domain errors become contracts: problem type URIs and codes documented in the API spec (OpenAPI) and stable across versions. What breaks: exceptions do not cross the wire; stack traces must not; a timeout is an unknown outcome; retries multiply per 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

Example: checkout in a microservice shop: the saga charges, reserves and ships; each step and each compensation carries a key; failures that exhaust retries land in a DLQ with an owning team.

Distributed data: replicas, caches and partitions ​

Where error handling changes: a read from a lagging replica returns stale data without any error; a cache can serve a stale value as a fallback (good) or hide an outage until TTL expires (bad); a failover turns writes into connection errors for seconds (retry transient errors on the whole transaction); network partitions mean some nodes see a dependency as up while others see it as down (per-instance breakers disagree, which is fine). See Replication & Failover.

Countermeasures: treat 40001/40P01/failover errors as retryable at the transaction level, mark fallback responses as stale, alert on breaker-open and DLQ growth, and run chaos experiments for partitions.

Scaling path: 1×, 10×, 100× ​

ScaleStructureError and fault-tolerance practice
1× (one app, one team)MonolithTyped errors, one handler, timeouts on every external call, Sentry
10× (several teams, queues)Modular monolith + workersProblem details contract, idempotency keys, job retryUntil/failed(), breaker per provider, bulkhead queues
100× (many services, regions)MicroservicesDeadline propagation, retry budgets, mesh-level outlier detection, load shedding by priority, SLO-driven alerts and error budgets, game days

Lab: order service vs a flaky payment API ​

You run an order service against a fake payment provider that injects faults on a schedule: a 503, a slow response (the provider charges, the client times out), the same slow response without an idempotency key, a declined card, an outage, and recovery. Everything runs offline.

Setup.

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())
}

Real output (deterministic: the jitter source is seeded and the breaker clock is advanced by hand):

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

Step 1: read the scenarios. A: a transient 503 is invisible to the user. B: the timeout was an unknown outcome; the retry with the same key gets the same ch_2, one charge. B': the same fault without a key creates ch_3 and ch_4 for one order: a double charge. C: a 402 is a domain outcome: one attempt, and the breaker does not count it. D: the third 503 trips the breaker, so attempt 4 never leaves the process; the order degrades to payment_pending. E: fail fast, zero requests. F: after the open period, one trial call closes the breaker and the queue drains with the original keys.

Step 2: break the classification. In lab/main.go, change IsFailure to nil (every error counts). Run again (we did): the declined card in C now counts toward the threshold, so in D the breaker opens after attempt 2 instead of attempt 3, and D sends 2 requests instead of 3 (provider so far: 9 requests). Restore it.

Step 3: add a second retry layer (on paper first). If OrderService.Checkout wrapped Charge in another resilience.Do with 3 attempts and no breaker existed, one order in D could cause 3 × 4 = 12 provider requests instead of 4: the SRE book's multiplication. With the breaker in place the inner layer returns ErrOpen, which IsTransient treats as permanent, so the outer layer stops early: one more reason to keep ErrOpen non-retryable and retries in one layer.

Step 4: remove jitter. Replace Rand: rng.Float64 with Rand: func() float64 { return 1 } and change rng := ... to _ = .... Run again (we did): every wait becomes the full ceiling, 20, 40, 80 ms, identical for every client: synchronized retries.

Step 5: Laravel. Copy PaymentGateway.php, CircuitBreaker.php and PaymentGatewayTest.php into a Laravel 13 app and run php artisan test --filter=PaymentGatewayTest. Expected output (not run here; PHP is not installed on the machine that wrote this page):

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

Common misconceptions ​

BeliefReality
Catching Throwable everywhere makes the app robustIt hides bugs (TypeError, Error) behind friendly messages
A timeout means the operation failedIt means the outcome is unknown; only idempotency makes a retry safe
More retries mean more reliabilityRetries at several layers multiply load and cause retry storms
Every error should be logged where it happensLog once at the boundary; inner layers add context
Wrapping with %w is always goodWrapping makes the cause part of your API
Business errors should alert on-callThey are outcomes; count them, do not page on them
A circuit breaker fixes the dependencyIt fails fast and gives the dependency room; you still need a fallback
4xx responses should trip the breakerOnly 5xx, timeouts and connection errors indicate an unhealthy dependency
recover is Go's catchOnly for the outermost edge; libraries return errors
finally runs only when something failsIt runs on every path
Exactly-once delivery can be guaranteed by the transportAt-least-once + idempotent processing is how exactly-once effects are built
Return the exception message so clients can debugProblem details describe the HTTP interface, not internals
Defensive null checks everywhere are safeThey turn bugs into silent wrong results; validate at the edge, assert inside

Cheat sheet ​

TopicRemember
TaxonomyBug → fail fast; domain → typed error, 4xx; infrastructure → transient (retry) or permanent (alert)
Go shapesSentinel + errors.Is; typed + errors.As/AsType; %w wraps, %v hides; errors.Join for many
PHP shapesError = bugs, Exception = recoverable; one BusinessException base with code()
Handle onceTranslate in adapters, decide in services, log + respond at the boundary
Laravel boundarywithExceptions: report, render, level, dontReport, throttle, context, dontRetry
TimeoutsAlways explicit; per attempt inside a caller deadline; Go default none, Laravel 30 s
RetryTransient only, one layer, exponential backoff + full jitter, budget, honour Retry-After
IdempotencyKey per business operation, reused on retries, fallbacks and jobs
Circuit breakerClosed → open on threshold → half-open after timeout → trial decides; only 5xx/timeouts count
BulkheadSeparate pools/queues per dependency
DegradationFallbacks are product decisions; shed low-priority load with 503 + Retry-After
API errorsRFC 9457 application/problem+json: type, title, status, detail, instance, code
Cleanupdefer + join Close errors; finally; no HTTP calls inside DB transactions
TestsTable-driven, fault injection (httptest, Http::fake), assert kinds and side effects

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — A Laravel action catches Throwable, logs it and returns null. Name two concrete problems. Must-know ​

Answer

Answer: It hides bugs (TypeError, Error) that should reach the tracker, and callers cannot tell a missing result from a failure, so the failure disappears. Catch the specific business or infrastructure exception you can handle; let the rest reach the boundary.

2 — Your repository returns fmt.Errorf("find: %w", err) where err is from pgx. What did you just promise callers? Important ​

Answer

Answer: That pgx errors are part of your API: callers may now errors.As into *pgconn.PgError, and you cannot switch drivers without breaking them. Translate to a domain sentinel (ErrOrderNotFound, ErrStoreUnavailable) and keep the driver text with %v. See Designing error types.

3 — A payment call timed out. Is it safe to retry? Must-know ​

Answer

Answer: Only if the request carries an idempotency key the provider honours. A timeout is an unknown outcome: the charge may already exist. Lab scenario B' shows the double charge without a key.

4 — Three layers each retry 3 times (4 attempts). How many attempts can one user action cause at the bottom? Must-know ​

Answer

Answer: 4 × 4 × 4 = 64, the SRE book's example. Retry at one layer only and add a budget.

5 — Which errors should trip a circuit breaker for a payment API? Important ​

Answer

Answer: Timeouts, connection errors and 5xx (and arguably 429). Never 402/4xx or domain errors: they say nothing about the provider's health.

6 — What is the difference between fail-fast and fail-safe? Give one example of each. Must-know ​

Answer

Answer: Fail-fast detects early and stops (panic on a nil order; reject immediately when the breaker is open). Fail-safe leaves a harmless state (roll back the transaction; deny access when the permission service is down).

7 — Why does a PHP circuit breaker keep its state in Redis instead of a static property? Important ​

Answer

Answer: PHP-FPM workers share no memory and forget everything after each request, so a static property would reset every time. Under Octane it would be per worker.

8 — Your Go HTTP handler starts go sendEmail() which panics. Does the Recoverer middleware save the server? Important ​

Answer

Answer: No. recover only works in the goroutine that panicked; a panic in an unrecovered goroutine terminates the process. Recover inside that goroutine or use errgroup. See Panics.

9 — What goes into an RFC 9457 response for a database outage, and what must not? Important ​

Answer

Answer: Status 503, a type such as .../unavailable, a short title, instance, a code, and a Retry-After header. Not the driver message, host names, SQL or stack trace.

10 — A queued job calls an unstable API. Which Laravel features give it a time budget, spaced retries, a queue-side breaker and a dead letter? Important ​

Answer

Answer: retryUntil() (or #[RetryFor]), #[Backoff([...])], the ThrottlesExceptions middleware, and failed() plus the failed_jobs table; dontRetry() for permanent errors.

11 — Why should an external HTTP call not run inside DB::transaction? Must-know ​

Answer

Answer: The transaction holds locks for the whole duration of the call (seconds during an incident), and a rollback cannot undo the remote side effect. Call outside, then record the result; use afterCommit() or an outbox for follow-ups.

Glossary ​

TermMeaning
Programmer bugA state the author did not anticipate; fail fast and fix
Domain error (expected error)A documented business outcome such as "declined" or "not found"
Infrastructure failureFailure of I/O or another component; transient or permanent
Transient errorMay succeed if retried later (timeout, 503, 429, deadlock)
Recoverable vs unrecoverableRust's and PHP's split: Result/Exception vs panic!/Error
Sentinel errorA package-level error value compared with errors.Is
Typed errorAn error type with fields, inspected with errors.As/errors.AsType
Wrapping (%w, Unwrap)Adding context while keeping the cause inspectable; makes it API
errors.JoinCombines several errors into one with Unwrap() []error
Error codeA stable machine-readable identifier at the boundary
ThrowablePHP's base interface for Error and Exception
ErrorExceptionPHP exception used to turn diagnostic errors into throwables
Checked exceptionAn exception the compiler forces callers to handle or declare (Java)
Result<T, E>Rust type that holds either a value or an error
Handle onceLog and respond in one place, the outermost boundary
Log and rethrowAnti-pattern: logging and propagating the same error
SwallowingCatching an error and doing nothing with it
InvariantA rule an object always keeps; breaking it is a domain error or a bug
AssertionA check that can fail only if the code has a bug
Fail-fastStop at the first sign of a problem (Nygard: reject early)
Fail-safeFail into a harmless state (deny, roll back)
Defensive programmingGuarding against impossible states; limited, because it hides bugs
panic / recoverGo's unwinding for bugs and its edge-only catch
defer / finally / RAIICleanup that runs on every path
Timeout / deadlineMax time for one operation / absolute time for a whole request
Deadline propagationPassing the caller's deadline to every downstream call
Exponential backoffWaiting longer after each failure
Full jitterRandom wait in [0, ceiling) to desynchronise clients
Retry stormLoad amplification from retries at many layers or clients
Retry budgetA cap on retries per process or per time window
Idempotency keyClient-generated id that lets the server replay instead of repeat
Circuit breakerClosed/open/half-open guard that fails fast while a dependency is down
Half-openBreaker state that allows limited trial calls
BulkheadIsolated resource pool per dependency
FallbackA lesser answer used when the primary fails
Graceful degradationReducing work or quality instead of failing
Load sheddingDropping some requests early under overload
Cascading failure"a failure that grows over time as a result of positive feedback" (SRE book)
Steady stateNygard pattern: the system keeps running without human cleanup (logs, data purge)
Let It CrashNygard pattern: restart a failed component rather than repair its state
Partial failurePart of a distributed operation succeeded, part did not
Two generals problemProof that agreement over an unreliable channel cannot be guaranteed
At-least-onceDelivery with retries; duplicates possible, receivers must be idempotent
Dead letter (DLQ, failed_jobs)Storage for work that failed permanently or ran out of retries
Saga / compensationLocal steps plus undo actions instead of a distributed transaction
OutboxWriting a message in the same DB transaction as the state change
RFC 9457 / application/problem+jsonStandard HTTP error body: type, title, status, detail, instance
Retry-AfterHTTP header telling clients how long to wait (RFC 9110)
Structured loggingLogs as key/value fields (log/slog, Monolog context)
SentryError tracker that groups exceptions into issues
Error budgetAllowed unreliability under an SLO
Fault injectionMaking dependencies fail on purpose in tests or experiments
Table-driven testOne test, many rows of input and expected error
Http::fakeLaravel's HTTP client fake for injecting responses and failures

References ​

Built by Morteza Negahi