Skip to content

Designing for Failure & Reliable Messaging in Microservices ​

"A consequence of using services as components, is that applications need to be designed so that they can tolerate the failure of services." — Martin Fowler و James Lewis، Microservices (۲۵ مارس ۲۰۱۴)، بخش «Design for failure»

خلاصه (Summary): یک bounded context وقتی همسایه‌هایش خراب می‌شوند درست می‌ماند که هر پیام را «ممکن است دیر، تکراری، جابه‌جا یا گم‌شده» فرض کند: یک aggregate و یک ردیف outbox در هر تراکنش محلی، یک inbox که consumer را idempotent می‌کند، یک saga با compensation و deadline برای فرایندهای میان‌contextی، و محصولی که وضعیت «در انتظار» را صادقانه نشان می‌دهد. تمرکز (Focus): طبقه‌بندی شکست‌هایی که context باید فرض کند، مدل Helland (entity و پیام) و اینکه چرا exactly-once بیشتر شعار است، aggregate به‌عنوان جزیرهٔ سازگاری، انتشار مطمئن (outbox، polling در برابر log tailing، ترتیب per-aggregate)، مصرف مطمئن (inbox، کلید dedup، version، handlerهای جابه‌جاپذیر)، retry با backoff و پیام‌های poison، saga سفارش (رزرو موجودی ← پرداخت ← ارسال) با مسیرهای شکست و timeout، سازگاری نهایی به‌عنوان تصمیم محصول، حالت‌های degraded، کلید idempotency در لبهٔ API، تست با تزریق شکست، observability و anti-patternها. هدف یادگیری (Learning goal): با داشتن جریانی که از Sales و Fulfilment و Billing می‌گذرد، پیام‌ها، جدول‌های outbox و inbox، state ی saga و compensationها را طوری طراحی کنید که هر شکست تکی، پیام تکراری یا جابه‌جایی به وضعیتی درست و قابل‌توضیح برسد؛ آن را در Go و Laravel بسازید؛ و با تست‌هایی که خود شکست را تزریق می‌کنند ثابتش کنید.

این فصل در گروه DD 03 (داده و API در میکروسرویس‌ها) است. این نگاه DDD و میکروسرویس به شکست است: یک bounded context چطور مدل خودش را درست نگه می‌دارد وقتی بقیه بد رفتار می‌کنند. مکانیک‌ها جای دیگری توضیح داده شده و این‌جا فقط لینک می‌شوند: الگوهای تاب‌آوری در سطح کد (timeout، retry، circuit breaker، bulkhead) در Error Handling & Fault Tolerance؛ تصمیم همگام یا ناهمگام در Service Communication؛ و مکانیک outbox و DLQ و idempotent consumer و saga در Transactional Outbox، Dead-Letter Queue، Idempotent Consumers & the Inbox و Saga Pattern. این‌جا آن‌ها را دور aggregate می‌چینیم و روی یک مثال جاری به کار می‌بریم.

مثال جاری همان است که در کل مسیر DDD می‌آید: کسب‌وکار سفارش آنلاین و ارسال با contextهای Sales، Fulfilment، Billing، Catalog و Identity. جریان: مشتری سفارش می‌دهد (Sales)، موجودی رزرو می‌شود (Fulfilment)، کارت شارژ می‌شود (Billing)، مرسوله ساخته می‌شود (Fulfilment)، سفارش تأیید می‌شود (Sales). هر context دیتابیس خودش را دارد (Data Ownership).

نقشهٔ صفحه (Page map) ​

دنبال چه هستیدبروید به
کل صفحه در چهار جدولهمه‌چیز در یک دقیقه
چرا context باید شکست را فرض کندچرا وجود دارد
Sagas 1987، Helland 2007، Nygard، Fowler، SRE، AWSاز کجا آمده
هشت شکستی که باید فرض کردطبقه‌بندی شکست
entity، activity، پیام، «exactly-once دروغ است»مدل Helland
aggregate به‌عنوان جزیره، یک تراکنش برای هر aggregateجزیره‌های سازگاری
outbox، polling در برابر log tailing، ترتیب per-aggregateانتشار مطمئن
inbox، کلید dedup، version، handler جابه‌جاپذیرمصرف مطمئن
partition key، بررسی version، gapترتیب
backoff، jitter، پیام poison، DLQ، parkingretry و پیام‌های poison
choreography و orchestration، compensation، timeoutSagaها
state ی saga به‌عنوان aggregateSaga به‌عنوان aggregate
وضعیت «در انتظار» و «ناموفق» در محصولسازگاری نهایی به‌عنوان تصمیم محصول
خواندن کهنه، feature flag، پذیرش سفارش وقتی Billing پایین استحالت‌های degraded
timeout، بودجهٔ زمان، breaker در لبهلبهٔ context
Idempotency-Key روی فرمان‌هافرمان idempotent در لبهٔ API
تزریق شکست، replay، contract testتست
correlation، causation، lag، عمق DLQObservability
آنچه نباید کردAnti-patternها
کد کاملGo، Laravel
مسئله‌های مشخص و راه‌حلحل مسئله‌های کلاسیک
کدام تکنیک برای کدام وضعیتانتخاب
از monolith تا توزیع‌شدهدر معماری
تمرین عملیآزمایشگاه
باورهای غلط، چکیده، خودآزمایی، واژه‌هابدفهمی‌ها، چکیده، خودآزمایی، واژه‌نامه

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

هشت شکستی که context باید فرض کند (هر کدام یک بلوک در طبقه‌بندی دارد):

شکستبه زبان سادهاگر نادیده گرفته شود چه می‌شکنددفاع اصلی
همسایه پایین است (Down)کسی جواب نمی‌دهدفراخواننده گیر می‌کند یا می‌افتدTimeout، پیام ناهمگام، حالت degraded
همسایه کند است (Slow)بعد از اینکه فراخواننده منصرف شد جواب می‌دهدthreadها انباشته می‌شوند، cascadeDeadline، بودجهٔ زمان، breaker، bulkhead
داده‌ی بی‌معنی (Garbage)پاسخی که قرارداد یا معنا را نقض می‌کندstate محلی خراب می‌شوداعتبارسنجی، ACL، contract test، DLQ
تکرار (Duplicate)یک پیام دو بارشارژ دوباره، رزرو دوبارهInbox، کلید idempotency، idempotency طبیعی
جابه‌جایی (Out of order)پیام ۲ قبل از ۱state قدیمی روی جدید می‌نشیندترتیب per-key، version، handler جابه‌جاپذیر
گم‌شدن (Lost)فرستاده شد و نرسیدسفارش برای همیشه معلق می‌ماندOutbox، at-least-once، deadline، reconciliation
شکست جزئی (Partial failure)گام ۲ از ۴ انجام شد، گام ۳ نهپول گرفته شد، چیزی ارسال نشدSaga با compensation
اختلاف ساعت (Clock skew)دو ماشین دربارهٔ «الان» اختلاف دارندترتیب و deadline غلطversion و sequence؛ deadline روی ساعت صاحب‌اش

جعبه‌ابزار پیام‌رسانی مطمئن:

بلوککجا زندگی می‌کندچه می‌دهدهزینه
Aggregate + versionدرون یک contextسازگاری فوری یک جزیرهaggregateهای کوچک، retry هنگام تداخل
Transactional outboxدیتابیس تولیدکننده«state عوض شد» و «پیام فرستاده می‌شود» یک واقعیت‌اندیک relay و یک جدول برای پاک‌سازی
Relay (polling یا log tailing)سمت تولیدکنندهانتشار at-least-onceتکرار، lag، یک پردازهٔ دیگر
Inbox / جدول processed-idsدیتابیس مصرف‌کنندهپردازش effectively-onceیک ردیف برای هر پیام، سیاست نگهداری
کلید Idempotencyلبهٔ API و فراخوانی providerretry امن برای کلاینتیک مخزن کلید
Sagaمیان contextهااتمیک بودن در سطح کسب‌وکار با compensationstate، timer، طراحی compensation
DLQ / parking lotسمت مصرف‌کنندهپیام poison صف را قفل نمی‌کندکسی باید آن را بخواند
Deadline و timersaga و لبههیچ‌کس تا ابد منتظر نمی‌ماندانتخاب timeout، پاسخ‌های دیررس

تضمین‌های تحویل در یک جدول (جزئیات در Delivery Guarantees):

تضمینچه چیز می‌تواند خراب شودچه کسی باید کنار بیایدکاربرد معمول
At-most-onceپیام گم می‌شودکسب‌وکار، با reconciliationmetric، اعلان بی‌اهمیت
At-least-onceپیام تکرار می‌شودconsumer، با idempotencyتقریباً همهٔ پیام‌رسانی کسب‌وکاری
«Exactly-once»شعار: at-least-once به‌علاوهٔ dedup، فقط درون مرز یک سیستمهرکس ادعا می‌کند، در مرز خودشتراکنش Kafka میان topicهای Kafka؛ دیتابیس شما بیرون است

نتیجه‌های saga در مثال جاری:

رویدادواکنش sagaCompensation
StockRejectedفوراً لغوهیچ: چیزی انجام نشده بود
PaymentDeclinedجبرانآزادسازی موجودی
ShipmentFailedجبرانبازپرداخت و آزادسازی موجودی
Timeout در هر گامجبران با فرمان‌هایی که هر کاری همسایه کرده باشد امن‌اندآزادسازی، بازپرداخت (idempotent، tombstone)
پاسخ دیررس بعد از لغودوباره خنثی می‌شوددوباره آزادسازی یا بازپرداخت

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

در یک monolith، «سفارش را ثبت کن، موجودی را رزرو کن و کارت را شارژ کن» یک تراکنش دیتابیس است: هر سه انجام می‌شوند یا هیچ. بعد از تقسیم، سه دیتابیس و یک شبکه وسط ایستاده است. Fowler و Lewis می‌گویند: "Distributed transactions are notoriously difficult to implement and as a consequence microservice architectures emphasize transactionless coordination between services, with explicit recognition that consistency may only be eventual consistency and problems are dealt with by compensating operations."

پرسش طراحی از «چطور این را اتمیک کنم؟» به «اگر فقط نصفش انجام شد چه چیز درست است و چه کسی درستش می‌کند؟» تغییر می‌کند.

Two-phase commit میان سرویس‌هاتراکنش محلی + پیام + compensation
شبیه monolith استمتفاوت به نظر می‌رسد؛ کسب‌وکار «در انتظار» را می‌بیند
قفل‌ها از روی شبکه نگه داشته می‌شوندقفل فقط درون یک دیتابیس
هر شرکت‌کننده باید پشتیبانی کند (broker، دیتابیس، provider)با هر دیتابیس و هر broker از نوع at-least-once کار می‌کند
یک شرکت‌کنندهٔ کند یا مرده همه را بلاک می‌کندهر گام خودش پیش می‌رود یا timeout می‌شود
دسترس‌پذیری کل حاصل‌ضرب دسترس‌پذیری اجزاستهر context برای کار خودش در دسترس می‌ماند
مرگ coordinator قفل‌های نامعلوم باقی می‌گذاردشکست یک state ی saga و یک timer باقی می‌گذارد که ادامه می‌دهند
میان شرکت‌ها دشوار (شبکهٔ کارت، پیک)طبیعی: گام بیرونی فقط یک پیام است

تشبیهی که در این صفحه تکرار می‌کنیم: پست سفارشی میان سه اداره. Sales و Fulfilment و Billing سه اداره‌اند. هرگز یک کمد پرونده مشترک ندارند؛ نامه می‌فرستند. نامه ممکن است دو بار برسد (منشی دوباره فرستاد چون رسید گم شد)، دیر برسد، جابه‌جا برسد یا اصلاً نرسد. هر اداره دفتر خودش را دارد (دیتابیسش)، شمارهٔ هر نامهٔ ورودی را در «دفتر دریافت» (inbox) ثبت می‌کند، و نامهٔ خروجی را در همان لحظه‌ای که دفتر خودش را به‌روز می‌کند در «سبد ارسال» (outbox) می‌گذارد. مدیر (saga) برای هر سفارش یک چک‌لیست دارد، برای هر گام یک مهلت، و برای هر گام موفق یک نامهٔ «لغو».

SalesFulfilmentBillingOrder aggregateversion, status, invariantsStock / Shipment aggregateown invariantsPayment aggregateown invariantsoutbox row (same tx)inbox row (same tx)inbox row (same tx)own databaseown databaseown databaseBroker: at-least-onceduplicated, delayed, lost, reordered, never in a shared transactionInside an island: ACID. Between islands: messages, ids, versions, compensations.

شکل سه context را به‌شکل جزیره نشان می‌دهد. درون هر جزیره یک تراکنش محلی اتمیک است: یک aggregate و یک ردیف outbox یا inbox. میان جزیره‌ها فقط پیام می‌رود، از طریق broker ای که at-least-once است. هیچ تراکنشی از دو جزیره نمی‌گذرد.

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

  1. «broker ما exactly-once تضمین می‌کند، پس consumer به dedup نیاز ندارد.» Exactly-once ویژگی درون یک مرز است (تراکنش‌های Kafka درون Kafka). همین‌که handler شما در PostgreSQL می‌نویسد، یک crash میان نوشتن و commit کردن offset پیام را دوباره تحویل می‌دهد. باز هم inbox لازم است (مصرف مطمئن).
  2. «retry همیشه امن است.» retry یک فراخوانی غیر-idempotent بعد از گم‌شدن پاسخ، مشتری را دو بار شارژ می‌کند. AWS: "a best practice is designing APIs to be idempotent, meaning they can be safely retried." (فرمان idempotent).
  3. «اگر Billing پایین است، Sales باید خطا بدهد.» Sales می‌تواند سفارش را در انتظار بپذیرد و وقتی Billing برگشت کار را تمام کند. اینکه مجاز است یا نه تصمیم محصول است، نه فنی (تصمیم محصول، حالت‌های degraded).

از کجا آمده ​

Garcia-Molina و Salem، ۱۹۸۷. مقالهٔ Sagas (ACM SIGMOD 1987) یک تراکنش طولانی را به دنباله‌ای از زیرتراکنش‌ها شکست که هرکدام یک تراکنش جبرانی دارد که از نظر معنایی آن را خنثی می‌کند، تا قفل‌ها در کل مدت نگه داشته نشوند. من خود مقاله را نتوانستم بخوانم (صفحهٔ ACM جلوی کلاینت‌های خودکار را می‌گیرد و PDF آزاد، اسکن بدون لایهٔ متن است)، پس این توضیح بر منبع ثانویهٔ microservices.io تکیه دارد که saga را "a reliably coordinated sequence of local transactions" تعریف می‌کند.

Nygard، Release It! (چاپ اول ۲۰۰۷). الگوهای پایداری Timeout و Circuit Breaker و Bulkhead. bliki ی Fowler به آن اشاره می‌کند: "In his excellent book Release It, Michael Nygard popularized the Circuit Breaker pattern to prevent this kind of catastrophic cascade." ما این الگوها را فقط به‌عنوان اشاره می‌آوریم؛ جایشان Error Handling & Fault Tolerance و Circuit Breaker است.

Helland، ۲۰۰۷. مقالهٔ CIDR با عنوان Life beyond Distributed Transactions: an Apostate's Opinion پایهٔ این فصل است. سه ادعایش: برنامه‌های مقیاس‌پذیر روی entityهای دارای شناسهٔ یکتا کار می‌کنند؛ "Atomic Transactions Cannot Span Entities"؛ و پیام‌رسانی میان entityها "at-least-once" است، پس گیرنده باید یادش بماند چه چیزی را پردازش کرده. این همان ایدهٔ aggregate در Evans است (Aggregates & Factories). مقالهٔ بعدی‌اش Idempotence Is Not a Medical Condition (ACM Queue، ۲۰۱۲) را بسیاری ارجاع می‌دهند؛ نتوانستم بگیرمش (Cloudflare کلاینت خودکار را رد می‌کند) پس هیچ چیز این صفحه از آن نقل نشده.

Fowler و Lewis، ۲۰۱۴. مقالهٔ microservices «Design for failure» را یک ویژگی می‌داند و «هماهنگی بدون تراکنش» با compensation را سبک سازگاری.

Richardson، microservices.io (از ۲۰۱۸ به بعد). صفحه‌های کاتالوگ Saga، Transactional Outbox، Polling Publisher، Transaction Log Tailing و Idempotent Consumer شکل الگوهای زیر را می‌دهند.

Google SRE و AWS Builders' Library. فصل Addressing Cascading Failures از کتاب SRE حالت شکستی را تعریف می‌کند که retry می‌تواند بسازد؛ مقاله‌های AWS با عنوان Timeouts, retries, and backoff with jitter و Avoiding fallback in distributed systems (هر دو منتشرشده ۵ دسامبر ۲۰۱۹) قواعد retry و fallback مورد استفاده در retry و حالت‌های degraded را می‌دهند.

text
     Year   Source                                     What it added
1    1987   Garcia-Molina & Salem, Sagas               Long transaction = sub-transactions + compensations
2    2007   Nygard, Release It!                        Timeout, circuit breaker, bulkhead as stability patterns
3    2007   Helland, Life beyond Distributed Tx        Entities, no atomic tx across them, at-least-once messages
4    2014   Fowler & Lewis, Microservices              "Design for failure"; eventual consistency + compensations
5    2016   Google SRE book, Cascading Failures        Retry amplification, deadlines, load shedding
6    2018   Richardson, microservices.io               Saga, outbox, polling publisher, log tailing, idempotent consumer
7    2019   AWS Builders' Library                      Backoff with jitter, retry limits, avoid untested fallback

سال ردیف‌های ۱، ۲، ۵ و ۶ (مقالهٔ Sagas، چاپ اول Release It!، کتاب SRE و کاتالوگ الگو) سال انتشار است آن‌طور که معمولاً ذکر می‌شود؛ روی صفحه‌هایی که ذخیره کردم چاپ نشده. ردیف‌های ۳، ۴ و ۷ از صفحه‌هایی است که خواندم.

فهرست مفاهیم ​

طبقه‌بندی شکست (Failure taxonomy) حیاتی ​

به زبان ساده: قبل از هر طراحی فهرست کنید همسایه‌ها چطور می‌توانند بد رفتار کنند. هشت راه هست و هرکدام جواب جدا می‌خواهد.

بدفهمی رایج: «شکست یعنی exception.» بیشتر شکست‌ها در پیام‌رسانی exception نیستند: پیام تکراری یا جابه‌جا یک پیام کاملاً معتبر است که در لحظهٔ نادرست می‌رسد، و همسایهٔ کند هیچ چیزی پرتاب نمی‌کند.

تعریف: مدل شکست (Failure model) یک context مجموعهٔ رفتارهای همسایه‌ها، broker و شبکه است که طراحی باید تحمل کند. مدل این صفحه: crash یا پایین بودن، کندی، داده‌ی بی‌معنی، تکرار، جابه‌جایی، گم‌شدن، شکست جزئی (فرایند چندگامی وسط راه می‌ایستد) و اختلاف ساعت.

text
     Sales                      Broker                     Billing
1    place order (tx commits)
2    outbox row "OrderPlaced"
3    relay publishes ---------> stored, ack LOST (network)
4    relay: no ack, retry ----> stored again (duplicate)
5                               delivers #1 ------------> charge, commit
6                               delivers #2 ------------> same message id: skipped by inbox
7                                                          reply "PaymentCharged" (outbox)
     Failure seen by Sales at step 3: "lost ack" = unknown outcome, never "failed"
شکستچطور دیده می‌شودسناریوی واقعینشانهٔ محصولیدفاعکجا در این صفحه
همسایه پایینConnection refused، consumer ی روی صف نیستdeploy ی Billing، failover دیتابیسخطا در checkout یا «در انتظار»پیام ناهمگام، deadline، حالت degradedDegraded
همسایه کندp99 بالا می‌رود، بعد timeoutصادرکنندهٔ کارت با ۸ ثانیهاتمام thread pool، cascadetimeout هر فراخوانی، انتشار deadline، breakerلبه
داده‌ی بی‌معنینقض schema، مقدار غیرممکن، نوع ناشناختهتولیدکننده qty: -1 می‌فرستدموجودی خراباعتبارسنجی در لبه، ACL، contract test، DLQRetry
تکرارهمان message_id دو بارcrash ی relay بعد از publish، redelivery بعد از crash ی consumerدو بار شارژInbox، کلید idempotencyمصرف
جابه‌جاییOrderCancelled قبل از OrderPlacedدو partition، retry، consumer موازیسفارش لغوشده «تأییدشده» دیده می‌شودpartition per-key، version، tombstoneترتیب
گم‌شدنهرگز نمی‌رسدdual write، crash بعد از commit، acks=0، auto-ack و بعد crashسفارش در انتظار گیر می‌کندOutbox، deadline، job ی reconciliationانتشار
شکست جزئیبعضی گام‌ها انجام شد، یکی نهموجودی رزرو شد، کارت رد شدموجودی برای همیشه نگه‌داشته می‌شودSaga با compensation و timerSagaها
اختلاف ساعتcreated_at ی B زودتر از A است در حالی که B معلول A بوددو host، drift ی NTP«آخرین برنده» غلط، timeout زودرسversion و شمارهٔ ترتیب؛ deadline روی ساعت صاحب‌اشترتیب، Sagaها

دفاع در هر محصول:

محصولمنبع تکرارتضمین ترتیبخطر گم‌شدن
RabbitMQredelivery بعد از crash ی consumer یا nack با requeue؛ retry ی publisher بدون dedup روی confirmper queue، با requeue و چند consumer می‌شکندauto-ack و crash؛ publish بدون confirm؛ صف غیر durable
Apache Kafkaretry ی producer بدون idempotence؛ پردازش دوبارهٔ consumer بعد از rebalanceper partitionacks=0/1 با از دست رفتن leader؛ commit ی offset قبل از پردازش
Redis Streamsبازپس‌گیری pending (XAUTOCLAIM) بعد از crash ی consumerper streamتنظیم persistence (سیاست fsync ی AOF)، XACK قبل از کار
Amazon SQSصف Standard at-least-once است؛ FIFO پنجرهٔ dedup داردStandard: تلاش بی‌تضمین؛ FIFO per message groupvisibility timeout کوتاه‌تر از کار، بعد delete
صف database/Redis در Laraveljob بعد از timeout یا crash ی worker دوباره اجرا می‌شود (retry_after)میان workerها هیچtries تمام شد و به failed_jobs می‌رود

رفتار محصولات در Broker Comparison، RabbitMQ، Kafka و Redis Streams & Pub/Sub آمده؛ جدول فقط می‌گوید هر شکست از کجا می‌آید.

مدل Helland: entity، activity، پیام حیاتی ​

به زبان ساده: سیستم را مجموعه‌ای از چیزهای کوچک (entity) فرض کنید که هرکدام داده‌اش را دارد و روی یک ماشین زندگی می‌کند. هرگز داده‌ی هم را تغییر نمی‌دهند؛ پیام می‌فرستند و یادشان می‌ماند با چه کسی صحبت کرده‌اند و چه چیزی را پردازش کرده‌اند (activity).

بدفهمی رایج: «exactly-once delivery قابلیتی است که روشنش می‌کنم.» فرض آغازین Helland عکس این است: بیشتر برنامه‌ها پیام‌رسانی at-least-once دارند و گیرنده "must be prepared in its durable state to be assailed with redundant messages that must be ignored."

تعریف: مقالهٔ Helland چهار بخش دارد که لازم است: entity یک کلید یکتا به‌علاوهٔ دادهٔ آن روی یک ماشین است و "the scope of serializability" است؛ "Atomic Transactions Cannot Span Entities"؛ پیام‌ها به entityها آدرس می‌شوند؛ و activity وضعیت per-partner ای است که entity برای مدیریت گفتگو نگه می‌دارد، از جمله یادآوری پیام‌های پردازش‌شده. دربارهٔ idempotence می‌نویسد: "the recipient entity is typically designed to remember that the message has been processed." در DDD: entity = نمونهٔ aggregate، activity = inbox (و برای گفتگوی بلندتر یک saga).

text
     Order #7 (Sales)                         Stock #mug (Fulfilment)
1    state: pending, v1
2    --- ReserveStock(msg 41) --------------->
3                                              activity[Sales]: seen {} -> apply, seen {41}
4    <-- StockReserved(msg 90) ----------------
5    --- ReserveStock(msg 41) (resent) ------>
6                                              activity[Sales]: 41 seen -> reply again, no effect

At-most-once، at-least-once، «exactly-once»:

ادعاواقعاً یعنی چههزینهکجا درست است
At-most-onceیک بار می‌فرستد، retry نه؛ پیام گمشده رفته استگم‌شدن بی‌صداlog و metric بی‌اهمیت
At-least-onceتا ack بگیرد retry؛ تکرار ممکن استconsumer باید dedup کندبیشتر brokerها به‌طور پیش‌فرض
Exactly-once deliveryروی پیوند نامطمئن تضمینش ناممکن است وقتی فرستنده نمی‌تواند «گم شد» را از «پردازش شد و ack گم شد» تشخیص دهد (مسئلهٔ two generals)n/aروی شبکهٔ واقعی هیچ‌جا
Effectively-once processingتحویل at-least-once به‌علاوهٔ اثر idempotentیک inbox یا idempotency طبیعیcontext شما، با طراحی
Exactly-once semantics در Kafkaread-process-write اتمیک میان topicهای Kafka درون تراکنش‌های Kafkaproducer id، commit تراکنشیدرون Kafka؛ دیتابیس SQL شما نه

استدلال two generals دلیل آن است که «گم‌شده» و «تکراری» دو روی یک عدم قطعیت‌اند: فرستنده‌ای که ack نمی‌بیند نمی‌داند کدام اتفاق افتاد، پس باید دوباره بفرستد و گیرنده باید تحمل کند. سمت broker در Delivery Guarantees آمده.

سناریوهای واقعی: یک کارت دو بار بعد از timeout ی gateway شارژ شد؛ دو مرسوله برای یک سفارش بعد از rebalance ی consumer؛ یک کوپن دو بار استفاده شد چون پاسخ HTTP گم شد؛ ایمیل خوش‌آمد دو بار بعد از restart ی worker رفت.

راه‌حل: هر اثر یا طبیعتاً idempotent باشد (وضعیت را روی confirmed بگذار؛ «برای سفارش ۷ موجودی رزرو کن» با کلید شناسهٔ سفارش) یا با رکورد dedup (inbox، کلید idempotency) محافظت شود. کد در مصرف مطمئن.

Aggregate به‌عنوان جزیرهٔ سازگاری حیاتی ​

به زبان ساده: درون یک aggregate دیتابیس در هر commit همه‌چیز را درست نگه می‌دارد. میان aggregateها، و به‌خصوص میان contextها، هیچ چیز در یک لحظه درست نیست؛ چیزها با پیام یکی‌یکی درست می‌شوند.

بدفهمی رایج: «می‌توانم Order و Stock را در یک تراکنش به‌روز کنم چون در یک دیتابیس‌اند.» در modular monolith از نظر فنی می‌شود، و آن‌وقت امکان جدا کردنشان در آینده را از دست می‌دهید و برای یک درخواست دو aggregate را قفل می‌کنید. مرز یک انتخاب طراحی است نه واقعیت deployment (Aggregates & Factories).

تعریف: واحد کار (Unit of work) این فصل: یک aggregate + یک ردیف outbox (یا یک ردیف inbox + اثر) در هر تراکنش محلی. هر چیز دیگر پیام است. Evans: "Within an aggregate boundary, apply consistency rules synchronously. Across boundaries, handle updates asynchronously." (Evans، DDD Reference، نقل‌شده در Aggregates & Factories).

text
     Request: place order                          What commits together
1    BEGIN
2    INSERT orders (id=o-1, status=pending, version=1)      aggregate
3    INSERT outbox (type=OrderPlaced, key=o-1, seq=1)       the promise to tell others
4    COMMIT
5    -- later, elsewhere, other transactions:
6    relay publishes; saga starts (own tx); Fulfilment reserves (own tx)
دامنهٔ سازگاریسازوکارتضمینمثال
درون یک aggregateتراکنش محلی، ستون versioninvariantها در هر commitجمع Order برابر مجموع سطرهایش
aggregate و پیام خروجی‌اشOutbox در همان تراکنش«state عوض شد» اگر و فقط اگر «پیام فرستاده می‌شود»OrderPlaced
پیام و اثرش در consumerInbox در همان تراکنش«پردازش شد» اگر و فقط اگر «اثر اعمال شد»موجودی یک بار رزرو شد
میان aggregateها در یک contextپیام یا saga، گاهی استثنائاً یک txنهاییوضعیت Order از نتیجهٔ saga پیروی می‌کند
میان contextهاSaga + compensationنهایی، با deadlineسفارش، موجودی، پرداخت، ارسال

چهار دلیل برای شکستن قاعدهٔ «یک aggregate در هر تراکنش» هست (Vernon، خلاصه در Aggregates & Factories); هیچ‌کدام «راحت‌تر است» نیست.

راه‌حل: کد در Go و Laravel: PlaceOrder یک تراکنش با یک aggregate و یک ردیف outbox است.

انتشار مطمئن: transactional outbox حیاتی ​

به زبان ساده: داخل تراکنش کسب‌وکار با broker صحبت نکنید. پیام را در همان تراکنش در یک جدول بنویسید و بگذارید پردازهٔ دیگری بفرستدش. اگر آن پردازه بعد از فرستادن و قبل از تیک زدن ردیف بمیرد، دوباره می‌فرستد.

بدفهمی رایج: «اول commit می‌کنم بعد publish؛ این تقریباً اتمیک است.» نیست: crash میان دو خط event را گم می‌کند و publish قبل از commit رویداد سفارش‌هایی را می‌فرستد که rollback می‌شوند. microservices.io مسئله را می‌گوید: "How to atomically update the database and send messages to a message broker?" و پاسخ: "store the message in the database as part of the transaction that updates the business entities. A separate process then sends the messages to the message broker."

تعریف: الگو یک فرستنده (سرویس)، یک جدول outbox در دیتابیس خود سرویس و یک message relay دارد. مزایا طبق صفحهٔ الگو: "2PC is not used"؛ پیام‌ها "if and only if the database transaction commits" فرستاده می‌شوند؛ و به ترتیبی که برنامه فرستاده به broker می‌روند. مشکل اعلام‌شده‌اش: "The Message relay might publish a message more than once"، پس "a message consumer must be idempotent".

text
     Producer tx            Outbox table                Relay                 Broker
1    BEGIN
2    UPDATE order
3    INSERT outbox  ------> row #812 sent_at=NULL
4    COMMIT
5                                                       SELECT unsent ORDER BY id
6                                                       publish #812 ----------> stored
7                                                       CRASH before UPDATE
8                           row #812 still unsent
9                                                       (restart) publish #812 -> stored again (duplicate)
10                          UPDATE sent_at=now()
Producer txOrder aggregate rowoutbox row (new)Relaypoll or tail the logBrokerat-least-onceConsumer txinbox (consumer, id) uniquebusiness effectparking lot (DLQ)poison / exhaustedthen mark sentpublish, THEN mark sentcrash in between: same id published twicethe inbox unique key turns "twice" into "once"One tx on each side; the broker call is never inside a database transaction.

شکل هر دو سمت را نشان می‌دهد: تراکنش تولیدکننده با ردیف outbox، relay که اول publish و بعد علامت می‌زند، broker، تراکنش مصرف‌کننده با ردیف inbox، و parking lot.

سبک‌های relay:

سبکچطورترتیبتأخیرهزینه و خطرمحصولات
Polling publisherSELECT ... WHERE sent_at IS NULL ORDER BY id LIMIT n با timerترتیب جدول با یک relay؛ با تراکنش‌های هم‌زمان شکاف id هستفاصلهٔ pollبار روی دیتابیس؛ "Tricky to publish events in order"؛ با هر SQL کار می‌کندهر دیتابیس SQL؛ دستور Laravel یا حلقهٔ Go؛ SQL publisher و Forwarder ی Watermill (مستند به‌عنوان "the outbox pattern")
Transaction log tailingخواندن WAL/binlog دیتابیس و انتشار ردیف‌های درج‌شده در جدول outboxترتیب logمیلی‌ثانیه"Relatively obscure although becoming increasing common"؛ "Requires database specific solutions"؛ "Tricky to avoid duplicate publishing"Debezium (PostgreSQL logical decoding، MySQL binlog)، Change Data Capture

(نقل‌قول‌های «Tricky...» معایب فهرست‌شده در صفحه‌های الگوی Polling Publisher و Transaction Log Tailing‌اند.)

ترتیب per-aggregate. ترتیب برای هر aggregate مهم است نه سراسری. نگهش دارید با: (۱) یک relay برای هر outbox (یا یکی برای هر partition ی outbox) تا ردیف‌ها به ترتیب id منتشر شوند، (۲) نگه‌داشتن ردیف‌های بعدی کلیدی که ردیف قبلی‌اش شکست خورده، (۳) استفاده از id ی aggregate به‌عنوان partition key در Kafka، routing key یا message group در SQS FIFO، و (۴) گذاشتن version ی aggregate در پیام تا consumer بتواند بررسی کند (ترتیب). در PostgreSQL، id ی sequence در زمان insert داده می‌شود نه commit، پس تراکنش طولانی ممکن است id ی کوچک‌تری را بعد از عبور relay commit کند: با پنجرهٔ ایمنی poll کنید، یا با xmin/موقعیت commit دنبال کنید، یا از log tailing استفاده کنید.

سناریوهای واقعی: رویداد ثبت سفارش بعد از commit؛ تغییر سطح موجودی برای index جست‌وجو؛ صدور فاکتور؛ تغییر ایمیل کاربر (Identity) تا Sales کپی‌اش را به‌روز کند.

چه چیزی فراهمش می‌کند:

پلتفرمپشتیبانی outbox
PostgreSQL / MySQLجدول ساده در همان تراکنش؛ log tailing با logical replication یا binlog
MongoDBتراکنش چندسندی روی replica set، یا change stream روی collection ی outbox
DynamoDBنوشتن تراکنشی به‌علاوهٔ DynamoDB Streams
LaravelDB::transaction + جدول + یک command؛ afterCommit روی dispatch outbox نیست (job می‌تواند میان commit و push گم شود)
Godatabase/sql با BeginTx + INSERT؛ goroutine ی relay یا باینری جدا

راه‌حل: Go outbox.Add و Relay.RunOnce؛ Laravel Outbox::record و outbox:relay. صفحهٔ کامل الگو Transactional Outbox است.

مصرف مطمئن: inbox، کلید dedup و handler جابه‌جاپذیر حیاتی ​

به زبان ساده: consumer می‌نویسد «پیام ۴۱ را پردازش کردم» در همان تراکنشی که اثر را اعمال می‌کند. اگر پیام ۴۱ دوباره بیاید، نوشتن روی کلید یکتا شکست می‌خورد و اثر رد می‌شود.

بدفهمی رایج: «اول چک کنم پردازش کرده‌ام یا نه، بعد پردازش کنم، بعد ثبت کنم.» این سه گام با دو شکاف است؛ دو نسخهٔ هم‌زمان هر دو از چک رد می‌شوند. ثبت و اثر باید یک تراکنش باشند و ثبت باید کلید یکتا باشد.

تعریف: Idempotent consumer (microservices.io): "Make a consumer idempotent by having it record the IDs of processed messages in the database"، یا در جدول جدای PROCESSED_MESSAGES (inbox) یا در خود entity ی کسب‌وکاری. سه تکنیک تقریباً همهٔ handlerها را پوشش می‌دهد:

تکنیکچطورمناسب برایمحدودیت
جدول Inbox (processed ids)INSERT inbox (consumer, message_id) یکتا؛ هنگام تعارض رد کن؛ در همان tx اثرهر handler، هر اثر در دیتابیس خودتانیک ردیف برای هر پیام؛ نیاز به retention
Idempotency طبیعیاثر یک set است نه increment: status = confirmed، upsert با کلید کسب‌وکاریhandlerهایی که state می‌گذارندبرای «یکی اضافه کن» نه
State نسخه‌دار (Versioned)فقط اگر message.version > stored.version اعمال کنread modelها، کپی‌های replicate‌شدهversion per-key در پیام لازم است
کلید idempotency نزد providerکلید خودتان را با فراخوانی بفرستید (gateway کارت)اثرهای بیرون از دیتابیس شماprovider باید پشتیبانی کند
Handler جابه‌جاپذیر (Commutative)ترتیب رسیدن state نهایی را عوض نمی‌کند (tombstone)compensation، جابه‌جاییطراحی per-handler می‌خواهد
text
     Consumer tx (message 41)                             Second delivery of 41
1    BEGIN                                                BEGIN
2    INSERT inbox(consumer='billing', id=41)  ok          INSERT inbox(...,41)  -> unique violation
3    charge card, INSERT payment                          (skip: ack and stop)
4    INSERT outbox PaymentCharged                         ROLLBACK / COMMIT of nothing
5    COMMIT

انتخاب کلید dedup:

کلیددر redelivery ثابت است؟استفاده
offset ی broker / delivery tagنه (با redelivery یا replay عوض می‌شود)هرگز به‌عنوان کلید dedup
message id ای که تولیدکننده هنگام insert در outbox می‌دهدبلهپیش‌فرض
کلید کسب‌وکاری (order_id + step)بلهوقتی پیام ممکن است با فرمان retry شده دوباره ساخته شود
id ی aggregate + versionبلهبرای جریان رویداد یک aggregate
hash ی payloadبله، اما دو پیام واقعاً یکسان برخورد می‌کنندآخرین راه

Retention. inbox بی‌پایان رشد می‌کند مگر پاک‌سازی شود. ردیف‌ها را دست‌کم به‌اندازهٔ بیشترین پنجرهٔ redelivery و replay ی broker نگه دارید (Kafka retention.ms، نگهداری پیام SQS تا ۱۴ روز، replay ای که برنامه دارید) و بعد دسته‌دسته حذف کنید. پنجره را مستند کنید: replay قدیمی‌تر از آن دو بار پردازش می‌شود.

چه چیزی فراهمش می‌کند:

پلتفرمچطور
PostgreSQLINSERT ... ON CONFLICT DO NOTHING، بررسی تعداد ردیف
MySQL / InnoDBINSERT IGNORE یا گرفتن خطای 1062
MongoDBunique index و insertOne، گرفتن E11000
RedisSET key NX EX ttl پیش‌فیلتر ارزان است؛ با اثر دیتابیس اتمیک نیست، پس سازوکار درستی نیست
LaravelDB::table(...)->insertOrIgnore()؛ ShouldBeUnique فقط از ورودی تکراری صف جلوگیری می‌کند نه پردازش تکراری

راه‌حل: Go inbox.Once؛ Laravel Inbox::once. صفحهٔ کامل الگو Idempotent Consumers & the Inbox است.

ترتیب: per key، version و تحمل مهم ​

به زبان ساده: فقط پیام‌های دربارهٔ همان aggregate باید ترتیب داشته باشند، و حتی آن‌وقت هم باید بتوانید رسیدن غلط‌ترتیب را تحمل کنید.

بدفهمی رایج: «با timestamp رویدادها را ترتیب بده.» ساعت دو ماشین فرق دارد (clock skew) و retry timestamp قدیمی را نگه می‌دارد. با چیزی که صاحب کنترلش است ترتیب بدهید: version ی aggregate.

تعریف: ترتیب per-key یعنی همهٔ پیام‌های یک aggregate از یک partition (Kafka)، یک consumer صف (single active consumer یا consistent-hash exchange در RabbitMQ) یا یک message group (SQS FIFO) می‌گذرند، Ordering & Partitioning. باز هم retry و redelivery ترتیب دقیق را می‌شکنند، پس handler یک بررسی اضافه می‌کند.

text
     Fulfilment read model "order status"               messages arrive in this order
1    v3 ParcelDispatched  arrives first                 apply: status=dispatched, version=3
2    v2 OrderPaid         arrives late                  2 < 3: ignore (stale)
3    v5 OrderCancelled    arrives (v4 missing)          5 > 3+1: GAP -> park for later, ask for v4
4    v4 OrderRefunded     arrives                       4 = 3+1: apply; then replay v5
تکنیک تحملقاعدهوقتی
دور انداختن کهنه (Drop stale)if msg.version <= stored.version: ignoreآخرین state برنده است (read model)
تشخیص gapif msg.version > stored.version + 1: retry laterهر رویداد مهم است (دفتر کل)
اثر جابه‌جاپذیرstate نهایی در هر ترتیب یکی استcompensation: release قبل از reserve tombstone می‌گذارد
دوباره‌گرفتن (Re-fetch)هنگام gap وضعیت فعلی را از API ی صاحب بپرسsnapshot پذیرفتنی است
یک نویسنده per keyبا key مسیریابی کن تا یک consumer پردازش کندتوان per-key کم است

timestamp دیواری برای نمایش و برای deadline ای که روی یک ماشین (ساعت خود saga) سنجیده می‌شود خوب است. برای تصمیم اینکه کدام یک از دو رویداد «جدیدتر» است خوب نیست.

راه‌حل: projection.Apply (read model ی نسخه‌دار که Applied، Stale یا Gap جواب می‌دهد) در Go؛ handler ی fulfilment (release قبل از reserve، cancel قبل از create) و OrderSaga.Handle (پاسخ‌های دیررس) در Go.

retry، backoff و پیام‌های poison حیاتی ​

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

بدفهمی رایج: «retry بیشتر یعنی مطمئن‌تر.» AWS: "Retries are 'selfish.' In other words, when a client retries, it spends more of the server's time to get a higher chance of success." وقتی شکست از overload است retry بدترش می‌کند؛ فصل SRE دربارهٔ cascading failure می‌گوید از "randomized exponential backoff" استفاده کنید، "Limit retries per request" و "a server-wide retry budget" را در نظر بگیرید.

تعریف: سیاست سمت consumer چهار بخش دارد: دسته‌بندی خطا (گذرا، دائمی، «نه» ی کسب‌وکار)، backoff نمایی با سقف و full jitter، حداکثر تعداد تلاش، و مقصد باقیمانده (DLQ یا parking lot). الگوهای سمت فراخواننده (timeout، circuit breaker) در Error Handling & Fault Tolerance و Timeouts, Retries & Jitter آمده؛ مکانیک retry در هر broker در Retry, Backoff & Delayed Delivery.

دستهٔ خطامثالretry؟اقدام
فنی گذراTimeout، 503، deadlock (SQLSTATE 40P01)، serialization failure (40001)بله، با backoff و jitterبرگرداندن به صف
وابستگی پایینgateway کارت چند دقیقه در دسترس نیستبله، اما برای همه آهسته‌ترthrottle کردن استثناها یا باز کردن breaker؛ پنجرهٔ retry
فنی دائمیpayload غیرقابل‌decode، نوع پیام ناشناخته، نقض schemaنهفوراً با دلیل park کن
«نه» ی کسب‌وکارموجودی نیست، کارت رد شدنه، پاسخ استپیام رد را برگردان؛ saga مدیریت می‌کند
gap ی ترتیبversion 5 آمد، 4 نیستبله، بعداًبا تأخیر بلندتر release کن، بعد park
باگ handlerبرای هر پیام TypeErrorنه (retry کمکی نمی‌کند)consumer را متوقف کن، alert، رفع، redrive

Full jitter: مدت انتظار تصادفی میان صفر و min(cap, base × 2^attempt). کلاینت‌هایی را که همزمان شکست خورده‌اند پخش می‌کند؛ AWS می‌گوید بدون آن "retries that increase load can make matters significantly worse" وقتی "all clients retry at the same time"، و jitter را برای "all timers, periodic jobs, and other delayed work" توصیه می‌کند.

text
     attempt   ceiling = min(2s, 100ms*2^n)    wait (full jitter, random in [0, ceiling))
1    0         100 ms                           e.g. 37 ms
2    1         200 ms                           e.g. 154 ms
3    2         400 ms                           e.g. 12 ms
4    3         800 ms                           e.g. 611 ms   -> attempts exhausted: park with reason

پیام‌های poison. پیام poison پیامی است که همیشه شکست می‌خورد. اگر consumer برای همیشه retry کند، هرچه پشتش است (در partition و صف ترتیبی) قفل می‌شود؛ اگر دورش بیندازد، یک رویداد کسب‌وکاری ناپدید می‌شود. کنارش بگذارید: خود پیام، دلیل، تعداد تلاش، زمان و نام consumer را در DLQ، dead-letter exchange در RabbitMQ، dead-letter topic در Kafka، dead-letter queue با maxReceiveCount در SQS یا ردیف failed_jobs در Laravel ذخیره کنید. بعد روی عمق alert بگذارید، بررسی کنید، رفع کنید و redrive (انتشار دوباره بعد از رفع). Dead-Letter Queue.

محصولابزار retryمقصد poisonRedrive
RabbitMQnack با requeue، یا صف‌های retry با TTL از طریق dead-letter exchange؛ delivery-limit در quorum queueDead-letter exchange (x-dead-letter-exchange)Shovel یا انتشار دستی دوباره
Apache Kafkatopicهای retry (orders.retry.5s) یا درون‌پردازه؛ nack per-message نداردDead-letter topicreplay از dead-letter topic
Redis Streamsلیست pending، XAUTOCLAIM بعد از idle؛ شمارش تحویل با XPENDINGانتقال به stream ی dead بعد از N تحویلXADD برگشتی
Amazon SQSvisibility timeout و maxReceiveCountredrive policy به dead-letter queue«Start DLQ redrive»
صف Laravel#[Tries]، #[Backoff]، #[MaxExceptions]، release()، retryUntil()جدول failed_jobs (make:queue-failed-table)، متد failed()queue:retry
Go (Watermill)middleware ی router؛ مستندات "Requeuing After Error" را فهرست می‌کنندpublisher ی صف poisonانتشار دوباره

راه‌حل: Go retry.Process و dlq.Queue؛ Laravel ConsumeMessage با attributeها و middleware، dontRetry(PermanentFailure::class) و failed().

Sagaها: فرایند میان contextها حیاتی ​

به زبان ساده: saga چک‌لیستی است که از contextها می‌گذرد. هر گام یک تراکنش محلی در یک context است. اگر گام بعدی شکست بخورد، saga برای گام‌های قبلی گام‌های «لغو» را مثل عملیات عادی کسب‌وکار اجرا می‌کند.

بدفهمی رایج: «saga یعنی rollback توزیع‌شده.» rollback پاک می‌کند؛ compensation یک عمل جدید و قابل‌دیدن کسب‌وکاری است. مشتری دید «موجودی رزرو شد» و ممکن است «پول برگشت» را ببیند. بعضی گام‌ها اصلاً قابل لغو نیستند (ایمیل فرستاده‌شده، بستهٔ ارسال‌شده) و compensation آن‌وقت عذرخواهی یا فرایند مرجوعی است.

تعریف: "A saga is a reliably coordinated sequence of local transactions. The coordination mechanism, which often uses asynchronous messaging, ensures that the saga finishes: either all steps complete successfully or, if a local transaction fails because it violates a business rule, the changes made by the completed steps are undone by compensating transactions." (microservices.io). دو سبک هماهنگی: "Choreography - each local transaction publishes domain events that trigger local transactions in other services" و "Orchestration - an orchestrator (object) tells the participants what local transactions to execute."

جنبهChoreographyOrchestration
چه کسی کل جریان را می‌داندهیچ‌کس؛ از اشتراک‌ها در رویدادها پدید می‌آیدorchestrator (saga/process manager)
Couplingسرویس‌ها به رویدادهای هم subscribe می‌کنند (وابستگی دوری پیدا می‌شود)شرکت‌کننده‌ها فرمان و پاسخ را می‌شناسند؛ orchestrator شرکت‌کننده‌ها را
دیده‌شدندشوار: جریان میان سرویس‌ها پخش استآسان: یک جا state ی هر سفارش دیده می‌شود
Timeout و deadlineهر سرویس خودش پیاده کندیک timer برای هر saga
ترتیب compensationضمنیصریح
تستکل سیستم لازم استsaga یک state machine ی خالص است
مناسبدو یا سه گام، جریان ثابت، یک تیمچهار گام یا بیشتر، انشعاب، compensation، چند تیم

جریان ما چهار گام، سه شاخهٔ شکست و دو تیم دارد، پس orchestrate می‌کنیم: saga در Sales زندگی می‌کند و Fulfilment و Billing را با فرمان هدایت می‌کند.

Order placedSales: pendingReserve stockFulfilmentCharge paymentBilling, idempotency keyCreate shipmentFulfilmentConfirmedSales: confirmedRelease stockon decline / timeoutRefund paymenton ship fail / timeoutCancel shipmenttimeout / late createCompensatingwaits for every ack; late replies undoneCancelledterminal, Order cancelledout of stock:nothing to undotimer: a deadline onevery step

شکل مسیر موفق را بالا نشان می‌دهد، پیکان شکست از هر گام به پایین، فرمان‌های جبرانی، وضعیت Compensating (که منتظر هر ack می‌ماند) و Cancelled پایانی؛ timer روی هر گام به همان مسیر جبران وصل می‌شود.

Compensationها عملیات دامنه‌اند. در زبان فراگیر نامشان را بگذارید (Ubiquitous Language): ReleaseStock، RefundPayment، CancelShipment، نه «rollback گام ۲». هر compensation باید خودش idempotent و با گام پیشرو جابه‌جاپذیر باشد، چون ممکن است قبل از چیزی که باید خنثی کند برسد (پیام پیشرو دیر شده):

گام پیشروCompensationاگر compensation زودتر برسداگر گام پیشرو دیر برسد
ReserveStockReleaseStocktombstone ی released بگذاررد کن: StockRejected("already released")
ChargePaymentRefundPaymenttombstone ی cancelled بگذاررد کن: PaymentDeclined("order already cancelled")
CreateShipmentCancelShipment (قبل از pickup) یا فرایند مرجوعیtombstoneرد کن
SendConfirmationEmailممکن نیستn/aایمیل عذرخواهی را به‌عنوان گام پیشروی جدید بفرست

Timeout و deadline. گام saga که پاسخی نمی‌گیرد نباید تا ابد صبر کند. saga روی هر گام یک deadline ذخیره می‌کند؛ timer می‌پرسد «کدام sagaها از deadline گذشته‌اند؟» و آن‌ها را با فرمان‌هایی که هر کاری همسایه کرده باشد امن‌اند به Compensating می‌برد (release و refund idempotent و tombstone-safe‌اند). پاسخی که بعد از لغو می‌رسد پاسخ دیررس (Late reply) است و باید دوباره خنثی شود نه اعمال (saga به StockReserved ی دیررس با یک ReleaseStock دیگر جواب می‌دهد). deadline روی ساعت خود saga سنجیده می‌شود، پس اختلاف ساعت میان ماشین‌ها اهمیتی ندارد.

text
     Saga (Sales)                 Billing (down)               Fulfilment
1    ReserveStock ---------------------------------------->   held
2    <-- StockReserved ----------------------------------
3    state=Charging, deadline=t+30s
4    ChargePayment ----> queued (Billing is down)
5    ... 30 s pass ...
6    TIMER: deadline passed -> state=Compensating, outstanding {Refund, Release}
7    RefundPayment ---> queued behind the charge
8    ReleaseStock -------------------------------------------> released
9    <-- StockReleased ----------------------------------
10   Billing returns: ChargePayment executes (money taken), then RefundPayment (money returned)
11   <-- PaymentCharged (late): refund already outstanding, ignore
12   <-- PaymentRefunded: outstanding empty -> state=Cancelled, emit OrderCancelled

چه چیزی orchestration را فراهم می‌کند:

پلتفرمپشتیبانی
aggregate ی saga دست‌نویسکنترل کامل؛ آنچه این فصل در Go و Laravel می‌سازد
Temporal، Cadence، Zeebe/Camunda، AWS Step Functionsموتور workflow پایدار: timer، retry و history داخلی (Durable Workflows & Jobs)
LaravelBus::chain زنجیرهٔ خطی job با catch است؛ Bus::batch jobها را موازی با callbackهای then/catch/finally اجرا می‌کند. هیچ‌کدام برنامهٔ compensation یا deadline ذخیره نمی‌کنند، پس saga ی کسب‌وکاری جدول state ی خودش را می‌خواهد
MassTransit / NServiceBus (.NET)، Axon (JVM)state machine ی saga در خود framework

راه‌حل: Go OrderSaga.Handle و Expire؛ Laravel OrderSaga و OrderSagaService. صفحهٔ کامل الگو Saga Pattern.

Saga به‌عنوان aggregate مهم ​

به زبان ساده: state ی خود saga (کدام گام، کدام deadline، کدام compensation هنوز باز است) داده‌ای با قاعده است؛ مثل هر aggregate مدلش کنید: یک سطر، یک version، متدهای رفتاری، یک تراکنش برای هر تغییر.

بدفهمی رایج: «saga اسکریپت workflow است که state اش را در حافظه یا cache نگه می‌دارد.» اگر پردازه بمیرد، سفارش نیمه‌کاره گم می‌شود. state باید به‌اندازهٔ خود سفارش‌ها پایدار باشد.

تعریف: saga یک aggregate در Sales با شناسهٔ همان id ی سفارش است (در نوشته‌های قدیمی‌تر DDD process manager). invariantهایش: گذارهای state قانونی‌اند (خروج از state ی پایانی نیست)؛ Cancelled فقط وقتی که هر compensation باز تأیید شده باشد؛ هر state ای که پاسخی منتظر است deadline دارد. همان واحد کار: پردازش یک پیام ورودی یک تراکنش است شامل ردیف inbox، state ی جدید saga و فرمان‌های خروجی در outbox.

فیلدمعناچرا هست
order_idهویت (همان id ی سفارش)یک saga برای هر سفارش؛ OrderPlaced ی تکراری نادیده گرفته می‌شود
statereserving_stock، charging، shipping، completed، compensating، cancelledstate machine ی صریح
deadlineزمانی که گام جاری timeout می‌شودtimerها با آن (index شده) query می‌کنند
outstandingcompensationهای فرستاده‌شده و هنوز تأییدنشده«Cancelled» فقط وقتی خالی است
reasonچرا compensation شروع شدبه پشتیبانی و مشتری نشان داده می‌شود
versionبا هر تغییر زیاد می‌شودبه‌عنوان seq در پیام‌های خروجی؛ همروندی خوش‌بینانه

دو کاری که saga نباید بکند: منتظر پاسخ بلاک شود (فقط به پیام و timer واکنش نشان می‌دهد)، و همسایه‌ها را مستقیم درون تراکنشش صدا بزند (فرمان‌ها را در outbox می‌نویسد).

راه‌حل: Go saga.Service.Handle و Tick؛ Laravel OrderSagaService::handle و tick.

سازگاری نهایی به‌عنوان تصمیم محصول حیاتی ​

به زبان ساده: تا وقتی saga در حال اجراست سفارش نه تأیید شده نه شکست‌خورده است. صفحه باید همین را بگوید و کسب‌وکار باید بگوید اگر تمام نشد چه می‌شود.

بدفهمی رایج: «سازگاری نهایی جزئیات مهندسی است که UI پنهانش می‌کند.» کاربر می‌بیندش: سفارشی که «تأییدشده» می‌گوید و بعد لغو می‌شود وعدهٔ شکسته است؛ «در انتظار» صادقانه است. Fowler و Lewis: "Often businesses handle a degree of inconsistency in order to respond quickly to demand, while having some kind of reversal process to deal with mistakes. The trade-off is worth it as long as the cost of fixing mistakes is less than the cost of lost business under greater consistency."

تعریف: مدل وضعیت (Status model) مجموعهٔ وضعیت‌های قابل‌دیدن برای مشتری در یک aggregate است که saga از آن‌ها می‌گذرد، همراه با کلمات و کارهایی که محصول در هر وضعیت می‌دهد.

وضعیت Order (Sales)state ی sagaمشتری چه می‌بیندکارهای مجازاعلان
pendingreserving، charging، shipping«سفارش شما دریافت شد و موجودی و پرداخت در حال بررسی است»مشاهده، درخواست لغوایمیل «سفارش دریافت شد»
confirmedcompleted«سفارش شما تأیید شد»مشاهده، بعداً مرجوعیایمیل «تأیید شد»
cancelled (دلیل: ناموجود)cancelled«متأسفیم، یکی از اقلام دیگر موجود نیست»سفارش دوبارهایمیل با دلیل
cancelled (دلیل: پرداخت رد شد)cancelled«پرداخت شما رد شد»تلاش با کارت دیگرایمیل با لینک
cancelled (دلیل: timeout)cancelled«نتوانستیم سفارش را به‌موقع کامل کنیم؛ از شما پولی کسر نشد»سفارش دوبارهایمیل؛ اگر پول جابه‌جا شد اعلان بازپرداخت

کسب‌وکار صاحب سه عدد است: timeout هر گام (چه مدت «در انتظار» می‌تواند بماند)، بیشترین پنجرهٔ ناسازگاری قابل‌قبول (ثانیه تا دقیقه) و هزینهٔ لغو (کوپن عذرخواهی). این‌ها با متخصصان دامنه تصمیم گرفته می‌شود نه حدس (Event Storming جایی است که شاخه‌های شکست اول بار روی sticky note ظاهر می‌شوند).

سناریوهای واقعی: صندلی هواپیما ۱۵ دقیقه نگه داشته می‌شود؛ رزرو هتل «در انتظار تأیید»؛ سفارش marketplace «در حال پردازش پرداخت»؛ انتقال بانکی «در جریان».

راه‌حل: فیلد وضعیت بخشی از aggregate است؛ نتیجهٔ saga آن را با پیامی که در تراکنش خودش پردازش می‌شود عوض می‌کند (sales.OnOutcome در Go، OutcomeHandler در Laravel)؛ API با 202 Accepted و وضعیت pending جواب می‌دهد (لبهٔ API).

حالت‌های degraded: مفید ماندن وقتی همسایه پایین است مهم ​

به زبان ساده: از قبل تصمیم بگیرید هر context وقتی وابستگی‌اش نیست چه کند: کار را بپذیرد، داده‌ی کمی کهنه بدهد، قابلیتی را خاموش کند یا مؤدبانه رد کند. هرگز جواب اختراع نکنید.

بدفهمی رایج: «یک fallback بگذار و کار می‌کند.» AWS: "Distributed fallback strategies are harder to test" و حالت‌های شکست (overload) "are hard to replicate in a test". fallback ای که هرگز در production اجرا نشده سیستم دومِ تست‌نشده‌ای است که در بدترین ساعت وارد می‌شود. fallback ی که دادهٔ ساختگی می‌دهد (قیمت صفر، موجودی ۹۹۹) باگی با ظاهر مؤدب است.

تعریف: حالت degraded یک کاهش طراحی‌شده، تست‌شده و قابل‌دیدن از عملکرد است:

وابستگی پایینحالت degradedصادقانه؟هزینه / خطر
Billing (شارژ)Sales سفارش را pending می‌پذیرد؛ saga وقتی Billing برگشت شارژ می‌کند؛ سفارش بعد از N دقیقه timeout می‌شودبله: وضعیت می‌گوید pendingسفارش مشتری با کارت بد دیرتر شکست می‌خورد
Catalog (قیمت)از snapshot ی قیمت در read model ی خود Sales با برچسب as of 09:02 استفاده کنبله اگر برچسب خورده باشدقیمت کهنه؛ کسب‌وکار حداکثر سن را تعیین می‌کند
Catalog (تصویر، نظرات)feature flag بخش را پنهان می‌کندبلهبرای جریان اصلی هیچ
Identity (ورود)session و token های موجود کار می‌کنند؛ ورود جدید نهبلهثبت‌نام ممکن نیست
Fulfilment (موجودی)حالت backorder: بپذیر، تاریخ بعدی قول بدهقاعدهٔ کسب‌وکاری لازم استخطر oversell صریحاً پذیرفته شده
Broker پایینoutbox رشد می‌کند؛ relay بعد از برگشت جبران می‌کندبله (گم‌شدن نیست)alarm ی backlog ی outbox، دیسک
Payment provider کندbreaker باز: سریع شکست بخور، «دوباره تلاش کنید» نشان بده، سبد را نگه داربلهتبدیل از دست‌رفته

قواعد: (۱) فقط آنچه کسب‌وکار موافقت کرده degrade کنید؛ (۲) در پاسخ بگویید (Stale، AsOf، وضعیت pending)؛ (۳) مرتب تمرینش کنید (game day، Chaos Engineering)؛ (۴) برای هر چیز مربوط به پول یا موجودی منتظر ماندن با saga را به حدس زدن ترجیح دهید؛ (۵) AWS سه جایگزین برای fallback ی پنهان نام می‌برد: "Let the caller handle errors" (retry، شکست را نمایان کن)، "Push data proactively" (داده را محلی نگه دار تا fallback لازم نشود؛ دقیقاً همان read model ی تغذیه‌شده با رویداد) و "Convert fallback into failover" (مسیر fallback را مداوم اجرا کن تا تمرین شود). هشدارش: "One of the worst things about fallback is that it isn't exercised regularly and is likely to fail or increase the scope of impact when it triggers during an outage." ببینید Bulkheads & Graceful Degradation و Cascading Failures.

read modelهایی که داده‌ی کهنه می‌دهند امن‌ترین حالت degraded‌اند چون read model از اول قرار است در نهایت سازگار باشد (Data Patterns): Sales کپی قیمت محصولات را دارد که با رویدادهای Catalog تغذیه می‌شود، پس قطعی Catalog فقط کپی را منجمد می‌کند.

راه‌حل: Go edge.WithStaleFallback (آخرین مقدار را با برچسب stale برمی‌گرداند، هرگز چیزی اختراع نمی‌کند).

لبهٔ context: timeout، بودجهٔ زمان و breaker مهم ​

به زبان ساده: هر فراخوانی که از context بیرون می‌رود محدودیت زمانی‌ای می‌گیرد که در زمانی که فراخواننده داده جا بگیرد، و جایی که شکست‌ها شمرده می‌شوند و واکنشی دارند. این‌ها در لایهٔ application و adapter زندگی می‌کنند، نه در مدل دامنه.

بدفهمی رایج: «annotation ی retry را روی متد دامنه بگذار.» مدل دامنه نباید بداند شبکه وجود دارد؛ timeout و breaker به adapter یا سرویس application تعلق دارند (Domain, Application & Infrastructure Services).

تعریف: در لبه این‌ها را اعمال می‌کنید: timeout هر فراخوانی؛ انتشار deadline ("a deadline is set high in the stack... The tree of RPCs emanating from an initial request will all have the same absolute deadline"، Google SRE)؛ بودجهٔ retry (SRE: "only allow 60 retries per minute in a process")؛ circuit breaker ("the circuit breaker trips, and all further calls to the circuit breaker return with an error, without the protected call being made at all"، Fowler)؛ و bulkhead (pool جدا برای هر وابستگی). پرداختن در سطح کد در Error Handling & Fault Tolerance؛ انتخاب معماری همگام یا ناهمگام در Service Communication؛ service meshها می‌توانند بخشی را اعمال کنند (API Gateway, BFF & Service Mesh).

سازوکارکجا زندگی می‌کنداز چه محافظت می‌کنداشاره
timeout و deadline هر فراخوانیadapter ی کلاینت HTTP/gRPC، context در Go، Http::timeout() در Laravelthread و connectionTimeouts, Retries & Jitter
Circuit breakeradapter دور وابستگیفراخواننده از callee ی در حال شکستCircuit Breaker
Bulkheadpool یا صف جدا برای هر وابستگیجلوگیری از گرسنگی بقیه توسط یک وابستگیBulkheads
Rate limit / load sheddingورودی contextخود context از overloadLoad Shedding
Deadline ی sagaaggregate ی sagaفرایند کسب‌وکارSagaها

راه‌حل: Go edge.CallWithin مقدار min(perCall, remaining − reserve) را حساب می‌کند و وقتی بودجه تمام شده رد می‌کند.

فرمان idempotent در لبهٔ API حیاتی ​

به زبان ساده: کلاینت با POST /orders یک Idempotency-Key یکتا می‌فرستد. اگر پاسخ گم شد و کلاینت دوباره فرستاد، سرور کلید را می‌شناسد و جواب اول را برمی‌گرداند نه یک سفارش دوم.

بدفهمی رایج: «POST idempotent نیست پس کلاینت هرگز نباید retry کند.» retry می‌کنند؛ شبکهٔ موبایل مجبورشان می‌کند. سرور با کلید POST را برای retry امن می‌کند.

تعریف: کلید همراه نتیجه در جدولی با constraint ی یکتا ذخیره می‌شود؛ اولین درخواست برنده است؛ درخواست‌های بعدی با همان کلید پاسخ ذخیره‌شده را می‌گیرند، یا اگر اولی هنوز در حال اجراست 409. الگوی کامل (scope ی کلید، انقضا، fingerprint ی درخواست، ذخیره) در API Idempotency؛ قرارداد در طراحی API جا دارد (API Realization).

text
     Client                         Sales API                          DB
1    POST /orders  Key: k-91 --->   INSERT idempotency_keys(k-91)  --> ok (first)
2                                   place order + outbox, store 202 {pending}
3    <-- (response lost) ---------
4    POST /orders  Key: k-91 --->   INSERT idempotency_keys(k-91)  --> conflict
5    <-- 202 {pending} (stored) --- return saved response, no second order
لایهسازوکاردامنه
کلاینت به Salesهدر Idempotency-Keyیک عمل کاربر
Sales به brokermessage_id ی outboxیک رویداد
Broker به Fulfilment/BillingInbox (consumer, message_id)یک تحویل
Billing به provider کارتکلید idempotency ی provider (charge-<order>)یک شارژ

کلیدها در هر لایه عمداً متفاوت‌اند؛ زنجیره فقط وقتی کار می‌کند که هر گام dedup کند.

راه‌حل: Laravel PlaceOrderController با insertOrIgnore؛ در Go همین شکل inbox.Once روی id ی درخواست HTTP است.

تست شکست مهم ​

به زبان ساده: منتظر نمانید production پیام را تکرار کند. broker را وادار کنید در تست تکرار، تأخیر، حذف و جابه‌جایی بسازد، relay را در بدترین لحظه بکشید و نتیجهٔ کسب‌وکاری را بررسی کنید.

بدفهمی رایج: «برای هر handler تست واحد داریم.» هر handler می‌تواند درست باشد و سیستم غلط؛ باگ‌ها در تعامل‌اند (تکرار به‌علاوهٔ جابه‌جایی به‌علاوهٔ crash).

تعریف: چهار سطح تست: (۱) state machineهای خالص (saga)، (۲) harness ی یکپارچگی با تزریق شکست (broker درون‌حافظه با Duplicate، Reverse، DropFirst، hook ی crash ی relay، یک همسایهٔ خاموش)، (۳) consumer contract test روی schema ی پیام‌ها (Context Maps & Integration Patterns)، (۴) chaos در محیط pre-production (Chaos Engineering); نکات تست در سطح broker در Testing Messaging Systems.

تستچه تزریق می‌کندچه چیز را assert می‌کنددر این فصل
تکرار و جابه‌جاییهر پیام دو بار، جدیدترین اولیک شارژ، یک بار رزرو، سفارش تأییدTestHappyPathSurvivesDuplicatesAndReordering
Compensationکارت رد شدموجودی آزاد، سفارش لغو، پولی گرفته نشدTestPaymentDeclinedCompensatesStock
پاسخ‌های دیررسBilling پایین، timeout، Billing برمی‌گرددسفارش لغو، موجودی برگشته، بازپرداخت دوم نیستTestBillingDownTimeoutThenLateReplies
Crash ی relaycrash بعد از publish و قبل از علامت‌زدنoutbox خالی شد، یک شارژTestRelayCrashAfterPublishIsHarmless
publishهای گم‌شده۳ publish اول شکست می‌خورندسفارش باز هم تأیید می‌شودTestLostPublishesAreRetriedByTheRelay
ارسال گیرکردهCreateShipment بعد از deadline نگه داشته شدسفارش لغو، create ی دیررس با tombstone رد شد، مرسوله‌ای نیستTestShippingStallsThenLateCreateIsRefused
Poisonنوع ساختگی، JSON خراببا ۱ تلاش park شد، صف قفل نشدTestPoisonMessageIsParkedNotSwallowed
اتمیک بودنسفارش نامعتبرنه سطر سفارش و نه سطر outboxTestPlaceOrderIsAtomicWithItsOutboxRow
Replayکل تاریخچه دوباره تحویلهمان state ی نهاییPump را با Duplicate دوباره اجرا کن؛ با inbox واقعی، replay قدیمی‌تر از retention استثناست
Contractschema ی OrderPlaced.v1consumerها هنوز decode می‌کنندContext Maps

راه‌حل: Go و Laravel.

Observability در طول یک saga مهم ​

به زبان ساده: روی هر پیام دو id بگذارید: یکی که می‌گوید «این به saga ی سفارش ۷ تعلق دارد» (correlation) و یکی که می‌گوید «این را آن پیام ایجاد کرد» (causation). بعد lag، backlog ی outbox و پیام‌های parked را اندازه بگیرید.

بدفهمی رایج: «distributed tracing همه‌چیز را پوشش می‌دهد.» trace یک درخواست را دنبال می‌کند؛ saga دقیقه‌ها یا روزها در درخواست‌ها و timerهای زیاد زندگی می‌کند. id های کسب‌وکاری در log و جدول saga قابل‌query آن چیزی است که تیم پشتیبانی استفاده می‌کند.

تعریف: envelope حامل id، correlation، causation، key، seq، type، at است. جدول saga داشبورد کسب‌وکار در جریان است. metric و alertها:

سیگنالمعناکی alert
backlog ی outbox (ردیف‌های ارسال‌نشده) و سن قدیمی‌ترینrelay عقب است یا گیر کردهسن بالاتر از پنجرهٔ ناسازگاری قابل‌قبول
lag ی consumer (عمق صف، lag ی consumer در Kafka)consumer نمی‌رسدN دقیقه رو به رشد
عمق DLQ / parkedپیام poison وجود داردهر مقداری، بعد page
سن saga به تفکیک state (مثلاً charging بیش از ۲ برابر timeout ی گام)timer یا همسایه خراب استتعداد بالای صفر
compensation در ساعتنرخ شکست کسب‌وکاریجهش
نرخ تکرار در inboxبسامد redeliveryجهش ناگهانی (مشکل broker یا relay)
نرخ retry و زمان backoffسلامت وابستگیپایدار

خط‌های log حامل order_id، correlation، message_id، attempt‌اند. جزئیات stack در Observability و Messaging Observability؛ دموی Go زنجیرهٔ علّی را چاپ می‌کند.

Anti-patternها حیاتی ​

Anti-patternچرا شکست می‌خوردبه‌جایش
Two-phase commit میان سرویس‌هاقفل از روی شبکه؛ coordinator ی مرده تراکنش‌های نامعلوم می‌گذارد؛ بسیاری از brokerها و providerها پشتیبانی نمی‌کنندتراکنش محلی + outbox + saga
Dual write (commit، بعد publish)crash میان این دو رویداد را گم می‌کند؛ ترتیب معکوس واقعیت‌های rollback‌شده را منتشر می‌کندOutbox
زنجیرهٔ همگام (A صدا می‌زند B صدا می‌زند C صدا می‌زند D)دسترس‌پذیری ضرب می‌شود، تأخیر جمع می‌شود؛ یک سرویس کند cascade می‌سازدپیام ناهمگام، یا یک فراخوانی با deadline و حالت degraded
retry ی عملیات غیر-idempotentشارژ دوبار بعد از گم‌شدن پاسخکلید idempotency، inbox
fallback ی بی‌صدامقدار ساختگی شکست را پنهان و داده را خراب می‌کندحالت degraded صریح با flag، یا بلند شکست بخور
بلعیدن پیام poison (catch، log، ack)رویدادهای کسب‌وکار ناپدید می‌شوندبا دلیل park کن، alert، redrive
retry ی فوری بی‌پایانطوفان retry؛ صف قفل می‌شودbackoff با سقف و jitter، حد تلاش
ترتیب با timestampاختلاف ساعتversion ی aggregate، sequence
state ی saga فقط در حافظه یا Redisبا restart گم می‌شودسطر aggregate ی پایدار
compensation بدون idempotency یا tombstoneبازپرداخت دوباره؛ گام پیشروی دیررس لغو را خنثی می‌کندcompensation ی idempotent و جابه‌جاپذیر
«Exactly-once» به‌عنوان تنها دفاعدر مرز یک سیستم متوقف می‌شودinbox در هر consumer
اشتراک دیتابیس برای پرهیز از پیام‌رسانییک schema، بدون ایزوله‌سازی شکست، coupling پنهانDatabase per service
رویداد به‌جای RPC (انتشار DoReserveStock به‌عنوان event و بعد منتظر جواب ماندن)coupling و همگامی پنهانفرمان به گیرندهٔ نام‌دار، event به‌عنوان واقعیت

سازوکار (Mechanics) ​

جدول‌ها ​

همین سه جدول در هر context ای که پیام می‌فرستد یا می‌گیرد وجود دارد (نحو PostgreSQL؛ migration ی Laravel همین شکل را دارد).

sql
-- Producer side: written in the SAME transaction as the aggregate.
CREATE TABLE outbox_messages (
  id             bigserial PRIMARY KEY,            -- relay order
  message_id     uuid        NOT NULL UNIQUE,      -- consumers' dedup key
  type           text        NOT NULL,             -- sales.order.placed.v1
  key            text        NOT NULL,             -- aggregate id: the ordering unit
  seq            bigint      NOT NULL,             -- aggregate version at emission
  correlation_id text        NOT NULL,
  causation_id   text,
  payload        jsonb       NOT NULL,
  created_at     timestamptz NOT NULL DEFAULT now(),
  sent_at        timestamptz
);
CREATE INDEX outbox_unsent ON outbox_messages (id) WHERE sent_at IS NULL;   -- partial index: stays tiny

-- Consumer side: the unique key IS the idempotency.
CREATE TABLE inbox_messages (
  consumer     text        NOT NULL,
  message_id   uuid        NOT NULL,
  processed_at timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (consumer, message_id)
);

-- The saga is an aggregate: one row per order, a version, a deadline.
CREATE TABLE order_sagas (
  order_id    text PRIMARY KEY,
  state       text        NOT NULL,
  version     bigint      NOT NULL,
  deadline_at timestamptz,
  outstanding jsonb       NOT NULL DEFAULT '{}',
  reason      text
);
CREATE INDEX saga_due ON order_sagas (deadline_at) WHERE state IN ('reserving_stock','charging','shipping');

سه query که تمام روز اجرا می‌شوند:

sql
-- 1. The consumer (inside the business transaction): 1 row = first time, 0 rows = duplicate.
INSERT INTO inbox_messages (consumer, message_id) VALUES ($1, $2) ON CONFLICT DO NOTHING;

-- 2. The relay (one relay per outbox keeps per-key order): oldest unsent first.
SELECT id, message_id, type, key, seq, payload FROM outbox_messages
WHERE sent_at IS NULL ORDER BY id LIMIT 100;

-- 3. The saga timer: which sagas are past their deadline? (lock so two timers do not both act)
SELECT order_id FROM order_sagas
WHERE state IN ('reserving_stock','charging','shipping') AND deadline_at <= now()
FOR UPDATE SKIP LOCKED;

نگهداری (دسته‌دسته، خارج از اوج): DELETE FROM outbox_messages WHERE sent_at < now() - interval '7 days' و DELETE FROM inbox_messages WHERE processed_at < now() - interval '14 days' با retention بلندتر از پنجرهٔ replay ی broker. در حجم بالا هر دو جدول را روزانه partition کنید و partitionها را drop کنید (Partitioning & Sharding).

دکمه‌هایی که تحویل را تعیین می‌کنند ​

محصولتنظیماثر روی این فصل
RabbitMQPublisher confirmsrelay ردیف را فقط بعد از تأیید broker «ارسال‌شده» علامت می‌زند؛ بدون confirm پیام می‌تواند بعد از بازگشت publish گم شود
RabbitMQack دستی consumer، prefetch_countبعد از commit ی تراکنش inbox ack کنید؛ auto-ack با crash پیام را گم می‌کند
RabbitMQصف durable، پیام persistent، quorum queueاز restart ی broker جان به در می‌برند
Apache Kafkaacks=all، enable.idempotence=true، min.insync.replicasبا تغییر leader گم‌شدن نیست؛ retry ی producer در یک session تکرار نمی‌سازد
Apache Kafkaenable.auto.commit=false، commit بعد از تراکنش handlerat-least-once؛ crash دوباره تحویل می‌دهد
Apache Kafkapartition key = id ی aggregateترتیب per-aggregate
Redis StreamsXACK بعد از تراکنش؛ min-idle-time ی XAUTOCLAIMورودی‌های consumer ی crash‌کرده دوباره تحویل می‌شوند
Amazon SQSvisibility timeout بزرگ‌تر از بدترین زمان handlerوگرنه نسخهٔ دوم هنگام اجرای اولی تحویل می‌شود
صف Laravelretry_after در config/queue.php بزرگ‌تر از timeout ی jobوگرنه worker دوم job در حال اجرا را برمی‌دارد
صف Laravelafter_commit، afterCommit()برای تراکنشی که commit نشده job نفرست (جایگزین outbox نیست)
صف Laravel#[Tries]، #[MaxExceptions]، #[Backoff]، retryUntil()retry محدود و فاصله‌دار
PostgreSQLsynchronous_commit، lag ی replicaردیف outbox خوانده‌شده از replica ی عقب‌مانده کهنه است: batch ی relay را از primary بخوانید

کدهای خطا و کار درست ​

کدمعناکار handler
PostgreSQL 23505 unique_violationکلید inbox یا idempotency از قبل هستتکرار: رد کن، ack بزن
MySQL خطای 1062ورودی تکراریهمان
MongoDB E11000کلید تکراریهمان
PostgreSQL 40001 serialization_failureتداخل تراکنش هم‌زمانکل تراکنش را دوباره اجرا کن
PostgreSQL 40P01 deadlock_detected / MySQL 1213قربانی deadlockبا jitter دوباره (Deadlocks)
ناهمخوانی version ی خوش‌بینانه (۰ سطر به‌روز شد)نویسندهٔ دیگری aggregate را عوض کرددوباره بار کن و تکرار، یا اگر کهنه است park
HTTP 409 Conflictدرخواستی با همان کلید idempotency هنوز در حال اجراستکلاینت صبر می‌کند و دوباره می‌فرستد
HTTP 422اعتبارسنجی شکست خورددائمی؛ retry نه
HTTP 429 / 503 / 504overload، پایین، gateway timeoutبا backoff، Retry-After را رعایت کن
AMQP 406 PRECONDITION_FAILEDکانال بسته شد (مثلاً ack ی delivery tag ی ناشناخته بعد از redelivery)دوباره باز کن، ادامه بده؛ inbox ، redelivery را امن می‌کند
Kafka NotLeaderForPartition، RebalanceInProgressleader جابه‌جا شد یا گروه rebalance می‌کندکلاینت retry می‌کند؛ تکرار را انتظار داشته باشید

Go ​

یک ماژول Go (academy/designing-for-failure-reliable-messaging)، فقط کتابخانهٔ استاندارد، go vet و go test -race تمیز. Sales و Fulfilment و Billing هرکدام دیتابیس درون‌حافظه‌ای خودشان (store.DB) را دارند با معنای واقعی تراکنش (همهٔ نوشتن‌های یک Tx با هم commit می‌شوند یا هیچ)، و outbox، relay و inbox خودشان. broker ی درون‌حافظه تکرار، جابه‌جایی و publish ی گم‌شده تزریق می‌کند.

envelope و زبان منتشرشده (Published Language) ​

هر پیام یک ID ی ثابت (کلید dedup)، Key و Seq (ترتیب)، Correlation و Causation (ردیابی) دارد.

go
// Package msg is the envelope every context sends: identity for dedup,
// a key and sequence for ordering, correlation and causation for tracing.
package msg

import (
	"encoding/json"
	"time"
)

type Message struct {
	ID          string          `json:"id"`          // unique, stable across redelivery: the dedup key
	Type        string          `json:"type"`        // e.g. sales.order.placed.v1
	Key         string          `json:"key"`         // aggregate id: the ordering unit
	Seq         int64           `json:"seq"`         // aggregate version at emission: per-key order
	Correlation string          `json:"correlation"` // the whole business flow (the saga)
	Causation   string          `json:"causation"`   // the message that caused this one
	At          time.Time       `json:"at"`
	Payload     json.RawMessage `json:"payload"`
}

func New[T any](typ, key string, seq int64, p T) (Message, error) {
	raw, err := json.Marshal(p)
	if err != nil {
		return Message{}, err
	}
	return Message{Type: typ, Key: key, Seq: seq, Payload: raw}, nil
}

func Decode[T any](m Message) (T, error) {
	var v T
	err := json.Unmarshal(m.Payload, &v)
	return v, err
}

زبان منتشرشده میان سه context (نوع و payload پیام‌ها، با نسخه در پسوند):

go
// Package contracts holds the published language between Sales, Fulfilment
// and Billing: the message types and their payloads.
package contracts

const (
	OrderPlaced       = "sales.order.placed.v1"
	OrderConfirmed    = "sales.order.confirmed.v1"
	OrderCancelled    = "sales.order.cancelled.v1"
	StockReserved     = "fulfilment.stock.reserved.v1"
	StockRejected     = "fulfilment.stock.rejected.v1"
	StockReleased     = "fulfilment.stock.released.v1"
	ShipmentCreated   = "fulfilment.shipment.created.v1"
	ShipmentFailed    = "fulfilment.shipment.failed.v1"
	ShipmentCancelled = "fulfilment.shipment.cancelled.v1"
	PaymentCharged    = "billing.payment.charged.v1"
	PaymentDeclined   = "billing.payment.declined.v1"
	PaymentRefunded   = "billing.payment.refunded.v1"

	CmdReserveStock   = "cmd.fulfilment.ReserveStock.v1"
	CmdReleaseStock   = "cmd.fulfilment.ReleaseStock.v1"
	CmdCreateShipment = "cmd.fulfilment.CreateShipment.v1"
	CmdCancelShipment = "cmd.fulfilment.CancelShipment.v1"
	CmdChargePayment  = "cmd.billing.ChargePayment.v1"
	CmdRefundPayment  = "cmd.billing.RefundPayment.v1"
)

type Line struct {
	SKU string `json:"sku"`
	Qty int    `json:"qty"`
}

type OrderPlacedV1 struct {
	OrderID    string `json:"order_id"`
	CustomerID string `json:"customer_id"`
	Total      int64  `json:"total_cents"`
	Lines      []Line `json:"lines"`
}

// OrderRef is the payload of every message that only needs the order id.
type OrderRef struct {
	OrderID string `json:"order_id"`
	Reason  string `json:"reason,omitempty"`
}

type ChargePayment struct {
	OrderID        string `json:"order_id"`
	Amount         int64  `json:"amount_cents"`
	IdempotencyKey string `json:"idempotency_key"`
}

type OrderLines struct {
	OrderID string `json:"order_id"`
	Lines   []Line `json:"lines"`
}

انتشار مطمئن: یک aggregate، یک ردیف outbox ​

PlaceOrder واحد کار است. هرگز broker را صدا نمی‌زند.

go
package sales

import (
	"fmt"

	"academy/designing-for-failure-reliable-messaging/contracts"
	"academy/designing-for-failure-reliable-messaging/msg"
	"academy/designing-for-failure-reliable-messaging/outbox"
	"academy/designing-for-failure-reliable-messaging/store"
)

const table = "orders"

// PlaceOrder is one unit of work: ONE aggregate + ONE outbox row in ONE
// local transaction. No broker call happens here.
func PlaceOrder(db *store.DB, id, customerID string, total int64, lines []contracts.Line) error {
	return db.Tx(func(tx *store.Tx) error {
		o, err := Place(id, customerID, total, lines)
		if err != nil {
			return err
		}
		if err := store.Save(tx, table, o.ID, o); err != nil {
			return err
		}
		m, err := msg.New(contracts.OrderPlaced, o.ID, o.Version, contracts.OrderPlacedV1{
			OrderID: o.ID, CustomerID: o.CustomerID, Total: o.Total, Lines: o.Lines,
		})
		if err != nil {
			return err
		}
		_, err = outbox.Add(tx, m, "", "")
		return err
	})
}

// Load reads an order (used by tests and read models).
func Load(db *store.DB, id string) (o Order, ok bool) {
	db.View(func(tx *store.Tx) { o, ok, _ = store.Load[Order](tx, table, id) })
	return o, ok
}

// OnOutcome applies the saga's verdict to the Order aggregate. It is a
// separate transaction from the saga's own: one aggregate per transaction.
func OnOutcome(tx *store.Tx, m msg.Message) error {
	ref, err := msg.Decode[contracts.OrderRef](m)
	if err != nil {
		return fmt.Errorf("decode: %w", err)
	}
	o, ok, err := store.Load[Order](tx, table, ref.OrderID)
	if err != nil || !ok {
		return fmt.Errorf("order %s not found: %v", ref.OrderID, err)
	}
	switch m.Type {
	case contracts.OrderConfirmed:
		_, err = o.Confirm()
	case contracts.OrderCancelled:
		_, err = o.Cancel(ref.Reason)
	default:
		return nil
	}
	if err != nil {
		return err
	}
	return store.Save(tx, table, o.ID, o)
}

outbox و relay. relay اول publish می‌کند و بعد علامت می‌زند؛ hook ی CrashAfterPublish فقط برای این است که تست‌ها بتوانند آن را در بدترین لحظه بکشند.

go
// Package outbox implements the transactional outbox and a polling relay.
// Add runs inside the business transaction; the relay publishes later.
// Delivery is at-least-once: a crash between publish and mark re-publishes.
package outbox

import (
	"context"
	"errors"
	"fmt"

	"academy/designing-for-failure-reliable-messaging/msg"
	"academy/designing-for-failure-reliable-messaging/store"
)

const Table = "outbox"

type Entry struct {
	Message msg.Message `json:"message"`
	Sent    bool        `json:"sent"`
}

// Add stores the message in the SAME transaction as the state change.
// It assigns the stable message id (database name + sequence).
func Add(tx *store.Tx, m msg.Message, correlation, causation string) (msg.Message, error) {
	n := tx.NextSeq()
	m.ID = fmt.Sprintf("%s-%06d", tx.DBName(), n)
	m.Correlation, m.Causation = correlation, causation
	if m.Correlation == "" {
		m.Correlation = m.ID
	}
	err := store.Save(tx, Table, fmt.Sprintf("%012d", n), Entry{Message: m})
	return m, err
}

type Publisher interface {
	Publish(ctx context.Context, m msg.Message) error
}

// ErrCrash simulates the relay process dying between publish and mark.
var ErrCrash = errors.New("outbox: relay crashed")

type Relay struct {
	DB  *store.DB
	Pub Publisher
	// CrashAfterPublish is a failure-injection hook used by tests.
	CrashAfterPublish func(m msg.Message) bool
}

// RunOnce publishes unsent entries in outbox order. If a publish fails, later
// messages of the SAME key are held back so per-aggregate order is kept;
// other keys continue.
func (r *Relay) RunOnce(ctx context.Context) (int, error) {
	var pending []Entry
	var keys []string
	r.DB.View(func(tx *store.Tx) {
		for _, k := range tx.Keys(Table) {
			e, _, _ := store.Load[Entry](tx, Table, k)
			if !e.Sent {
				pending = append(pending, e)
				keys = append(keys, k)
			}
		}
	})
	blocked := map[string]bool{}
	published := 0
	for i, e := range pending {
		if blocked[e.Message.Key] {
			continue
		}
		if err := r.Pub.Publish(ctx, e.Message); err != nil {
			blocked[e.Message.Key] = true
			continue
		}
		if r.CrashAfterPublish != nil && r.CrashAfterPublish(e.Message) {
			return published, ErrCrash // published, NOT marked: duplicate on restart
		}
		err := r.DB.Tx(func(tx *store.Tx) error {
			e.Sent = true
			return store.Save(tx, Table, keys[i], e)
		})
		if err != nil {
			return published, err
		}
		published++
	}
	return published, nil
}

// Backlog is the number of unsent entries: the first outbox metric to alert on.
func Backlog(db *store.DB) int {
	n := 0
	db.View(func(tx *store.Tx) {
		for _, k := range tx.Keys(Table) {
			if e, _, _ := store.Load[Entry](tx, Table, k); !e.Sent {
				n++
			}
		}
	})
	return n
}

aggregate ای که نتیجهٔ saga وضعیتش را عوض می‌کند. Confirm و Cancel idempotent‌اند و سفارش پایانی هرگز به نتیجهٔ مخالف برنمی‌گردد:

go
// Package sales holds the Order aggregate: the consistency island that owns
// the order's status. Other contexts never write it; they send messages.
package sales

import (
	"errors"
	"fmt"

	"academy/designing-for-failure-reliable-messaging/contracts"
)

type Status string

const (
	Pending   Status = "pending"
	Confirmed Status = "confirmed"
	Cancelled Status = "cancelled"
)

var ErrEmptyOrder = errors.New("sales: an order needs at least one line")

type Order struct {
	ID         string           `json:"id"`
	CustomerID string           `json:"customer_id"`
	Lines      []contracts.Line `json:"lines"`
	Total      int64            `json:"total_cents"`
	Status     Status           `json:"status"`
	Reason     string           `json:"reason,omitempty"`
	Version    int64            `json:"version"`
}

func Place(id, customerID string, total int64, lines []contracts.Line) (*Order, error) {
	if len(lines) == 0 {
		return nil, ErrEmptyOrder
	}
	return &Order{ID: id, CustomerID: customerID, Lines: lines, Total: total, Status: Pending, Version: 1}, nil
}

// Confirm and Cancel are idempotent: repeating the same outcome is a no-op,
// and a terminal order never flips to the opposite outcome.
func (o *Order) Confirm() (changed bool, err error) {
	switch o.Status {
	case Confirmed:
		return false, nil
	case Cancelled:
		return false, fmt.Errorf("sales: order %s is cancelled, cannot confirm", o.ID)
	}
	o.Status, o.Version = Confirmed, o.Version+1
	return true, nil
}

func (o *Order) Cancel(reason string) (changed bool, err error) {
	switch o.Status {
	case Cancelled:
		return false, nil
	case Confirmed:
		return false, fmt.Errorf("sales: order %s is confirmed, cannot cancel", o.ID)
	}
	o.Status, o.Reason, o.Version = Cancelled, reason, o.Version+1
	return true, nil
}

مصرف مطمئن: inbox ​

go
// Package inbox makes a consumer idempotent: the dedup record and the
// business effect commit in ONE local transaction, so "processed" and
// "recorded as processed" cannot disagree.
package inbox

import (
	"errors"

	"academy/designing-for-failure-reliable-messaging/msg"
	"academy/designing-for-failure-reliable-messaging/store"
)

const Table = "inbox"

// Once runs fn at most once per (consumer, message id). It returns false when
// the message was already processed (a duplicate), without calling fn.
func Once(db *store.DB, consumer string, m msg.Message, fn func(tx *store.Tx) error) (bool, error) {
	processed := false
	err := db.Tx(func(tx *store.Tx) error {
		if err := tx.Insert(Table, consumer+"|"+m.ID, m.Type); err != nil {
			if errors.Is(err, store.ErrDuplicate) {
				return nil // already done: ack and move on
			}
			return err
		}
		if err := fn(tx); err != nil {
			return err // rolls back the inbox row too: the retry starts clean
		}
		processed = true
		return nil
	})
	return processed, err
}

handlerهای Fulfilment idempotent‌اند (همان id ی سفارش)، جابه‌جاپذیرند (release قبل از reserve tombstone می‌گذارد) و از طریق outbox خودشان جواب می‌دهند:

go
// Package fulfilment is the Fulfilment context's side of the conversation:
// idempotent, commutative handlers over its own database.
package fulfilment

import (
	"fmt"

	"academy/designing-for-failure-reliable-messaging/contracts"
	"academy/designing-for-failure-reliable-messaging/inbox"
	"academy/designing-for-failure-reliable-messaging/msg"
	"academy/designing-for-failure-reliable-messaging/outbox"
	"academy/designing-for-failure-reliable-messaging/retry"
	"academy/designing-for-failure-reliable-messaging/store"
)

type Reservation struct {
	OrderID string           `json:"order_id"`
	Status  string           `json:"status"` // held | released
	Lines   []contracts.Line `json:"lines"`
}

type Service struct {
	DB *store.DB
	// FailShipmentFor lets a test make the carrier reject an order.
	FailShipmentFor map[string]bool
}

func (s *Service) Stock(sku string) (n int) {
	s.DB.View(func(tx *store.Tx) {
		raw, _ := tx.Get("stock", sku)
		fmt.Sscan(raw, &n)
	})
	return n
}

func (s *Service) Seed(sku string, qty int) {
	_ = s.DB.Tx(func(tx *store.Tx) error { tx.Put("stock", sku, fmt.Sprint(qty)); return nil })
}

func (s *Service) Handle(m msg.Message) error {
	_, err := inbox.Once(s.DB, "fulfilment", m, func(tx *store.Tx) error {
		in, err := msg.Decode[contracts.OrderLines](m)
		if err != nil || in.OrderID == "" {
			return retry.Permanent{Err: fmt.Errorf("undecodable %s", m.Type)}
		}
		switch m.Type {
		case contracts.CmdReserveStock:
			return s.reserve(tx, in, m)
		case contracts.CmdReleaseStock:
			return s.release(tx, in.OrderID, m)
		case contracts.CmdCreateShipment:
			return s.ship(tx, in, m)
		case contracts.CmdCancelShipment:
			return s.cancelShipment(tx, in.OrderID, m)
		}
		return retry.Permanent{Err: fmt.Errorf("unknown command %s", m.Type)}
	})
	return err
}

func (s *Service) reply(tx *store.Tx, typ, orderID, reason string, cause msg.Message) error {
	out, err := msg.New(typ, orderID, 0, contracts.OrderRef{OrderID: orderID, Reason: reason})
	if err != nil {
		return err
	}
	_, err = outbox.Add(tx, out, cause.Correlation, cause.ID)
	return err
}

func (s *Service) reserve(tx *store.Tx, in contracts.OrderLines, cause msg.Message) error {
	if r, ok, _ := store.Load[Reservation](tx, "reservations", in.OrderID); ok {
		if r.Status == "released" { // Release arrived first (reordering): stay released
			return s.reply(tx, contracts.StockRejected, in.OrderID, "already released", cause)
		}
		return s.reply(tx, contracts.StockReserved, in.OrderID, "", cause) // same command again
	}
	for _, l := range in.Lines {
		var have int
		raw, _ := tx.Get("stock", l.SKU)
		fmt.Sscan(raw, &have)
		if have < l.Qty {
			return s.reply(tx, contracts.StockRejected, in.OrderID, "insufficient "+l.SKU, cause)
		}
	}
	for _, l := range in.Lines {
		var have int
		raw, _ := tx.Get("stock", l.SKU)
		fmt.Sscan(raw, &have)
		tx.Put("stock", l.SKU, fmt.Sprint(have-l.Qty))
	}
	if err := store.Save(tx, "reservations", in.OrderID, Reservation{OrderID: in.OrderID, Status: "held", Lines: in.Lines}); err != nil {
		return err
	}
	return s.reply(tx, contracts.StockReserved, in.OrderID, "", cause)
}

// release is a compensation. It is idempotent and commutative with reserve:
// releasing something never reserved leaves a tombstone, so a late reserve is refused.
func (s *Service) release(tx *store.Tx, orderID string, cause msg.Message) error {
	r, ok, _ := store.Load[Reservation](tx, "reservations", orderID)
	if ok && r.Status == "held" {
		for _, l := range r.Lines {
			var have int
			raw, _ := tx.Get("stock", l.SKU)
			fmt.Sscan(raw, &have)
			tx.Put("stock", l.SKU, fmt.Sprint(have+l.Qty))
		}
	}
	r.OrderID, r.Status = orderID, "released"
	if err := store.Save(tx, "reservations", orderID, r); err != nil {
		return err
	}
	return s.reply(tx, contracts.StockReleased, orderID, "", cause)
}

func (s *Service) ship(tx *store.Tx, in contracts.OrderLines, cause msg.Message) error {
	switch status, _ := tx.Get("shipments", in.OrderID); status {
	case "cancelled": // CancelShipment arrived first: refuse the late create
		return s.reply(tx, contracts.ShipmentFailed, in.OrderID, "already cancelled", cause)
	case "created": // same command again
		return s.reply(tx, contracts.ShipmentCreated, in.OrderID, "", cause)
	}
	if s.FailShipmentFor[in.OrderID] {
		return s.reply(tx, contracts.ShipmentFailed, in.OrderID, "carrier rejected address", cause)
	}
	tx.Put("shipments", in.OrderID, "created")
	return s.reply(tx, contracts.ShipmentCreated, in.OrderID, "", cause)
}

// cancelShipment is a compensation: idempotent, and commutative with ship
// (a cancel before the create leaves a tombstone that refuses the create).
func (s *Service) cancelShipment(tx *store.Tx, orderID string, cause msg.Message) error {
	tx.Put("shipments", orderID, "cancelled")
	return s.reply(tx, contracts.ShipmentCancelled, orderID, "", cause)
}

// Shipment returns "", "created" or "cancelled".
func (s *Service) Shipment(orderID string) (status string) {
	s.DB.View(func(tx *store.Tx) { status, _ = tx.Get("shipments", orderID) })
	return status
}

Billing کلید idempotency سطح کسب‌وکار و tombstone ی refund را اضافه می‌کند:

go
// Package billing charges and refunds idempotently, keyed by the caller's
// idempotency key. A refund for an unknown charge leaves a tombstone so a
// late charge for the same order is declined (commutative handlers).
package billing

import (
	"fmt"

	"academy/designing-for-failure-reliable-messaging/contracts"
	"academy/designing-for-failure-reliable-messaging/inbox"
	"academy/designing-for-failure-reliable-messaging/msg"
	"academy/designing-for-failure-reliable-messaging/outbox"
	"academy/designing-for-failure-reliable-messaging/retry"
	"academy/designing-for-failure-reliable-messaging/store"
)

type Payment struct {
	OrderID string `json:"order_id"`
	Amount  int64  `json:"amount_cents"`
	Status  string `json:"status"` // charged | refunded | cancelled (tombstone)
}

type Service struct {
	DB *store.DB
	// DeclineFor lets a test make the card issuer decline an order.
	DeclineFor map[string]bool
}

// Charges counts money actually taken: the number that must never exceed one.
func (s *Service) Charges(orderID string) (n int) {
	s.DB.View(func(tx *store.Tx) {
		raw, _ := tx.Get("charge_count", orderID)
		fmt.Sscan(raw, &n)
	})
	return n
}

func (s *Service) Handle(m msg.Message) error {
	_, err := inbox.Once(s.DB, "billing", m, func(tx *store.Tx) error {
		switch m.Type {
		case contracts.CmdChargePayment:
			c, err := msg.Decode[contracts.ChargePayment](m)
			if err != nil || c.IdempotencyKey == "" {
				return retry.Permanent{Err: fmt.Errorf("undecodable charge")}
			}
			return s.charge(tx, c, m)
		case contracts.CmdRefundPayment:
			r, err := msg.Decode[contracts.OrderRef](m)
			if err != nil || r.OrderID == "" {
				return retry.Permanent{Err: fmt.Errorf("undecodable refund")}
			}
			return s.refund(tx, r.OrderID, m)
		}
		return retry.Permanent{Err: fmt.Errorf("unknown command %s", m.Type)}
	})
	return err
}

func (s *Service) reply(tx *store.Tx, typ, orderID, reason string, cause msg.Message) error {
	out, err := msg.New(typ, orderID, 0, contracts.OrderRef{OrderID: orderID, Reason: reason})
	if err != nil {
		return err
	}
	_, err = outbox.Add(tx, out, cause.Correlation, cause.ID)
	return err
}

func (s *Service) charge(tx *store.Tx, c contracts.ChargePayment, cause msg.Message) error {
	// Natural idempotency: the second command with the same key is answered, not re-executed.
	if p, ok, _ := store.Load[Payment](tx, "payments", c.IdempotencyKey); ok {
		return s.reply(tx, contracts.PaymentCharged, c.OrderID, "replayed "+p.Status, cause)
	}
	if t, ok, _ := store.Load[Payment](tx, "payments", "order-"+c.OrderID); ok && t.Status == "cancelled" {
		return s.reply(tx, contracts.PaymentDeclined, c.OrderID, "order already cancelled", cause)
	}
	if s.DeclineFor[c.OrderID] {
		return s.reply(tx, contracts.PaymentDeclined, c.OrderID, "card declined", cause)
	}
	p := Payment{OrderID: c.OrderID, Amount: c.Amount, Status: "charged"}
	if err := store.Save(tx, "payments", c.IdempotencyKey, p); err != nil {
		return err
	}
	if err := store.Save(tx, "payments", "order-"+c.OrderID, p); err != nil {
		return err
	}
	var n int
	raw, _ := tx.Get("charge_count", c.OrderID)
	fmt.Sscan(raw, &n)
	tx.Put("charge_count", c.OrderID, fmt.Sprint(n+1))
	return s.reply(tx, contracts.PaymentCharged, c.OrderID, "", cause)
}

func (s *Service) refund(tx *store.Tx, orderID string, cause msg.Message) error {
	p, ok, _ := store.Load[Payment](tx, "payments", "order-"+orderID)
	if ok && p.Status == "charged" {
		p.Status = "refunded"
	} else if !ok {
		p = Payment{OrderID: orderID, Status: "cancelled"} // tombstone
	}
	if err := store.Save(tx, "payments", "order-"+orderID, p); err != nil {
		return err
	}
	return s.reply(tx, contracts.PaymentRefunded, orderID, "", cause)
}

retry، backoff و parking lot ​

go
// Package retry is the consumer-side retry loop: capped exponential backoff
// with full jitter, a hard limit, and a way to say "this will never work".
package retry

import (
	"errors"
	"time"

	"academy/designing-for-failure-reliable-messaging/msg"
)

// Permanent marks an error that no retry can fix (bad payload, unknown type).
type Permanent struct{ Err error }

func (e Permanent) Error() string { return "permanent: " + e.Err.Error() }
func (e Permanent) Unwrap() error { return e.Err }

type Parker interface {
	Park(m msg.Message, reason string, attempts int) error
}

type Policy struct {
	MaxAttempts int
	Base, Cap   time.Duration
	Rand        func() float64 // injectable so tests are deterministic
}

// Delay is "full jitter": a random wait in [0, min(cap, base*2^attempt)).
func (p Policy) Delay(attempt int) time.Duration {
	if attempt > 30 {
		attempt = 30
	}
	ceiling := min(p.Cap, p.Base<<attempt)
	return time.Duration(p.Rand() * float64(ceiling))
}

// Process handles m. Transient errors are retried after a backoff; permanent
// errors and exhausted attempts go to the parking lot. It never drops silently:
// the result is either "handled" or "parked with a reason".
func Process(p Policy, sleep func(time.Duration), m msg.Message, handle func(msg.Message) error, parker Parker) (parked bool, err error) {
	var last error
	for attempt := 0; attempt < p.MaxAttempts; attempt++ {
		last = handle(m)
		if last == nil {
			return false, nil
		}
		if errors.As(last, new(Permanent)) {
			return true, parker.Park(m, last.Error(), attempt+1)
		}
		sleep(p.Delay(attempt))
	}
	return true, parker.Park(m, "attempts exhausted: "+last.Error(), p.MaxAttempts)
}
go
// Package dlq is the parking lot for poison messages: kept with the reason
// and the attempt count so a human (or a repair job) can decide.
package dlq

import (
	"fmt"
	"sync"

	"academy/designing-for-failure-reliable-messaging/msg"
)

type Parked struct {
	Message  msg.Message
	Reason   string
	Attempts int
}

type Queue struct {
	mu    sync.Mutex
	items []Parked
}

func (q *Queue) Park(m msg.Message, reason string, attempts int) error {
	q.mu.Lock()
	defer q.mu.Unlock()
	q.items = append(q.items, Parked{Message: m, Reason: reason, Attempts: attempts})
	return nil
}

// Depth is the second metric to alert on: anything above zero needs a human.
func (q *Queue) Depth() int {
	q.mu.Lock()
	defer q.mu.Unlock()
	return len(q.items)
}

func (q *Queue) Items() []Parked {
	q.mu.Lock()
	defer q.mu.Unlock()
	return append([]Parked(nil), q.items...)
}

func (p Parked) String() string {
	return fmt.Sprintf("%s (%s) after %d attempts: %s", p.Message.ID, p.Message.Type, p.Attempts, p.Reason)
}

Saga به‌عنوان aggregate، با timeout و compensation ​

state machine خالص است: پیام و ساعت وارد می‌شود، state ی جدید و پیام‌های خروجی بیرون می‌آید. پاسخ‌های دیررس، تکراری‌ها و stateهای پایانی همگی این‌جا مدیریت می‌شوند.

go
// Package saga is the Order -> Reserve stock -> Charge -> Ship process as an
// aggregate. Handle is a pure state machine: message in, state change and
// outgoing messages out. Persistence, dedup and the outbox live in service.go.
package saga

import (
	"time"

	"academy/designing-for-failure-reliable-messaging/contracts"
	"academy/designing-for-failure-reliable-messaging/msg"
)

type State string

const (
	ReservingStock State = "reserving_stock"
	Charging       State = "charging"
	Shipping       State = "shipping"
	Completed      State = "completed" // terminal
	Compensating   State = "compensating"
	Cancelled      State = "cancelled" // terminal
)

type OrderSaga struct {
	OrderID     string           `json:"order_id"`
	State       State            `json:"state"`
	Lines       []contracts.Line `json:"lines"`
	Total       int64            `json:"total_cents"`
	Deadline    time.Time        `json:"deadline"`
	Outstanding map[string]bool  `json:"outstanding"` // compensations not yet acknowledged
	Reason      string           `json:"reason,omitempty"`
	Version     int64            `json:"version"`
}

// Out is a message the saga wants to send (a command or an outcome event).
type Out struct {
	Type    string
	Payload any
}

func (s *OrderSaga) terminal() bool { return s.State == Completed || s.State == Cancelled }

func Start(placed contracts.OrderPlacedV1, now time.Time, stepTimeout time.Duration) (*OrderSaga, []Out) {
	s := &OrderSaga{OrderID: placed.OrderID, State: ReservingStock, Lines: placed.Lines, Total: placed.Total,
		Deadline: now.Add(stepTimeout), Outstanding: map[string]bool{}, Version: 1}
	return s, []Out{{contracts.CmdReserveStock, contracts.OrderLines{OrderID: s.OrderID, Lines: s.Lines}}}
}

// Handle applies one reply. Replies that make no sense in the current state
// (late, duplicated, reordered) are ignored or answered with a compensation:
// the saga never panics and never moves backwards from a terminal state.
func (s *OrderSaga) Handle(m msg.Message, now time.Time, stepTimeout time.Duration) []Out {
	if s.terminal() && s.State == Completed {
		return nil
	}
	ref := contracts.OrderRef{OrderID: s.OrderID}
	var outs []Out
	switch m.Type {
	case contracts.StockReserved:
		switch s.State {
		case ReservingStock:
			s.advance(Charging, now, stepTimeout)
			outs = append(outs, Out{contracts.CmdChargePayment, contracts.ChargePayment{
				OrderID: s.OrderID, Amount: s.Total, IdempotencyKey: "charge-" + s.OrderID}})
		case Compensating, Cancelled: // late reply after a timeout: undo it again
			outs = append(outs, Out{contracts.CmdReleaseStock, ref})
		}
	case contracts.StockRejected:
		if s.State == ReservingStock {
			outs = s.cancel("out of stock", nil)
		}
	case contracts.PaymentCharged:
		switch s.State {
		case Charging:
			s.advance(Shipping, now, stepTimeout)
			outs = append(outs, Out{contracts.CmdCreateShipment, contracts.OrderLines{OrderID: s.OrderID, Lines: s.Lines}})
		case Compensating, Cancelled:
			if !s.Outstanding[contracts.CmdRefundPayment] { // not already being undone
				outs = append(outs, Out{contracts.CmdRefundPayment, ref})
				s.Outstanding[contracts.CmdRefundPayment] = true
			}
		}
	case contracts.PaymentDeclined:
		if s.State == Charging {
			outs = s.compensate("payment declined", contracts.CmdReleaseStock)
		}
	case contracts.ShipmentCreated:
		switch s.State {
		case Shipping:
			s.State, s.Version = Completed, s.Version+1
			outs = append(outs, Out{contracts.OrderConfirmed, ref})
		case Compensating, Cancelled: // late reply: a parcel exists for a cancelled order
			if !s.Outstanding[contracts.CmdCancelShipment] {
				s.Outstanding[contracts.CmdCancelShipment] = true
				outs = append(outs, Out{contracts.CmdCancelShipment, ref})
			}
		}
	case contracts.ShipmentFailed:
		if s.State == Shipping {
			outs = s.compensate("shipment failed", contracts.CmdRefundPayment, contracts.CmdReleaseStock)
		}
	case contracts.StockReleased:
		outs = s.acknowledge(contracts.CmdReleaseStock)
	case contracts.PaymentRefunded:
		outs = s.acknowledge(contracts.CmdRefundPayment)
	case contracts.ShipmentCancelled:
		outs = s.acknowledge(contracts.CmdCancelShipment)
	}
	return outs
}

// Expire is called by a timer. A silent neighbour is not an answer: we move to
// compensation with the commands that are safe whatever the neighbour did.
func (s *OrderSaga) Expire(now time.Time) []Out {
	if s.terminal() || s.State == Compensating || now.Before(s.Deadline) {
		return nil
	}
	switch s.State {
	case ReservingStock:
		return s.compensate("timeout reserving stock", contracts.CmdReleaseStock)
	case Charging:
		return s.compensate("timeout charging payment", contracts.CmdRefundPayment, contracts.CmdReleaseStock)
	default: // Shipping: the shipment may or may not exist, so cancel it too (tombstone-safe)
		return s.compensate("timeout shipping", contracts.CmdCancelShipment, contracts.CmdRefundPayment, contracts.CmdReleaseStock)
	}
}

func (s *OrderSaga) advance(next State, now time.Time, timeout time.Duration) {
	s.State, s.Deadline, s.Version = next, now.Add(timeout), s.Version+1
}

func (s *OrderSaga) compensate(reason string, cmds ...string) []Out {
	s.State, s.Reason, s.Version = Compensating, reason, s.Version+1
	var outs []Out
	for _, c := range cmds {
		s.Outstanding[c] = true
		outs = append(outs, Out{c, contracts.OrderRef{OrderID: s.OrderID}})
	}
	return outs
}

func (s *OrderSaga) acknowledge(cmd string) []Out {
	if s.State != Compensating {
		return nil
	}
	delete(s.Outstanding, cmd)
	if len(s.Outstanding) == 0 {
		return s.cancel(s.Reason, nil)
	}
	return nil
}

func (s *OrderSaga) cancel(reason string, _ []Out) []Out {
	s.State, s.Reason, s.Version = Cancelled, reason, s.Version+1
	return []Out{{contracts.OrderCancelled, contracts.OrderRef{OrderID: s.OrderID, Reason: reason}}}
}

service پایداری را اضافه می‌کند: ردیف inbox، ردیف saga و فرمان‌های خروجی در یک تراکنش؛ Tick sagaهای منقضی را پیدا می‌کند، هر saga در یک تراکنش.

go
package saga

import (
	"fmt"
	"time"

	"academy/designing-for-failure-reliable-messaging/contracts"
	"academy/designing-for-failure-reliable-messaging/inbox"
	"academy/designing-for-failure-reliable-messaging/msg"
	"academy/designing-for-failure-reliable-messaging/outbox"
	"academy/designing-for-failure-reliable-messaging/store"
)

const table = "sagas"

// Service persists the saga aggregate. Every handled message is ONE
// transaction: inbox row + saga state + outgoing commands in the outbox.
type Service struct {
	DB          *store.DB
	Now         func() time.Time
	StepTimeout time.Duration
}

func (s *Service) Handle(m msg.Message) error {
	_, err := inbox.Once(s.DB, "saga", m, func(tx *store.Tx) error {
		if m.Type == contracts.OrderPlaced {
			placed, err := msg.Decode[contracts.OrderPlacedV1](m)
			if err != nil {
				return Permanent(err)
			}
			if _, exists, _ := store.Load[OrderSaga](tx, table, placed.OrderID); exists {
				return nil // a second OrderPlaced for the same order
			}
			sg, outs := Start(placed, s.Now(), s.StepTimeout)
			return s.persist(tx, sg, outs, m)
		}
		ref, err := msg.Decode[contracts.OrderRef](m)
		if err != nil || ref.OrderID == "" {
			return Permanent(fmt.Errorf("undecodable %s", m.Type))
		}
		sg, ok, err := store.Load[OrderSaga](tx, table, ref.OrderID)
		if err != nil || !ok {
			return fmt.Errorf("saga %s not found yet", ref.OrderID) // transient: OrderPlaced may arrive later
		}
		outs := sg.Handle(m, s.Now(), s.StepTimeout)
		return s.persist(tx, &sg, outs, m)
	})
	return err
}

// Tick is driven by a scheduler. One saga per transaction.
func (s *Service) Tick() error {
	var ids []string
	s.DB.View(func(tx *store.Tx) { ids = tx.Keys(table) })
	for _, id := range ids {
		err := s.DB.Tx(func(tx *store.Tx) error {
			sg, _, err := store.Load[OrderSaga](tx, table, id)
			if err != nil {
				return err
			}
			outs := sg.Expire(s.Now())
			if len(outs) == 0 {
				return nil
			}
			return s.persist(tx, &sg, outs, msg.Message{ID: "timer", Correlation: id})
		})
		if err != nil {
			return err
		}
	}
	return nil
}

func (s *Service) persist(tx *store.Tx, sg *OrderSaga, outs []Out, cause msg.Message) error {
	if err := store.Save(tx, table, sg.OrderID, sg); err != nil {
		return err
	}
	for _, o := range outs {
		m, err := msg.New(o.Type, sg.OrderID, sg.Version, o.Payload)
		if err != nil {
			return err
		}
		corr := cause.Correlation
		if corr == "" {
			corr = cause.ID
		}
		if _, err := outbox.Add(tx, m, corr, cause.ID); err != nil {
			return err
		}
	}
	return nil
}

// Get is a read helper for tests and dashboards.
func (s *Service) Get(orderID string) (sg OrderSaga, ok bool) {
	s.DB.View(func(tx *store.Tx) { sg, ok, _ = store.Load[OrderSaga](tx, table, orderID) })
	return sg, ok
}

read model ی نسخه‌دار ​

فیلد Seq همان چیزی است که این بسته می‌خواند: پیام فقط وقتی اعمال می‌شود که دقیقاً version بعدی باشد؛ قدیمی‌ترها نادیده گرفته می‌شوند و پرش یک gap است که باید بعداً دوباره تلاش شود.

go
// Package projection is a version-checked read model: it applies messages of
// one key in version order, ignores stale ones and refuses to jump over a gap.
// This is what the Seq field of the envelope is for.
package projection

import (
	"fmt"

	"academy/designing-for-failure-reliable-messaging/msg"
	"academy/designing-for-failure-reliable-messaging/store"
)

type Result string

const (
	Applied Result = "applied"
	Stale   Result = "stale" // seq <= stored: already reflected, ignore and ack
	Gap     Result = "gap"   // seq > stored+1: something is missing, retry later
)

// Apply writes value for the key if m.Seq is exactly the next version.
// Gap is returned as a result, not an error: the caller maps it to a delayed
// retry (transient), then to parking after a limit.
func Apply(tx *store.Tx, table string, m msg.Message, value string) Result {
	var stored int64
	raw, _ := tx.Get(table+"_version", m.Key)
	fmt.Sscan(raw, &stored)
	switch {
	case m.Seq <= stored:
		return Stale
	case m.Seq > stored+1:
		return Gap
	}
	tx.Put(table, m.Key, value)
	tx.Put(table+"_version", m.Key, fmt.Sprint(m.Seq))
	return Applied
}

// Get returns the stored value and version.
func Get(tx *store.Tx, table, key string) (value string, version int64) {
	value, _ = tx.Get(table, key)
	raw, _ := tx.Get(table+"_version", key)
	fmt.Sscan(raw, &version)
	return value, version
}

لبه: بودجهٔ زمان و degrade صادقانه ​

go
// Package edge shows where timeouts, budgets and degraded answers live: in the
// application layer at the context's edge, never inside the domain model.
// Circuit breakers and bulkheads are covered in design/error-handling-fault-tolerance.
package edge

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

var ErrBudgetSpent = errors.New("edge: not enough time left for another call")

// CallWithin runs fn with a timeout of min(perCall, what is left of the
// caller's deadline minus a reserve for our own work). Deadline propagation:
// the whole request tree shares one absolute deadline.
func CallWithin[T any](ctx context.Context, perCall, reserve time.Duration, fn func(context.Context) (T, error)) (T, error) {
	var zero T
	timeout := perCall
	if dl, ok := ctx.Deadline(); ok {
		left := time.Until(dl) - reserve
		if left <= 0 {
			return zero, ErrBudgetSpent
		}
		timeout = min(timeout, left)
	}
	cctx, cancel := context.WithTimeout(ctx, timeout)
	defer cancel()
	return fn(cctx)
}

// Answer says how fresh a degraded read is, so the UI can show "as of 09:02".
type Answer[T any] struct {
	Value    T
	Stale    bool
	AsOf     time.Time
	Fallback string // why we degraded; empty when fresh
}

// WithStaleFallback returns the live value, or the last known value flagged as
// stale. It never invents a value: no cache entry means the error is returned.
func WithStaleFallback[T any](ctx context.Context, live func(context.Context) (T, error), last func() (T, time.Time, bool)) (Answer[T], error) {
	v, err := live(ctx)
	if err == nil {
		return Answer[T]{Value: v, AsOf: time.Now()}, nil
	}
	if cached, at, ok := last(); ok {
		return Answer[T]{Value: cached, Stale: true, AsOf: at, Fallback: err.Error()}, nil
	}
	return Answer[T]{}, err
}

broker ی خصمانه و تست‌ها ​

go
// Package broker is an in-memory at-least-once broker with failure injection:
// duplicates, reordering and drops. It has one queue per consumer group.
package broker

import (
	"context"
	"strings"
	"sync"

	"academy/designing-for-failure-reliable-messaging/msg"
)

type Faults struct {
	Duplicate bool // deliver every message twice
	Reverse   bool // newest first: worst-case reordering
	DropFirst int  // lose the first N publishes (publisher sees an error)
}

type Memory struct {
	mu     sync.Mutex
	Faults Faults
	subs   map[string][]string // consumer -> type prefixes
	queues map[string][]msg.Message
	drops  int
}

func New() *Memory {
	return &Memory{subs: map[string][]string{}, queues: map[string][]msg.Message{}}
}

func (b *Memory) Subscribe(consumer string, prefixes ...string) {
	b.mu.Lock()
	defer b.mu.Unlock()
	b.subs[consumer] = prefixes
}

type ErrLost struct{}

func (ErrLost) Error() string { return "broker: publish not acknowledged" }

func (b *Memory) Publish(_ context.Context, m msg.Message) error {
	b.mu.Lock()
	defer b.mu.Unlock()
	if b.drops < b.Faults.DropFirst {
		b.drops++
		return ErrLost{}
	}
	for consumer, prefixes := range b.subs {
		for _, p := range prefixes {
			if !strings.HasPrefix(m.Type, p) {
				continue
			}
			copies := 1
			if b.Faults.Duplicate {
				copies = 2
			}
			for i := 0; i < copies; i++ {
				if b.Faults.Reverse {
					b.queues[consumer] = append([]msg.Message{m}, b.queues[consumer]...)
				} else {
					b.queues[consumer] = append(b.queues[consumer], m)
				}
			}
			break
		}
	}
	return nil
}

// Receive pops the next message for a consumer group.
func (b *Memory) Receive(consumer string) (msg.Message, bool) {
	b.mu.Lock()
	defer b.mu.Unlock()
	q := b.queues[consumer]
	if len(q) == 0 {
		return msg.Message{}, false
	}
	b.queues[consumer] = q[1:]
	return q[0], true
}

// Lag is the queue depth of a consumer group: a metric to alert on.
func (b *Memory) Lag(consumer string) int {
	b.mu.Lock()
	defer b.mu.Unlock()
	return len(b.queues[consumer])
}

// Push puts a message straight back on one consumer's queue (used by tests to
// release messages that were held back).
func (b *Memory) Push(consumer string, m msg.Message) {
	b.mu.Lock()
	defer b.mu.Unlock()
	b.queues[consumer] = append(b.queues[consumer], m)
}

world سه context را به یک broker وصل می‌کند، با کلیدی برای «Billing پایین است»:

go
// Package sim wires three contexts, each with its own database, outbox relay
// and inbox, to one at-least-once broker. It is the integration edge the
// tests attack with duplicates, reordering, lost publishes, crashes and a
// neighbour that is down.
package sim

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

	"academy/designing-for-failure-reliable-messaging/billing"
	"academy/designing-for-failure-reliable-messaging/broker"
	"academy/designing-for-failure-reliable-messaging/contracts"
	"academy/designing-for-failure-reliable-messaging/dlq"
	"academy/designing-for-failure-reliable-messaging/fulfilment"
	"academy/designing-for-failure-reliable-messaging/inbox"
	"academy/designing-for-failure-reliable-messaging/msg"
	"academy/designing-for-failure-reliable-messaging/outbox"
	"academy/designing-for-failure-reliable-messaging/retry"
	"academy/designing-for-failure-reliable-messaging/saga"
	"academy/designing-for-failure-reliable-messaging/sales"
	"academy/designing-for-failure-reliable-messaging/store"
)

type Clock struct{ T time.Time }

func (c *Clock) Now() time.Time          { return c.T }
func (c *Clock) Advance(d time.Duration) { c.T = c.T.Add(d) }

type heldMessage struct {
	consumer string
	m        msg.Message
}

type World struct {
	Clock  *Clock
	Broker *broker.Memory
	DLQ    *dlq.Queue

	SalesDB, FulfilDB, BillDB *store.DB
	Saga                      *saga.Service
	Fulfil                    *fulfilment.Service
	Bill                      *billing.Service
	Relays                    []*outbox.Relay

	BillingDown bool // the neighbour is down: its queue fills, nobody answers
	Policy      retry.Policy
	Sleeps      []time.Duration // recorded backoff waits
	Handled     map[string]int  // consumer -> messages that reached the handler
	Trace       func(consumer string, m msg.Message)
	// Hold lets a test delay chosen messages: a slow neighbour or a stuck partition.
	Hold func(consumer string, m msg.Message) bool
	held []heldMessage
}

func NewWorld() *World {
	w := &World{
		Clock:   &Clock{T: time.Date(2026, 11, 25, 9, 0, 0, 0, time.UTC)},
		Broker:  broker.New(),
		DLQ:     &dlq.Queue{},
		Handled: map[string]int{},
	}
	w.SalesDB, w.FulfilDB, w.BillDB = store.New("sales"), store.New("fulfilment"), store.New("billing")
	w.Saga = &saga.Service{DB: w.SalesDB, Now: w.Clock.Now, StepTimeout: 30 * time.Second}
	w.Fulfil = &fulfilment.Service{DB: w.FulfilDB, FailShipmentFor: map[string]bool{}}
	w.Bill = &billing.Service{DB: w.BillDB, DeclineFor: map[string]bool{}}
	for _, db := range []*store.DB{w.SalesDB, w.FulfilDB, w.BillDB} {
		w.Relays = append(w.Relays, &outbox.Relay{DB: db, Pub: w.Broker})
	}
	w.Broker.Subscribe("saga", "sales.order.placed", "fulfilment.", "billing.")
	w.Broker.Subscribe("sales-order", "sales.order.confirmed", "sales.order.cancelled")
	w.Broker.Subscribe("notify", "sales.order.confirmed", "sales.order.cancelled")
	w.Broker.Subscribe("fulfilment", "cmd.fulfilment.")
	w.Broker.Subscribe("billing", "cmd.billing.")
	rng := rand.New(rand.NewPCG(1, 2))
	w.Policy = retry.Policy{MaxAttempts: 4, Base: 100 * time.Millisecond, Cap: 2 * time.Second, Rand: rng.Float64}
	return w
}

func (w *World) handlers() map[string]func(msg.Message) error {
	return map[string]func(msg.Message) error{
		"saga":        w.Saga.Handle,
		"fulfilment":  w.Fulfil.Handle,
		"billing":     w.Bill.Handle,
		"sales-order": w.salesOrder,
		"notify":      w.notify,
	}
}

func (w *World) salesOrder(m msg.Message) error {
	_, err := inbox.Once(w.SalesDB, "sales-order", m, func(tx *store.Tx) error {
		if err := sales.OnOutcome(tx, m); err != nil {
			return retry.Permanent{Err: err}
		}
		return nil
	})
	return err
}

// notify sends the customer an e-mail. "Add one e-mail" is NOT naturally
// idempotent: without the inbox a duplicate message means a duplicate e-mail.
func (w *World) notify(m msg.Message) error {
	_, err := inbox.Once(w.SalesDB, "notify", m, func(tx *store.Tx) error {
		ref, err := msg.Decode[contracts.OrderRef](m)
		if err != nil {
			return retry.Permanent{Err: err}
		}
		var n int
		raw, _ := tx.Get("emails", ref.OrderID)
		fmt.Sscan(raw, &n)
		tx.Put("emails", ref.OrderID, fmt.Sprint(n+1))
		return nil
	})
	return err
}

// Emails is the number of e-mails sent for an order.
func (w *World) Emails(orderID string) (n int) {
	w.SalesDB.View(func(tx *store.Tx) {
		raw, _ := tx.Get("emails", orderID)
		fmt.Sscan(raw, &n)
	})
	return n
}

// Pump runs relays and consumers until nothing moves. It returns the number
// of rounds it needed. A relay crash stops that round; the next one resumes.
func (w *World) Pump() int {
	ctx := context.Background()
	handlers := w.handlers()
	for round := 1; round <= 200; round++ {
		moved := false
		for _, r := range w.Relays {
			if n, _ := r.RunOnce(ctx); n > 0 {
				moved = true
			}
		}
		for _, name := range []string{"saga", "sales-order", "notify", "fulfilment", "billing"} {
			if name == "billing" && w.BillingDown {
				continue
			}
			for {
				m, ok := w.Broker.Receive(name)
				if !ok {
					break
				}
				moved = true
				if w.Hold != nil && w.Hold(name, m) {
					w.held = append(w.held, heldMessage{name, m})
					continue
				}
				w.Handled[name]++
				if w.Trace != nil {
					w.Trace(name, m)
				}
				h := handlers[name]
				_, _ = retry.Process(w.Policy, func(d time.Duration) { w.Sleeps = append(w.Sleeps, d) }, m, h, w.DLQ)
			}
		}
		// A relay that failed to publish is not "idle": it polls again next round.
		backlog := outbox.Backlog(w.SalesDB) + outbox.Backlog(w.FulfilDB) + outbox.Backlog(w.BillDB)
		if !moved && backlog == 0 {
			return round
		}
	}
	return 200
}

// ReleaseHeld delivers the delayed messages now (late replies and late commands).
func (w *World) ReleaseHeld() {
	for _, h := range w.held {
		w.Broker.Push(h.consumer, h.m)
	}
	w.held = nil
}

// Order places an order for one SKU and returns its id.
func (w *World) Order(id, sku string, qty int, total int64) error {
	return sales.PlaceOrder(w.SalesDB, id, "cust-1", total, []contracts.Line{{SKU: sku, Qty: qty}})
}

تست‌ها شکست‌های طبقه‌بندی را تزریق می‌کنند و نتیجهٔ کسب‌وکاری را assert می‌کنند:

go
package sim

import (
	"context"
	"errors"
	"testing"
	"time"

	"academy/designing-for-failure-reliable-messaging/broker"
	"academy/designing-for-failure-reliable-messaging/contracts"
	"academy/designing-for-failure-reliable-messaging/msg"
	"academy/designing-for-failure-reliable-messaging/outbox"
	"academy/designing-for-failure-reliable-messaging/saga"
	"academy/designing-for-failure-reliable-messaging/sales"
)

func newWorld(t *testing.T) *World {
	t.Helper()
	w := NewWorld()
	w.Fulfil.Seed("sku-mug", 5)
	return w
}

func mustOrder(t *testing.T, w *World, id string) {
	t.Helper()
	if err := w.Order(id, "sku-mug", 2, 3000); err != nil {
		t.Fatal(err)
	}
}

func assertOrder(t *testing.T, w *World, id string, want sales.Status) {
	t.Helper()
	o, ok := sales.Load(w.SalesDB, id)
	if !ok || o.Status != want {
		t.Fatalf("order %s: got %+v ok=%v, want status %s", id, o, ok, want)
	}
}

func TestHappyPathSurvivesDuplicatesAndReordering(t *testing.T) {
	w := newWorld(t)
	w.Broker.Faults = broker.Faults{Duplicate: true, Reverse: true}
	mustOrder(t, w, "o-1")
	w.Pump()

	assertOrder(t, w, "o-1", sales.Confirmed)
	if n := w.Bill.Charges("o-1"); n != 1 {
		t.Fatalf("charged %d times, want exactly 1", n)
	}
	if got := w.Fulfil.Stock("sku-mug"); got != 3 {
		t.Fatalf("stock = %d, want 3 (reserved once)", got)
	}
	if w.Emails("o-1") != 1 {
		t.Fatalf("e-mails sent = %d, want 1: an additive effect needs the inbox", w.Emails("o-1"))
	}
	if w.DLQ.Depth() != 0 {
		t.Fatalf("unexpected parked messages: %v", w.DLQ.Items())
	}
	if sg, _ := w.Saga.Get("o-1"); sg.State != saga.Completed {
		t.Fatalf("saga state = %s", sg.State)
	}
}

func TestPaymentDeclinedCompensatesStock(t *testing.T) {
	w := newWorld(t)
	w.Bill.DeclineFor["o-2"] = true
	mustOrder(t, w, "o-2")
	w.Pump()

	assertOrder(t, w, "o-2", sales.Cancelled)
	if got := w.Fulfil.Stock("sku-mug"); got != 5 {
		t.Fatalf("stock = %d, want 5 (reservation released)", got)
	}
	if w.Bill.Charges("o-2") != 0 {
		t.Fatal("money was taken for a declined order")
	}
}

func TestOutOfStockCancelsWithoutCompensation(t *testing.T) {
	w := NewWorld()
	w.Fulfil.Seed("sku-mug", 1)
	mustOrder(t, w, "o-3")
	w.Pump()
	assertOrder(t, w, "o-3", sales.Cancelled)
	if w.Bill.Charges("o-3") != 0 {
		t.Fatal("charged an order that never got stock")
	}
}

func TestShipmentFailureRefundsAndReleases(t *testing.T) {
	w := newWorld(t)
	w.Fulfil.FailShipmentFor["o-4"] = true
	mustOrder(t, w, "o-4")
	w.Pump()

	assertOrder(t, w, "o-4", sales.Cancelled)
	if got := w.Fulfil.Stock("sku-mug"); got != 5 {
		t.Fatalf("stock = %d, want 5", got)
	}
	if sg, _ := w.Saga.Get("o-4"); sg.State != saga.Cancelled || sg.Reason != "shipment failed" {
		t.Fatalf("saga = %+v", sg)
	}
}

// Billing is down. Sales keeps accepting orders; the saga times out and
// compensates; when Billing returns it replays the old charge and then the
// refund, and everything converges to "cancelled, refunded, stock back".
func TestBillingDownTimeoutThenLateReplies(t *testing.T) {
	w := newWorld(t)
	w.BillingDown = true
	mustOrder(t, w, "o-5")
	w.Pump()
	assertOrder(t, w, "o-5", sales.Pending) // the customer sees "pending", not an error

	w.Clock.Advance(31 * time.Second)
	if err := w.Saga.Tick(); err != nil {
		t.Fatal(err)
	}
	w.Pump()
	if sg, _ := w.Saga.Get("o-5"); sg.State != saga.Compensating {
		t.Fatalf("saga = %s, want compensating while the refund is outstanding", sg.State)
	}

	w.BillingDown = false
	w.Pump()
	assertOrder(t, w, "o-5", sales.Cancelled)
	if got := w.Fulfil.Stock("sku-mug"); got != 5 {
		t.Fatalf("stock = %d, want 5", got)
	}
	if sg, _ := w.Saga.Get("o-5"); sg.State != saga.Cancelled {
		t.Fatalf("saga = %s", sg.State)
	}
}

func TestRelayCrashAfterPublishIsHarmless(t *testing.T) {
	w := newWorld(t)
	crashed := false
	w.Relays[0].CrashAfterPublish = func(msg.Message) bool {
		if crashed {
			return false
		}
		crashed = true
		return true
	}
	mustOrder(t, w, "o-6")
	w.Pump()

	assertOrder(t, w, "o-6", sales.Confirmed)
	if w.Bill.Charges("o-6") != 1 {
		t.Fatal("duplicate publish caused a double charge")
	}
	if !crashed {
		t.Fatal("crash hook never fired")
	}
	if outbox.Backlog(w.SalesDB) != 0 {
		t.Fatal("outbox not drained after restart")
	}
}

func TestLostPublishesAreRetriedByTheRelay(t *testing.T) {
	w := newWorld(t)
	w.Broker.Faults.DropFirst = 3
	mustOrder(t, w, "o-7")
	w.Pump()
	assertOrder(t, w, "o-7", sales.Confirmed)
}

func TestPoisonMessageIsParkedNotSwallowed(t *testing.T) {
	w := newWorld(t)
	_ = w.Broker.Publish(context.Background(), msg.Message{ID: "x-1", Type: "cmd.fulfilment.Bogus.v1", Key: "o-8", Payload: []byte(`{"order_id":"o-8"}`)})
	_ = w.Broker.Publish(context.Background(), msg.Message{ID: "x-2", Type: contracts.CmdReserveStock, Key: "o-9", Payload: []byte(`not json`)})
	mustOrder(t, w, "o-10")
	w.Pump()

	if w.DLQ.Depth() != 2 {
		t.Fatalf("parked = %d, want 2: %v", w.DLQ.Depth(), w.DLQ.Items())
	}
	for _, p := range w.DLQ.Items() {
		if p.Attempts != 1 {
			t.Fatalf("permanent errors must not be retried: %s", p)
		}
	}
	assertOrder(t, w, "o-10", sales.Confirmed) // the poison did not block the queue
}

func TestPlaceOrderIsAtomicWithItsOutboxRow(t *testing.T) {
	w := newWorld(t)
	if err := sales.PlaceOrder(w.SalesDB, "o-11", "c", 1, nil); !errors.Is(err, sales.ErrEmptyOrder) {
		t.Fatalf("err = %v", err)
	}
	if _, ok := sales.Load(w.SalesDB, "o-11"); ok || outbox.Backlog(w.SalesDB) != 0 {
		t.Fatal("a rolled-back order left an order row or an outbox row")
	}
}

// A stuck partition delays CreateShipment past the saga's deadline. The saga
// cancels everything; the late command is then refused by the tombstone.
func TestShippingStallsThenLateCreateIsRefused(t *testing.T) {
	w := newWorld(t)
	w.Hold = func(consumer string, m msg.Message) bool { return m.Type == contracts.CmdCreateShipment }
	mustOrder(t, w, "o-12")
	w.Pump()
	assertOrder(t, w, "o-12", sales.Pending)

	w.Clock.Advance(31 * time.Second)
	if err := w.Saga.Tick(); err != nil {
		t.Fatal(err)
	}
	w.Hold = nil
	w.Pump()
	assertOrder(t, w, "o-12", sales.Cancelled)

	w.ReleaseHeld() // the stuck CreateShipment is finally delivered
	w.Pump()
	if got := w.Fulfil.Shipment("o-12"); got != "cancelled" {
		t.Fatalf("shipment = %q: a parcel exists for a cancelled, refunded order", got)
	}
	if got := w.Fulfil.Stock("sku-mug"); got != 5 {
		t.Fatalf("stock = %d, want 5", got)
	}
	assertOrder(t, w, "o-12", sales.Cancelled)
}

سیاست retry، saga ی خالص، inbox، handlerهای Fulfilment، projection و کمک‌های لبه تست‌های متمرکز خودشان را دارند (retry/retry_test.go، saga/saga_test.go، inbox/inbox_test.go، fulfilment/service_test.go، projection/projection_test.go، edge/edge_test.go). دموی اجرایی cmd/demo/main.go است.

آنچه نباید نوشت ​

anti-patternها به‌صورت کد، تا در review شناخته شوند:

go
// Package wrong collects the anti-patterns this chapter warns about. It
// compiles and it "works" on a good day. Do not copy it.
package wrong

import (
	"context"
	"database/sql"
	"net/http"
)

type Publisher interface {
	Publish(ctx context.Context, topic string, body []byte) error
}

// DualWrite commits the database, then calls the broker. A crash (or a broker
// error) between the two lines loses the event forever: the order exists and
// nobody was told. Swapping the lines gives the opposite bug: an event for an
// order that was rolled back.
func DualWrite(ctx context.Context, db *sql.DB, pub Publisher, id string) error {
	if _, err := db.ExecContext(ctx, `INSERT INTO orders (id, status) VALUES ($1, 'pending')`, id); err != nil {
		return err
	}
	return pub.Publish(ctx, "order.placed", []byte(id)) // not atomic with the INSERT
}

// ChargeWithBlindRetry retries a non-idempotent call. If the first attempt
// succeeded but the response was lost, the customer is charged twice.
func ChargeWithBlindRetry(client *http.Client, url string) error {
	var err error
	for i := 0; i < 3; i++ {
		var resp *http.Response
		resp, err = client.Post(url, "application/json", nil) // no Idempotency-Key header
		if err == nil {
			resp.Body.Close()
			return nil
		}
	}
	return err
}

// SwallowEverything acknowledges a message whatever happened. A bug in the
// handler turns into silently lost business events and an empty dashboard.
func SwallowEverything(handle func([]byte) error, body []byte) {
	_ = handle(body) // error ignored, message acked, no log, no DLQ
}

// SilentFallback hides a dead neighbour behind a made-up answer. The order is
// "confirmed" with a price of zero, and nobody is alerted.
func SilentFallback(get func() (int64, error)) int64 {
	price, err := get()
	if err != nil {
		return 0
	}
	return price
}

نگاه Go ​

  • database/sql: db.BeginTx(ctx, nil) برای تراکنش تولیدکننده، tx.ExecContext برای درج aggregate و outbox؛ نقض یکتایی inbox را با نوع خطای driver بررسی کنید (pgx: *pgconn.PgError با کد 23505). همیشه defer tx.Rollback() و commit صریح.
  • context: deadline را از درخواست تا هر فراخوانی خروجی ببرید (context.WithTimeout)؛ handler ای که ctx.Done() را نادیده بگیرد بعد از رفتن فراخواننده هم کار می‌کند.
  • golang.org/x/sync/errgroup: فراخوانی‌های fan-out با cancel مشترک (errgroup.WithContext)؛ برای خواندن موازی، نه برای نوشتنی که باید اتمیک باشد.
  • Watermill یک "Forwarder (the outbox pattern)"، SQL Pub/Sub برای PostgreSQL و MySQL، middleware ی router و "Requeuing After Error" را مستند کرده؛ قبل از نوشتن relay ی خودتان به آن نگاه کنید (Watermill docs). snippetهای این‌جا هیچ وابستگی ندارند تا هر خط دیده شود.
  • goroutine ها relay را ساده می‌کنند و restart را سخت: relay را طوری بنویسید که در هر خط بتوان کشتش (تست CrashAfterPublish).

اجرای کل ماژول: cd docs/snippets/ddd/designing-for-failure-reliable-messaging/go && go vet ./... && go test -race ./....

Laravel ​

Laravel 13 روی PHP 8.4. با php -l و خواندن بررسی شده، اجرا نشده (برنامهٔ Laravel در مخزن نیست)؛ رفتار شکست همین طراحی را ماژول Go ثابت می‌کند. قابلیت‌های صف همان‌هایی است که مستندات Queues در Laravel 13 دارد: attributeهای Tries، Backoff، MaxExceptions، Timeout و UniqueFor، ShouldBeUnique، WithoutOverlapping، ThrottlesExceptions، retryUntil، failed_jobs، dontRetry و batchها. RabbitMQ و Kafka driver ی داخلی نیستند؛ relay ی زیر از طریق interface ی Publisher منتشر می‌کند که با بسته‌ای که انتخاب می‌کنید پیاده می‌شود (Laravel Queue Internals).

جدول‌ها ​

php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        // Written in the SAME transaction as the aggregate; read by the relay.
        Schema::create('outbox_messages', function (Blueprint $t) {
            $t->id();                                   // relay order
            $t->uuid('message_id')->unique();           // the consumers' dedup key
            $t->string('type');
            $t->string('key');                          // aggregate id: the ordering unit
            $t->unsignedBigInteger('seq');              // aggregate version at emission
            $t->string('correlation_id');
            $t->string('causation_id')->nullable();
            $t->json('payload');
            $t->timestamp('sent_at')->nullable();
            $t->timestamp('created_at')->useCurrent();
            $t->index(['sent_at', 'id']);
        });

        // One row per (consumer, message): the unique index IS the idempotency.
        Schema::create('inbox_messages', function (Blueprint $t) {
            $t->string('consumer');
            $t->uuid('message_id');
            $t->timestamp('processed_at')->useCurrent();
            $t->primary(['consumer', 'message_id']);
        });

        // The saga is an aggregate: its own row, its own version.
        Schema::create('order_sagas', function (Blueprint $t) {
            $t->string('order_id')->primary();
            $t->string('state');
            $t->unsignedBigInteger('version');
            $t->timestamp('deadline_at')->nullable();
            $t->json('lines');
            $t->unsignedBigInteger('total_cents');
            $t->json('outstanding');                    // compensations not yet acknowledged
            $t->string('reason')->nullable();
            $t->index(['state', 'deadline_at']);
        });

        // The parking lot for poison messages (a table, so humans can query it).
        Schema::create('parked_messages', function (Blueprint $t) {
            $t->id();
            $t->string('consumer');
            $t->uuid('message_id');
            $t->string('type');
            $t->json('payload');
            $t->text('reason');
            $t->unsignedSmallInteger('attempts');
            $t->timestamp('parked_at')->useCurrent();
        });

        // Idempotency keys for the HTTP edge of Sales.
        Schema::create('idempotency_keys', function (Blueprint $t) {
            $t->string('key')->primary();
            $t->unsignedSmallInteger('status')->nullable();
            $t->json('response')->nullable();
            $t->timestamp('created_at')->useCurrent();
        });

        Schema::create('orders', function (Blueprint $t) {
            $t->string('id')->primary();
            $t->string('customer_id');
            $t->unsignedBigInteger('total_cents');
            $t->json('lines');
            $t->string('status');
            $t->string('reason')->nullable();
            $t->unsignedBigInteger('version')->default(1);
            $t->timestamps();
        });

        // Fulfilment: stock, reservations (with tombstones) and shipments (with tombstones).
        Schema::create('stock', function (Blueprint $t) {
            $t->string('sku')->primary();
            $t->unsignedInteger('qty');
        });
        Schema::create('reservations', function (Blueprint $t) {
            $t->string('order_id')->primary();
            $t->string('status');                       // held | released (tombstone)
            $t->json('lines');
        });
        Schema::create('shipments', function (Blueprint $t) {
            $t->string('order_id')->primary();
            $t->string('status');                       // created | cancelled (tombstone)
        });

        Schema::create('payments', function (Blueprint $t) {
            $t->string('idempotency_key')->primary();   // the provider call is keyed by it too
            $t->string('order_id')->index();
            $t->unsignedBigInteger('amount_cents');
            $t->string('status');                       // charged | refunded | cancelled (tombstone)
            $t->timestamps();
        });
    }

    public function down(): void
    {
        foreach (['shipments', 'reservations', 'stock', 'payments', 'orders', 'idempotency_keys', 'parked_messages', 'order_sagas', 'inbox_messages', 'outbox_messages'] as $table) {
            Schema::dropIfExists($table);
        }
    }
};

انتشار مطمئن: aggregate، ردیف outbox، دستور relay ​

php
<?php

namespace App\Sales\Domain;

use Illuminate\Database\Eloquent\Model;

/**
 * The Order aggregate: the consistency island that owns the order status.
 * Other contexts never write it; they send messages.
 */
final class Order extends Model
{
    public $incrementing = false;
    protected $keyType = 'string';
    protected $table = 'orders';
    protected $guarded = [];
    protected $casts = ['lines' => 'array'];

    /** @param list<array{sku: string, qty: int}> $lines */
    public static function place(string $id, string $customerId, int $totalCents, array $lines): self
    {
        if ($lines === []) {
            throw new \DomainException('An order needs at least one line');
        }

        return new self([
            'id' => $id, 'customer_id' => $customerId, 'total_cents' => $totalCents,
            'lines' => $lines, 'status' => 'pending', 'version' => 1,
        ]);
    }

    /** Idempotent: repeating the outcome is a no-op; a terminal order never flips. */
    public function confirm(): bool
    {
        if ($this->status === 'confirmed') {
            return false;
        }
        if ($this->status === 'cancelled') {
            throw new \DomainException("Order {$this->id} is cancelled, cannot confirm");
        }
        $this->status = 'confirmed';
        $this->version++;

        return true;
    }

    public function cancel(string $reason): bool
    {
        if ($this->status === 'cancelled') {
            return false;
        }
        if ($this->status === 'confirmed') {
            throw new \DomainException("Order {$this->id} is confirmed, cannot cancel");
        }
        $this->status = 'cancelled';
        $this->reason = $reason;
        $this->version++;

        return true;
    }
}
php
<?php

namespace App\Sales\Application;

use App\Messaging\Outbox;
use App\Sales\Domain\Order;
use Illuminate\Support\Facades\DB;

final class PlaceOrder
{
    /**
     * One unit of work: ONE aggregate + ONE outbox row in ONE local
     * transaction. No broker call here; the relay publishes later.
     *
     * @param list<array{sku: string, qty: int}> $lines
     */
    public function __invoke(string $orderId, string $customerId, int $totalCents, array $lines): Order
    {
        return DB::transaction(function () use ($orderId, $customerId, $totalCents, $lines): Order {
            $order = Order::place($orderId, $customerId, $totalCents, $lines);
            $order->save();

            Outbox::record('sales.order.placed.v1', $order->id, $order->version, [
                'order_id' => $order->id, 'customer_id' => $customerId,
                'total_cents' => $totalCents, 'lines' => $lines,
            ]);

            return $order;
        });
    }
}
php
<?php

namespace App\Messaging;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

final class Outbox
{
    /**
     * Must be called INSIDE the transaction that changes the aggregate.
     * Throws if there is no open transaction: a forgotten wrapper is a bug,
     * not a silent dual write.
     *
     * @param array<string, mixed> $payload
     */
    public static function record(
        string $type,
        string $key,
        int $seq,
        array $payload,
        ?string $correlationId = null,
        ?string $causationId = null,
    ): string {
        if (DB::transactionLevel() === 0) {
            throw new \LogicException('Outbox::record() outside a transaction');
        }

        $id = (string) Str::uuid();

        DB::table('outbox_messages')->insert([
            'message_id' => $id,
            'type' => $type,
            'key' => $key,
            'seq' => $seq,
            'correlation_id' => $correlationId ?? $id,
            'causation_id' => $causationId,
            'payload' => json_encode($payload, JSON_THROW_ON_ERROR),
        ]);

        return $id;
    }
}

relay یک دستور Artisan بلندمدت زیر Supervisor است (php artisan outbox:relay)، با Cache::lock تا فقط یکی اجرا شود؛ ردیف‌های بعدی کلیدی را که ردیف قبلی‌اش شکست خورده نگه می‌دارد:

php
<?php

namespace App\Console;

use App\Messaging\Publisher;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

/**
 * Polling publisher. Publish first, mark after: a crash in between means a
 * duplicate, never a loss. Consumers dedup with the inbox.
 *
 * Ordering per aggregate: one relay at a time (Cache::lock), rows in id order,
 * and a failed key blocks only its own later rows.
 */
final class RelayOutbox extends Command
{
    protected $signature = 'outbox:relay {--once : Run one batch and exit} {--batch=100}';
    protected $description = 'Publish unsent outbox rows to the broker';

    public function handle(Publisher $publisher): int
    {
        do {
            $published = Cache::lock('outbox-relay', 30)->get(fn () => $this->runBatch($publisher, (int) $this->option('batch')));

            if ($this->option('once')) {
                return self::SUCCESS;
            }

            if (! $published) {
                usleep(200_000); // idle: poll again in 200 ms
            }
        } while (true);
    }

    private function runBatch(Publisher $publisher, int $batch): int
    {
        $rows = DB::table('outbox_messages')->whereNull('sent_at')->orderBy('id')->limit($batch)->get();
        $blocked = [];
        $published = 0;

        foreach ($rows as $row) {
            if (isset($blocked[$row->key])) {
                continue; // keep per-aggregate order
            }

            try {
                $publisher->publish([
                    'id' => $row->message_id, 'type' => $row->type, 'key' => $row->key, 'seq' => $row->seq,
                    'correlation' => $row->correlation_id, 'causation' => $row->causation_id,
                    'payload' => json_decode($row->payload, true, flags: JSON_THROW_ON_ERROR),
                ]);
            } catch (\Throwable $e) {
                report($e);
                $blocked[$row->key] = true;

                continue;
            }

            DB::table('outbox_messages')->where('id', $row->id)->update(['sent_at' => now()]);
            $published++;
        }

        return $published;
    }
}
php
<?php

namespace App\Messaging;

interface Publisher
{
    /** Throw on any failure; the relay will retry the same message later. */
    public function publish(array $message): void;
}

مصرف مطمئن: inbox ​

php
<?php

namespace App\Messaging;

use Closure;
use Illuminate\Support\Facades\DB;

final class Inbox
{
    /**
     * Run $effect at most once per (consumer, message id). The dedup row and
     * the business effect commit together; if $effect throws, the dedup row
     * rolls back and the redelivery is processed normally.
     *
     * @param Closure(): void $effect
     * @return bool false when the message was a duplicate
     */
    public static function once(string $consumer, string $messageId, Closure $effect): bool
    {
        return DB::transaction(function () use ($consumer, $messageId, $effect): bool {
            // INSERT ... ON CONFLICT DO NOTHING (PostgreSQL) / INSERT IGNORE (MySQL)
            $inserted = DB::table('inbox_messages')->insertOrIgnore([
                'consumer' => $consumer,
                'message_id' => $messageId,
            ]);

            if ($inserted === 0) {
                return false; // already processed: acknowledge and move on
            }

            $effect();

            return true;
        });
    }
}

Billing دوبار idempotent است، با message id و با کلید کسب‌وکاری، و برای refund ی که قبل از charge می‌رسد tombstone می‌گذارد:

php
<?php

namespace App\Billing;

use App\Messaging\Inbox;
use App\Messaging\MessageHandler;
use App\Messaging\Outbox;
use App\Messaging\PermanentFailure;
use Illuminate\Support\Facades\DB;

/**
 * Idempotent twice over: the inbox dedups the message, and the payments table
 * dedups the business command by its idempotency key. A refund for an unknown
 * charge leaves a tombstone so a late charge for that order is declined.
 */
final class ChargeHandler implements MessageHandler
{
    public function __construct(private readonly PaymentProvider $provider) {}

    public function handle(array $message): void
    {
        Inbox::once('billing', $message['id'], function () use ($message): void {
            $p = $message['payload'];
            $orderId = $p['order_id'] ?? throw new PermanentFailure('order_id missing');

            match ($message['type']) {
                'cmd.billing.ChargePayment.v1' => $this->charge($message, $p),
                'cmd.billing.RefundPayment.v1' => $this->refund($message, $orderId),
                default => throw new PermanentFailure("Unknown command {$message['type']}"),
            };
        });
    }

    /** @param array<string, mixed> $p */
    private function charge(array $message, array $p): void
    {
        $key = $p['idempotency_key'] ?? throw new PermanentFailure('idempotency_key missing');

        if (DB::table('payments')->where('idempotency_key', $key)->exists()) {
            $this->reply($message, 'billing.payment.charged.v1', $p['order_id']); // same key: answer, do not charge again

            return;
        }
        $tombstone = DB::table('payments')->where('order_id', $p['order_id'])->where('status', 'cancelled')->exists();
        if ($tombstone || ! $this->provider->charge($key, $p['amount_cents'])) { // the provider call carries the same key
            $this->reply($message, 'billing.payment.declined.v1', $p['order_id']);

            return;
        }

        DB::table('payments')->insert([
            'idempotency_key' => $key, 'order_id' => $p['order_id'], 'amount_cents' => $p['amount_cents'],
            'status' => 'charged', 'created_at' => now(), 'updated_at' => now(),
        ]);
        $this->reply($message, 'billing.payment.charged.v1', $p['order_id']);
    }

    private function refund(array $message, string $orderId): void
    {
        $charged = DB::table('payments')->where('order_id', $orderId)->where('status', 'charged')->first();
        if ($charged !== null) {
            $this->provider->refund("refund-{$orderId}", $charged->amount_cents);
            DB::table('payments')->where('idempotency_key', $charged->idempotency_key)->update(['status' => 'refunded']);
        } elseif (! DB::table('payments')->where('order_id', $orderId)->exists()) {
            DB::table('payments')->insert([ // tombstone
                'idempotency_key' => "cancelled-{$orderId}", 'order_id' => $orderId, 'amount_cents' => 0,
                'status' => 'cancelled', 'created_at' => now(), 'updated_at' => now(),
            ]);
        }
        $this->reply($message, 'billing.payment.refunded.v1', $orderId);
    }

    private function reply(array $cause, string $type, string $orderId): void
    {
        Outbox::record($type, $orderId, 0, ['order_id' => $orderId], $cause['correlation'] ?? $cause['id'], $cause['id']);
    }
}

handler ی Fulfilment (reserve، release، ساخت و لغو مرسوله) از decrement ی شرطی (بدون race ی «بخوان-بعد-بنویس»)، DB::transaction ی تودرتو به‌عنوان savepoint تا سطر ردشده سطرهای قبلی را خنثی کند، و tombstone استفاده می‌کند:

php
<?php

namespace App\Fulfilment;

use App\Messaging\Inbox;
use App\Messaging\MessageHandler;
use App\Messaging\Outbox;
use App\Messaging\PermanentFailure;
use Illuminate\Support\Facades\DB;

/**
 * Reserve/Release are commutative: Release before Reserve leaves a tombstone,
 * so the late Reserve is refused and the final state is the same either way.
 */
final class StockHandler implements MessageHandler
{
    public function handle(array $message): void
    {
        Inbox::once('fulfilment', $message['id'], function () use ($message): void {
            $orderId = $message['payload']['order_id'] ?? throw new PermanentFailure('order_id missing');

            match ($message['type']) {
                'cmd.fulfilment.ReserveStock.v1' => $this->reserve($message, $orderId),
                'cmd.fulfilment.ReleaseStock.v1' => $this->release($message, $orderId),
                'cmd.fulfilment.CreateShipment.v1' => $this->ship($message, $orderId),
                'cmd.fulfilment.CancelShipment.v1' => $this->cancelShipment($message, $orderId),
                default => throw new PermanentFailure("Unknown command {$message['type']}"),
            };
        });
    }

    private function reserve(array $message, string $orderId): void
    {
        $existing = DB::table('reservations')->where('order_id', $orderId)->first();
        if ($existing !== null) {
            $this->reply($message, $existing->status === 'held' ? 'fulfilment.stock.reserved.v1' : 'fulfilment.stock.rejected.v1', $orderId);

            return;
        }

        try {
            // Nested DB::transaction() is a savepoint: a refused line undoes the lines before it.
            DB::transaction(function () use ($message, $orderId): void {
                foreach ($message['payload']['lines'] as $line) {
                    // Atomic conditional update: no read-then-write race (see optimistic-pessimistic-locking).
                    $ok = DB::table('stock')->where('sku', $line['sku'])->where('qty', '>=', $line['qty'])->decrement('qty', $line['qty']);
                    if ($ok === 0) {
                        throw new StockRejected($orderId, $line['sku']);
                    }
                }
            });
        } catch (StockRejected) {
            // A business "no" is an answer, not a failure: reply, do not retry.
            $this->reply($message, 'fulfilment.stock.rejected.v1', $orderId);

            return;
        }
        DB::table('reservations')->insert(['order_id' => $orderId, 'status' => 'held', 'lines' => json_encode($message['payload']['lines'])]);
        $this->reply($message, 'fulfilment.stock.reserved.v1', $orderId);
    }

    private function release(array $message, string $orderId): void
    {
        $r = DB::table('reservations')->where('order_id', $orderId)->first();
        if ($r !== null && $r->status === 'held') {
            foreach (json_decode($r->lines, true) as $line) {
                DB::table('stock')->where('sku', $line['sku'])->increment('qty', $line['qty']);
            }
            DB::table('reservations')->where('order_id', $orderId)->update(['status' => 'released']);
        } elseif ($r === null) {
            DB::table('reservations')->insert(['order_id' => $orderId, 'status' => 'released', 'lines' => '[]']); // tombstone
        }
        $this->reply($message, 'fulfilment.stock.released.v1', $orderId);
    }

    private function ship(array $message, string $orderId): void
    {
        $status = DB::table('shipments')->where('order_id', $orderId)->value('status');

        if ($status === 'cancelled') { // CancelShipment arrived first: refuse the late create
            $this->reply($message, 'fulfilment.shipment.failed.v1', $orderId);
        } else {
            if ($status === null) {
                DB::table('shipments')->insert(['order_id' => $orderId, 'status' => 'created']);
            }
            $this->reply($message, 'fulfilment.shipment.created.v1', $orderId);
        }
    }

    /** Compensation: idempotent, and commutative with ship() through the tombstone. */
    private function cancelShipment(array $message, string $orderId): void
    {
        DB::table('shipments')->upsert([['order_id' => $orderId, 'status' => 'cancelled']], ['order_id'], ['status']);
        $this->reply($message, 'fulfilment.shipment.cancelled.v1', $orderId);
    }

    private function reply(array $cause, string $type, string $orderId): void
    {
        Outbox::record($type, $orderId, 0, ['order_id' => $orderId], $cause['correlation'] ?? $cause['id'], $cause['id']);
    }
}
php
<?php

namespace App\Fulfilment;

/** A business "no", not a technical failure: the handler turns it into a StockRejected event, no retry. */
final class StockRejected extends \DomainException
{
    public function __construct(public readonly string $orderId, public readonly string $sku)
    {
        parent::__construct("Insufficient stock for {$sku}");
    }
}

retry، middleware و failed jobها ​

یک پیام broker می‌شود یک job در صف. job فقط حمل‌کننده است؛ تضمین از Inbox::once() می‌آید. ShouldBeUnique فیلتر اولیهٔ ارزانی در برابر صف‌کردن دوبارهٔ همان پیام است، نه سازوکار درستی.

php
<?php

namespace App\Messaging;

use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\Attributes\Backoff;
use Illuminate\Queue\Attributes\MaxExceptions;
use Illuminate\Queue\Attributes\Timeout;
use Illuminate\Queue\Attributes\Tries;
use Illuminate\Queue\Attributes\UniqueFor;
use Illuminate\Queue\Middleware\ThrottlesExceptions;
use Illuminate\Queue\Middleware\WithoutOverlapping;
use Illuminate\Support\Facades\DB;

/**
 * One broker message = one queued job. The job is only the transport; the
 * guarantee comes from Inbox::once() inside the handler.
 *
 *  - ShouldBeUnique + UniqueFor: do not enqueue the same message twice in a row
 *    (cheap first filter; NOT the correctness mechanism, the inbox is).
 *  - WithoutOverlapping(key): one message per aggregate at a time, so a
 *    version-checked handler never races with itself.
 *  - ThrottlesExceptions: if the neighbour keeps failing, stop hammering it.
 *  - Tries/Backoff/MaxExceptions/Timeout: bounded, spaced retries.
 */
#[Tries(6)]
#[MaxExceptions(5)]
#[Backoff([2, 10, 30, 120, 600])]
#[Timeout(30)]
#[UniqueFor(3600)]
final class ConsumeMessage implements ShouldQueue, ShouldBeUnique
{
    use InteractsWithQueue;
    use Queueable;

    /** @param array{id: string, type: string, key: string, payload: array<string, mixed>} $message */
    public function __construct(
        public readonly string $consumer,
        public readonly array $message,
    ) {}

    public function uniqueId(): string
    {
        return $this->consumer . ':' . $this->message['id'];
    }

    /** @return array<int, object> */
    public function middleware(): array
    {
        return [
            new WithoutOverlapping($this->consumer . ':' . $this->message['key']),
            new ThrottlesExceptions(10, 5 * 60),
        ];
    }

    public function retryUntil(): \DateTimeInterface
    {
        return now()->plus(minutes: 30);
    }

    public function handle(HandlerRegistry $handlers): void
    {
        $handlers->for($this->consumer)->handle($this->message);
    }

    /**
     * Called once, after the last attempt (or after a dontRetry exception).
     * Park the message with the reason: never swallow it.
     */
    public function failed(?\Throwable $e): void
    {
        DB::table('parked_messages')->insert([
            'consumer' => $this->consumer,
            'message_id' => $this->message['id'],
            'type' => $this->message['type'],
            'payload' => json_encode($this->message['payload']),
            'reason' => $e?->getMessage() ?? 'unknown',
            'attempts' => $this->attempts(),
        ]);
    }
}
php
<?php

namespace App\Messaging;

interface MessageHandler
{
    /** @param array{id: string, type: string, key: string, payload: array<string, mixed>} $message */
    public function handle(array $message): void;
}
php
<?php

namespace App\Messaging;

final class HandlerRegistry
{
    /** @param array<string, MessageHandler> $handlers consumer name => handler */
    public function __construct(private readonly array $handlers) {}

    public function for(string $consumer): MessageHandler
    {
        return $this->handlers[$consumer]
            ?? throw new PermanentFailure("No handler for consumer {$consumer}");
    }
}
php
<?php

namespace App\Messaging;

/** Retrying cannot fix this (bad payload, unknown type). Registered with dontRetry(). */
final class PermanentFailure extends \RuntimeException {}

پیام‌های poison یک بار در bootstrap/app.php با dontRetry اعلام می‌شوند تا retryها را رد کنند و در failed() و جدول parked_messages بنشینند:

php
<?php

use App\Messaging\PermanentFailure;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(web: __DIR__ . '/../routes/web.php', commands: __DIR__ . '/../routes/console.php')
    ->withProviders([\App\Providers\MessagingServiceProvider::class])
    ->withCommands([\App\Console\RelayOutbox::class])
    ->withMiddleware(function (Middleware $middleware): void {
        //
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        // Poison messages: no retry, straight to failed() and the parking table.
        $exceptions->dontRetry([PermanentFailure::class]);
    })
    ->create();

عملیات: php artisan queue:work --tries=6 --backoff=... را attributeها override می‌کنند؛ php artisan queue:failed jobهای ناموفق را فهرست می‌کند و php artisan queue:retry all بعد از رفع آن‌ها را دوباره صف می‌کند (redrive)؛ php artisan queue:prune-failed و queue:prune-batches جدول‌ها را کوچک نگه می‌دارند. Bus::batch([...])->allowFailures() برای fan-out ی jobهای مستقل می‌خورد (مثلاً ارسال ۵۰۰ اعلان)؛ saga نیست.

Sagaها ​

state machine PHP ساده و بی‌وابستگی به framework است، پس بدون دیتابیس unit test می‌شود:

php
<?php

namespace App\Sales\Saga;

enum SagaState: string
{
    case ReservingStock = 'reserving_stock';
    case Charging = 'charging';
    case Shipping = 'shipping';
    case Completed = 'completed';       // terminal
    case Compensating = 'compensating';
    case Cancelled = 'cancelled';       // terminal

    public function isTerminal(): bool
    {
        return $this === self::Completed || $this === self::Cancelled;
    }
}
php
<?php

namespace App\Sales\Saga;

/** A message the saga wants to send: a command to a neighbour or an outcome event. */
final readonly class Out
{
    /** @param array<string, mixed> $payload */
    public function __construct(public string $type, public array $payload) {}
}
php
<?php

namespace App\Sales\Saga;

use DateTimeImmutable;

/**
 * Order -> Reserve stock -> Charge -> Ship, as an aggregate.
 * handle() is a pure state machine: message in, state change + outgoing
 * messages out. Persistence, inbox and outbox live in OrderSagaService.
 */
final class OrderSaga
{
    /**
     * @param list<array{sku: string, qty: int}> $lines
     * @param array<string, bool> $outstanding compensations not yet acknowledged
     */
    public function __construct(
        public readonly string $orderId,
        public SagaState $state,
        public array $lines,
        public int $totalCents,
        public DateTimeImmutable $deadline,
        public array $outstanding = [],
        public ?string $reason = null,
        public int $version = 1,
    ) {}

    /** @return array{0: self, 1: list<Out>} */
    public static function start(string $orderId, array $lines, int $totalCents, DateTimeImmutable $now, int $stepSeconds): array
    {
        $saga = new self($orderId, SagaState::ReservingStock, $lines, $totalCents, $now->modify("+{$stepSeconds} seconds"));

        return [$saga, [new Out('cmd.fulfilment.ReserveStock.v1', ['order_id' => $orderId, 'lines' => $lines])]];
    }

    /** @return list<Out> */
    public function handle(string $type, DateTimeImmutable $now, int $stepSeconds): array
    {
        if ($this->state === SagaState::Completed) {
            return [];
        }
        $ref = ['order_id' => $this->orderId];

        return match ($type) {
            'fulfilment.stock.reserved.v1' => match ($this->state) {
                SagaState::ReservingStock => $this->advance(SagaState::Charging, $now, $stepSeconds, [
                    new Out('cmd.billing.ChargePayment.v1', $ref + [
                        'amount_cents' => $this->totalCents, 'idempotency_key' => "charge-{$this->orderId}",
                    ]),
                ]),
                SagaState::Compensating, SagaState::Cancelled => [new Out('cmd.fulfilment.ReleaseStock.v1', $ref)], // late reply
                default => [],
            },
            'fulfilment.stock.rejected.v1' => $this->state === SagaState::ReservingStock ? $this->cancel('out of stock') : [],
            'billing.payment.charged.v1' => match ($this->state) {
                SagaState::Charging => $this->advance(SagaState::Shipping, $now, $stepSeconds, [
                    new Out('cmd.fulfilment.CreateShipment.v1', ['order_id' => $this->orderId, 'lines' => $this->lines]),
                ]),
                SagaState::Compensating, SagaState::Cancelled => $this->undoLateCharge($ref),
                default => [],
            },
            'billing.payment.declined.v1' => $this->state === SagaState::Charging
                ? $this->compensate('payment declined', ['cmd.fulfilment.ReleaseStock.v1']) : [],
            'fulfilment.shipment.created.v1' => match ($this->state) {
                SagaState::Shipping => $this->complete(),
                SagaState::Compensating, SagaState::Cancelled => $this->undoLateShipment($ref), // a parcel exists for a cancelled order
                default => [],
            },
            'fulfilment.shipment.failed.v1' => $this->state === SagaState::Shipping
                ? $this->compensate('shipment failed', ['cmd.billing.RefundPayment.v1', 'cmd.fulfilment.ReleaseStock.v1']) : [],
            'fulfilment.stock.released.v1' => $this->acknowledge('cmd.fulfilment.ReleaseStock.v1'),
            'billing.payment.refunded.v1' => $this->acknowledge('cmd.billing.RefundPayment.v1'),
            'fulfilment.shipment.cancelled.v1' => $this->acknowledge('cmd.fulfilment.CancelShipment.v1'),
            default => [],
        };
    }

    /** A silent neighbour is not an answer: compensate with commands that are safe whatever it did. @return list<Out> */
    public function expire(DateTimeImmutable $now): array
    {
        if ($this->state->isTerminal() || $this->state === SagaState::Compensating || $now < $this->deadline) {
            return [];
        }

        return match ($this->state) {
            SagaState::ReservingStock => $this->compensate('timeout reserving stock', ['cmd.fulfilment.ReleaseStock.v1']),
            // The shipment may or may not exist: cancel it too (tombstone-safe).
            SagaState::Shipping => $this->compensate('timeout in shipping', [
                'cmd.fulfilment.CancelShipment.v1', 'cmd.billing.RefundPayment.v1', 'cmd.fulfilment.ReleaseStock.v1',
            ]),
            default => $this->compensate('timeout in ' . $this->state->value, ['cmd.billing.RefundPayment.v1', 'cmd.fulfilment.ReleaseStock.v1']),
        };
    }

    /** @param list<Out> $outs @return list<Out> */
    private function advance(SagaState $next, DateTimeImmutable $now, int $stepSeconds, array $outs): array
    {
        $this->state = $next;
        $this->deadline = $now->modify("+{$stepSeconds} seconds");
        $this->version++;

        return $outs;
    }

    /** @param list<string> $commands @return list<Out> */
    private function compensate(string $reason, array $commands): array
    {
        $this->state = SagaState::Compensating;
        $this->reason = $reason;
        $this->version++;
        $outs = [];
        foreach ($commands as $command) {
            $this->outstanding[$command] = true;
            $outs[] = new Out($command, ['order_id' => $this->orderId]);
        }

        return $outs;
    }

    /** @return list<Out> */
    private function acknowledge(string $command): array
    {
        if ($this->state !== SagaState::Compensating) {
            return [];
        }
        unset($this->outstanding[$command]);

        return $this->outstanding === [] ? $this->cancel($this->reason ?? 'cancelled') : [];
    }

    /** @return list<Out> */
    private function cancel(string $reason): array
    {
        $this->state = SagaState::Cancelled;
        $this->reason = $reason;
        $this->version++;

        return [new Out('sales.order.cancelled.v1', ['order_id' => $this->orderId, 'reason' => $reason])];
    }

    /** @return list<Out> */
    private function complete(): array
    {
        $this->state = SagaState::Completed;
        $this->version++;

        return [new Out('sales.order.confirmed.v1', ['order_id' => $this->orderId])];
    }

    /** @param array<string, string> $ref @return list<Out> */
    private function undoLateCharge(array $ref): array
    {
        if (isset($this->outstanding['cmd.billing.RefundPayment.v1'])) {
            return []; // a refund is already on its way
        }
        $this->outstanding['cmd.billing.RefundPayment.v1'] = true;

        return [new Out('cmd.billing.RefundPayment.v1', $ref)];
    }

    /** @param array<string, string> $ref @return list<Out> */
    private function undoLateShipment(array $ref): array
    {
        if (isset($this->outstanding['cmd.fulfilment.CancelShipment.v1'])) {
            return [];
        }
        $this->outstanding['cmd.fulfilment.CancelShipment.v1'] = true;

        return [new Out('cmd.fulfilment.CancelShipment.v1', $ref)];
    }
}

service آن را ذخیره می‌کند، یک تراکنش برای هر پیام و یکی برای هر saga ی منقضی، با lockForUpdate:

php
<?php

namespace App\Sales\Saga;

use App\Messaging\Inbox;
use App\Messaging\Outbox;
use DateTimeImmutable;
use Illuminate\Support\Facades\DB;

/**
 * Persists the saga aggregate. Each handled message is ONE transaction:
 * inbox row + saga state + outgoing commands in the outbox.
 */
final class OrderSagaService
{
    public function __construct(private readonly int $stepSeconds = 30) {}

    /** @param array{id: string, type: string, payload: array<string, mixed>} $message */
    public function handle(array $message, ?DateTimeImmutable $now = null): bool
    {
        $now ??= new DateTimeImmutable();

        return Inbox::once('saga', $message['id'], function () use ($message, $now): void {
            $orderId = $message['payload']['order_id'];

            if ($message['type'] === 'sales.order.placed.v1') {
                if ($this->find($orderId) !== null) {
                    return; // second OrderPlaced for the same order
                }
                [$saga, $outs] = OrderSaga::start($orderId, $message['payload']['lines'], $message['payload']['total_cents'], $now, $this->stepSeconds);
                $this->persist($saga, $outs, $message, insert: true);

                return;
            }

            $saga = $this->find($orderId)
                ?? throw new \RuntimeException("Saga {$orderId} not found yet"); // transient: retry later

            $outs = $saga->handle($message['type'], $now, $this->stepSeconds);
            $this->persist($saga, $outs, $message);
        });
    }

    /** Called by the scheduler: expire sagas whose deadline passed, one saga per transaction. */
    public function tick(?DateTimeImmutable $now = null): int
    {
        $now ??= new DateTimeImmutable();
        $expired = DB::table('order_sagas')
            ->whereNotIn('state', ['completed', 'cancelled', 'compensating'])
            ->where('deadline_at', '<=', $now->format('Y-m-d H:i:s'))
            ->pluck('order_id');

        foreach ($expired as $orderId) {
            DB::transaction(function () use ($orderId, $now): void {
                $row = DB::table('order_sagas')->where('order_id', $orderId)->lockForUpdate()->first();
                $saga = $row ? $this->hydrate($row) : null;
                $outs = $saga?->expire($now) ?? [];
                if ($saga !== null && $outs !== []) {
                    $this->persist($saga, $outs, ['id' => 'timer-' . $orderId, 'correlation' => $orderId]);
                }
            });
        }

        return $expired->count();
    }

    private function find(string $orderId): ?OrderSaga
    {
        $row = DB::table('order_sagas')->where('order_id', $orderId)->lockForUpdate()->first();

        return $row ? $this->hydrate($row) : null;
    }

    private function hydrate(object $row): OrderSaga
    {
        return new OrderSaga(
            $row->order_id, SagaState::from($row->state), json_decode($row->lines, true), (int) $row->total_cents,
            new DateTimeImmutable($row->deadline_at), json_decode($row->outstanding, true), $row->reason, (int) $row->version,
        );
    }

    /** @param list<Out> $outs @param array<string, mixed> $cause */
    private function persist(OrderSaga $saga, array $outs, array $cause, bool $insert = false): void
    {
        $values = [
            'state' => $saga->state->value, 'version' => $saga->version,
            'deadline_at' => $saga->deadline->format('Y-m-d H:i:s'),
            'lines' => json_encode($saga->lines), 'total_cents' => $saga->totalCents,
            'outstanding' => json_encode((object) $saga->outstanding), 'reason' => $saga->reason,
        ];
        $insert
            ? DB::table('order_sagas')->insert(['order_id' => $saga->orderId] + $values)
            : DB::table('order_sagas')->where('order_id', $saga->orderId)->update($values);

        foreach ($outs as $out) {
            Outbox::record($out->type, $saga->orderId, $saga->version, $out->payload, $cause['correlation'] ?? $cause['id'], $cause['id']);
        }
    }
}

نتیجهٔ saga از handler و تراکنش خودش به aggregate ی Order می‌رسد:

php
<?php

namespace App\Sales;

use App\Messaging\Inbox;
use App\Messaging\MessageHandler;
use App\Messaging\PermanentFailure;
use App\Sales\Domain\Order;
use Illuminate\Support\Facades\DB;

/** Applies the saga's verdict to the Order aggregate: a separate transaction from the saga's own. */
final class OutcomeHandler implements MessageHandler
{
    public function handle(array $message): void
    {
        Inbox::once('sales-order', $message['id'], function () use ($message): void {
            $order = Order::query()->lockForUpdate()->find($message['payload']['order_id'])
                ?? throw new \RuntimeException('Order not found yet'); // transient

            try {
                match ($message['type']) {
                    'sales.order.confirmed.v1' => $order->confirm(),
                    'sales.order.cancelled.v1' => $order->cancel($message['payload']['reason'] ?? 'cancelled'),
                    default => throw new PermanentFailure("Unexpected {$message['type']}"),
                };
            } catch (\DomainException $e) {
                throw new PermanentFailure($e->getMessage(), previous: $e);
            }

            $order->save();
        });
    }
}

timer یک command زمان‌بندی‌شده است (Schedule::command('saga:tick')->everyMinute()->withoutOverlapping()):

php
<?php

use App\Sales\Saga\OrderSagaService;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Schedule;

// The relay runs as a long-lived process under Supervisor: `php artisan outbox:relay`.
// The saga timer runs every minute; withoutOverlapping() keeps ticks from piling up.
Artisan::command('saga:tick', function (OrderSagaService $sagas): void {
    $this->info('expired sagas handled: ' . $sagas->tick());
})->purpose('Compensate sagas whose step deadline passed');

Schedule::command('saga:tick')->everyMinute()->withoutOverlapping();

// Alert inputs (pointer): outbox backlog, parked messages, saga age. See the observability section.
Artisan::command('outbox:backlog', function (): void {
    $this->line((string) \Illuminate\Support\Facades\DB::table('outbox_messages')->whereNull('sent_at')->count());
})->purpose('Number of unsent outbox rows');

سیم‌کشی: چه کسی چه چیزی را مصرف می‌کند ​

یک service provider رجیستری handlerها، router (consumerها با پیشوند نوع subscribe می‌کنند، مثل broker ی Go) و دو adapter را که در production عوض می‌کنید می‌بندد: publisher ی broker و payment gateway. LogPublisher و FakePaymentProvider جایگزین‌های توسعه‌اند تا relay و handlerها بدون زیرساخت امتحان شوند.

php
<?php

namespace App\Providers;

use App\Billing\ChargeHandler;
use App\Billing\FakePaymentProvider;
use App\Billing\PaymentProvider;
use App\Fulfilment\StockHandler;
use App\Messaging\HandlerRegistry;
use App\Messaging\LogPublisher;
use App\Messaging\MessageRouter;
use App\Messaging\Publisher;
use App\Sales\OutcomeHandler;
use App\Sales\Saga\OrderSagaService;
use App\Sales\Saga\SagaHandler;
use Illuminate\Support\ServiceProvider;

/** Wiring: who consumes what, and which adapters are in use. Register it in bootstrap/providers.php. */
final class MessagingServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->singleton(OrderSagaService::class, fn () => new OrderSagaService(stepSeconds: 30));
        $this->app->singleton(PaymentProvider::class, FakePaymentProvider::class); // swap for the real gateway adapter
        $this->app->singleton(Publisher::class, LogPublisher::class);              // swap for the broker adapter

        $this->app->singleton(MessageRouter::class, fn () => new MessageRouter([
            'saga' => ['sales.order.placed', 'fulfilment.', 'billing.'],
            'sales-order' => ['sales.order.confirmed', 'sales.order.cancelled'],
            'fulfilment' => ['cmd.fulfilment.'],
            'billing' => ['cmd.billing.'],
        ]));

        $this->app->singleton(HandlerRegistry::class, fn ($app) => new HandlerRegistry([
            'saga' => $app->make(SagaHandler::class),
            'sales-order' => $app->make(OutcomeHandler::class),
            'fulfilment' => $app->make(StockHandler::class),
            'billing' => $app->make(ChargeHandler::class),
        ]));
    }
}
php
<?php

namespace App\Messaging;

/**
 * The broker transport (a RabbitMQ or Kafka package, or the relay itself in a
 * modular monolith) calls route() for every message it receives. Each consumer
 * subscribes by type prefix, exactly like the Go broker.
 */
final class MessageRouter
{
    /** @param array<string, list<string>> $subscriptions consumer => type prefixes */
    public function __construct(private readonly array $subscriptions) {}

    /** @param array{id: string, type: string, key: string, payload: array<string, mixed>} $message */
    public function route(array $message): void
    {
        foreach ($this->subscriptions as $consumer => $prefixes) {
            foreach ($prefixes as $prefix) {
                if (str_starts_with($message['type'], $prefix)) {
                    ConsumeMessage::dispatch($consumer, $message); // one job per consumer
                    break;
                }
            }
        }
    }
}
php
<?php

namespace App\Sales\Saga;

use App\Messaging\MessageHandler;

/** Adapter: lets the saga service be the handler of the `saga` consumer. */
final class SagaHandler implements MessageHandler
{
    public function __construct(private readonly OrderSagaService $sagas) {}

    public function handle(array $message): void
    {
        $this->sagas->handle($message);
    }
}
php
<?php

namespace App\Messaging;

use Illuminate\Support\Facades\Log;

/**
 * Development stand-in for the broker adapter: writes to the log and hands the
 * message to the router in-process, so the relay can be tried without a broker.
 * Replace it with your RabbitMQ or Kafka publisher in production.
 */
final class LogPublisher implements Publisher
{
    public function __construct(private readonly MessageRouter $router) {}

    public function publish(array $message): void
    {
        Log::info('publish', ['id' => $message['id'], 'type' => $message['type'], 'key' => $message['key']]);
        $this->router->route($message);
    }
}
php
<?php

namespace App\Billing;

/** Development stand-in for the card gateway: approves everything. Replace in production. */
final class FakePaymentProvider implements PaymentProvider
{
    /** @var array<string, bool> */
    private array $seen = [];

    public function charge(string $idempotencyKey, int $amountCents): bool
    {
        $this->seen[$idempotencyKey] = true; // a real provider returns the first result for a repeated key

        return true;
    }

    public function refund(string $idempotencyKey, int $amountCents): void
    {
        $this->seen[$idempotencyKey] = true;
    }
}

لبهٔ API ​

php
<?php

namespace App\Sales\Http;

use App\Sales\Application\PlaceOrder;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * Idempotent command at the API edge: the client sends an Idempotency-Key and
 * may retry the POST after a timeout without creating a second order.
 * (The full pattern, including key scope and expiry, is in api-idempotency.)
 */
final class PlaceOrderController
{
    public function __invoke(Request $request, PlaceOrder $placeOrder): JsonResponse
    {
        $key = $request->header('Idempotency-Key')
            ?? abort(422, 'Idempotency-Key header is required');
        $data = $request->validate([
            'order_id' => 'required|string', 'customer_id' => 'required|string', 'total_cents' => 'required|integer|min:1',
            'lines' => 'required|array|min:1', 'lines.*.sku' => 'required|string', 'lines.*.qty' => 'required|integer|min:1',
        ]);

        return DB::transaction(function () use ($key, $data, $placeOrder): JsonResponse {
            // The unique key makes "first writer wins" a database fact, not an if-statement.
            $first = DB::table('idempotency_keys')->insertOrIgnore(['key' => $key]) === 1;

            if (! $first) {
                $saved = DB::table('idempotency_keys')->where('key', $key)->lockForUpdate()->first();

                return response()->json(json_decode($saved->response ?? '{"status":"in_progress"}', true), $saved->status ?? 409);
            }

            $order = $placeOrder($data['order_id'], $data['customer_id'], $data['total_cents'], $data['lines']);
            $body = ['order_id' => $order->id, 'status' => $order->status]; // "pending": the saga is still running
            DB::table('idempotency_keys')->where('key', $key)->update(['status' => 202, 'response' => json_encode($body)]);

            return response()->json($body, 202);
        });
    }
}
php
<?php

use App\Sales\Http\PlaceOrderController;
use Illuminate\Support\Facades\Route;

// 202 Accepted: the order exists as "pending"; confirmation arrives asynchronously.
Route::post('/orders', PlaceOrderController::class);
php
<?php

namespace App\Billing;

interface PaymentProvider
{
    /** Idempotent at the provider too: the same key never charges twice. */
    public function charge(string $idempotencyKey, int $amountCents): bool;

    public function refund(string $idempotencyKey, int $amountCents): void;
}

فراخوانی‌های HTTP خروجی محدودیت صریح می‌گیرند (Http::timeout(3)->connectTimeout(1)->retry(...) فقط برای فراخوانی‌های idempotent یا حامل کلید idempotency)؛ circuit breaker دور payment gateway در Error Handling & Fault Tolerance آمده.

تست‌ها ​

php
<?php

namespace Tests\Unit;

use App\Sales\Saga\OrderSaga;
use App\Sales\Saga\SagaState;
use DateTimeImmutable;
use PHPUnit\Framework\TestCase;

final class OrderSagaTest extends TestCase
{
    private function started(): OrderSaga
    {
        [$saga] = OrderSaga::start('o-1', [['sku' => 'mug', 'qty' => 2]], 3000, new DateTimeImmutable('2026-11-25 09:00:00'), 30);

        return $saga;
    }

    public function test_duplicate_reply_does_not_advance_twice(): void
    {
        $saga = $this->started();
        $now = new DateTimeImmutable('2026-11-25 09:00:05');

        $first = $saga->handle('fulfilment.stock.reserved.v1', $now, 30);
        $second = $saga->handle('fulfilment.stock.reserved.v1', $now, 30);

        $this->assertCount(1, $first);
        $this->assertSame('cmd.billing.ChargePayment.v1', $first[0]->type);
        $this->assertSame('charge-o-1', $first[0]->payload['idempotency_key']);
        $this->assertSame([], $second);
        $this->assertSame(SagaState::Charging, $saga->state);
    }

    public function test_timeout_in_charging_compensates_with_safe_commands(): void
    {
        $saga = $this->started();
        $saga->handle('fulfilment.stock.reserved.v1', new DateTimeImmutable('2026-11-25 09:00:05'), 30);

        $outs = $saga->expire(new DateTimeImmutable('2026-11-25 09:01:00'));

        $this->assertSame(SagaState::Compensating, $saga->state);
        $this->assertEqualsCanonicalizing(
            ['cmd.billing.RefundPayment.v1', 'cmd.fulfilment.ReleaseStock.v1'],
            array_map(fn ($o) => $o->type, $outs),
        );
    }

    public function test_late_payment_after_timeout_does_not_send_a_second_refund(): void
    {
        $saga = $this->started();
        $saga->handle('fulfilment.stock.reserved.v1', new DateTimeImmutable('2026-11-25 09:00:05'), 30);
        $saga->expire(new DateTimeImmutable('2026-11-25 09:01:00'));

        $outs = $saga->handle('billing.payment.charged.v1', new DateTimeImmutable('2026-11-25 09:02:00'), 30);

        $this->assertSame([], $outs); // a refund is already outstanding
    }

    public function test_cancelled_only_after_every_compensation_is_acknowledged(): void
    {
        $saga = $this->started();
        $now = new DateTimeImmutable('2026-11-25 09:00:05');
        $saga->handle('fulfilment.stock.reserved.v1', $now, 30);
        $saga->handle('billing.payment.charged.v1', $now, 30);
        $saga->handle('fulfilment.shipment.failed.v1', $now, 30);

        $saga->handle('billing.payment.refunded.v1', $now, 30);
        $this->assertSame(SagaState::Compensating, $saga->state);

        $outs = $saga->handle('fulfilment.stock.released.v1', $now, 30);
        $this->assertSame(SagaState::Cancelled, $saga->state);
        $this->assertSame('sales.order.cancelled.v1', $outs[0]->type);
    }

    public function test_shipping_timeout_cancels_the_shipment_and_a_late_create_is_undone_once(): void
    {
        $saga = $this->started();
        $t = new DateTimeImmutable('2026-11-25 09:00:05');
        $saga->handle('fulfilment.stock.reserved.v1', $t, 30);
        $saga->handle('billing.payment.charged.v1', $t, 30); // shipping

        $outs = $saga->expire(new DateTimeImmutable('2026-11-25 09:05:00'));
        $this->assertContains('cmd.fulfilment.CancelShipment.v1', array_map(fn ($o) => $o->type, $outs));

        foreach (['fulfilment.shipment.cancelled.v1', 'billing.payment.refunded.v1', 'fulfilment.stock.released.v1'] as $type) {
            $saga->handle($type, $t, 30);
        }
        $this->assertSame(SagaState::Cancelled, $saga->state);

        $late = $saga->handle('fulfilment.shipment.created.v1', $t, 30);
        $this->assertSame('cmd.fulfilment.CancelShipment.v1', $late[0]->type);
        $this->assertSame([], $saga->handle('fulfilment.shipment.created.v1', $t, 30));
    }
}
php
<?php

namespace Tests\Feature;

use App\Sales\Application\PlaceOrder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

final class OutboxAtomicityTest extends TestCase
{
    use RefreshDatabase;

    public function test_order_and_outbox_row_commit_together(): void
    {
        (new PlaceOrder())('o-1', 'c-1', 3000, [['sku' => 'mug', 'qty' => 2]]);

        $this->assertDatabaseHas('orders', ['id' => 'o-1', 'status' => 'pending']);
        $this->assertDatabaseHas('outbox_messages', ['type' => 'sales.order.placed.v1', 'key' => 'o-1', 'sent_at' => null]);
    }

    public function test_a_rolled_back_order_leaves_no_event(): void
    {
        try {
            (new PlaceOrder())('o-2', 'c-1', 3000, []); // domain rule: at least one line
        } catch (\DomainException) {
        }

        $this->assertDatabaseMissing('orders', ['id' => 'o-2']);
        $this->assertDatabaseCount('outbox_messages', 0);
    }
}
php
<?php

namespace Tests\Feature;

use App\Messaging\Inbox;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

final class InboxTest extends TestCase
{
    use RefreshDatabase;

    public function test_second_delivery_is_skipped(): void
    {
        $effects = 0;
        $id = '8f4e1c9a-0000-4000-8000-000000000001';

        $this->assertTrue(Inbox::once('billing', $id, function () use (&$effects): void { $effects++; }));
        $this->assertFalse(Inbox::once('billing', $id, function () use (&$effects): void { $effects++; }));
        $this->assertSame(1, $effects);
        $this->assertTrue(Inbox::once('saga', $id, function () use (&$effects): void { $effects++; })); // other consumer: own record
    }

    public function test_a_failing_effect_leaves_no_dedup_row(): void
    {
        $id = '8f4e1c9a-0000-4000-8000-000000000002';

        try {
            Inbox::once('billing', $id, function (): void { throw new \RuntimeException('provider down'); });
        } catch (\RuntimeException) {
        }

        $this->assertDatabaseMissing('inbox_messages', ['message_id' => $id]);
        $this->assertTrue(Inbox::once('billing', $id, fn () => null)); // the redelivery is processed
    }
}
php
<?php

namespace Tests\Feature;

use App\Messaging\Outbox;
use App\Messaging\Publisher;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;

final class RelayOutboxTest extends TestCase
{
    use RefreshDatabase;

    public function test_failed_publish_is_retried_and_order_per_key_is_kept(): void
    {
        DB::transaction(function (): void {
            Outbox::record('evt.a', 'o-1', 1, ['n' => 1]);
            Outbox::record('evt.b', 'o-1', 2, ['n' => 2]);
            Outbox::record('evt.c', 'o-2', 1, ['n' => 3]);
        });

        $log = new \ArrayObject();
        $this->app->instance(Publisher::class, new class($log) implements Publisher {
            private int $calls = 0;

            public function __construct(private \ArrayObject $log) {}

            public function publish(array $message): void
            {
                if (++$this->calls === 1) {
                    throw new \RuntimeException('broker timeout'); // first publish of o-1 fails
                }
                $this->log[] = $message['type'];
            }
        });

        $this->artisan('outbox:relay --once')->assertSuccessful();
        // o-1 is blocked (evt.b must not overtake evt.a); o-2 went through
        $this->assertSame(['evt.c'], $log->getArrayCopy());

        $this->artisan('outbox:relay --once')->assertSuccessful();
        $this->assertSame(['evt.c', 'evt.a', 'evt.b'], $log->getArrayCopy());
        $this->assertDatabaseCount('outbox_messages', 3);
        $this->assertSame(0, DB::table('outbox_messages')->whereNull('sent_at')->count());
    }
}
php
<?php

namespace Tests\Feature;

use App\Billing\ChargeHandler;
use App\Billing\PaymentProvider;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;

final class BillingIdempotencyTest extends TestCase
{
    use RefreshDatabase;

    private function provider(): PaymentProvider
    {
        return new class implements PaymentProvider {
            public int $charges = 0;

            public function charge(string $idempotencyKey, int $amountCents): bool
            {
                $this->charges++;

                return true;
            }

            public function refund(string $idempotencyKey, int $amountCents): void {}
        };
    }

    private function charge(string $messageId): array
    {
        return ['id' => $messageId, 'type' => 'cmd.billing.ChargePayment.v1', 'key' => 'o-1', 'payload' => [
            'order_id' => 'o-1', 'amount_cents' => 3000, 'idempotency_key' => 'charge-o-1',
        ]];
    }

    public function test_same_message_and_same_business_key_charge_once(): void
    {
        $provider = $this->provider();
        $handler = new ChargeHandler($provider);

        $handler->handle($this->charge('8f4e1c9a-0000-4000-8000-00000000000a'));
        $handler->handle($this->charge('8f4e1c9a-0000-4000-8000-00000000000a')); // duplicate delivery: the inbox
        $handler->handle($this->charge('8f4e1c9a-0000-4000-8000-00000000000b')); // new message, same key: the payments table

        $this->assertSame(1, $provider->charges);
        $this->assertSame(1, DB::table('payments')->where('order_id', 'o-1')->count());
    }

    public function test_refund_before_charge_leaves_a_tombstone_that_declines_the_late_charge(): void
    {
        $provider = $this->provider();
        $handler = new ChargeHandler($provider);

        $handler->handle(['id' => '8f4e1c9a-0000-4000-8000-00000000000c', 'type' => 'cmd.billing.RefundPayment.v1', 'key' => 'o-1', 'payload' => ['order_id' => 'o-1']]);
        $handler->handle($this->charge('8f4e1c9a-0000-4000-8000-00000000000d'));

        $this->assertSame(0, $provider->charges);
        $this->assertDatabaseHas('outbox_messages', ['type' => 'billing.payment.declined.v1', 'key' => 'o-1']);
    }
}
php
<?php

namespace Tests\Feature;

use App\Messaging\ConsumeMessage;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

final class ParkPoisonTest extends TestCase
{
    use RefreshDatabase;

    public function test_failed_job_is_parked_with_its_reason_not_swallowed(): void
    {
        $job = new ConsumeMessage('fulfilment', [
            'id' => '8f4e1c9a-0000-4000-8000-0000000000aa', 'type' => 'cmd.fulfilment.Bogus.v1', 'key' => 'o-9', 'payload' => ['x' => 1],
        ]);

        $job->failed(new \RuntimeException('Unknown command cmd.fulfilment.Bogus.v1'));

        $this->assertDatabaseHas('parked_messages', ['consumer' => 'fulfilment', 'type' => 'cmd.fulfilment.Bogus.v1']);
    }

    public function test_unique_id_is_consumer_plus_message_id(): void
    {
        $job = new ConsumeMessage('billing', ['id' => '8f4e1c9a-0000-4000-8000-0000000000bb', 'type' => 't', 'key' => 'o-1', 'payload' => []]);
        $this->assertSame('billing:8f4e1c9a-0000-4000-8000-0000000000bb', $job->uniqueId());
    }
}

نگاه Laravel ​

  • DB::transaction(fn) واحد کار است؛ فراخوانی تودرتو savepoint است. lockForUpdate() ردیف saga را سریال می‌کند (Locks & Concurrency). DB::table(...)->insertOrIgnore() درج idempotent قابل‌حمل است.
  • jobی که درون تراکنش dispatch شود ممکن است قبل از commit اجرا شود مگر after_commit تنظیم شده باشد یا afterCommit() به کار رود؛ حتی آن‌وقت job می‌تواند میان commit و push گم شود، پس منبع حقیقت رویدادها outbox است نه صف.
  • ShouldBeUnique (با #[UniqueFor] و uniqueId()) و WithoutOverlapping بر قفل cache تکیه دارند و best-effort‌اند؛ کار تکراری را کم می‌کنند اما جای inbox را نمی‌گیرند.
  • RateLimited (با RateLimiter::for('payments', ...)) سرعت برخورد jobها به provider را محدود می‌کند و ThrottlesExceptions(10, 5 * 60) به شکست واکنش نشان می‌دهد: اولی محدودیت سرعت است، دومی مکث بعد از دردسر. ThrottlesExceptions(10, 5 * 60) بعد از ۱۰ استثنای پیاپی job را ۵ دقیقه متوقف می‌کند، که به provider ناپایدار می‌خورد؛ با retryUntil() جفتش کنید.
  • eventها و listenerها (Event::dispatch) درون‌پردازه و به‌طور پیش‌فرض همگام‌اند؛ domain event‌اند نه پیام مطمئن (Domain Events vs Integration Events).

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

مسئلهراه‌حلچطورمزیتهزینه / محدودیت
سفارش ذخیره شد، رویداد هرگز نرفتTransactional outboxردیف پیام در همان تراکنش؛ relayبدون گم‌شدن، بدون 2PCrelay، تکرار، پاک‌سازی
مشتری دو بار شارژ شدInbox + کلید idempotency(consumer, message_id) یکتا؛ کلید provider charge-<order>retry امن در همه‌جاذخیرهٔ کلید، retention
موجودی بعد از پرداخت ناموفق نگه‌داشته شدCompensation ی saga + timerReleaseStock هنگام رد؛ deadline برای هر گامبدون پاک‌سازی دستیstate ی saga، طراحی compensation
پیام poison صف را قفل می‌کنددسته‌بندی، park، alert، redriveنوع خطای Permanent، DLQ با دلیلصف حرکت می‌کند، چیزی گم نمی‌شودکسی باید triage کند
Billing در اوج پایین استوضعیت pending + saga + retry کندشدهسفارش را بپذیر، بعداً شارژ کن، deadlineدرآمد ادامه داردشکست دیررس، پیام‌رسانی به مشتری
لغو قبل از ثبت می‌رسدمدیریت gap ی version، retry بعداًبررسی seq؛ خطای گذرای «saga هنوز پیدا نشد»نتیجه مستقل از ترتیبسیاست gap و حد park لازم است
پاسخ دیررس بعد از لغودوباره خنثی کنsaga به StockReserved ی دیررس با ReleaseStock جواب می‌دهدرزرو نشتی نیستcompensationها باید idempotent باشند
backlog ی outbox رشد می‌کندindex، batch، partition، یا رفتن به log tailingpartial index روی ارسال‌نشده‌ها؛ relay برای هر partitionlag کمترقطعات متحرک بیشتر
جدول inbox رشد می‌کندRetention + partitionحذف قدیمی‌تر از پنجرهٔ replayاندازهٔ محدودreplay قدیمی‌تر از پنجره تکرار می‌شود
طوفان retry بعد از بازیابیfull jitter، بودجهٔ retry، throttleretry.Policy، ThrottlesExceptionsبازیابی با کلاینت‌های خودش کشته نمی‌شودرسیدن کندتر
پیام با schema ی ناشناختهنوع نسخه‌دار، ACL، contract test...OrderPlaced.v1تکامل امنچند نسخه همزمان
دو relay همان ردیف را منتشر می‌کنندیک relay (قفل) یا پذیرش تکرارCache::lock، advisory lock، leader electionترتیب حفظ می‌شودنقطهٔ واحد؛ تأخیر failover

انتخاب ​

وضعیتتوصیهتکنیک اضافهدلیل
یک گام از context می‌گذرد (اعلان، index)Outbox + event، consumer با inboxاگر ممکن است idempotency طبیعیsaga لازم نیست
دو یا سه گام، یک تیم، پایدارChoreographyconsumer ی idempotent، correlation idساده، بدون جزء اضافه
چهار گام یا بیشتر، compensation، deadlineSaga ی orchestrated به‌عنوان aggregatetimer، outbox برای فرمان‌هایک جا state دیده می‌شود
فرایند ساعت‌ها یا روزها، گام انسانیموتور workflow پایدارTemporal، Step Functionstimer و history داخلی
پول جابه‌جا می‌شودکلید idempotency در هر گام، saga، reconciliationدفتر کل، گزارش روزانهیک شکست گران‌تر از کل ماشین‌آلات است
داده‌ی عمدتاً-خواندنی از context دیگرread model ی تغذیه‌شده با eventبررسی version، برچسب as ofقطعی همسایه منجمد می‌کند نه می‌شکند
پاسخ فوری از همسایه لازم استفراخوانی همگام با deadline، breaker، حالت degradedcache ی آخرین مقدار خوب، با برچسبجواب فوری، صادق دربارهٔ سن
broker تراکنش نداردOutbox + inboxpartition per-keyبا هر broker ی at-least-once کار می‌کند
نرخ بالای رویداد از یک دیتابیسLog tailing (Debezium)جدول outbox با فیلتر CDCتأخیر کم، بدون بار polling
ترتیب per-aggregate حیاتی استpartition key = id ی aggregate + بررسی versionیک consumer برای هر keyترتیب به‌علاوهٔ تور ایمنی
کسب‌وکار می‌گوید «هرگز pending نشان نده»مرزها را بازنگری کن یا coupling ی همگام را بپذیرظرفیت را همگام رزرو کنتصمیم محصولی با هزینه، نه آرزوی رایگان

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

Monolith: یک پردازه، یک دیتابیس ​

ثبت سفارش، رزرو موجودی و شارژ کارت در یک تراکنش دیتابیس؛ شکست یعنی rollback. با این حال رویدادها را از جدول outbox بنویسید: یک insert هزینه دارد و روزی که ماژولی جدا شود رویدادها آماده‌اند. فراخوانی‌های بیرونی (provider ی کارت) اولین شکستی‌اند که ظاهر می‌شوند: آن‌ها را بعد از تراکنش و با کلید idempotency صدا بزنید، یا به‌عنوان گام مبتنی بر outbox، هرگز هنگام نگه‌داشتن قفل ردیف. مثال: یک monolith ی Laravel که PlaceOrder اش orders + outbox_messages را commit می‌کند و worker صف ایمیل تأیید را از ردیف outbox می‌فرستد. ACID & Transactions.

Modular monolith: ماژول‌های جدا، قاعده‌های جدا ​

یک deployable و اغلب یک دیتابیس، اما ماژول‌ها (Sales، Fulfilment، Billing) جدول‌هایشان را دارند و فقط API نشان می‌دهند (Modular Monolith). قاعده: هیچ تراکنشی از دو ماژول نمی‌گذرد. ماژول‌ها از طریق bus ی درون‌پردازه صحبت می‌کنند که پشتش جدول‌های outbox و inbox است تا saga، handlerهای idempotent و مدل وضعیت از همین حالا کار کنند و استخراج بعدی فقط transport را عوض کند. مثال: جدول order_sagas در schema ی Sales؛ StockHandler ی Fulfilment که از همان صف جدول دیتابیس مصرف می‌کند؛ inbox_messages ی هر ماژول. خطر «تراکنش آسانِ» میان‌ماژولی است: همان مدیریت شکستی را که بعداً لازم دارید حذف می‌کند.

Microservices: سه دیتابیس، یک broker ​

مثال جاری سرتاسری (دموی Go این رد را چاپ می‌کند؛ هر پیام دو بار ظاهر می‌شود چون broker تکرار می‌کند):

text
     Sales (db sales)              Broker              Fulfilment / Billing
1    tx: order o-1 pending + outbox OrderPlaced
2    relay -> OrderPlaced -------> saga queue
3    saga tx: inbox + saga(reserving) + outbox ReserveStock
4    relay -> ReserveStock ------> fulfilment: inbox + reserve + outbox StockReserved
5    saga tx: charging + outbox ChargePayment (key charge-o-1)
6    relay -> ChargePayment -----> billing: inbox + payment + outbox PaymentCharged
7    saga tx: shipping + outbox CreateShipment
8    relay -> CreateShipment ----> fulfilment: shipment + outbox ShipmentCreated
9    saga tx: completed + outbox OrderConfirmed
10   sales-order tx: order confirmed (version 2)

قرارداد میان contextها: نوع و payload پیام‌ها در contracts (زبان منتشرشده، Context Maps)؛ فرمان‌ها به یک گیرندهٔ نام‌دار می‌روند، eventها واقعیت‌اند؛ هر نوع پسوند نسخه دارد (.v1) و consumerها فیلدهای ناشناخته را نادیده می‌گیرند. مسیرهای شکست: گام ۵ با کارت ردشده ReleaseStock می‌فرستد؛ شکست گام ۸ RefundPayment و ReleaseStock می‌فرستد. مالکیت تیمی: Sales صاحب saga است چون صاحب وعدهٔ مشتری است.

دادهٔ توزیع‌شده: replica، cache، چند-region ​

  • Replicaها. relay و timer ی saga جدول‌های outbox و saga را از primary می‌خوانند؛ replica ی عقب‌مانده ردیف‌های ارسال‌نشده یا deadline های تازه را پنهان می‌کند (Replication & Failover). read modelهایی که از replica سرو می‌شوند طبق طراحی کهنه‌اند؛ as of را نشان دهید.
  • Cacheها. cache جلوی aggregate ی Order ممکن است بعد از تأیید saga هنوز pending نشان دهد؛ TTL کوتاه بگذارید یا با رویداد OrderConfirmed باطل کنید، و هرگز قاعدهٔ کسب‌وکاری را از cache تصمیم نگیرید.
  • دیتابیس‌های shard شده. id ی aggregate را کلید shard بگیرید تا aggregate و ردیف‌های outbox و inbox اش روی یک shard بمانند؛ آن‌وقت تراکنش محلی، محلی می‌ماند (Sharding).
  • چند-region. message id باید سراسری یکتا باشد؛ inbox باید در regionی باشد که اثر را اعمال می‌کند؛ failover ی region می‌تواند پیام‌ها را replay کند، پس retentionها باید failover را پوشش دهند. sagaهای میان‌region به deadline هایی بلندتر از تأخیر میان‌region به‌علاوهٔ lag ی broker نیاز دارند. مفاهیم: Consistency Models، Eventual Consistency in Databases، Distributed SQL & 2PC.

مسیر مقیاس (Scaling path): 1×، 10×، 100× ​

مقیاسانتشارمصرفSagaهاتغییر معمول
1× (صدها سفارش در روز)Outbox + یک relay ی polling (۲۰۰ms)inbox در هر سرویسردیف saga ی دست‌نویسکد Laravel یا Go ی این فصل
10× (ده‌ها سفارش در ثانیه)partial index، تنظیم اندازهٔ batch، relay برای هر partitionپاک‌سازی، partition per-key، consumer ی موازی با WithoutOverlapping برای هر keytimer با SKIP LOCKED، index ی sagaKafka یا RabbitMQ با quorum queue به‌جای صف دیتابیس
100× (هزاران در ثانیه)Log tailing (Debezium) از جدول outbox، outbox ی partition شدهجدول‌های inbox ی partition شده، نوشتن idempotent به‌صورت batchموتور workflow (Temporal، Step Functions)، saga ها shard شده با id ی سفارشتیم پلتفرم اختصاصی، schema registry، ابزار خودکار redrive و replay

آزمایشگاه: عمداً بشکنیدش ​

بخش Go آفلاین روی یک ماشین اجرا می‌شود (تک‌پردازه، بدون container). بخش Laravel به‌صورت دستور و خروجی مورد انتظار نوشته شده و اجرا نشده.

آماده‌سازی (اجرا شده).

bash
cd docs/snippets/ddd/designing-for-failure-reliable-messaging/go
go vet ./... && go test -count=1 -race ./...
# ok  academy/designing-for-failure-reliable-messaging/edge
# ok  academy/designing-for-failure-reliable-messaging/fulfilment
# ok  academy/designing-for-failure-reliable-messaging/inbox
# ok  academy/designing-for-failure-reliable-messaging/retry
# ok  academy/designing-for-failure-reliable-messaging/saga
# ok  academy/designing-for-failure-reliable-messaging/sim

گام ۱: ببینید broker ی تکرارکننده آسیبی نمی‌زند (اجرا شده).

bash
go run ./cmd/demo
text
== order o-1
  saga        <- sales.order.placed.v1              id=sales-000001   caused-by=
  saga        <- sales.order.placed.v1              id=sales-000001   caused-by=
  fulfilment  <- cmd.fulfilment.ReserveStock.v1     id=sales-000002   caused-by=sales-000001
  fulfilment  <- cmd.fulfilment.ReserveStock.v1     id=sales-000002   caused-by=sales-000001
  ...
  => order=confirmed saga=completed charges=1 stock=3 rounds=9 parked=0
== order o-2
  ...
  => order=cancelled saga=cancelled charges=0 stock=3 rounds=9 parked=0

هر پیام دو بار تحویل می‌شود؛ charges=1 و stock=3 ثابت می‌کند هر اثر یک بار اجرا شد. کارت سفارش o-2 رد شد: موجودی آزاد شد و پولی گرفته نشد.

گام ۲: inbox را جایی که مهم است بردارید (اجرا شده). در sim/world.go، در notify، عبارت inbox.Once(w.SalesDB, "notify", m, func(tx *store.Tx) error { را با w.SalesDB.Tx(func(tx *store.Tx) error { عوض کنید (و مقدار برگشتی بلااستفاده را بردارید) و go test -run TestHappyPath ./sim را اجرا کنید. خروجی (اجرا شده):

text
--- FAIL: TestHappyPathSurvivesDuplicatesAndReordering (0.00s)
    world_test.go:53: e-mails sent = 2, want 1: an additive effect needs the inbox

«یک ایمیل دیگر بفرست» طبیعتاً idempotent نیست، پس تحویل تکراری دو ایمیل می‌فرستد. حالا inbox را از billing، fulfilment و saga بردارید: تست‌ها باز هم می‌گذرند، چون آن handlerها با کلید idempotency ی کسب‌وکاری، رکورد رزرو و بررسی state ی saga هم محافظت می‌شوند. این دفاع در عمق است و دلیل نگه‌داشتن inbox در همه‌جا: نمی‌توانید هر handler آینده را از نظر idempotency طبیعی ممیزی کنید. برگردانید.

گام ۳: relay را بکشید (اجرا شده). TestRelayCrashAfterPublishIsHarmless relay را یک بار بعد از اولین publish و قبل از علامت‌زدن ردیف می‌کشد. hook را وادار کنید هر بار true بدهد (خطوط if crashed { return false } را حذف کنید) و اجرا کنید. خروجی (اجرا شده):

text
--- FAIL: TestRelayCrashAfterPublishIsHarmless (0.00s)
    world_test.go:144: order o-6: got {... Status:pending ...}, want status confirmed

relay ای که همیشه قبل از علامت‌زدن crash کند هرگز از ردیف اولش جلو نمی‌رود: سفارش pending می‌ماند. هشدار این وضعیت در production سن قدیمی‌ترین ردیف outbox ی ارسال‌نشده است. برگردانید.

گام ۴: Billing پایین، بعد برگشت (اجرا شده). TestBillingDownTimeoutThenLateReplies نشان می‌دهد: سفارش pending می‌ماند؛ بعد از ۳۱ ثانیهٔ زمان ساختگی saga.Tick saga را به compensating می‌برد؛ وقتی Billing برمی‌گردد charge ی صف‌شده و بعد refund را اجرا می‌کند؛ saga در cancelled تمام می‌شود، موجودی به ۵ برمی‌گردد و refund دوم نیست (PaymentCharged ی دیررس نادیده گرفته می‌شود چون refund در جریان است).

گام ۵: poison (اجرا شده). TestPoisonMessageIsParkedNotSwallowed یک فرمان ناشناخته و یک payload خراب منتشر می‌کند. انتظار: DLQ.Depth() == 2، هرکدام با Attempts == 1 (خطای دائمی retry نمی‌شود)، و سفارش مشروع o-10 هنوز تأیید می‌شود.

گام ۶: Laravel (مورد انتظار، اجرا نشده).

bash
php artisan migrate
php artisan test --filter='InboxTest|OutboxAtomicityTest|RelayOutboxTest|BillingIdempotencyTest|OrderSagaTest|ParkPoisonTest'
# PASS  Tests\Unit\OrderSagaTest
# PASS  Tests\Feature\InboxTest
# PASS  Tests\Feature\OutboxAtomicityTest
# PASS  Tests\Feature\RelayOutboxTest
# PASS  Tests\Feature\BillingIdempotencyTest
# PASS  Tests\Feature\ParkPoisonTest
php artisan outbox:relay --once      # publishes unsent rows, exits
php artisan saga:tick                # expired sagas handled: 0
php artisan queue:work --queue=default

گام ۷: تنظیم. StepTimeout را در sim.NewWorld روی 5 * time.Second بگذارید و TestBillingDown... را با پیش‌روی ۶ ثانیه دوباره اجرا کنید. بحث: هزینهٔ timeout ی خیلی کوتاه چیست؟ (لغو سفارش‌هایی که charge شان موفق می‌شد؛ PaymentCharged ی دیررس آن‌وقت به refund نیاز دارد.)

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

باورواقعیت
exactly-once ی broker نیاز به consumer ی idempotent را برمی‌دارددرون مرز broker برقرار است؛ نوشتن دیتابیس شما بیرون آن است
retry سیستم را مطمئن‌تر می‌کندretry هنگام قطعی بار را ضرب می‌کند؛ backoff، jitter، سقف و بودجه می‌خواهد
saga یعنی rollback توزیع‌شدهsaga عملیات جبرانی کسب‌وکاری اجرا می‌کند؛ دیده می‌شوند و ممکن است ناقص باشند
choreography همیشه ساده‌تر استبرای دو یا سه گام ساده است و بعد از آن مبهم
timestamp رویدادها را ترتیب می‌دهدساعت‌ها اختلاف دارند؛ version ی aggregate یا sequence
dispatch با afterCommit همان outbox استjob می‌تواند میان commit و push گم شود؛ ردیف outbox پایدار است
اول commit بعد publish تقریباً اتمیک استcrash میان دو خط رویداد را گم می‌کند
ShouldBeUnique handler را idempotent می‌کندورودی تکراری صف را با قفل cache حذف می‌کند؛ پردازش هنوز می‌تواند تکرار شود
DLQ جایی است که پیام‌ها می‌میرندصف کار برای آدم‌هاست؛ روی عمقش alert بگذارید و redrive کنید
fallback ما را امن نگه می‌داردfallback ی تست‌نشده سیستم دومی است که هنگام قطعی شکست می‌خورد
UI می‌تواند سازگاری نهایی را پنهان کندpending و failed وضعیت‌های محصولی‌اند که کاربر می‌بیند
two-phase commit درون یک شرکت اشکالی ندارددسترس‌پذیری و قفل را میان سرویس‌ها جفت می‌کند و از هر شرکت‌کننده پشتیبانی می‌خواهد

چکیده ​

موضوعچه چیز را یادتان بماند
مدل شکستپایین، کند، بی‌معنی، تکرار، جابه‌جا، گم، جزئی، اختلاف ساعت
واحد کاریک aggregate + یک ردیف outbox (یا ردیف inbox + اثر) در هر تراکنش محلی
تحویلat-least-once را فرض کن؛ exactly-once ویژگی ی محلی در یک مرز است
Outboxهمان تراکنش؛ relay اول publish بعد علامت؛ تکرار ممکن است
Relayبرای ترتیب یک relay برای هر outbox؛ polling ساده، log tailing سریع
Inbox(consumer, message_id) یکتا در تراکنش اثر
کلید dedupmessage id ای که تولیدکننده می‌دهد، هرگز offset ی broker
ترتیبpartition با id ی aggregate؛ version را بررسی کن؛ handlerها را جابه‌جاپذیر کن
Retrybackoff نمایی با سقف و full jitter؛ حد و بودجه
Poisonخطای دائمی یعنی با دلیل park، روی عمق alert، بعد از رفع redrive
Sagaتراکنش محلی + compensation + deadline؛ state یک aggregate است
Compensationیک فرمان دامنه؛ idempotent؛ جابه‌جاپذیر با گام پیشرو (tombstone)
پاسخ دیررسدوباره خنثی کن؛ هرگز از state ی پایانی عقب نرو
محصولpending و failed وضعیت واقعی با کلمه، timer و عمل‌اند
حالت degradedطراحی‌شده، با برچسب، تمرین‌شده؛ هرگز داده نساز
لبهٔ APIIdempotency-Key همراه نتیجه ذخیره شود؛ 202 با وضعیت pending
تستتکرار، جابه‌جایی، گم‌شدن، crash و همسایهٔ مرده را تزریق کن؛ نتیجهٔ کسب‌وکاری را assert کن
Observabilitycorrelation و causation id؛ سن outbox، lag، عمق DLQ، سن saga

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

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

۱ — هشت شکستی را که context باید فرض کند فهرست کنید و برای هرکدام یک دفاع بگویید. مهم ​

پاسخ

پاسخ: همسایه پایین (timeout، پیام ناهمگام)، کند (deadline، breaker)، بی‌معنی (اعتبارسنجی، ACL، DLQ)، تکرار (inbox، کلید idempotency)، جابه‌جایی (partition per-key، version)، گم‌شدن (outbox، deadline، reconciliation)، شکست جزئی (saga با compensation)، اختلاف ساعت (version به‌جای timestamp). طبقه‌بندی را ببینید.

۲ — چرا crash میان COMMIT و broker.Publish را با try/catch نمی‌شود درست کرد؟ حیاتی ​

پاسخ

پاسخ: بعد از crash پردازه رفته است؛ چیزی برای catch نمانده. رویداد فقط در حافظه بود. outbox وعده را به همان تراکنش state می‌برد تا relay ی دوباره‌راه‌افتاده هنوز پیدایش کند. انتشار مطمئن.

۳ — relay پیامی را منتشر کرد و قبل از علامت‌زدن crash کرد. چه می‌شود و چه کسی مدیریتش می‌کند؟ حیاتی ​

پاسخ

پاسخ: با restart همان message id دوباره منتشر می‌شود. inbox ی consumer به کلید یکتا می‌خورد و نسخهٔ دوم را رد می‌کند. relay می‌تواند تکرار کند؛ نباید گم کند. مصرف مطمئن.

۴ — چرا ردیف inbox و اثر کسب‌وکاری باید در یک تراکنش باشند؟ حیاتی ​

پاسخ

پاسخ: وگرنه crash میان آن‌ها یا اثری بدون رکورد می‌گذارد (تکرار دوباره اجرایش می‌کند) یا رکوردی بدون اثر (پیام برای همیشه رد می‌شود). یک تراکنش «ثبت‌شده» و «انجام‌شده» را یک واقعیت می‌کند.

۵ — چرا offset ی broker کلید dedup بدی است؟ مهم ​

پاسخ

پاسخ: با redelivery، replay و انتشار دوباره عوض می‌شود، پس تکرار همان پیام کسب‌وکاری جدید به نظر می‌رسد. از id ای استفاده کنید که تولیدکننده هنگام ساخت ردیف outbox می‌دهد.

۶ — تفاوت compensation و rollback چیست و چرا compensationها باید با گام پیشرویشان جابه‌جاپذیر باشند؟ تکمیلی ​

پاسخ

پاسخ: rollback تغییر commit نشده را پاک می‌کند؛ compensation عمل جدید commit‌شده‌ای است که عمل قبلی را از نظر معنایی خنثی می‌کند. چون پیام‌ها جابه‌جا می‌شوند، compensation ممکن است قبل از گام پیشرو برسد؛ tombstone گام دیررس را بی‌اثر می‌کند تا هر دو ترتیب به یک state برسند.

۷ — Billing جواب نمی‌دهد. saga چه می‌کند و اگر Billing بعد از لغو جواب بدهد چه می‌شود؟ مهم ​

پاسخ

پاسخ: در deadline saga به Compensating می‌رود و فرمان‌های امن و idempotent می‌فرستد (آزادسازی موجودی، refund). PaymentCharged ی دیررس saga را در Compensating یا Cancelled می‌یابد؛ جلو نمی‌رود و فقط اگر refund ی در جریان نباشد refund می‌فرستد. Sagaها.

۸ — کی choreography کافی است و کی orchestrate می‌کنید؟ حیاتی ​

پاسخ

پاسخ: choreography برای دو یا سه گام، جریان پایدار و یک تیم. با چهار گام یا بیشتر، انشعاب، compensation، deadline یا چند تیم، orchestrator یک جا برای state و timer می‌دهد.

۹ — پیام poison می‌رسد. سه واکنش غلط و واکنش درست را بگویید. حیاتی ​

پاسخ

پاسخ: غلط: retry ی بی‌پایان (صف را قفل می‌کند)، catch-log-ack (رویداد ناپدید می‌شود)، کرش‌دادن مکرر consumer. درست: دائمی دسته‌بندی کن، با دلیل و تعداد تلاش park کن، روی عمق DLQ alert بگذار، رفع کن، redrive. Retry.

۱۰ — چرا «Sales تا وقتی Billing پایین است خطا برمی‌گرداند» تصمیم محصول است؟ مهم ​

پاسخ

پاسخ: گزینهٔ فنی هست (pending بپذیر، بعداً شارژ کن)، اما آنچه مشتری می‌بیند و هزینهٔ شکست‌های بعدی (لغوهای دیررس) را عوض می‌کند. فقط کسب‌وکار می‌تواند سفارش از دست‌رفته را با شکست دیررس بسنجد. سازگاری نهایی به‌عنوان تصمیم محصول.

۱۱ — timeout و circuit breaker در یک context ی DDD کجا زندگی می‌کنند؟ حیاتی ​

پاسخ

پاسخ: در لایهٔ application و adapterهای زیرساخت در لبهٔ context، هرگز در مدل دامنه. deadline ی خود saga state ی دامنه است چون وعدهٔ کسب‌وکاری را بیان می‌کند. لبهٔ context.

واژه‌نامه ​

واژهمعنا
طراحی برای شکست (Design for failure)شکست هر فراخوانی سرویس را حالت عادی فرض کردن (Fowler و Lewis)
طبقه‌بندی شکست (Failure taxonomy)فهرست رفتارهای همسایه که طراحی باید تحمل کند
جزیرهٔ سازگاری (Consistency island)aggregate (و دیتابیسش) که درونش invariantها در هر commit برقرارند
واحد کار (Unit of work)یک aggregate به‌علاوهٔ یک ردیف outbox یا inbox در یک تراکنش محلی
Entity ی Hellandمجموعهٔ دادهٔ دارای کلید یکتا روی یک ماشین؛ دامنهٔ serializability
Activityوضعیت per-partner که entity نگه می‌دارد، از جمله id ی پیام‌های پردازش‌شده
At-most-onceیک بار می‌فرستد، retry نه؛ گم‌شدن ممکن
At-least-onceتا ack بگیرد retry؛ تکرار ممکن
Effectively-onceتحویل at-least-once به‌علاوهٔ اثر idempotent
مسئلهٔ دو ژنرال (Two generals problem)ناممکن بودن قطعیت روی پیوند نامطمئن؛ چرا ack ی غایب مبهم است
Transactional outboxردیف پیام که در تراکنش aggregate نوشته و بعداً منتشر می‌شود
Relayپردازه‌ای که ردیف‌های outbox را به broker می‌برد
Polling publisherrelay ی که دوره‌ای جدول outbox را query می‌کند
Transaction log tailingrelay ی که log دیتابیس را می‌خواند (CDC، Debezium)
Inboxجدول id ی پیام‌های پردازش‌شده با کلید یکتا، نوشته‌شده با اثر
Idempotent consumerconsumer ی که پردازش تکراری یک پیام اثر اضافه ندارد
کلید Idempotencyکلید یکتایی که کلاینت یا فراخواننده می‌دهد و فرمان را برای retry امن می‌کند
کلید Dedupشناسه‌ای که برای تشخیص تکرار به کار می‌رود
Idempotency طبیعیاثری که set است نه increment
Handler جابه‌جاپذیر (Commutative)handler ی که state نهایی‌اش به ترتیب پیام‌ها بستگی ندارد
Tombstoneرکوردی که چیزی را «از قبل خنثی/لغوشده» علامت می‌زند تا رسیدن دیررس رد شود
Version / seqversion ی aggregate در پیام برای ترتیب و تشخیص gap
Gapversion ی گمشده میان آنچه ذخیره شده و آنچه رسیده
پیام Poisonپیامی که هرگز نمی‌تواند با موفقیت پردازش شود
DLQ / parking lotصف یا جدول برای پیام‌های کنارگذاشته با دلیل
Redriveانتشار دوبارهٔ پیام‌های park شده بعد از رفع
Backoffمکث فزایندهٔ میان retryها
Full jitterانتظار تصادفی میان صفر و سقف فعلی backoff
بودجهٔ Retryسقف تعداد retry در بازهٔ زمانی در سراسر یک پردازه
انتشار Deadlineیک deadline ی مطلق مشترک برای کل درخت فراخوانی
Circuit breakerمحافظی که بعد از شکست‌های مکرر وابستگی سریع شکست می‌دهد
Bulkheadایزوله‌کردن منابع به‌ازای وابستگی تا یکی بقیه را گرسنه نکند
Sagaدنبالهٔ هماهنگ‌شدهٔ تراکنش‌های محلی با compensation
Choreographyهماهنگی saga با event میان سرویس‌ها
Orchestrationهماهنگی saga با شیء مرکزی که فرمان می‌فرستد
Process managerنام قدیمی‌تر DDD برای orchestrator ی stateful
تراکنش جبرانی (Compensating transaction)عمل کسب‌وکاری که عمل commit‌شدهٔ قبلی را از نظر معنایی خنثی می‌کند
پاسخ دیررس (Late reply)پاسخی که بعد از انصراف saga از آن گام می‌رسد
مدل وضعیت (Status model)وضعیت‌های قابل‌دیدن برای مشتری در یک aggregate هنگام فرایند ناهمگام
حالت Degradedکاهش طراحی‌شدهٔ عملکرد هنگام شکست وابستگی
Read modelکپی محلی، تغذیه‌شده با event و در نهایت سازگار از داده‌ی context دیگر
Correlation idid ی مشترک همهٔ پیام‌های یک جریان کسب‌وکاری
Causation idid ی پیامی که مستقیماً این پیام را ایجاد کرد
Consumer lagمیزان عقب‌ماندن consumer از سر صف
Consumer contract testتست اینکه پیام تولیدکننده هنوز انتظارات consumer را برآورده می‌کند
تزریق شکست (Failure injection)عمداً وادار کردن محیط تست به تکرار، تأخیر، حذف یا crash
Dual writeنوشتن در دیتابیس و broker به‌صورت دو گام مستقل
Two-phase commit (2PC)پروتکل commit ی اتمیک میان شرکت‌کننده‌ها با قفل‌هایی که هنگام انتظار نگه داشته می‌شوند
ShouldBeUniqueinterface ی Laravel که با قفل cache از صف‌شدن دوبارهٔ همان job جلوگیری می‌کند
ThrottlesExceptionsmiddleware ی job در Laravel که بعد از استثناهای پیاپی job را متوقف می‌کند
failed_jobsجدول Laravel برای jobهایی که تلاش‌هایشان تمام شد

منابع ​

  • Martin Fowler و James Lewis، Microservices، ۲۵ مارس ۲۰۱۴: «Design for failure»، مدیریت غیرمتمرکز داده و compensating operations. ذخیره: sources/designing-for-failure-reliable-messaging/fowler-microservices.txt.
  • Martin Fowler، CircuitBreaker، ۶ مارس ۲۰۱۴ (طبق چاپ صفحه): رفتار trip و اشاره به Release It! ی Nygard. ذخیره: fowler-cb.txt.
  • Pat Helland، Life beyond Distributed Transactions: an Apostate's Opinion، CIDR 2007: entity، "Atomic Transactions Cannot Span Entities"، پیام‌رسانی at-least-once، activity، idempotence. ذخیره: helland-cidr.txt.
  • Chris Richardson، microservices.io: Saga، Transactional outbox، Idempotent Consumer، Polling publisher، Transaction log tailing. ذخیره: msio-*.txt.
  • AWS Builders' Library، Timeouts, retries, and backoff with jitter و Avoiding fallback in distributed systems، هر دو ۵ دسامبر ۲۰۱۹. ذخیره: aws-retries.txt، aws-fallback.txt.
  • Google SRE book، Addressing Cascading Failures: بازخورد مثبت، retry، انتشار deadline، بودجهٔ retry. ذخیره: sre-cascading.txt.
  • Laravel 13، Queues: ShouldBeUnique، UniqueFor، Tries، Backoff، MaxExceptions، Timeout، WithoutOverlapping، ThrottlesExceptions، RateLimited، dontRetry، failed()، queue:failed، queue:retry، queue:prune-failed، batchها. ذخیره: laravel-queues.txt (صفحهٔ رندرشده، ناقص) و laravel-queues-13x.md (منبع خام مستندات 13.x، کامل؛ برای تأیید failed(?Throwable $exception)، queue:failed و queue:prune-failed).
  • Eric Evans، Domain-Driven Design Reference (2015)، جملهٔ "Within an aggregate boundary, apply consistency rules synchronously. Across boundaries, handle updates asynchronously." ذخیره: evans-ddd-reference.normalized.txt (کپی از منابع فصل همسایه).
  • مستندات Watermill، watermill.io/docs: Forwarder (the outbox pattern)، SQL Pub/Sub، middleware ی router، requeuing after error (فقط صفحهٔ فهرست). ذخیره: watermill.txt.
  • Martin Kleppmann، Designing Data-Intensive Applications (سایت خوانده شد؛ فصل‌های ۱۱ و ۱۲ دربارهٔ stream processing و آیندهٔ سیستم‌های داده گرفته نشد، پس هیچ ادعایی این‌جا از آن‌ها نقل نشده).
  • نخوانده‌ام: Garcia-Molina و Salem، Sagas (SIGMOD 1987؛ PDF آزاد لایهٔ متن ندارد)؛ Helland، Idempotence Is Not a Medical Condition (ACM Queue 2012؛ برای کلاینت خودکار مسدود است)؛ Nygard، Release It! و Newman، Building Microservices (کتاب؛ گزیدهٔ عمومی نخواندم). آنچه به آن‌ها نسبت داده شده بر منابع ثانویهٔ بالا تکیه دارد و برچسب خورده است.
  • همسایه‌ها: Aggregates & Factories، Domain Events vs Integration Events، Context Maps & Integration Patterns، Data Patterns، API Realization، Service Communication، Data Ownership، Error Handling & Fault Tolerance، Data Persistence in Design، Outbox، Saga، DLQ، Idempotent Consumers.

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