Saga Pattern
"Compensating transactions might not always succeed" — Microsoft، Saga distributed transactions pattern
خلاصه: ساگا (Saga) چند تراکنش محلیِ commitشده را در مرزهایی هماهنگ میکند که یک تراکنش اتمی مشترک ندارند؛ جبران، بخشی از قرارداد کسبوکار است. تمرکز: هماهنگسازی مرکزی و واکنش رویدادی، وضعیت پایدار، جبران، timeout مبهم، نقطهٔ تعهد، کنترل ناهنجاریهای همزمانی و انتقال فرمان و پاسخ روی brokerها. هدف یادگیری: گردش سفارش را در برابر تکرار پیام و مرگ worker مقاوم کنید، فرق refund با rollback را توضیح دهید و تشخیص دهید کجا Saga مرز سازگاری مناسبی نیست.
این فصل مالک سازوکار ساگا است. انتشار قابل اتکا در Transactional Outbox، حذف اثر تکراری در Idempotent Consumer، زمانبندی retry در Retry & Backoff و موتورهای گردش کار در Durable Workflows قرار دارند. نگاه DDD را در طراحی برای شکست ببینید؛ ساگا چند سرویس را به یک aggregate تبدیل نمیکند.
نقشهٔ صفحه
| دنبال چه هستید؟ | بخش |
|---|---|
| تعهد الگو و نام وضعیتها | یک دقیقه |
| چرا تراکنش محلی کافی نیست | چرایی |
| ریشهٔ دیتابیسی و کاربرد سرویسها | پیشینه |
| commit محلی، جبران و هماهنگی | مفهومها |
| پاسخ گمشده و مرز بازگشتناپذیری | Timeout، Pivot |
| ناهنجاریها و شش راهکار مقابله | Countermeasures |
| وضعیت، تاریخچه، قفل و خطا | سازوکار |
| نجات عملیات گیرکرده | راهحلها |
| نمونههای Go و Laravel | Go، Laravel |
| مرز تضمین انتقال | تفاوت brokerها |
| انتخاب طراحی و رشد آن | انتخاب، معماری |
| آزمایش شکستها | آزمایشگاه |
| مرور و اصطلاحات | بدفهمیها، خودآزمایی، واژهنامه |
همهچیز در یک دقیقه
| اصطلاح | معنای ساده | مثال سفارش |
|---|---|---|
| تراکنش محلی (Local transaction) | هر مشارکتکننده invariant خودش را commit میکند | رزرو مقدار مشخص از کالا |
| ساگا (Saga) | پیشرفت پایدار میان چند commit | رزرو، پرداخت، ارسال |
| جبران (Compensation) | اقدام جدیدی اثر قبلی را اصلاح میکند | آزادکردن رزرو یا refund |
| هماهنگسازی مرکزی (Orchestration) | یک تصمیمگیر فرمان بعدی را انتخاب میکند | ارسال ReserveStock توسط ساگای سفارش |
| هماهنگی رویدادی (Choreography) | مشارکتکننده به یک واقعیت واکنش دارد | واکنش انبار به OrderPlaced |
| نقطهٔ تعهد (Pivot) | مرزی که پس از آن بازیابی رو به جلو است | پرداخت تأییدشده ما را متعهد به fulfilment میکند |
| قفل معنایی (Semantic lock) | وضعیت کسبوکار جلوی تغییر ناسازگار را میگیرد | سفارش PENDING مثل APPROVED لغو نمیشود |
| گیرکرده (Stuck) | بودجهٔ بازیابی خودکار تمام شده | refund نیازمند تطبیق توسط اپراتور است |
| وضعیت | کار مجاز | خروج |
|---|---|---|
running | اجرای گام جاری یا retry آن | گام بعد، جبران، completed یا stuck |
compensating | اجرای undo جاری یا retry آن | undo قبلی، compensated یا stuck |
completed | اجرای خودکار گام متوقف است | فقط گردش کسبوکار جدید و صریح |
compensated | اجرای forward متوقف است | تلاش جدید با saga id جدید |
stuck | بررسی؛ حذف خاموش ممنوع | فرمان بازیابی ثبتشده پس از تطبیق |
وضعیت ذخیرهشده مرجع تصمیم است. خالیشدن صف، HTTP 200، publisher confirm و کاملشدن ساگا چهار مشاهدهٔ متفاوتاند.
چرا ساگا لازم میشود؟
دیتابیس سفارش نمیتواند charge ثبتشده نزد درگاه پرداخت را rollback کند. باز نگهداشتن تراکنش SQL هنگام انتظار برای درگاه، فقط قفلهای محلی را طولانیتر نگه میدارد؛ درگاه عضو آن تراکنش نمیشود. ساگا وضعیتهای میانی کسبوکار را میپذیرد و روش رسیدن از آنها به نتیجهٔ معتبر را ثبت میکند.
| یک تراکنش محلی ACID | ساگا میان تراکنشهای محلی |
|---|---|
| commit دیتابیس مرز اتمی است | هر مشارکتکننده commit مستقل دارد |
| rollback تغییر محلیِ commitنشده را برمیدارد | جبران اثر قبلاً قابل مشاهده را اصلاح میکند |
| جداسازی دیتابیس داخل همان مرز برقرار است | راهکار کسبوکار invariant میان گامها را نگه میدارد |
| قفل معمولاً کوتاه است | پیشرفت پایدار ممکن است ساعتها یا روزها بماند |
| برای دادهٔ زیر یک مالک سادهتر است | وقتی مالکیت یا API خارجی مانع تراکنش مشترک است کاربرد دارد |
تصویر روزمره: آژانس سفر بلیت، هتل و خودرو رزرو میکند. اگر خودرو پیدا نشود، لغو بلیت یک عملیات تازه و شاید مشمول جریمه است. ایمیل تأیید و رزرو مسافر دیگری پاک نمیشود. آژانس شناسههای رزرو را نگه میدارد تا فردا هم بتواند بازیابی را ادامه دهد.
سه تصور را از ابتدا کنار بگذارید: جبران همان rollback نیست؛ orchestrator قفل توزیعشدهٔ دیتابیس نیست؛ و انتقال ناهمگام نیاز به ذخیرهٔ deadline و outcome را حذف نمیکند.
از کجا آمده است؟
Hector Garcia-Molina و Kenneth Salem در مقالهٔ Sagas سال ۱۹۸۷، تراکنش بلندعمر (Long-lived transaction) را به تراکنشهای کوچکتری شکستند که با کارهای دیگر درهمتنیده اجرا شوند. هر گام با جبران معنایی و اطلاعات بازیابی همراه میشد. مسئله پیش از microservices وجود داشت: نگهداشتن منابع برای یک تراکنش طولانی هزینه داشت.
در معماری سرویسها همین ایده به دیتابیسهای مستقل و سیستمهای خارجی میرسد. Richardson دو شیوهٔ choreography و orchestration را تفکیک میکند؛ الگوی Process Manager در EIP نقش مسیریابیِ تصمیمگیرِ دارای وضعیت را توضیح میدهد. وقتی آن فرایند مسئول سازگاری و جبران است، میتواند هماهنگکنندهٔ ساگا باشد. هر workflow جبران لازم ندارد و هر همکاری رویدادمحور ساگا نیست.
فهرست مفهومها
commit محلی و مرز ساگا حیاتی
به زبان ساده: هر سرویس یک کار کوچک را تمام میکند، اما عملیات کلی کسبوکار هنوز ناتمام است.
بدفهمی رایج: «همهٔ سرویسها transaction دارند، پس checkout اتمی است.» آنها تراکنشهای متفاوت و معمولاً دیتابیسهای متفاوتاند.
تعریف: ساگا دنبالهای هماهنگ از تراکنشهای محلی (Local transactions) است که اجرای جزئی آن با کار رو به جلو یا تراکنش جبرانی (Compensating transaction) بازیابی میشود. invariant کسبوکار مشخص میکند کدام وضعیت میانی و نهایی پذیرفتنی است.
1 Orders: INSERT order PENDING + saga state -> local COMMIT
2 Inventory: reserve reservation S1 -> local COMMIT
3 Payments: charge S1 -> local COMMIT
4 Shipping: schedule S1 -> local COMMIT
5 Orders: mark APPROVED -> local COMMITسناریوهای واقعی: سفارش متصل به درگاه پرداخت، رزرو سفر میان چند تأمینکننده، onboarding با احراز هویت خارجی و فعالسازی اشتراک پولی. انتقال میان دو حساب زیر یک دیتابیس معمولاً به همان تراکنش محلی نیاز دارد.
| مرز | چه چیزی را محافظت میکند؟ | چه چیزی بیرون میماند؟ |
|---|---|---|
| تراکنش PostgreSQL | وضعیت و outbox روی همان connection | charge خارجی |
| تراکنش Kafka | رکوردها و offset در محدودهٔ پشتیبانیشدهٔ Kafka | SQL انبار یا API بانک |
| publisher confirm در RabbitMQ | پذیرش broker با دوامِ تنظیمشده | موفقیت کسبوکار مشارکتکننده |
XACK در Redis Streams | حسابداری تحویل pending | اتمام کل ساگا |
راهحل: ابتدا مالکیت سرویس و invariant را روشن کنید. اثر محلی و رکورد dedup مشارکتکننده در یک تراکنش باشند. برای اتمیبودن وضعیت و قصد انتشار، outbox به کار ببرید؛ Store نمونهٔ Go همین مرز را نشان میدهد.
جبران یک عملیات کسبوکار است حیاتی
به زبان ساده: رزرو خودتان را آزاد کنید؛ تغییر دیگران در موجودی را پاک نکنید.
بدفهمی رایج: «جبران snapshot قبلی دیتابیس را برمیگرداند.» نوشتن available=10 پس از فعالیت سفارشهای دیگر، کار آنها را بازنویسی میکند.
تعریف: تراکنش جبرانی (Compensation) اثر commitشده را از نظر معنای کسبوکار اصلاح میکند. ممکن است جریمه یا رد حسابرسی داشته باشد، باید تکرارپذیر و همتوان باشد و خودش هم میتواند شکست بخورد. ترتیب معکوس سیاست نمونهٔ خطی ماست؛ وابستگیها ممکن است ترتیب دیگری بخواهند یا جبرانهای مستقل را موازی کنند.
1 S1 reserves 2 units: available 10 -> 8
2 S2 reserves 3 units: available 8 -> 5
3 S1 payment rejected
4 S1 releases reservation S1: available 5 -> 7
5 S1 must NOT restore available to 10سناریوها: آزادکردن کالا، لغو رزرو، refund و پسگرفتن دسترسی موقت. ایمیل را نمیتوان unsend کرد؛ اصلاحیه یک اقدام جدید است. کالای تحویلشده به شرکت حمل شاید به فرایند مرجوعی نیاز داشته باشد، نه endpoint سادهٔ undo.
| اثر رو به جلو | جبران | اطلاعات لازم برای آینده |
|---|---|---|
| رزرو انبار | آزادسازی همان رزرو | شناسه و SKU/مقدار تغییرناپذیر |
| دریافت پرداخت | refund یا void طبق سیاست ارائهدهنده | شناسهٔ عملیات، ارز و مبلغ |
| دسترسی موقت | ابطال دسترسی موقت | شناسهٔ مجوز و نسخهٔ سیاست |
| رزرو تأمینکننده | لغو رزرو | مرجع تأمینکننده و شرایط لغو |
راهحل: ورودی جبران را پیش از ازدسترفتن نگه دارید. کلیدهای پایدار و جدا مثل saga:step:do و saga:step:undo بسازید. تکرار undo نباید refund دوم تولید کند. شکست refund وضعیت بازیابی است، نه compensated.
هماهنگکنندهٔ پایدار حیاتی
به زبان ساده: یک جزء مالک تصمیم «گام بعدی چیست؟» است.
بدفهمی رایج: «هماهنگی مرکزی یعنی یک process و یک نقطهٔ شکست.» چند worker میتوانند از وضعیت پایدار مشترک استفاده کنند؛ گذارهای همزمان یک ساگا همچنان باید سری شوند.
تعریف: هماهنگکننده (Orchestrator) پاسخ و وضعیت ذخیرهشده را تفسیر میکند، فرمان بعدی را تصمیم میگیرد و اطلاعات بازیابی را ثبت میکند. منطق آن میتواند ماشین حالت خالص (Pure state machine) باشد؛ storage و transport adapter هستند.
1 Reply StockReserved arrives twice
2 Worker A locks saga S1, advances step, records ChargePayment
3 Worker B locks S1 after A commits
4 B sees the stock step is no longer current; duplicate has no effect
5 Relay sends ChargePayment; a crash can cause a repeated commandسناریوها: سفارش چندمشارکتکنندهای، onboarding با الزام حسابرسی یا جبرانی که به پیشوند دقیق گامهای اجراشده وابسته است.
| محصول | ابزار هماهنگی | مرز |
|---|---|---|
| PostgreSQL | ردیف ساگا، FOR UPDATE و تاریخچه | گذار یک ردیف، نه اثر remote |
| RabbitMQ | صف پایدار فرمان و پاسخ | ماشین حالت کسبوکار را نگه نمیدارد |
| Kafka | فرمان و پاسخ keyed | ترتیب داخل topic partition است |
| Redis Streams | stream فرمان/پاسخ و consumer group | PEL جدول وضعیت ساگا نیست |
راهحل: گذار وضعیت و فرمان خروجی را اتمی ثبت کنید، یا deadline پایداری داشته باشید که ارسال گمشده را بازیابی کند. Go از outbox استفاده میکند؛ نمونهٔ پیاممحور Laravel بازیابی با deadline و پنجرهٔ انتشارش را صریح نشان میدهد.
هماهنگی رویدادی و قراردادها مهم
به زبان ساده: هر مشارکتکننده به یک واقعیت واکنش میدهد و نتیجهٔ خودش را اعلام میکند.
بدفهمی رایج: «بدون orchestrator دیگر coupling نداریم.» وابستگی به معنای رویداد، ترتیب و سیاست جبران باقی است؛ فقط کشف گردش کار دشوارتر میشود.
تعریف: در هماهنگی رویدادی (Choreography)، تصمیم گذار میان مشارکتکنندهها پخش است. تراکنش محلی رویدادی تولید میکند که کار مشارکتکنندهٔ بعدی را فعال میکند؛ رویداد شکست هم بازیابی را راه میاندازد. وضعیت پایدار و انتشار قابل اتکا همچنان ضروریاند.
1 Orders publishes OrderPlaced
2 Inventory reserves stock -> StockReserved
3 Payments declines charge -> PaymentDeclined
4 Inventory releases reservation; Orders rejects PENDING order
5 A status projection correlates all facts by order/saga idسناریوها: جریان کوتاه سفارش با قرارداد ثابت، فعالسازی اشتراک توسط تیمهای مستقل و اعلانهایی که واقعاً پیامد یک واقعیت دامنهاند. دهها subscription چرخهای و وابستگی پنهان، نشانهٔ بازنگری در مدل هماهنگی است.
| پرسش | Choreography | Orchestration |
|---|---|---|
| چه کسی گام بعد را انتخاب میکند؟ | handlerهای رویداد | تعریف coordinator |
| پیشرفت کجا دیده میشود؟ | وضعیت مشارکتکننده و projection همبسته | ردیف ساگا و step log |
| تغییر ترتیب با کیست؟ | چند قرارداد/handler | coordinator و قرارداد مشارکتکنندهٔ درگیر |
| ریسک معمول | چرخه، گردش ضمنی و مالک نامشخص بازیابی | coordinator حجیم و انتقال منطق دامنه به آن |
راهحل: جریان رویداد را مستند کنید، برای هر بازیابی مالک بگذارید و نتیجه را قابل اتکا منتشر کنید. bus حافظهای Go و listenerهای Laravel طرح آموزشیاند؛ استقرار میان سرویسها به مرزهای outbox/inbox لینکشده نیاز دارد.
مهلت، ابهام و فرمان دیررس حیاتی
به زبان ساده: نبود پاسخ نمیگوید پول جابهجا شده یا نشده است.
بدفهمی رایج: «Timeout همان رد پرداخت است.» پاسخ رد قطعی میتواند تضمین کند اثر commit نشده؛ timeout فقط نبود نتیجهٔ تأییدشده را میگوید.
تعریف: نتیجهٔ مبهم (Ambiguous outcome) زمانی است که اثر شاید commit شده اما پاسخ نداریم. میتوان از مشارکتکننده استعلام گرفت، با همان کلید عملیات retry کرد یا وقتی قرارداد لغو اجازه میدهد، خود گام ساکت را هم جبران کرد.
1 Payments commits charge S1
2 Reply is lost
3 Coordinator deadline expires; same charge key is retried
4 Retry budget expires; coordinator requests undo for charge S1 too
5 Refund arrives before a delayed duplicate charge: cancellation tombstone rejects late doسناریوها: timeout پس از charge موفق، مرگ worker بعد از commit، پاسخ گمشده در failover و مسابقهٔ لغو با فرمان دیررس.
| مشاهده | تفسیر | اقدام بعد |
|---|---|---|
| رد قطعی کسبوکار | مشارکتکننده نبود commit رو به جلو را تضمین میکند | جبران گامهای قبلی |
| timeout انتقال | نتیجه نامعلوم است | استعلام یا retry همان کلید؛ رد ساختگی نسازید |
| انقضای گام جبرانپذیر | خود گام ساکت شاید commit شده | آن را در برنامهٔ جبران امن بگنجانید |
| انقضا پس از pivot | سیاست بازگشت را ممنوع کرده | forward retry یا توقف برای تطبیق |
| پاسخ تکراری/دیررس | شاید متعلق به گذار قدیمی باشد | بررسی saga id، step و action |
راهحل: جاروبگر پایدار (Sweeper) deadline را زیر قفل ردیف دوباره بررسی کند. زمان ذخیره و پرسوجوی انقضا باید از یک ساعت مرجع بیاید. TTL broker میتواند پیام را حذف کند، اما اثر commitشده را لغو نمیکند. نشان لغو (Tombstone) را بهاندازهٔ بازهٔ replay و retry حفظ کنید.
نقطهٔ تعهد و جهت بازیابی مهم
به زبان ساده: مشخص کنید کسبوکار از کجا متعهد به تمامکردن کار میشود.
بدفهمی رایج: «هر خطا باید همهٔ compensationها را اجرا کند.» refund بعد از ارسال برگشتناپذیر ممکن است سفارش رایگان بسازد.
تعریف: گام جبرانپذیر (Compensable) بازیابی رو به عقب دارد. نقطهٔ تعهد (Pivot) مرزی است که پس از آن گامها با بازیابی رو به جلو (Forward recovery) تکمیل میشوند. Microsoft بسته به فرایند، pivot را آخرین گام جبرانپذیر یا اولین عملیات retryable میداند. Retryable یک سیاست بازیابی است، نه وعدهٔ بیخطابودن زیرساخت.
1 Reserve stock compensable
2 Charge payment succeeds this example's business pivot
3 Schedule shipment fails retry forward with same key
4 Retry budget exhausted STUCK; operator reconciles shipment
5 Do not automatically refund merely because step 3 is unavailableسناریوها: پرداخت تأییدشدهای که تعهد ارسال میآورد، صدور نهایی بلیت و تأییدی که provisioning بعدی را الزامی میکند. pivot را با مالک کسبوکار انتخاب کنید؛ سیاست authorization/capture پرداخت میتواند طراحی را عوض کند.
| گام نمونه | پیش از موفقیت تأییدشده | پس از موفقیت تأییدشده |
|---|---|---|
| رزرو کالا | رد یا retry | آزادسازی ممکن است |
| charge | نتیجهٔ مبهم شاید لغو/refund بخواهد | سیاست به forward recovery میرود |
| برنامهریزی ارسال | retry یا repair | ساگا کامل میشود |
راهحل: نمونهٔ ما charge تأییدنشده هنگام لغو را refund میکند و charge دیررس پس از لغو را رد میکند. این نیازمند قرارداد مشارکتکنندهٔ پرداخت است. اگر provider چنین قراردادی ندارد، کار را park و استعلام کنید؛ undo-before-do را بیدلیل امن فرض نکنید.
ناهنجاریهای جداسازی و راهکارها حیاتی
به زبان ساده: عملیات دیگر میتوانند نتیجهٔ جزئی ساگا را ببینند و تغییر دهند.
بدفهمی رایج: «SERIALIZABLE در همهٔ سرویسها ساگا را serializable میکند.» آن سطح فقط تراکنش محلی را پوشش میدهد؛ میان گامها مرز آزاد شده است.
تعریف: بهروزرسانی گمشده (Lost update)، خواندن کثیف (Dirty read) و خواندن تکرارناپذیر (Nonrepeatable read) در سطح ساگا، مربوط به درهمتنیدگی وضعیتهای محلیِ commitشدهاند. دادهٔ provisional کسبوکار ممکن است در SQL کاملاً commit شده باشد؛ این همان dirty read دیتابیسی نیست.
1 S1 creates order APPROVAL_PENDING
2 S2 attempts cancel-as-approved while S1 is charging
3 Conditional UPDATE refuses S2: state is not APPROVED
4 S1 completes -> APPROVED, or compensates -> REJECTED
5 S2 re-reads and applies its own valid transitionسناریوها: رقابت برای آخرین کالا، لغو هنگام پرداخت، تغییر قیمت میان quote و charge و رسیدن release پیش از reserve.
| راهکار مقابله (Countermeasure) | سازوکار | هزینه / محدودیت |
|---|---|---|
| قفل معنایی (Semantic lock) | وضعیت PENDING گذار ناسازگار را میبندد | تا بازیابی ممکن است بماند؛ همهٔ writerها باید رعایت کنند |
| تغییر جابجاپذیر (Commutative updates) | delta بهجای بازگرداندن snapshot | پذیرش تحت محدودیت موجودی هنوز به ترتیب وابسته است |
| دید بدبینانه (Pessimistic view) | تغییر پرریسکِ قابل مشاهده به پس از pivot منتقل میشود | UX یا ترتیب کسبوکار عوض میشود |
| بازخوانی مقدار (Reread values) | نسخه پیش از نوشتن بعدی بررسی میشود | تعارض نیازمند تصمیم retry یا جبران است |
| پروندهٔ نسخهها (Version file) | تاریخچهٔ عملیات و ترتیب قانونی حفظ میشود | نگهداری تاریخچه و سریسازی هر entity |
| بر پایهٔ ارزش (By value) | برای ریسک بالا هماهنگی قویتر یا بررسی انسانی | مرز قویِ واقعاً قابل اجرا لازم است؛ فلگ جادویی 2PC نداریم |
راهحل: SQL شرطی قفل معنایی را اعمال میکند؛ نمونههای Go و Laravel عملیات یک رزرو را هم سری میکنند. گرفتن خطای PostgreSQL 23505 و commit همان تراکنش abortشده غلط است: از ON CONFLICT DO NOTHING یا rollback/retry استفاده کنید.
UPDATE orders SET status = 'CANCEL_PENDING', version = version + 1
WHERE id = 'o-1' AND status = 'APPROVED';
-- expected: 0 rows while APPROVAL_PENDING; caller re-reads instead of cancelling blindly.
SELECT pg_advisory_xact_lock(hashtextextended('reservation-S1', 0));
-- In a short local transaction: serialize reserve and release for the same reservation.// Package countermeasures maps Richardson's saga countermeasures to code in
// one participant (inventory) and in the order service, using pgx. Each
// function is one local transaction; none of them is a saga by itself.
package countermeasures
import (
"context"
"errors"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
const Schema = `
CREATE TABLE orders (
id text PRIMARY KEY,
status text NOT NULL, -- APPROVAL_PENDING | APPROVED | CANCEL_PENDING | ...
total bigint NOT NULL,
version int NOT NULL DEFAULT 0 -- for reread value
);
CREATE TABLE stock (
sku text PRIMARY KEY,
available int NOT NULL CHECK (available >= 0)
);
-- Version file: every operation on a reservation, in arrival order.
CREATE TABLE reservation_ops (
saga_id text NOT NULL,
op text NOT NULL, -- 'reserve' | 'release'
at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (saga_id, op)
);`
var (
ErrLocked = errors.New("record is held by another saga, retry later")
ErrNoStock = errors.New("not enough stock")
ErrStale = errors.New("record changed since the saga read it")
ErrLateDo = errors.New("already released: refusing a late reserve")
ErrNeedsHuman = errors.New("high value: route to the 2PC/manual path")
)
// SemanticLock: cancelling is allowed only from a final state. While a
// create-order saga runs, the order is APPROVAL_PENDING and cancel is refused.
func SemanticLock(ctx context.Context, db *pgxpool.Pool, orderID string) error {
tag, err := db.Exec(ctx,
`UPDATE orders SET status = 'CANCEL_PENDING', version = version + 1
WHERE id = $1 AND status = 'APPROVED'`, orderID)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return ErrLocked // still *_PENDING: the client retries later
}
return nil
}
// CommutativeReserve: "subtract 3" commutes with any other subtract or
// add arithmetically; admission under a stock constraint still depends on order.
// Conditional atomic SQL avoids the lost-update race of read-modify-write. The CHECK constraint is the business rule.
func CommutativeReserve(ctx context.Context, db *pgxpool.Pool, sku string, qty int) error {
if qty <= 0 {
return ErrNoStock
}
tag, err := db.Exec(ctx,
`UPDATE stock SET available = available - $2 WHERE sku = $1 AND available >= $2`,
sku, qty)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return ErrNoStock
}
return nil
}
// RereadValue: the saga carried the version it read in an earlier step;
// the update only applies if nobody changed the row since (compare-and-set).
func RereadValue(ctx context.Context, db *pgxpool.Pool, orderID string, readVersion int) error {
tag, err := db.Exec(ctx,
`UPDATE orders SET status = 'APPROVED', version = version + 1
WHERE id = $1 AND version = $2 AND status = 'APPROVAL_PENDING'`,
orderID, readVersion)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return ErrStale // stop this step; the orchestrator compensates or restarts
}
return nil
}
// VersionFile: record each operation; a release that arrives before its
// reserve (reordered or retried messages) is remembered, and the late
// reserve is refused instead of leaking stock forever.
func VersionFile(ctx context.Context, db *pgxpool.Pool, sagaID, op, sku string, qty int) error {
if (op != "reserve" && op != "release") || qty <= 0 {
return errors.New("invalid reservation operation")
}
return pgx.BeginFunc(ctx, db, func(tx pgx.Tx) error {
// Serialize BOTH operation kinds for this reservation, even before rows exist.
// Hash collisions only serialize unrelated reservations; they do not lose data.
if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1, 0))`, sagaID); err != nil {
return err
}
tag, err := tx.Exec(ctx, `INSERT INTO reservation_ops (saga_id,op) VALUES ($1,$2) ON CONFLICT DO NOTHING`, sagaID, op)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return nil
}
var other bool
if err := tx.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM reservation_ops WHERE saga_id=$1 AND op<>$2)`, sagaID, op).Scan(&other); err != nil {
return err
}
switch {
case op == "reserve" && other:
return ErrLateDo
case op == "release" && !other:
return nil
case op == "reserve":
tag, err = tx.Exec(ctx, `UPDATE stock SET available=available-$2 WHERE sku=$1 AND available >= $2`, sku, qty)
default:
tag, err = tx.Exec(ctx, `UPDATE stock SET available=available+$2 WHERE sku=$1`, sku, qty)
}
if err != nil {
return err
}
if tag.RowsAffected() != 1 {
return ErrNoStock
}
return nil
})
}
// ByValue: pick the mechanism by business risk. Low value goes through the
// saga; high value takes a path with stronger guarantees or a human.
func ByValue(totalCents int64) error {
if totalCents > 1_000_000 {
return ErrNeedsHuman
}
return nil
}<?php
namespace App\Sagas;
use Illuminate\Support\Facades\DB;
use RuntimeException;
final class Countermeasures
{
public static function cancel(string $orderId): void
{
if (DB::table('orders')->where('id',$orderId)->where('status','approved')->update(['status'=>'cancel_pending'])!==1) {
throw new RuntimeException('Semantic lock: order not ready to cancel');
}
}
public static function reread(string $orderId,int $version): void
{
if (DB::table('orders')->where('id',$orderId)->where('version',$version)->where('status','pending')
->update(['status'=>'approved','version'=>$version+1])!==1) { throw new RuntimeException('Version changed'); }
}
/** PostgreSQL; reservation_ops has PRIMARY KEY(saga_id,op). SKU/qty are immutable per reservation. */
public static function reservation(string $id,string $op,string $sku,int $qty): void
{
if (!in_array($op,['reserve','release'],true)||$qty<1) { throw new RuntimeException('Invalid operation'); }
DB::transaction(function () use ($id,$op,$sku,$qty) {
DB::select('SELECT pg_advisory_xact_lock(hashtextextended(?,0))',[$id]);
if (DB::table('reservation_ops')->insertOrIgnore(['saga_id'=>$id,'op'=>$op,'at'=>DB::raw('CURRENT_TIMESTAMP')])===0) { return; }
$other=DB::table('reservation_ops')->where('saga_id',$id)->where('op','!=',$op)->exists();
if ($op==='reserve' && $other) { throw new RuntimeException('Late reserve refused'); }
if ($op==='release' && !$other) { return; } // tombstone fences a late do
$q=DB::table('stock')->where('sku',$sku);
$n=$op==='reserve'?$q->where('available','>=',$qty)->decrement('available',$qty):$q->increment('available',$qty);
if ($n!==1) { throw new RuntimeException('Stock unavailable'); }
});
}
}بازیابی پایدار و ساگای گیرکرده حیاتی
به زبان ساده: فرایند کسبوکار باید از process اجراکنندهٔ خود عمر بیشتری داشته باشد.
بدفهمی رایج: «broker دوباره تحویل میدهد، پس saga log لازم نیست.» پیام تکراری بهتنهایی نمیگوید کدام جبران هنوز باقی مانده است.
تعریف: بازیابی پایدار (Durable recovery) گام جاری، جهت، attempts، deadline، version، ورودی جبران و نتیجهٔ نهایی را ثبت میکند. تاریخچهٔ هماهنگکننده (SEC log) گذارهای commitشده را نگه میدارد؛ log قبل از commit فقط تلاش برای گذار است.
1 Coordinator commits state=compensating, step=charge-payment
2 Worker refunds; dies before reply reaches coordinator
3 Deadline resends same undo key
4 Participant returns stored refund result; no second refund
5 Coordinator records undo success and advances to release-stockسناریوها: deploy در میانهٔ workflow روزانه، failover هنگام گذار، شکست دائمی جبران و ادامه پس از اصلاح نگاشت حساب توسط اپراتور.
| دادهٔ پایدار | چرا لازم است؟ | از چه بپرهیزیم؟ |
|---|---|---|
| Saga id و نوع/نسخهٔ تعریف | همبستگی و بازیابی سازگار | تفسیر وضعیت قدیمی با ترتیب گام جدید |
| گام و action جاری | پاسخ قانونی بعدی را تعیین میکند | پذیرفتن هر success بهعنوان نتیجهٔ گام فعلی |
| attempts و deadline | کار خودکار را محدود میکند | retry داغ و بیپایان |
| ورودی جبران | undo فردا را ممکن میکند | محاسبهٔ قیمت تاریخی از کاتالوگ امروز |
| تاریخچه و علت | تصمیم و بازیابی انسانی را توضیح میدهد | payload حساس در error log |
راهحل: پس از تمامشدن بودجه وضعیت stuck ثبت کنید، روی سن آن هشدار بگذارید و فرمان resume/cancel/reconcile حسابرسیشده داشته باشید. نمونه یک تعریف ثابت دارد؛ production باید نسخهٔ تعریف مورد نیاز ساگاهای باز را حفظ کند. dedup و شناسهٔ provider باید دستکم تا پایان افق بازیابی و replay باقی بمانند.
سازوکار: گذار پایدار و تحویل
در schema نمونهٔ Go جدولهای sagas، saga_steps و saga_outbox داریم. handler پاسخ یک ساگا را قفل میکند، گذار خالص را حساب میکند، version را افزایش میدهد، تاریخچه را درج میکند و فرمان بعدی را در همان تراکنش PostgreSQL ثبت میکند. ack پیام پس از commit است. مرگ relay ممکن است فرمان را تکرار کند؛ پس کلید همتوانی (Idempotency key) مشارکتکننده همچنان لازم است.
relay آموزشی هنگام انتشار قفل ردیف را نگه میدارد تا مرز تراکنش روشن باشد؛ این توصیهٔ throughput برای production نیست. چند relay میتوانند فرمانها را درهمتنیده منتشر کنند. صحت باید در برابر جابهجایی do و undo دوام بیاورد؛ راهبردها و محدودیت ordering در Outbox آمدهاند. قطع broker نباید connection دیتابیس را بینهایت اشغال کند؛ I/O و زمان batch را محدود و pool را پایش کنید.
| پارامتر / شناسه | سیاست نمونه | معنا |
|---|---|---|
MaxAttempts | 5 | سقف retry پیش از جبران یا Stuck |
StepTimeout | 30 ثانیه در wiring اجرایی | آستانهٔ سکوت پاسخ، نه لغو کار remote |
version | افزایش در هر گذار commitشده | تشخیص نوشتن stale و کلید audit |
FOR UPDATE SKIP LOCKED | batchهای sweeper/relay | تقسیم کار محلی بدون انتظار پشت ردیف قفلشده |
saga_id:step:action | ثابت در retry | هویت do و undo جداست |
prefetch_count در RabbitMQ | 32 پاسخ | سقف تحویل unsettled، نه تعداد کل ساگاهای باز |
DisableAutoCommit در Kafka | فعال در Go | commit پس از ثبت پایدار وضعیت |
BlockRebalanceOnPoll در Kafka | فعال در Go | محدودکردن زمان handler؛ اجازهٔ rebalance پس از commit |
XAUTOCLAIM در Redis | idle برابر 60 ثانیه و پیمایش cursor | پسگرفتن تحویل رهاشده، نه timeout کسبوکار |
UniqueFor در Laravel | 60 ثانیه برای job اختیاری | بازهٔ جلوگیری از dispatch تکراری، نه exactly-once effect |
| خطا / وضعیت | تفسیر | سیاست |
|---|---|---|
PostgreSQL 40001 | تعارض serialization | retry کل تراکنش محلی با بودجه |
PostgreSQL 40P01 | قربانی deadlock | retry و بازبینی ترتیب قفل |
PostgreSQL 23505 | تعارض unique | تشخیص تعارض dedup مورد انتظار؛ همهٔ تعارضها را نبلعید |
PostgreSQL 25P02 | تراکنش قبلاً abort شده | rollback؛ ادامهٔ business SQL ممنوع |
AMQP 406 PRECONDITION_FAILED | ناسازگاری declaration یا پیششرط پروتکل | اصلاح تنظیم و ساخت channel سالم |
basic.return | انتشار mandatory مسیری نداشته | confirm مثبت را تحویل کسبوکار ندانید |
| شکست fetch/commit در Kafka | موقعیت پردازش شاید مبهم است | بستن و ساخت client جدید از offset commitشده |
Redis BUSYGROUP | group از قبل وجود دارد | فقط همین وضعیت مشخص setup نادیده گرفته شود |
| پاسخ malformed | مشکل قرارداد یا poison message | نگهداری برای repair؛ skip و commit خاموش نکنید |
| timeout پرداخت | نتیجهٔ کسبوکار نامعلوم | استعلام، retry همان کلید یا تطبیق |
کلید یکتا متعلق به payload ثابت است. استفادهٔ دوباره از reservation id با SKU یا مقدار متفاوت، قرارداد نمونه را نقض میکند؛ inbox واقعی باید ناسازگاری key/payload را رد کند. آزمون ماشین حالت فقط تصمیم را ثابت میکند، نه رفتار provider یا failover دیتابیس را.
راهحل مسئلههای کلاسیک
| مسئله | راهحل ترجیحی | فایده | محدودیت |
|---|---|---|---|
| charge موفق و پاسخ گمشده | تکرار/استعلام با operation key ثابت | نتیجهٔ معلوم بازیابی میشود | provider باید نتیجه و کلید را کافی نگه دارد |
| undo زودتر میرسد | tombstone لغو و گذار سری هر رزرو | اثر forward دیررس متوقف میشود | retention بخشی از صحت است |
| وضعیت commit شده ولی فرمان نیست | state و outbox در یک transaction | قصد انتشار پایدار | relay حداقل یکبار است |
| callback بعد از commit گم شده | sweeper پایدار فرمان جاری را دوباره میفرستد | مسیر صریح بازیابی نمونهٔ Laravel | تأخیر تا deadline؛ پایان بودجه شاید به جبران برسد |
| مسابقهٔ دو handler پاسخ | قفل ردیف و افزایش version/audit | یک گذار قانونی در لحظه | کار remote طولانی خارج از قفل بماند |
| شکست مکرر جبران | retry محدود، Stuck، هشدار و تطبیق | عملیات خاموش رها نمیشود | مالک عملیاتی لازم دارد |
| تغییر workflow در deploy | نسخهٔ تعریف روی هر ساگا | معنای کار قدیمی حفظ میشود | handler قدیمیِ سازگار باید بماند |
| retry کاربر برای checkout | request key کسبوکار به یک order/saga نگاشت شود | دو ساگای جدا ساخته نمیشود | correlation id انتقال کافی نیست |
| replay پاسخ قدیمی | بررسی step/action و retention | نتیجهٔ stale نادیده میماند | فرمان قدیمی هنوز fencing مشارکتکننده میخواهد |
| اقدام برگشتناپذیر زود است | جابهجایی pivot یا بازطراحی مرز | بار جبران کمتر میشود | زمانبندی جدید باید برای کسبوکار قابل قبول باشد |
دستورکار بازیابی: saga id و شناسهٔ provider را پیدا کنید؛ حقیقت مشارکتکننده را استعلام بگیرید؛ نبود پاسخ را از نبود اثر جدا کنید؛ طبق سیاست ثبتشده forward recovery یا compensation انتخاب کنید؛ تصمیم اپراتور را ثبت کنید؛ همان operation key را نگه دارید؛ وضعیت نهایی سفارش و مشارکتکننده را بررسی کنید. حذف ردیف stuck فقط مدرک را حذف میکند.
انتخاب مدل هماهنگی
| موقعیت | انتخاب | همراه آن | دلیل |
|---|---|---|---|
| invariant زیر یک دیتابیس است | تراکنش محلی | isolation مناسب | ساگا وضعیت میانی بیدلیل اضافه میکند |
| چند وابستگی رویدادی ثابت | Choreography | قرارداد قابل ردگیری و مالک بازیابی | واکنش نزدیک مشارکتکننده میماند |
| گامهای شرطی/جبرانی زیاد | Orchestration | وضعیت، timer و audit پایدار | تصمیمها آشکارند |
| انتظار طولانی، تأیید انسانی و timer پیچیده | موتور workflow | activity همتوان و جبران کسبوکار | mechanics اجرا را پایدار میکند |
| ناسازگاری موقت پذیرفته نیست | بازنگری مرز سرویس یا پروتکل اتمیِ پشتیبانیشده | تحلیل availability/latency | جبران اتمیبودن لحظهای نمیدهد |
| پرداخت خارجی با ارزش بالا | تطبیق و state model ویژهٔ provider | escalation انسانی، نه retry کور | هزینهٔ ابهام از throughput مهمتر است |
| پرسوجوی fan-out فقط خواندنی | API composition | deadline و سیاست نتیجهٔ جزئی | اثری برای جبران commit نمیشود |
اجرای پایدار Temporal/Cadence میتواند میزبان ساگا باشد، اما refund یا سیاست isolation را اختراع نمیکند. Durable Workflows، Request-Reply و Distributed Transactions را مقایسه کنید.
Go
قبل: فراخوانی پشتسرهم بدون بازیابی
// Package main places an order by calling three services in a row over HTTP
// and calls the whole thing a "transaction". It is not one: each call commits
// in its own database, and nothing undoes the earlier calls when a later one
// fails or when this process dies half way through.
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"time"
)
type Order struct {
ID string `json:"id"`
CustomerID string `json:"customer_id"`
SKU string `json:"sku"`
Qty int `json:"qty"`
TotalCents int64 `json:"total_cents"`
}
type Checkout struct {
client *http.Client
}
func (c *Checkout) post(ctx context.Context, url string, body any) error {
b, err := json.Marshal(body)
if err != nil {
return err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(b))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
resp, err := c.client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode >= 300 {
return fmt.Errorf("%s: %s", url, resp.Status)
}
return nil
}
// PlaceOrder looks atomic in the code and is not atomic in the world.
func (c *Checkout) PlaceOrder(ctx context.Context, o Order) error {
// Step 1 commits in the inventory database.
if err := c.post(ctx, "http://inventory/reservations", o); err != nil {
return err
}
// Step 2 commits in the payment provider. If it fails, the stock
// reserved in step 1 stays reserved forever.
if err := c.post(ctx, "http://payments/charges", o); err != nil {
return err
}
// Step 3: if this times out, the customer is charged, the stock is held,
// and nobody knows whether a shipment exists. A crash of this process
// between any two lines leaves the same mess with no record of it.
return c.post(ctx, "http://shipping/shipments", o)
}
func main() {
c := &Checkout{client: &http.Client{Timeout: 5 * time.Second}}
err := c.PlaceOrder(context.Background(), Order{ID: "o-1", CustomerID: "c-1", SKU: "book", Qty: 1, TotalCents: 2500})
if err != nil {
log.Println("order failed, state unknown:", err)
}
}بعد: تصمیم خالص، وضعیت پایدار، انتقال جدا
// Package saga is a small orchestrator: a saga definition (steps with
// compensations), a pure state machine that decides the next command, and a
// Postgres store that persists the state and the outgoing command in one
// local transaction (a transactional outbox).
package saga
import (
"context"
"encoding/json"
"fmt"
)
type Status string
const (
Running Status = "running"
Compensating Status = "compensating"
Completed Status = "completed"
Compensated Status = "compensated"
Stuck Status = "stuck" // a compensation keeps failing: a human decides
)
type Action string
const (
Do Action = "do"
Undo Action = "undo"
)
// Step is one local transaction in one participant. Steps before the pivot
// are compensable; steps after it are marked Retry and are never compensated,
// only retried until they succeed (forward recovery).
type Step struct {
Name string // "reserve-stock"
Participant string // logical destination: "inventory"
Retry bool
}
type Definition struct {
Type string
Steps []Step
// MaxAttempts bounds every retry loop: a silent step, a post-pivot
// step that keeps failing, and a compensation that keeps failing.
// Past it the saga is parked as Stuck (the saga dead-letter).
MaxAttempts int
}
// Command is what the orchestrator asks a participant to do.
type Command struct {
SagaID string `json:"saga_id"`
Step string `json:"step"`
Action Action `json:"action"`
Attempt int `json:"attempt"`
Payload json.RawMessage `json:"payload"`
}
// IdempotencyKey is identical across retries of the same command, so the
// participant can deduplicate it in its inbox table.
func (c Command) IdempotencyKey() string {
return fmt.Sprintf("%s:%s:%s", c.SagaID, c.Step, c.Action)
}
// Reply is what a participant sends back. OK=false on a Do means "my local
// transaction rolled back for a business reason".
type Reply struct {
SagaID string `json:"saga_id"`
Step string `json:"step"`
Action Action `json:"action"`
OK bool `json:"ok"`
Reason string `json:"reason,omitempty"`
}
// State is one row of the sagas table.
type State struct {
ID string
Status Status
Step int // index of the step whose command is in flight
Attempts int
Version int // bumped on every transition: optimistic check + step log key
Reason string
Payload json.RawMessage
}
// Sender publishes a command to a participant. One implementation per broker.
type Sender interface {
Send(ctx context.Context, participant string, cmd Command) error
}
// ReplySource delivers replies to handle and acknowledges a reply only after
// handle returned nil. One implementation per broker.
type ReplySource interface {
Replies(ctx context.Context, handle func(context.Context, Reply) error) error
}
func (d Definition) command(s State, a Action) *Command {
return &Command{SagaID: s.ID, Step: d.Steps[s.Step].Name, Action: a, Attempt: s.Attempts, Payload: s.Payload}
}
// Validate rejects empty, ambiguous or unbounded definitions before persistence.
func (d Definition) Validate() error {
if len(d.Steps) == 0 || d.MaxAttempts < 1 {
return fmt.Errorf("steps and positive MaxAttempts required")
}
seen := map[string]bool{}
retryOnly := false
for _, st := range d.Steps {
if st.Name == "" || st.Participant == "" || seen[st.Name] || (retryOnly && !st.Retry) {
return fmt.Errorf("invalid or ambiguous saga definition")
}
seen[st.Name] = true
retryOnly = retryOnly || st.Retry
}
return nil
}
func (d Definition) valid(s State) bool {
return d.Validate() == nil && s.Step >= 0 && s.Step < len(d.Steps) && s.Attempts >= 0
}
// Begin returns the first command of a new saga; Store validates first.
func (d Definition) Begin(s State) *Command {
if !d.valid(s) {
return nil
}
return d.command(s, Do)
}
// Next is the whole state machine. It is pure: no I/O, easy to test.
// A reply that does not match the step in flight is a duplicate or a late
// message, and is ignored (nil command, unchanged state).
func (d Definition) Next(s State, r Reply) (State, *Command) {
if !d.valid(s) {
s.Status, s.Reason = Stuck, "invalid persisted state"
return s, nil
}
if r.SagaID != s.ID {
return s, nil
}
expected := Do
if s.Status == Compensating {
expected = Undo
}
if (s.Status != Running && s.Status != Compensating) ||
r.Step != d.Steps[s.Step].Name || r.Action != expected {
return s, nil
}
switch {
case s.Status == Running && r.OK:
s.Step, s.Attempts = s.Step+1, 0
if s.Step == len(d.Steps) {
s.Status, s.Step = Completed, len(d.Steps)-1
return s, nil
}
return s, d.command(s, Do)
case s.Status == Running && d.Steps[s.Step].Retry:
// Past the pivot there is no going back: retry forward, bounded.
return d.retry(s, Do, r.Reason)
case s.Status == Running:
// A business "no": the participant rolled its local transaction
// back, so only the steps before this one need undoing.
s.Reason = r.Reason
return d.compensateFrom(s, s.Step-1)
case s.Status == Compensating && r.OK:
return d.compensateFrom(s, s.Step-1)
default:
// A compensation failed. It must eventually succeed, so retry it,
// and park the saga for a human when it does not.
return d.retry(s, Undo, r.Reason)
}
}
// Timeout is what the sweeper calls when the step in flight stayed silent
// past its deadline. Silence is NOT a business "no": the participant may
// have committed and the reply may be lost. So after MaxAttempts resends a
// compensable step is compensated starting with ITSELF (its undo must cope
// with "nothing to undo" and with a late do), not with the step before it.
func (d Definition) Timeout(s State) (State, *Command) {
if !d.valid(s) {
s.Status, s.Reason = Stuck, "invalid persisted state"
return s, nil
}
if s.Status != Running && s.Status != Compensating {
return s, nil
}
action := Do
if s.Status == Compensating {
action = Undo
}
if s.Attempts+1 < d.MaxAttempts {
s.Attempts++
return s, d.command(s, action) // resend; participants deduplicate
}
if s.Status == Running && !d.Steps[s.Step].Retry {
s.Reason = "timeout"
return d.compensateFrom(s, s.Step)
}
s.Status, s.Reason = Stuck, "timeout after max attempts"
return s, nil
}
func (d Definition) retry(s State, a Action, reason string) (State, *Command) {
s.Attempts++
if s.Attempts >= d.MaxAttempts {
s.Status, s.Reason = Stuck, reason
return s, nil
}
return s, d.command(s, a)
}
func (d Definition) compensateFrom(s State, i int) (State, *Command) {
s.Status, s.Step, s.Attempts = Compensating, i, 0
if i < 0 {
s.Status, s.Step = Compensated, 0
return s, nil
}
return s, d.command(s, Undo)
}
// OrderSaga is the running example: stock, then payment (the pivot, the last
// compensable step under this business policy), then shipping, which may only
// be retried. An unknown charge outcome is refunded before that boundary is
// confirmed; participants must fence late do after undo. Real payment policies differ.
var OrderSaga = Definition{
Type: "create-order",
MaxAttempts: 5,
Steps: []Step{
{Name: "reserve-stock", Participant: "inventory"},
{Name: "charge-payment", Participant: "payments"},
{Name: "schedule-shipment", Participant: "shipping", Retry: true},
},
}package saga
import (
"context"
"database/sql"
"encoding/json"
"errors"
"log/slog"
"time"
)
// Schema is the persisted saga log. The orchestrator itself is stateless:
// any instance can pick up any saga after a crash.
const Schema = `
CREATE TABLE IF NOT EXISTS sagas (
id text PRIMARY KEY,
type text NOT NULL,
status text NOT NULL,
step int NOT NULL,
attempts int NOT NULL DEFAULT 0,
version int NOT NULL DEFAULT 0,
reason text,
payload jsonb NOT NULL,
deadline_at timestamptz NOT NULL,
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS sagas_open_by_deadline
ON sagas (deadline_at) WHERE status IN ('running', 'compensating');
-- The step log: one row per transition. It answers "what happened to
-- saga X" and is the audit trail a human reads before fixing a stuck saga.
CREATE TABLE IF NOT EXISTS saga_steps (
saga_id text NOT NULL REFERENCES sagas (id),
version int NOT NULL,
step text NOT NULL,
from_status text NOT NULL,
to_status text NOT NULL,
attempts int NOT NULL,
reason text,
at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (saga_id, version)
);
CREATE TABLE IF NOT EXISTS saga_outbox (
id bigserial PRIMARY KEY,
participant text NOT NULL,
command jsonb NOT NULL,
published_at timestamptz
);`
type Store struct {
DB *sql.DB
Def Definition
StepTimeout time.Duration // how long a step may stay silent
}
// ErrConcurrentUpdate means another orchestrator instance moved the saga
// between our read and our write. With the row lock below it cannot
// happen; it guards code paths that read without FOR UPDATE.
var ErrConcurrentUpdate = errors.New("saga: version changed underneath us")
// Start inserts the saga and its first command in one local transaction.
func (s *Store) Start(ctx context.Context, id string, payload json.RawMessage) error {
if err := s.Def.Validate(); err != nil {
return err
}
if s.StepTimeout <= 0 {
return errors.New("positive step timeout required")
}
st := State{ID: id, Status: Running, Payload: payload}
return s.inTx(ctx, func(tx *sql.Tx) error {
_, err := tx.ExecContext(ctx,
`INSERT INTO sagas (id, type, status, step, payload, deadline_at)
VALUES ($1, $2, $3, 0, $4, now() + make_interval(secs => $5))`,
id, s.Def.Type, st.Status, payload, s.StepTimeout.Seconds())
if err != nil {
return err
}
return s.enqueue(ctx, tx, st, s.Def.Begin(st))
})
}
// HandleReply is the message-driven step runner: lock the row, run the state
// machine, persist the new state and the next command atomically.
func (s *Store) HandleReply(ctx context.Context, r Reply) error {
return s.inTx(ctx, func(tx *sql.Tx) error {
old, err := s.load(ctx, tx, r.SagaID)
if errors.Is(err, sql.ErrNoRows) {
return nil // unknown saga: nothing to do, ack the message
}
if err != nil {
return err
}
next, cmd := s.Def.Next(old, r)
return s.save(ctx, tx, old, next, cmd)
})
}
// Sweep handles dead sagas: steps whose reply never came. The decision is
// the pure Definition.Timeout: resend (participants deduplicate), then
// compensate starting with the silent step, then park as Stuck.
func (s *Store) Sweep(ctx context.Context) error {
return s.inTx(ctx, func(tx *sql.Tx) error {
rows, err := tx.QueryContext(ctx,
`SELECT id FROM sagas
WHERE status IN ('running', 'compensating') AND deadline_at < now()
ORDER BY deadline_at LIMIT 100 FOR UPDATE SKIP LOCKED`)
if err != nil {
return err
}
var ids []string
for rows.Next() {
var id string
if err := rows.Scan(&id); err != nil {
rows.Close()
return err
}
ids = append(ids, id)
}
rows.Close()
if err := rows.Err(); err != nil {
return err
}
for _, id := range ids {
old, err := s.load(ctx, tx, id)
if err != nil {
return err
}
next, cmd := s.Def.Timeout(old)
if err := s.save(ctx, tx, old, next, cmd); err != nil {
return err
}
}
return nil
})
}
// Relay publishes pending commands. It is a polling outbox relay; see the
// outbox page for CDC-based relays and their ordering guarantees.
func (s *Store) Relay(ctx context.Context, out Sender) error {
return s.inTx(ctx, func(tx *sql.Tx) error {
rows, err := tx.QueryContext(ctx,
`SELECT id, participant, command FROM saga_outbox
WHERE published_at IS NULL ORDER BY id LIMIT 100 FOR UPDATE SKIP LOCKED`)
if err != nil {
return err
}
type pending struct {
id int64
participant string
cmd Command
}
var batch []pending
for rows.Next() {
var p pending
var raw []byte
if err := rows.Scan(&p.id, &p.participant, &raw); err != nil {
rows.Close()
return err
}
if err := json.Unmarshal(raw, &p.cmd); err != nil {
rows.Close()
return err
}
batch = append(batch, p)
}
rows.Close()
if err := rows.Err(); err != nil {
return err
}
for _, p := range batch {
// At-least-once: a crash after Send and before the UPDATE
// publishes the command again. Participants deduplicate.
if err := out.Send(ctx, p.participant, p.cmd); err != nil {
return err
}
if _, err := tx.ExecContext(ctx,
`UPDATE saga_outbox SET published_at = now() WHERE id = $1`, p.id); err != nil {
return err
}
}
return nil
})
}
func (s *Store) load(ctx context.Context, tx *sql.Tx, id string) (State, error) {
st := State{ID: id}
err := tx.QueryRowContext(ctx,
`SELECT status, step, attempts, version, coalesce(reason, ''), payload
FROM sagas WHERE id = $1 FOR UPDATE`, id).
Scan(&st.Status, &st.Step, &st.Attempts, &st.Version, &st.Reason, &st.Payload)
if err == nil && !s.Def.valid(st) {
return st, errors.New("invalid saga state: operator repair required")
}
return st, err
}
func (s *Store) save(ctx context.Context, tx *sql.Tx, old, next State, cmd *Command) error {
if cmd == nil && next.Status == old.Status && next.Step == old.Step && next.Attempts == old.Attempts {
return nil // duplicate or late reply
}
next.Version = old.Version + 1
res, err := tx.ExecContext(ctx,
`UPDATE sagas SET status = $2, step = $3, attempts = $4, version = $5,
reason = nullif($6, ''), deadline_at = now() + make_interval(secs => $7), updated_at = now()
WHERE id = $1 AND version = $8`,
next.ID, next.Status, next.Step, next.Attempts, next.Version,
next.Reason, s.StepTimeout.Seconds(), old.Version)
if err != nil {
return err
}
if n, err := res.RowsAffected(); err != nil {
return err
} else if n != 1 {
return ErrConcurrentUpdate
}
if _, err := tx.ExecContext(ctx,
`INSERT INTO saga_steps (saga_id, version, step, from_status, to_status, attempts, reason)
VALUES ($1, $2, $3, $4, $5, $6, nullif($7, ''))`,
next.ID, next.Version, s.Def.Steps[next.Step].Name, old.Status, next.Status,
next.Attempts, next.Reason); err != nil {
return err
}
// This is an attempted transition log; transaction commit may still fail.
// The committed saga_steps table is the authoritative audit trail.
slog.InfoContext(ctx, "saga transition", "saga_id", next.ID, "type", s.Def.Type,
"from", old.Status, "to", next.Status, "step", s.Def.Steps[next.Step].Name,
"attempts", next.Attempts)
return s.enqueue(ctx, tx, next, cmd)
}
func (s *Store) enqueue(ctx context.Context, tx *sql.Tx, st State, cmd *Command) error {
if cmd == nil {
return nil
}
body, err := json.Marshal(cmd)
if err != nil {
return err
}
_, err = tx.ExecContext(ctx,
`INSERT INTO saga_outbox (participant, command) VALUES ($1, $2)`,
s.Def.Steps[st.Step].Participant, body)
return err
}
func (s *Store) inTx(ctx context.Context, fn func(*sql.Tx) error) error {
tx, err := s.DB.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
if err := fn(tx); err != nil {
return err
}
return tx.Commit()
}// Package main wires the orchestrator to one broker, chosen by SAGA_BROKER.
// It exits immediately when the environment is not configured, so it builds
// and vets without Postgres or a broker running.
package main
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"log"
"os"
"os/signal"
"time"
_ "github.com/jackc/pgx/v5/stdlib"
amqp "github.com/rabbitmq/amqp091-go"
"github.com/redis/go-redis/v9"
"academy/saga-pattern/after/kafka"
"academy/saga-pattern/after/rabbitmq"
"academy/saga-pattern/after/redisstreams"
"academy/saga-pattern/after/saga"
)
type transport interface {
saga.Sender
saga.ReplySource
}
func main() {
dsn, broker, addr := os.Getenv("DATABASE_URL"), os.Getenv("SAGA_BROKER"), os.Getenv("BROKER_ADDR")
if dsn == "" || broker == "" || addr == "" {
log.Println("set DATABASE_URL, SAGA_BROKER (rabbitmq|kafka|redis) and BROKER_ADDR")
return
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
db, err := sql.Open("pgx", dsn)
if err != nil {
log.Fatal(err)
}
defer db.Close()
if _, err := db.ExecContext(ctx, saga.Schema); err != nil {
log.Fatal(err)
}
store := &saga.Store{DB: db, Def: saga.OrderSaga, StepTimeout: 30 * time.Second}
var t transport
switch broker {
case "rabbitmq":
conn, err := amqp.Dial(addr)
if err != nil {
log.Fatal(err)
}
defer conn.Close()
ch, err := conn.Channel()
if err != nil {
log.Fatal(err)
}
if t, err = rabbitmq.New(ch, "inventory", "payments", "shipping"); err != nil {
log.Fatal(err)
}
case "kafka":
if t, err = kafka.New(addr); err != nil {
log.Fatal(err)
}
case "redis":
host, _ := os.Hostname()
rdb := redis.NewClient(&redis.Options{Addr: addr, ContextTimeoutEnabled: true, DialTimeout: 3 * time.Second, ReadTimeout: 6 * time.Second, WriteTimeout: 3 * time.Second})
defer rdb.Close()
rt := redisstreams.New(rdb, fmt.Sprintf("%s-%d-%d", host, os.Getpid(), time.Now().UnixNano()))
t = rt
go every(ctx, 15*time.Second, func() error { return rt.Reclaim(ctx, store.HandleReply) })
default:
log.Fatal("unsupported SAGA_BROKER")
}
// Three loops: the relay publishes commands, the sweeper finds dead
// sagas, and the reply consumer drives the state machine.
go every(ctx, time.Second, func() error { return store.Relay(ctx, t) })
go every(ctx, 10*time.Second, func() error { return store.Sweep(ctx) })
payload, _ := json.Marshal(map[string]any{"order_id": "o-1", "sku": "book", "qty": 1, "total_cents": 2500})
if err := store.Start(ctx, "o-1", payload); err != nil {
log.Println("start:", err)
}
if err := t.Replies(ctx, store.HandleReply); err != nil && ctx.Err() == nil {
log.Fatal(err)
}
}
func every(ctx context.Context, d time.Duration, fn func() error) {
tick := time.NewTicker(d)
defer tick.Stop()
for {
select {
case <-ctx.Done():
return
case <-tick.C:
if err := fn(); err != nil {
log.Println(err)
}
}
}
}نگاه Go
ماشین حالت به broker وابسته نیست. context.Context ورودی/خروجیِ همکاریکننده را محدود میکند؛ cancellation رد کسبوکار نیست. runner درونفرایندی برای جبران یک cleanup context جدا و محدود میسازد، اما در برابر crash پایدار نیست. fakeها برای فهم ترتیباند و جای Store پایدار را نمیگیرند.
// Package main is an in-process saga runner for a (modular) monolith: the
// steps are calls into modules or remote APIs, the saga runs in one
// goroutine, and each step has its own retries and its own deadline. It is
// the Step interface with Execute and Compensate that the message-driven
// orchestrator generalises. Run it: go run ./inprocess
package main
import (
"context"
"errors"
"fmt"
"time"
)
// Step is one local transaction plus its semantic undo.
type Step interface {
Name() string
Execute(ctx context.Context) error
Compensate(ctx context.Context) error
}
// ErrRejected is a business "no": do not retry, start compensating.
var ErrRejected = errors.New("rejected")
// Policy is per step: how often to retry a transient error and how long
// one attempt may take (the step deadline).
type Policy struct {
Attempts int
Timeout time.Duration
Backoff time.Duration
Pivot bool // the point of no return: later steps are retry-only
}
type planned struct {
step Step
policy Policy
}
// Saga runs steps in order and compensates in reverse on failure.
type Saga struct {
steps []planned
log func(format string, args ...any)
}
func (s *Saga) Add(st Step, p Policy) *Saga {
s.steps = append(s.steps, planned{st, p})
return s
}
// ErrNeedsHuman is returned when a compensation, or a step past the pivot,
// cannot be completed: the saga must be parked, never silently dropped.
var ErrNeedsHuman = errors.New("saga stuck: manual intervention needed")
func (s *Saga) Run(ctx context.Context) error {
pastPivot := false
for i, p := range s.steps {
if p.policy.Attempts < 1 || p.policy.Timeout <= 0 {
return errors.New("positive attempts and timeout required")
}
err := s.attempt(ctx, p, p.step.Execute)
if err == nil {
pastPivot = pastPivot || p.policy.Pivot
continue
}
if pastPivot {
s.log("%s failed after the pivot: %v", p.step.Name(), err)
return ErrNeedsHuman
}
// A timeout is not a "no": the step may have committed. Undo it too.
from := i - 1
if !errors.Is(err, ErrRejected) {
from = i
}
s.log("%s failed (%v): compensating from step %d", p.step.Name(), err, from)
cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
defer cancel()
for j := from; j >= 0; j-- {
c := s.steps[j]
if err := s.attempt(cleanup, c, c.step.Compensate); err != nil {
s.log("compensation %s failed: %v", c.step.Name(), err)
return ErrNeedsHuman
}
}
return fmt.Errorf("saga compensated: %w", err)
}
return nil
}
func (s *Saga) attempt(ctx context.Context, p planned, fn func(context.Context) error) error {
var err error
for n := 1; n <= p.policy.Attempts; n++ {
stepCtx, cancel := context.WithTimeout(ctx, p.policy.Timeout)
err = fn(stepCtx)
cancel()
if err == nil || errors.Is(err, ErrRejected) {
return err
}
s.log(" %s attempt %d: %v", p.step.Name(), n, err)
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(p.policy.Backoff * time.Duration(n)):
}
}
return err
}
// fake is a participant whose behaviour the demo scripts.
type fake struct {
name string
slowOnce bool // the first call blocks past the deadline
reject bool
calls int
}
func (f *fake) Name() string { return f.name }
func (f *fake) Execute(ctx context.Context) error {
f.calls++
if f.slowOnce && f.calls == 1 {
<-ctx.Done() // a hung dependency: only the deadline gets us out
return ctx.Err()
}
if f.reject {
return fmt.Errorf("%s: %w", f.name, ErrRejected)
}
fmt.Printf(" do %s\n", f.name)
return nil
}
func (f *fake) Compensate(ctx context.Context) error {
fmt.Printf(" undo %s\n", f.name)
return nil
}
func main() {
logf := func(format string, args ...any) { fmt.Printf(format+"\n", args...) }
p := Policy{Attempts: 3, Timeout: 50 * time.Millisecond, Backoff: 10 * time.Millisecond}
pivot := p
pivot.Pivot = true
fmt.Println("run 1: payment declined")
s := (&Saga{log: logf}).
Add(&fake{name: "reserve-stock", slowOnce: true}, p).
Add(&fake{name: "charge-payment", reject: true}, pivot).
Add(&fake{name: "schedule-shipment"}, p)
fmt.Println("result:", s.Run(context.Background()))
fmt.Println("run 2: happy path")
s = (&Saga{log: logf}).
Add(&fake{name: "reserve-stock"}, p).
Add(&fake{name: "charge-payment"}, pivot).
Add(&fake{name: "schedule-shipment"}, p)
fmt.Println("result:", s.Run(context.Background()))
}// Package main is the choreographed version of the order saga: no
// orchestrator, only event handlers. Each service subscribes to the events
// it cares about, does one local transaction, and publishes its own event.
// The bus here is an in-memory FIFO so the program runs anywhere; in
// production each Publish is an outbox insert and each handler a consumer
// with an inbox. Run it: go run ./choreography
package main
import "fmt"
type Event struct {
Type string
OrderID string // the correlation id: every event of one saga carries it
Reason string
}
type Bus struct {
subs map[string][]func(Event)
queue []Event
}
func (b *Bus) Subscribe(t string, h func(Event)) { b.subs[t] = append(b.subs[t], h) }
func (b *Bus) Publish(e Event) { b.queue = append(b.queue, e) }
// Drain delivers events in order. Handlers publish more events, which is
// exactly how the saga "moves" in choreography.
func (b *Bus) Drain() {
for len(b.queue) > 0 {
e := b.queue[0]
b.queue = b.queue[1:]
fmt.Printf(" event %-16s order=%s %s\n", e.Type, e.OrderID, e.Reason)
for _, h := range b.subs[e.Type] {
h(e)
}
}
}
// Orders owns the order status. PENDING is the semantic lock.
type Orders struct{ status map[string]string }
// Inventory keeps reservations keyed by order id: that key makes the
// handlers idempotent and lets a release arrive before a reserve.
type Inventory struct {
available int
reserved map[string]int
released map[string]bool // version file: remembers "release before reserve"
}
type Payments struct{ limit int }
func wire(b *Bus, o *Orders, inv *Inventory, pay *Payments) {
b.Subscribe("OrderPlaced", func(e Event) {
if inv.released[e.OrderID] || inv.reserved[e.OrderID] > 0 {
return // late or duplicate: already handled
}
if inv.available < 1 {
b.Publish(Event{Type: "StockRejected", OrderID: e.OrderID, Reason: "out of stock"})
return
}
inv.available-- // a commutative decrement in SQL: available = available - 1
inv.reserved[e.OrderID] = 1
b.Publish(Event{Type: "StockReserved", OrderID: e.OrderID})
})
b.Subscribe("StockReserved", func(e Event) {
if pay.limit < 25 {
b.Publish(Event{Type: "PaymentDeclined", OrderID: e.OrderID, Reason: "card declined"})
return
}
b.Publish(Event{Type: "PaymentCharged", OrderID: e.OrderID})
})
// Compensation lives in the participant that owns the data.
b.Subscribe("PaymentDeclined", func(e Event) {
if n := inv.reserved[e.OrderID]; n > 0 {
inv.available += n
delete(inv.reserved, e.OrderID)
}
inv.released[e.OrderID] = true
})
// The order service listens to the end of every path. Note how the
// flow is only visible by reading all these subscriptions together.
for _, t := range []string{"StockRejected", "PaymentDeclined"} {
b.Subscribe(t, func(e Event) { o.status[e.OrderID] = "REJECTED" })
}
b.Subscribe("PaymentCharged", func(e Event) { o.status[e.OrderID] = "APPROVED" })
}
func main() {
for _, limit := range []int{100, 10} {
b := &Bus{subs: map[string][]func(Event){}}
o := &Orders{status: map[string]string{}}
inv := &Inventory{available: 1, reserved: map[string]int{}, released: map[string]bool{}}
wire(b, o, inv, &Payments{limit: limit})
fmt.Printf("card limit %d:\n", limit)
o.status["o-1"] = "PENDING"
b.Publish(Event{Type: "OrderPlaced", OrderID: "o-1"})
b.Drain()
fmt.Printf(" order=%s available=%d\n", o.status["o-1"], inv.available)
}
}package saga
import (
"reflect"
"testing"
)
// drive feeds replies into the pure state machine and records every
// command it emits, like an orchestrator with a perfect broker.
func drive(t *testing.T, replies func(Command) Reply) (State, []string) {
t.Helper()
s := State{ID: "o-1", Status: Running}
var log []string
cmd := OrderSaga.Begin(s)
for i := 0; cmd != nil; i++ {
if i > 50 {
t.Fatal("saga did not terminate")
}
log = append(log, string(cmd.Action)+":"+cmd.Step)
s, cmd = OrderSaga.Next(s, replies(*cmd))
}
return s, log
}
// failAt answers "no" to one (step, action) and "ok" to everything else.
func failAt(step string, action Action, times int) func(Command) Reply {
failures := 0
return func(c Command) Reply {
ok := !(c.Step == step && c.Action == action && failures < times)
if !ok {
failures++
}
return Reply{SagaID: c.SagaID, Step: c.Step, Action: c.Action, OK: ok, Reason: "test"}
}
}
func TestStepFailures(t *testing.T) {
tests := []struct {
name string
reply func(Command) Reply
status Status
log []string
}{
{"happy path", failAt("", Do, 0), Completed,
[]string{"do:reserve-stock", "do:charge-payment", "do:schedule-shipment"}},
{"stock rejected: nothing to undo", failAt("reserve-stock", Do, 1), Compensated,
[]string{"do:reserve-stock"}},
{"payment declined: release stock", failAt("charge-payment", Do, 1), Compensated,
[]string{"do:reserve-stock", "do:charge-payment", "undo:reserve-stock"}},
{"shipping fails twice after the pivot: retried forward", failAt("schedule-shipment", Do, 2), Completed,
[]string{"do:reserve-stock", "do:charge-payment", "do:schedule-shipment",
"do:schedule-shipment", "do:schedule-shipment"}},
{"shipping never succeeds: stuck, never refunded", failAt("schedule-shipment", Do, 99), Stuck,
[]string{"do:reserve-stock", "do:charge-payment", "do:schedule-shipment",
"do:schedule-shipment", "do:schedule-shipment", "do:schedule-shipment", "do:schedule-shipment"}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s, log := drive(t, tt.reply)
if s.Status != tt.status {
t.Fatalf("status = %s, want %s", s.Status, tt.status)
}
if !reflect.DeepEqual(log, tt.log) {
t.Fatalf("commands = %v\nwant %v", log, tt.log)
}
})
}
}
func TestCompensationThatKeepsFailingParksTheSaga(t *testing.T) {
declineThenFailUndo := func(c Command) Reply {
ok := !(c.Step == "charge-payment" && c.Action == Do) &&
!(c.Step == "reserve-stock" && c.Action == Undo)
return Reply{SagaID: c.SagaID, Step: c.Step, Action: c.Action, OK: ok}
}
s, _ := drive(t, declineThenFailUndo)
if s.Status != Stuck {
t.Fatalf("status = %s, want stuck", s.Status)
}
}
func TestDuplicateAndLateRepliesAreIgnored(t *testing.T) {
s := State{ID: "o-1", Status: Running, Step: 1}
late := Reply{SagaID: "o-1", Step: "reserve-stock", Action: Do, OK: true} // redelivered
next, cmd := OrderSaga.Next(s, late)
if cmd != nil || !reflect.DeepEqual(next, s) {
t.Fatalf("a stale reply changed the saga: %+v %+v", next, cmd)
}
}
// TestTimeoutCompensatesTheSilentStepItself: the charge may have succeeded
// with its reply lost, so the refund must be attempted too.
func TestTimeoutCompensatesTheSilentStepItself(t *testing.T) {
s := State{ID: "o-1", Status: Running, Step: 1, Attempts: OrderSaga.MaxAttempts - 1}
next, cmd := OrderSaga.Timeout(s)
if next.Status != Compensating || cmd == nil || cmd.Step != "charge-payment" || cmd.Action != Undo {
t.Fatalf("got %+v %+v, want undo:charge-payment", next, cmd)
}
}
func TestTimeoutResendsBeforeGivingUp(t *testing.T) {
s := State{ID: "o-1", Status: Running, Step: 0}
next, cmd := OrderSaga.Timeout(s)
if next.Status != Running || next.Attempts != 1 || cmd.Action != Do {
t.Fatalf("got %+v %+v, want a resend", next, cmd)
}
}
// TestReplayIsDeterministic: replaying the same reply log (as after a crash
// that lost the in-memory state) reaches the same state, and replaying it a
// second time on top changes nothing.
func TestReplayIsDeterministic(t *testing.T) {
replies := []Reply{
{SagaID: "o-1", Step: "reserve-stock", Action: Do, OK: true},
{SagaID: "o-1", Step: "charge-payment", Action: Do, OK: false, Reason: "card declined"},
{SagaID: "o-1", Step: "reserve-stock", Action: Undo, OK: true},
}
play := func(s State) State {
for _, r := range replies {
s, _ = OrderSaga.Next(s, r)
}
return s
}
once := play(State{ID: "o-1", Status: Running})
twice := play(once)
if once.Status != Compensated || !reflect.DeepEqual(once, twice) {
t.Fatalf("once = %+v, twice = %+v", once, twice)
}
}
func TestWrongSagaAndInvalidState(t *testing.T) {
s := State{ID: "ours", Status: Running}
next, cmd := OrderSaga.Next(s, Reply{SagaID: "other", Step: "reserve-stock", Action: Do, OK: true})
if cmd != nil || !reflect.DeepEqual(s, next) {
t.Fatal("wrong saga accepted")
}
s.Step = 100
next, cmd = OrderSaga.Timeout(s)
if next.Status != Stuck || cmd != nil {
t.Fatal("corrupt state not parked")
}
if (Definition{}).Validate() == nil {
t.Fatal("empty definition accepted")
}
}برنامهٔ اجرایی فقط با environment تنظیمشده شروع میشود. آن برنامه coordinator و transport را سیمکشی میکند، نه سه سرویس کامل Inventory/Payments/Shipping را. مشارکتکننده باید قرارداد فرمان را پیاده کند و اثر محلی و نتیجهٔ dedup را با هم ثبت کند. نمونههای PostgreSQL ورودی رزرو تغییرناپذیر و writerهای همکار را فرض میکنند.
Laravel 13
قبل: rollback محلی اثر remote را برنمیگرداند
<?php
// app/Http/Controllers/OrderController.php
// Three services, three commits, one controller pretending they are one
// transaction. DB::transaction() here would only wrap the local insert; it
// cannot roll back a reservation or a charge made in another service.
namespace App\Http\Controllers;
use App\Models\Order;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
final class OrderController
{
public function store(Request $request): JsonResponse
{
$order = Order::create($request->validate([
'customer_id' => ['required', 'integer'],
'sku' => ['required', 'string'],
'qty' => ['required', 'integer', 'min:1'],
'total_cents' => ['required', 'integer', 'min:1'],
]) + ['status' => 'pending']);
// Commits in the inventory service.
Http::post(config('services.inventory.url').'/reservations', [
'order_id' => $order->id, 'sku' => $order->sku, 'qty' => $order->qty,
])->throw();
// Commits at the payment provider. If this throws, the stock above
// stays reserved and nothing will ever release it.
Http::post(config('services.payments.url').'/charges', [
'order_id' => $order->id, 'amount' => $order->total_cents,
])->throw();
// If this times out the customer is charged and the order is stuck in
// "pending"; if the PHP worker is killed here, there is no record of
// which of the three calls happened.
Http::post(config('services.shipping.url').'/shipments', [
'order_id' => $order->id,
])->throw();
$order->update(['status' => 'approved']);
return response()->json($order, 201);
}
}بعد: وضعیت صریح و deadline بازیابی
<?php
// database/migrations/2026_01_01_000000_create_sagas_table.php
// The persisted saga log. Every step and every compensation reads and writes
// this row under a row lock, so any worker can resume any saga after a crash.
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('sagas', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->string('type'); // 'create_order'
$table->unsignedInteger('version')->default(0);
$table->unsignedInteger('attempts')->default(0);
$table->string('status'); // running|compensating|completed|compensated|stuck
$table->json('payload'); // order id, amounts, sku...
$table->json('completed_steps'); // ordered list, the compensation plan
$table->string('current_step')->nullable();
$table->text('failure_reason')->nullable();
$table->timestamp('deadline_at'); // when a silent saga counts as dead
$table->timestamps();
$table->index(['status', 'deadline_at']);
});
Schema::create('saga_steps', function (Blueprint $table) {
$table->uuid('saga_id'); $table->unsignedInteger('version');
$table->string('step'); $table->string('from_status'); $table->string('to_status');
$table->unsignedInteger('attempts'); $table->text('reason')->nullable(); $table->timestamp('created_at');
$table->primary(['saga_id','version']); $table->foreign('saga_id')->references('id')->on('sagas');
});
Schema::create('saga_inbox', function (Blueprint $table) {
$table->string('key')->primary(); $table->json('reply'); $table->timestamp('created_at');
});
}
public function down(): void
{
Schema::dropIfExists('saga_inbox');
Schema::dropIfExists('saga_steps');
Schema::dropIfExists('sagas');
}
};<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Model;
final class Saga extends Model
{
use HasUuids;
protected $guarded = [];
protected function casts(): array
{
return [
'payload' => 'array', 'version'=>'integer', 'attempts'=>'integer',
'completed_steps' => 'array',
'deadline_at' => 'datetime',
];
}
}
// app/Sagas/StepRejected.php — a business "no" from a participant.<?php
namespace App\Sagas\Messaging;
use InvalidArgumentException;
/** Pure decisions: callers persist the returned state before sending commands. */
final class Definition
{
public const STEPS = ['reserve-stock' => 'inventory', 'charge-payment' => 'payments', 'schedule-shipment' => 'shipping'];
public const MAX_ATTEMPTS = 5;
/** @return array{0: array, 1: ?array} */
public static function next(array $s, ?array $reply = null, bool $timeout = false): array
{
$names = array_keys(self::STEPS);
$i = array_search($s['current_step'], $names, true);
if ($i === false || $s['attempts'] < 0) { throw new InvalidArgumentException('Invalid persisted saga state'); }
if (!in_array($s['status'], ['running', 'compensating'], true)) { return [$s, null]; }
$action = $s['status'] === 'compensating' ? 'undo' : 'do';
if (!$timeout) {
if ($reply === null || !isset($reply['saga_id'], $reply['step'], $reply['action'], $reply['ok']) || !is_bool($reply['ok'])) {
throw new InvalidArgumentException('Invalid reply contract');
}
if ($reply['saga_id'] !== $s['id'] || $reply['step'] !== $s['current_step'] || $reply['action'] !== $action) { return [$s, null]; }
}
if ($timeout || ($s['status'] === 'compensating' && !$reply['ok']) || ($s['status'] === 'running' && $i === 2 && !$reply['ok'])) {
$s['attempts']++;
if ($s['attempts'] < self::MAX_ATTEMPTS) { return [$s, self::command($s, $action)]; }
if ($timeout && $s['status'] === 'running' && $i < 2) {
$s['failure_reason'] = 'timeout: outcome unknown';
return self::undoFrom($s, $i); // include silent step, not only completed steps
}
$s['status'] = 'stuck'; $s['failure_reason'] = $reply['reason'] ?? 'attempt budget exhausted';
return [$s, null];
}
if ($s['status'] === 'running' && $reply['ok']) {
$s['attempts'] = 0;
if ($i === count($names)-1) { $s['status'] = 'completed'; return [$s, null]; }
$s['current_step'] = $names[$i+1];
return [$s, self::command($s, 'do')];
}
if ($s['status'] === 'running') { $s['failure_reason'] = $reply['reason'] ?? 'business rejection'; }
return self::undoFrom($s, $i-1);
}
private static function undoFrom(array $s, int $i): array
{
$s['attempts'] = 0;
if ($i < 0) { $s['status'] = 'compensated'; return [$s, null]; }
$s['status'] = 'compensating'; $s['current_step'] = array_keys(self::STEPS)[$i];
return [$s, self::command($s, 'undo')];
}
public static function command(array $s, string $action): array
{
return ['saga_id'=>$s['id'], 'step'=>$s['current_step'], 'action'=>$action, 'attempt'=>$s['attempts'], 'payload'=>$s['payload']];
}
}<?php
namespace App\Sagas\Messaging;
use App\Models\Order;
use App\Models\Saga;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\DB;
/** Durable state plus a durable deadline. See outbox-pattern for atomic publication. */
final class SagaOrchestrator
{
public function __construct(private SagaTransport $transport) {}
public function start(Order $order): Saga
{
return DB::transaction(function () use ($order) {
$saga = Saga::create([
'type'=>'create_order_messages', 'status'=>'running', 'version'=>0, 'attempts'=>0,
'payload'=>$order->only(['sku','qty','total_cents'])+['order_id'=>$order->id],
'completed_steps'=>[], 'current_step'=>'reserve-stock', 'deadline_at'=>$this->deadline(),
]);
$command = Definition::command($this->state($saga), 'do');
// The committed deadline is the recovery mechanism if this callback is lost.
DB::afterCommit(fn () => $this->send($command));
return $saga;
});
}
public function onReply(array $reply): void
{
if (!isset($reply['saga_id'])) { throw new \InvalidArgumentException('Missing saga id'); }
DB::transaction(function () use ($reply) {
$saga=Saga::whereKey($reply['saga_id'])->where('type','create_order_messages')->lockForUpdate()->first();
if ($saga===null) { return; }
$old=$this->state($saga);
[$next,$command]=Definition::next($old,$reply);
$this->persist($saga,$old,$next,$command);
});
}
/** Recheck under the lock: a stale sweeper candidate cannot expire a fresh step. */
public function expire(string $id): void
{
DB::transaction(function () use ($id) {
$saga=Saga::whereKey($id)->where('type','create_order_messages')->whereIn('status',['running','compensating'])
->where('deadline_at','<',DB::raw('CURRENT_TIMESTAMP'))->lockForUpdate()->first();
if ($saga===null) { return; }
$old=$this->state($saga);
[$next,$command]=Definition::next($old,timeout:true);
$this->persist($saga,$old,$next,$command);
});
}
private function persist(Saga $saga,array $old,array $next,?array $command): void
{
if ($next===$old && $command===null) { return; }
$version=$saga->version+1;
$saga->update([
'status'=>$next['status'], 'current_step'=>$next['current_step'], 'attempts'=>$next['attempts'],
'failure_reason'=>$next['failure_reason']??null,'version'=>$version,'deadline_at'=>$this->deadline(),
]);
DB::table('saga_steps')->insert([
'saga_id'=>$saga->id,'version'=>$version,'step'=>$next['current_step'],
'from_status'=>$old['status'],'to_status'=>$next['status'],'attempts'=>$next['attempts'],
'reason'=>$next['failure_reason']??null,'created_at'=>DB::raw('CURRENT_TIMESTAMP'),
]);
if (in_array($next['status'],['completed','compensated'],true)) {
Order::whereKey($saga->payload['order_id'])->update(['status'=>$next['status']==='completed'?'approved':'rejected']);
}
if ($command!==null) { DB::afterCommit(fn () => $this->send($command)); }
}
private function state(Saga $s): array
{
return ['id'=>(string)$s->id,'status'=>$s->status,'current_step'=>$s->current_step,
'attempts'=>(int)$s->attempts,'failure_reason'=>$s->failure_reason,'payload'=>$s->payload];
}
private function deadline(): CarbonImmutable
{
// PostgreSQL clock, shared with the sweeper; 30 s is this example's policy.
return CarbonImmutable::parse(DB::selectOne('SELECT CURRENT_TIMESTAMP AS clock')->clock)->addSeconds(30);
}
public function send(array $command): void
{
$this->transport->send(Definition::STEPS[$command['step']],$command);
}
}<?php
namespace App\Sagas\Messaging;
use Illuminate\Support\Facades\DB;
final class Participant
{
/** Runs a command once per idempotency key; a duplicate gets the same reply again. */
public static function run(array $command, StepWork $work): array
{
$key = "{$command['saga_id']}:{$command['step']}:{$command['action']}";
return DB::transaction(function () use ($key, $command, $work) {
$seen = DB::table('saga_inbox')->where('key', $key)->value('reply');
if ($seen !== null) {
return json_decode($seen, true);
}
$reply = [
'saga_id' => $command['saga_id'], 'step' => $command['step'], 'action' => $command['action'],
] + $work($command);
// A concurrent duplicate fails on the primary key and rolls back
// its local work with it.
DB::table('saga_inbox')->insert(['key' => $key, 'reply' => json_encode($reply), 'created_at' => now()]);
return $reply;
});
}
}<?php
namespace App\Sagas\Messaging;
interface StepWork
{
/** Local work only (same DB connection), returns ['ok' => bool, 'reason' => ?string]. */
public function __invoke(array $command): array;
}
// app/Sagas/Messaging/SagaOrchestrator.php<?php
namespace App\Sagas\Messaging;
interface SagaTransport
{
/** @param array{saga_id: string, step: string, action: string, payload: array} $command */
public function send(string $participant, array $command): void;
}
// app/Sagas/Messaging/StepWork.php — bound per participant app.<?php
namespace App\Http\Controllers;
use App\Models\Order;
use App\Sagas\Messaging\SagaOrchestrator;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
final class MessagingOrderController
{
public function store(Request $request,SagaOrchestrator $sagas): JsonResponse
{
$data=$request->validate(['sku'=>['required','string'],'qty'=>['required','integer','min:1'],'total_cents'=>['required','integer','min:1']]);
$saga=DB::transaction(function () use ($data,$sagas) {
$order=Order::create($data+['status'=>'pending']);
return $sagas->start($order);
});
return response()->json(['saga_id'=>$saga->id,'status'=>'pending'],202);
}
}<?php
use App\Models\Saga;
use App\Sagas\Messaging\SagaOrchestrator;
use Illuminate\Support\Facades\Schedule;
Schedule::call(function () {
Saga::where('type','create_order_messages')->whereIn('status',['running','compensating'])->where('deadline_at','<',\Illuminate\Support\Facades\DB::raw('CURRENT_TIMESTAMP'))
->select('id')->lazy()->each(fn (Saga $s) => app(SagaOrchestrator::class)->expire($s->id));
})->everyTenSeconds();
// Multiple schedulers are safe: expire() rechecks under a DB row lock.این نسخه بازیابی با deadline را عمداً نشان میدهد: DB::afterCommit جلوی ارسال پیش از commit را میگیرد، اما انتشار اتمی نیست. اگر callback از دست برود، deadline ذخیرهشده باعث resend یا compensation در expire() میشود. برای قصد انتشار پایدار بدون انتظار تا timeout، transactional outbox لازم است. controller سفارش و ساگای آغازین را در یک تراکنش میسازد. فراخوانی HTTP خارجی نباید داخل تراکنش محلی StepWork اجرا شود.
نگاه Laravel
فهرست مستند Laravel میگوید: «including the database, Amazon SQS, Redis, and Beanstalkd drivers». driver نوع null هم job را دور میریزد.
Laravel 13 گزینههای صف database، Redis، SQS، Beanstalkd و اجرای synchronous/background دارد؛ RabbitMQ و Kafka بستهٔ جدا میخواهند. driver صف Redis از list و sorted set استفاده میکند، نه Redis Streams. قرارداد ShouldBeUnique با قفل cache از dispatch تکراری میکاهد؛ جای inbox یا کلید همتوانی پرداخت را نمیگیرد. مدت قفل باید با زمان اجرا و retry سازگار باشد.
<?php
namespace App\Sagas\Messaging;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\UniqueFor;
use Illuminate\Queue\Attributes\Tries;
use Throwable;
/** Optional standalone job; dispatch uniqueness reduces work, it is not the inbox. */
#[UniqueFor(60)]
#[Tries(5)]
final class ExecuteStep implements ShouldQueue, ShouldBeUnique
{
use Queueable;
public function __construct(public array $command) {}
public function uniqueId(): string { return $this->command['saga_id'].':'.$this->command['step'].':'.$this->command['action']; }
public function handle(StepWork $work, ReplyPublisher $publisher): void
{
$publisher->publish(Participant::run($this->command,$work));
}
public function failed(?Throwable $e): void
{
// Do NOT fabricate a business rejection after an ambiguous effect.
// No reply: the persisted orchestrator deadline triggers compensation or Stuck.
logger()->error('Saga participant exhausted retries',['key'=>$this->uniqueId(),'error'=>$e?->getMessage()]);
}
}<?php
namespace App\Sagas\Messaging;
interface ReplyPublisher { public function publish(array $reply): void; }Bus::chain برای ترتیب jobها مفید است، اما failure callback آن موتور کامل ساگا نیست. طرح chain همراه، گام درحال اجرا را پیش از تماس ثبت میکند، گام مبهم را هم جبران میکند و completion را شرطی کرده است. برای پنجرهٔ dispatch همچنان reconciliation برنامهٔ میزبان لازم دارد؛ نمونهٔ message-driven برای تحلیل گذار پایدار روشنتر است.
دو نسخه با نوعهای create_order_chain و create_order_messages جدا شدهاند. sweeper و handler پیام فقط نوع message-driven را میپذیرند؛ chain به مسیر reconciliation خودش نیاز دارد. موفقیت دیررسِ job تکراری تنها در compensating یا compensated جبران میشود؛ در completed یا stuck نباید خودکار سفارش تأییدشده را refund کرد.
<?php
namespace App\Sagas;
use App\Models\Order;
use App\Models\Saga;
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Facades\DB;
use Throwable;
final class CreateOrderSaga
{
/** @var array<string, class-string<SagaStep>> */
private const STEPS = [
'reserve-stock' => ReserveStock::class,
'charge-payment' => ChargePayment::class,
'schedule-shipment' => ScheduleShipment::class,
];
private const PIVOT = 'charge-payment';
public static function step(string $name, string $sagaId): SagaStep
{
$class = self::STEPS[$name];
return new $class($sagaId);
}
public function start(Order $order): Saga
{
$saga = Saga::create([
'type' => 'create_order_chain',
'status' => 'running',
'payload' => $order->only(['sku', 'qty', 'total_cents']) + ['order_id' => $order->id],
'completed_steps' => [],
'deadline_at' => now()->addMinutes(15),
]);
$sagaId = $saga->id;
$jobs = array_map(fn (string $class) => new $class($sagaId), array_values(self::STEPS));
$jobs[] = static function () use ($sagaId) {
CreateOrderSaga::complete($sagaId);
};
Bus::chain($jobs)
->catch(static function (Throwable $e) use ($sagaId) {
// Serialized and run later by a worker: no $this in here.
CreateOrderSaga::onStepFailed($sagaId, $e->getMessage());
})
->dispatch();
return $saga;
}
public static function onStepFailed(string $sagaId, string $reason): void
{
$saga = Saga::whereKey($sagaId)->where('type','create_order_chain')->first();
if ($saga===null) { return; }
if (in_array(self::PIVOT, $saga->completed_steps, true)) {
// Past the point of no return: park it for a human, never undo.
Saga::whereKey($sagaId)->where('status','running')->update(['status' => 'stuck', 'failure_reason' => $reason]);
return;
}
CompensateCreateOrder::dispatch($sagaId, $reason);
}
public static function complete(string $sagaId): void
{
DB::transaction(function () use ($sagaId) {
$saga = Saga::whereKey($sagaId)->lockForUpdate()->firstOrFail();
if ($saga->type !== 'create_order_chain' || $saga->status !== 'running' || !in_array('schedule-shipment',$saga->completed_steps,true)) { return; }
$saga->update(['status' => 'completed']);
Order::whereKey($saga->payload['order_id'])->update(['status' => 'approved']);
});
}
}
// app/Http/Controllers/OrderController.php — answers 202, the saga runs on.<?php
namespace App\Sagas;
final class LateOutcomePolicy
{
public static function shouldCompensate(string $status): bool
{
return in_array($status, ['compensating', 'compensated'], true);
}
}<?php
namespace App\Sagas;
use App\Models\Saga;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\DB;
abstract class SagaStep implements ShouldQueue
{
use Queueable;
public function __construct(public string $sagaId) {}
abstract public static function name(): string;
// Calls the participant; must be idempotent under $key.
abstract protected function perform(Saga $saga, string $key): void;
// Semantic undo; must be idempotent and must cope with "undo before do".
abstract public function compensate(Saga $saga, string $key): void;
public function handle(): void
{
$saga = Saga::findOrFail($this->sagaId);
if ($saga->type !== 'create_order_chain' || $saga->status !== 'running' || in_array(static::name(), $saga->completed_steps, true)) {
return; // duplicate delivery, or the saga is already unwinding
}
// Record the in-flight step BEFORE the remote side can commit.
$saga = DB::transaction(function () {
$row=Saga::whereKey($this->sagaId)->lockForUpdate()->firstOrFail();
if ($row->type !== 'create_order_chain' || $row->status !== 'running' || in_array(static::name(), $row->completed_steps, true)) { return null; }
$row->update(['current_step'=>static::name(),'deadline_at'=>now()->addMinutes(15)]);
return $row;
});
if ($saga===null) { return; }
try {
// Never hold a row lock across a network call.
$this->perform($saga, "{$saga->id}:".static::name().':do');
} catch (StepRejected $e) {
$this->fail($e); // no retries: the chain's catch() runs now
return;
}
$recorded = DB::transaction(function () {
$saga = Saga::whereKey($this->sagaId)->lockForUpdate()->firstOrFail();
if ($saga->status !== 'running') {
// A late duplicate must never refund a completed or forward-recovery saga.
return LateOutcomePolicy::shouldCompensate($saga->status) ? 'undo' : 'ignore';
}
if (in_array(static::name(), $saga->completed_steps, true)) { return 'ignore'; }
$saga->update([
'completed_steps' => array_values(array_unique([...$saga->completed_steps, static::name()])),
'current_step' => static::name(),
'deadline_at' => now()->addMinutes(15),
]);
return true;
});
if ($recorded === 'undo') {
// A late success after compensation began: undo our own work.
$this->compensate($saga, "{$saga->id}:".static::name().':undo');
}
}
}
// app/Sagas/Steps.php — the three participants, each a step/compensation pair.<?php
namespace App\Sagas;
use App\Models\Order;
use App\Models\Saga;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\Backoff;
use Illuminate\Queue\Attributes\RetryFor;
use Illuminate\Support\Facades\DB;
use Throwable;
#[RetryFor(hours: 24)]
#[Backoff([10, 60, 300])]
final class CompensateCreateOrder implements ShouldQueue
{
use Queueable;
public function __construct(public string $sagaId, public string $reason) {}
public function handle(): void
{
$saga = DB::transaction(function () {
$saga = Saga::whereKey($this->sagaId)->lockForUpdate()->firstOrFail();
if ($saga->type !== 'create_order_chain') { return $saga; }
if ($saga->status === 'running' && in_array('charge-payment', $saga->completed_steps, true)) {
$saga->update(['status'=>'stuck','failure_reason'=>$this->reason]);
return $saga; // Recheck pivot under lock; failure selection may be stale.
}
if (in_array($saga->status, ['running', 'compensating'], true)) {
$saga->update(['status' => 'compensating', 'failure_reason' => $this->reason]);
}
return $saga;
});
if ($saga->type !== 'create_order_chain' || $saga->status !== 'compensating') {
return;
}
// Include the silent in-flight step: its remote effect may have committed.
// Undo must record a tombstone even when nothing exists yet.
$undo = array_values(array_unique([...$saga->completed_steps, ...($saga->current_step ? [$saga->current_step] : [])]));
foreach (array_reverse($undo) as $name) {
CreateOrderSaga::step($name, $saga->id)->compensate($saga, "{$saga->id}:{$name}:undo");
DB::transaction(function () use ($name) {
$saga = Saga::whereKey($this->sagaId)->lockForUpdate()->firstOrFail();
$saga->update(['completed_steps' => array_values(array_diff($saga->completed_steps, [$name])), 'current_step' => null]);
});
}
DB::transaction(function () use ($saga) {
Saga::whereKey($saga->id)->update(['status' => 'compensated']);
// The order left its semantic lock ("pending") for a final state.
Order::whereKey($saga->payload['order_id'])->update(['status' => 'rejected']);
});
}
public function failed(Throwable $e): void
{
// A compensation that cannot succeed is an incident, not a retry.
Saga::whereKey($this->sagaId)->update(['status' => 'stuck', 'failure_reason' => $e->getMessage()]);
}
}
// app/Sagas/CreateOrderSaga.php — the orchestrator-lite: a job chain.<?php
namespace App\Sagas;
use App\Models\Saga;
use Illuminate\Queue\Attributes\Backoff;
use Illuminate\Queue\Attributes\RetryFor;
use Illuminate\Queue\Attributes\Tries;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
#[Tries(5)]
#[Backoff([5, 30, 120])]
final class ChargePayment extends SagaStep
{
public static function name(): string
{
return 'charge-payment';
}
protected function perform(Saga $saga, string $key): void
{
$response = Http::withHeaders(['Idempotency-Key' => $key])->connectTimeout(2)->timeout(5)
->post(config('services.payments.url').'/charges', [
'charge_id' => $saga->id,
'amount' => $saga->payload['total_cents'],
]);
if ($response->status() === 402) {
throw new StepRejected('card declined');
}
$response->throw();
}
public function compensate(Saga $saga, string $key): void
{
$response=Http::withHeaders(['Idempotency-Key' => $key])->connectTimeout(2)->timeout(5)
->post(config('services.payments.url').'/refunds', ['charge_id' => $saga->id]);
// Contract: 404 records cancellation so a late charge is refused.
if ($response->status() !== 404) { $response->throw(); }
}
}
// After the pivot: retried for a day, never compensated.404 endpoint نمایشی refund یعنی مشارکتکننده لغو را ثبت کرده، حتی اگر charge هنوز وجود نداشته باشد. این قرارداد صریح نمونه است و قاعدهٔ عمومی API پرداخت نیست. برنامهٔ میزبان Order، جدولهای مشارکتکننده، bindingها، تنظیم broker و endpointهای HTTP را فراهم میکند. کلاسهای جدا را طبق namespaceهای App\... در host قرار دهید؛ هر فایل PHP یک namespace دارد.
تفاوتهای اجرا در brokerها
RabbitMQ
برای هر مشارکتکننده صف فرمان پایدار و برای coordinator صف پاسخ پایدار بسازید؛ نمونهٔ Go از quorum queue استفاده میکند. ack دستی پاسخ پس از commit وضعیت ساگا است. نتیجهٔ confirm از نظر nack و نتیجهٔ mandatory از نظر return بررسی میشود. فرستندهٔ Go انتشار را روی channel اختصاصی سری میکند تا buffer تکعضوی return با batch پر نشود. channel پس از timeout بسته و دوباره ساخته میشود تا confirmation دیررس به ارسال تازه نسبت داده نشود.
PublishWithContext در amqp091-go نوشتنِ آغازشده روی socket را قطع نمیکند؛ deadline نوشتن در سطح connection باید در برنامهٔ میزبان تنظیم شود. context بهتنهایی سقف سخت برای I/O این transport نیست.
// Package rabbitmq carries saga commands and replies over RabbitMQ: one
// durable command queue per participant, one reply queue for the
// orchestrator, and the saga id as the AMQP correlation id.
package rabbitmq
import (
"context"
"encoding/json"
"fmt"
"sync"
amqp "github.com/rabbitmq/amqp091-go"
"academy/saga-pattern/after/saga"
)
const ReplyQueue = "order-saga.replies"
type Transport struct {
ch *amqp.Channel
mu sync.Mutex
returns <-chan amqp.Return
}
func New(ch *amqp.Channel, participants ...string) (*Transport, error) {
for _, q := range append(participants, ReplyQueue) {
if q != ReplyQueue {
q += ".commands"
}
// durable=true, autoDelete=false, exclusive=false, noWait=false
if _, err := ch.QueueDeclare(q, true, false, false, false, amqp.Table{
"x-queue-type": "quorum",
}); err != nil {
return nil, err
}
}
// Publisher confirms: Send only returns after the broker took the message.
if err := ch.Confirm(false); err != nil {
return nil, err
}
return &Transport{ch: ch, returns: ch.NotifyReturn(make(chan amqp.Return, 1))}, nil
}
func (t *Transport) Send(ctx context.Context, participant string, cmd saga.Command) error {
t.mu.Lock()
defer t.mu.Unlock()
body, err := json.Marshal(cmd)
if err != nil {
return err
}
// The default exchange routes by queue name. One outstanding publish under
// mu ensures the return buffer cannot overflow. This channel must be dedicated.
// A timeout closes it: reconnect instead of attributing a late return to a new send.
conf, err := t.ch.PublishWithDeferredConfirmWithContext(ctx, "", participant+".commands", true, false,
amqp.Publishing{
ContentType: "application/json",
DeliveryMode: amqp.Persistent,
CorrelationId: cmd.SagaID, // ties the reply to the saga
ReplyTo: ReplyQueue, // where the participant answers
MessageId: cmd.IdempotencyKey(), // the participant's dedup key
Type: string(cmd.Action),
Body: body,
})
if err != nil {
return err
}
ok, err := conf.WaitContext(ctx)
if err != nil {
_ = t.ch.Close()
return err
}
if !ok {
return fmt.Errorf("broker nacked saga command")
}
select {
case r, open := <-t.returns:
if !open {
return fmt.Errorf("reply channel closed")
}
return fmt.Errorf("unroutable saga command: %d %s", r.ReplyCode, r.ReplyText)
default:
return nil
}
}
// Replies consumes the reply queue with manual acks: a reply is acked only
// after the saga row and the next command are committed.
func (t *Transport) Replies(ctx context.Context, handle func(context.Context, saga.Reply) error) error {
if err := t.ch.Qos(32, 0, false); err != nil {
return err
}
deliveries, err := t.ch.ConsumeWithContext(ctx, ReplyQueue, "orchestrator", false, false, false, false, nil)
if err != nil {
return err
}
for d := range deliveries {
var r saga.Reply
if err := json.Unmarshal(d.Body, &r); err != nil {
return fmt.Errorf("malformed reply remains unacked for operator repair: %w", err)
}
r.SagaID = d.CorrelationId
if err := handle(ctx, r); err != nil {
if nackErr := d.Nack(false, true); nackErr != nil {
return nackErr
}
return err
}
if err := d.Ack(false); err != nil {
return err
}
}
if ctx.Err() != nil {
return ctx.Err()
}
return fmt.Errorf("RabbitMQ reply consumer closed: reconnect")
}<?php
namespace App\Sagas\Messaging\RabbitMQ;
use App\Sagas\Messaging\Participant;
use App\Sagas\Messaging\SagaOrchestrator;
use App\Sagas\Messaging\SagaTransport;
use App\Sagas\Messaging\StepWork;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
final class RabbitTransport implements SagaTransport
{
public function send(string $participant, array $command): void
{
SagaCommand::dispatch($command)
->onConnection('rabbitmq')
->onQueue("{$participant}.commands");
}
}
// Runs in the participant service: php artisan queue:work rabbitmq --queue=inventory.commands<?php
namespace App\Sagas\Messaging\RabbitMQ;
use App\Sagas\Messaging\Participant;
use App\Sagas\Messaging\SagaOrchestrator;
use App\Sagas\Messaging\SagaTransport;
use App\Sagas\Messaging\StepWork;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
final class SagaCommand implements ShouldQueue
{
use Queueable;
public function __construct(public array $command) {}
public function handle(StepWork $work): void
{
$reply = Participant::run($this->command, $work);
SagaReply::dispatch($reply)
->onConnection('rabbitmq')
->onQueue('order-saga.replies');
}
}
// Runs in the order service: php artisan queue:work rabbitmq --queue=order-saga.replies<?php
namespace App\Sagas\Messaging\RabbitMQ;
use App\Sagas\Messaging\Participant;
use App\Sagas\Messaging\SagaOrchestrator;
use App\Sagas\Messaging\SagaTransport;
use App\Sagas\Messaging\StepWork;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
final class SagaReply implements ShouldQueue
{
use Queueable;
public function __construct(public array $reply) {}
public function handle(SagaOrchestrator $orchestrator): void
{
// The worker acks the message only after handle() returns.
$orchestrator->onReply($this->reply);
}
}adapter لاراول از vladimir-yuldashev/laravel-queue-rabbitmq و job سریالشده استفاده میکند. دو سمت کلاس job را میشناسند؛ producer خارجی به ادغام RabbitMQJob سفارشی نیاز دارد. در source بررسیشده، publishBasic به basic_publish واگذار میکند؛ موفقیت dispatch لاراول را معادل پروتکل confirm فرستندهٔ Go ندانید. deadline پایدار، فرمان یا پاسخ گمشده را دوباره درخواست میکند. برای تحویل سختگیرانهٔ outbox، publisher تأییدشونده و envelope سازگار فراهم کنید. Direct Reply-To پاسخ را at-most-once میدهد و نباید تنها مدرک پایدار پاسخ ساگا باشد. پاسخ malformed در Go unacked میماند تا repair شود؛ پیش از اجرای بینظارت سیاست parking صریح بسازید.
Kafka
داخل هر topic فرمان/پاسخ از saga id بهعنوان key استفاده کنید. این کار رکوردهای یک ساگا را در partition همان topic میگذارد، اما میان topicهای مشارکتکننده ترتیب کلی نمیسازد. مصرفکنندهٔ Go auto commit را غیرفعال میکند، در شکست متوقف میشود و client را میبندد تا client تازه از offset commitشده شروع کند. تکرار poll loop روی همان client ممکن است از موقعیت محلیِ قبلاً fetchشده جلو برود. زمان handler باید داخل بودجهٔ rebalance بماند.
// Package kafka carries saga commands and replies over Kafka: one command
// topic per participant, one reply topic, and the saga id as the record key
// so every message of one saga lands in one partition WITHIN EACH TOPIC. Different topics have no shared order.
package kafka
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/twmb/franz-go/pkg/kgo"
"academy/saga-pattern/after/saga"
)
const ReplyTopic = "order-saga.replies"
type Transport struct {
cl *kgo.Client
}
func New(brokers ...string) (*Transport, error) {
cl, err := kgo.NewClient(
kgo.SeedBrokers(brokers...),
kgo.RequiredAcks(kgo.AllISRAcks()),
kgo.ConsumerGroup("order-saga-orchestrator"),
kgo.ConsumeTopics(ReplyTopic),
kgo.BlockRebalanceOnPoll(),
kgo.DisableAutoCommit(), // commit only after the saga row is committed
)
if err != nil {
return nil, err
}
return &Transport{cl: cl}, nil
}
func (t *Transport) Close() { t.cl.Close() }
func (t *Transport) Send(ctx context.Context, participant string, cmd saga.Command) error {
body, err := json.Marshal(cmd)
if err != nil {
return err
}
rec := &kgo.Record{
Topic: participant + ".commands",
Key: []byte(cmd.SagaID), // same saga, same partition, same order
Value: body,
Headers: []kgo.RecordHeader{
{Key: "reply-topic", Value: []byte(ReplyTopic)},
{Key: "idempotency-key", Value: []byte(cmd.IdempotencyKey())},
},
}
return t.cl.ProduceSync(ctx, rec).FirstErr()
}
// Replies polls the reply topic. Offsets are committed after the batch is
// handled, so a crash replays replies, which the state machine ignores
// when they no longer match the step in flight.
// Replies owns the client lifecycle: after any exit, create a NEW Transport.
// Handler time must remain below the rebalance timeout.
func (t *Transport) Replies(ctx context.Context, handle func(context.Context, saga.Reply) error) error {
defer t.cl.CloseAllowingRebalance()
for {
fetches := t.cl.PollFetches(ctx)
if fetches.IsClientClosed() || ctx.Err() != nil {
return ctx.Err()
}
var errs []error
fetches.EachError(func(_ string, _ int32, err error) { errs = append(errs, err) })
if len(errs) > 0 {
return errors.Join(errs...)
}
var handleErr error
fetches.EachRecord(func(r *kgo.Record) {
if handleErr != nil {
return
}
var reply saga.Reply
if err := json.Unmarshal(r.Value, &reply); err != nil {
handleErr = fmt.Errorf("malformed reply %s/%d/%d requires repair: %w", r.Topic, r.Partition, r.Offset, err)
return
}
reply.SagaID = string(r.Key)
handleErr = handle(ctx, reply)
})
if handleErr != nil {
// Do not commit: the group re-reads from the last commit on restart.
return handleErr
}
if err := t.cl.CommitUncommittedOffsets(ctx); err != nil {
return err
}
t.cl.AllowRebalance()
}
}<?php
namespace App\Sagas\Messaging\Kafka;
use App\Sagas\Messaging\SagaTransport;
use Junges\Kafka\Facades\Kafka;
use Junges\Kafka\Message\Message;
final class KafkaTransport implements SagaTransport
{
public function send(string $participant, array $command): void
{
$sent = Kafka::publish(config('services.kafka.brokers'))
->onTopic("{$participant}.commands")
->withMessage(new Message(
headers: ['reply-topic' => 'order-saga.replies'],
body: $command,
key: $command['saga_id'],
))
->send();
if (!$sent) { throw new \RuntimeException("Kafka publish not confirmed"); }
}
}
// app/Console/Commands/ConsumeSagaReplies.php — run under a process monitor.<?php
namespace App\Console\Commands;
use App\Sagas\Messaging\SagaOrchestrator;
use Illuminate\Console\Command;
use Junges\Kafka\Contracts\ConsumerMessage;
use Junges\Kafka\Contracts\MessageConsumer;
use Junges\Kafka\Facades\Kafka;
final class ConsumeSagaReplies extends Command
{
protected $signature = 'saga:consume-replies';
protected $description = 'Drive the order saga from the order-saga.replies topic.';
public function handle(SagaOrchestrator $orchestrator): void
{
Kafka::consumer(['order-saga.replies'], 'order-saga-orchestrator', config('services.kafka.brokers'))
->withManualCommit()->stopOnFailure()
->withHandler(function (ConsumerMessage $message, MessageConsumer $consumer) use ($orchestrator) {
$body = $message->getBody();
$orchestrator->onReply(is_array($body) ? $body : json_decode($body, true, 512, JSON_THROW_ON_ERROR));
// Commit the offset only after the saga row is committed.
$consumer->commit($message);
})
->build()
->consume();
}
}
// app/Console/Commands/ConsumeInventoryCommands.php — in the inventory service.<?php
namespace App\Console\Commands;
use App\Sagas\Messaging\Participant;
use App\Sagas\Messaging\StepWork;
use Illuminate\Console\Command;
use Junges\Kafka\Contracts\ConsumerMessage;
use Junges\Kafka\Contracts\MessageConsumer;
use Junges\Kafka\Facades\Kafka;
use Junges\Kafka\Message\Message;
final class ConsumeInventoryCommands extends Command
{
protected $signature = 'saga:consume-inventory';
protected $description = 'Run saga commands addressed to the inventory service.';
public function handle(StepWork $work): void
{
$brokers = config('services.kafka.brokers');
Kafka::consumer(['inventory.commands'], 'inventory', $brokers)
->withManualCommit()->stopOnFailure()
->withHandler(function (ConsumerMessage $message, MessageConsumer $consumer) use ($work, $brokers) {
$body = $message->getBody();
$reply = Participant::run(is_array($body) ? $body : json_decode($body, true, 512, JSON_THROW_ON_ERROR), $work);
$sent = Kafka::publish($brokers)
->onTopic('order-saga.replies')
->withMessage(new Message(body: $reply, key: $reply['saga_id']))
->send();
if (!$sent) { throw new \RuntimeException("Kafka publish not confirmed"); }
$consumer->commit($message);
})
->build()
->consume();
}
}Laravel از mateusjunges/laravel-kafka، withManualCommit() و stopOnFailure() استفاده میکند. commit پس از مدیریت وضعیت باشد و نتیجهٔ تحویل producer بررسی شود. تراکنش Kafka شامل وضعیت PostgreSQL ساگا یا charge خارجی نیست. retention باید زمان بازیابی را پوشش دهد؛ compaction وضعیت جای audit log گذارها را نمیگیرد.
Redis Streams
فرمانها stream جدا برای هر مشارکتکننده و پاسخها consumer group دارند. group نمونه از 0 ساخته میشود تا پاسخ موجود را ببیند؛ ack بعد از گذار است و XAUTOCLAIM با cursor برگشتی پیمایش میشود. زمان reclaim آستانهٔ idle عملیاتی است؛ deadline ساگا آستانهٔ بازیابی کسبوکار است. این دو را مستقل تنظیم کنید.
// Package redisstreams carries saga commands and replies over Redis Streams:
// one stream per participant's commands, one reply stream, and a consumer
// group so several orchestrator instances share the replies.
package redisstreams
import (
"context"
"encoding/json"
"errors"
"strings"
"time"
"github.com/redis/go-redis/v9"
"academy/saga-pattern/after/saga"
)
const (
ReplyStream = "order-saga:replies"
Group = "orchestrator"
)
type Transport struct {
rdb *redis.Client
consumer string // unique per process incarnation, not a shared hostname
}
func New(rdb *redis.Client, consumer string) *Transport {
return &Transport{rdb: rdb, consumer: consumer}
}
func (t *Transport) Send(ctx context.Context, participant string, cmd saga.Command) error {
body, err := json.Marshal(cmd)
if err != nil {
return err
}
return t.rdb.XAdd(ctx, &redis.XAddArgs{
Stream: participant + ":commands",
// Retention is an operator policy: do not trim unresolved commands blindly.
Values: map[string]any{
"saga_id": cmd.SagaID,
"idempotency_key": cmd.IdempotencyKey(),
"reply_stream": ReplyStream,
"body": body,
},
}).Err()
}
// Replies reads with XREADGROUP and acknowledges with XACK after handle
// succeeds. Unacked entries stay in the pending entries list; a reclaimer
// (XAUTOCLAIM) picks them up if this consumer dies.
func (t *Transport) Replies(ctx context.Context, handle func(context.Context, saga.Reply) error) error {
err := t.rdb.XGroupCreateMkStream(ctx, ReplyStream, Group, "0").Err()
if err != nil && !strings.HasPrefix(err.Error(), "BUSYGROUP") {
return err
}
for ctx.Err() == nil {
streams, err := t.rdb.XReadGroup(ctx, &redis.XReadGroupArgs{
Group: Group,
Consumer: t.consumer,
Streams: []string{ReplyStream, ">"},
Count: 32,
Block: 5 * time.Second,
}).Result()
if errors.Is(err, redis.Nil) {
continue // block timed out, nothing new
}
if err != nil {
return err
}
for _, s := range streams {
for _, msg := range s.Messages {
body, _ := msg.Values["body"].(string)
var r saga.Reply
if err := json.Unmarshal([]byte(body), &r); err != nil {
continue // malformed: leave it pending for inspection
}
if err := handle(ctx, r); err != nil {
continue // not acked: stays in the PEL and is retried
}
if err := t.rdb.XAck(ctx, ReplyStream, Group, msg.ID).Err(); err != nil {
return err
}
}
}
}
return ctx.Err()
}
// Reclaim takes over replies that another orchestrator instance read but
// never acknowledged (it crashed mid-transition). Run it on a ticker in
// every instance; MinIdle must exceed the slowest normal transition.
func (t *Transport) Reclaim(ctx context.Context, handle func(context.Context, saga.Reply) error) error {
start := "0-0"
for {
msgs, next, err := t.rdb.XAutoClaim(ctx, &redis.XAutoClaimArgs{
Stream: ReplyStream,
Group: Group,
Consumer: t.consumer,
MinIdle: time.Minute,
Start: start,
Count: 32,
}).Result()
if err != nil {
return err
}
for _, msg := range msgs {
body, _ := msg.Values["body"].(string)
var r saga.Reply
if json.Unmarshal([]byte(body), &r) != nil || handle(ctx, r) != nil {
continue
}
if err := t.rdb.XAck(ctx, ReplyStream, Group, msg.ID).Err(); err != nil {
return err
}
}
if next == "0-0" {
return nil // scanned the whole pending entries list
}
start = next
}
}<?php
namespace App\Sagas\Messaging\Redis;
use App\Sagas\Messaging\SagaTransport;
use Illuminate\Support\Facades\Redis;
final class RedisStreamsTransport implements SagaTransport
{
public function send(string $participant, array $command): void
{
$id=Redis::xadd("{$participant}:commands", '*', [
'saga_id' => $command['saga_id'],
'reply_stream' => 'order-saga:replies',
'body' => json_encode($command),
]);
if ($id===false) { throw new \RuntimeException("XADD failed"); }
}
}
// app/Console/Commands/ConsumeSagaRepliesFromStream.php<?php
namespace App\Console\Commands;
use App\Sagas\Messaging\SagaOrchestrator;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;
use Throwable;
final class ConsumeSagaRepliesFromStream extends Command
{
protected $signature='saga:consume-replies-redis';
protected $description='Consume and reclaim saga replies (phpredis client).';
public function handle(SagaOrchestrator $orchestrator): void
{
$stream='order-saga:replies';$group='orchestrator';$consumer=gethostname().'-'.getmypid().'-'.bin2hex(random_bytes(4));
try { Redis::xgroup('CREATE',$stream,$group,'0',true); }
catch (Throwable $e) { if (!str_contains($e->getMessage(),'BUSYGROUP')) { throw $e; } }
$cursor='0-0';$running=true;
$this->trap([SIGTERM,SIGINT],function () use (&$running) { $running=false; });
while ($running) {
$claimed=Redis::xautoclaim($stream,$group,$consumer,60000,$cursor,32);
if ($claimed===false) { throw new \RuntimeException('XAUTOCLAIM failed'); }
$cursor=$claimed[0];$this->apply($orchestrator,$stream,$group,$claimed[1]??[]);
$batch=Redis::xreadgroup($group,$consumer,[$stream=>'>'],32,1000);
// The facade may prefix returned keys; iterate values, not $batch[$stream].
foreach ($batch?:[] as $messages) { $this->apply($orchestrator,$stream,$group,$messages); }
}
}
private function apply(SagaOrchestrator $orchestrator,string $stream,string $group,array $messages): void
{
foreach ($messages as $id=>$fields) {
try { $orchestrator->onReply(json_decode($fields['body'],true,512,JSON_THROW_ON_ERROR)); }
catch (Throwable $e) { report($e); continue; } // pending; repair poison replies explicitly
if (Redis::xack($stream,$group,[$id])===false) { throw new \RuntimeException('XACK failed'); }
}
}
}worker PHP ترتیب آرگومان phpredis را هدف میگیرد، هویت یکتای هر اجرای consumer دارد و بهجای فرض کلید بیprefix، valueهای stream برگشتی را میخواند. timeout کلاینت باید از blocking read محدود بیشتر باشد. فرمان حلنشده را صرفاً بهخاطر بزرگی stream trim نکنید؛ ممکن است body مورد اشارهٔ PEL حذف شود. تنظیم persistence/failover مرز دوام Redis را تعیین میکند؛ موفقیت XADD تضمین نامشروط دیسک نیست.
در سیستمهای واقعی
| رفتار قابل بررسی | پیامد طراحی |
|---|---|
| تراکنش و قفل PostgreSQL تغییر محلی را کنترل میکنند | I/O خارجی را بیرون قفل تراکنش مشارکتکننده نگه دارید |
| confirm و consumer ack در RabbitMQ جدا هستند | تأیید فرمان، نتیجهٔ کسبوکار ساگا نیست |
| offset مصرفکنندهٔ Kafka موقعیت replay را تعیین میکند | ثبت پیش از commit و handler همتوان لازم است |
| PEL در Redis با دوام تنظیمشده از مرگ consumer عبور میکند | delivery را reclaim کنید، وضعیت کسبوکار را جدا نگه دارید |
| jobهای Laravel retry و exhaustion دارند | failure hook باید ابهام outcome را برای بازیابی حفظ کند |
| NATS JetStream، Pulsar و SQS سازوکار ack/replay خود را دارند | جبران کسبوکار را خودکار نمیسازند؛ Other Brokers |
در معماری: از یک فرایند تا سامانهٔ توزیعشده
مونولیت (Monolith)
اگر موجودی، سفارش و balance واقعاً یک دیتابیس و مالک دارند، تراکنش محلی سادهتر است. درگاه پرداخت خارجی حتی در یک process مرز سازگاری دیگری میسازد. runner درونفرایندی ترتیب را نشان میدهد؛ اگر crash نباید پیشرفت را پاک کند، Store پایدار لازم است.
مونولیت ماژولار (Modular monolith)
ماژولها میتوانند با interface فرمان مبادله و از جدول ساگای پایدار استفاده کنند. سفارش PENDING قفل معنایی برای دیگر ماژولها است؛ ماژول دیگر نباید با update بیشرط آن را دور بزند. دیتابیس جدا یا تأمینکنندهٔ خارجی همان سیاست بازیابی microservice را لازم دارد.
میکروسرویسها (Microservices)
Order مالک هماهنگی، Inventory مالک رزرو، Payments مالک شناسهٔ provider و Shipping مالک وضعیت ارسال است. فرمان saga id، step، action و payload تغییرناپذیر دارد. هر مشارکتکننده اثر محلی و نتیجهٔ dedup را commit و سپس reply میکند؛ فرمان تکراری همان نتیجهٔ منطقی را میگیرد. منطق دامنه را به coordinator منتقل نکنید.
1 POST /orders -> Order PENDING + Saga + outgoing intent -> 202
2 Inventory command -> reservation + inbox -> reply
3 Order transition -> payment command -> payment result
4 Order pivot decision -> shipping command
5 Final reply -> Order APPROVED; client polls status or receives notificationدادهٔ توزیعشده (Distributed data)
replica عقبمانده ممکن است پس از completion روی primary هنوز PENDING نشان دهد؛ تصمیم را از وضعیت مرجع بگیرید. نویسندههای فعال چندمنطقهای برای هر ساگا به single-writer/consensus یا حل تعارض واقعی نیاز دارند. اختلاف ساعت host میتواند گام را زود expire کند؛ به همین دلیل نمونه از ساعت دیتابیس استفاده میکند. failover ممکن است فرمان را تکرار یا ack با دوام ضعیفتر را گم کند؛ کلید پایدار و reconciliation همچنان لازماند. Replication و Distributed SQL جزئیات را دارند.
مسیر مقیاس (Scaling path)
| بار / پیچیدگی | تغییر | چیزی که باید حفظ شود |
|---|---|---|
| گردش کوچک | یک worker و دیتابیس پایدار | وضعیت و مالک بازیابی صریح |
| ساگاهای همزمان بیشتر | worker بیشتر، index deadline و batch کوچک | سریسازی گذار یک ساگا |
| فشار broker/DB | تقسیم با saga id، محدودیت in-flight و batch | fencing میان do/undo و همتوانی مشارکتکننده |
| timer و شاخهٔ طولانی زیاد | اجرای پایدار workflow | جبران و نسخهٔ تعریف کسبوکار |
| چند منطقه | مالکیت ساگا و سیاست failover | یک تاریخچهٔ مرجع گذار |
آزمایشگاه: تجربههای شکست
همهٔ سناریوهای این بخش expected, not run هستند. Docker یا cluster راهاندازی نشده است. compile و unit check میزبان جدا در HANDOFF ثبت میشود. آزمایش دیتابیس/broker به محیط توسعهٔ ازپیشآماده و مشارکتکنندههای پیادهشده توسط خواننده نیاز دارد.
cd docs/snippets/messaging/saga-pattern/go
# expected, not run: pure state-machine scenarios pass without brokers
go test ./after/saga -v
# expected, not run: first demo compensates; second completes
go run ./inprocess
# expected, not run: in-memory choreography shows approve/reject paths
go run ./choreography| آزمایش | اقدام | نتیجهٔ مورد انتظار، اجرا نشده |
|---|---|---|
| رد کسبوکار | reply false برای charge-payment | آزادسازی stock؛ برای رد قطعیِ بدون commit، refund نداریم |
| پاسخ charge گمشده | charge ثبت شود، پاسخ تا پایان budget پنهان بماند | do با همان کلید retry و خود charge هم safely undo شود |
| شکست جبران | همهٔ undoها رد شوند | وضعیت Stuck؛ stock بهدروغ آزاد اعلام نشود |
| پاسخ تکراری | StockReserved دو بار پس از پیشرفت برسد | version برای آن گذار یکبار افزایش یابد |
| مرگ مصرفکنندهٔ پاسخ | پس از commit ساگا و پیش از ack کشته شود | redelivery اثر وضعیت را تکرار نکند |
| sweeper قدیمی | candidate منقضی انتخاب، سپس پاسخ معتبر قبل از قفل expire پردازش شود | deadline تازه بررسی و timeout قدیمی رد شود |
| undo پیش از do | tombstone آزادسازی، سپس reservation دیررس | do رد و stock ثابت بماند |
-- Reader-provisioned PostgreSQL; run after loading the sample schema.
SELECT id,status,step,attempts,version,deadline_at FROM sagas ORDER BY id;
SELECT saga_id,version,step,from_status,to_status FROM saga_steps ORDER BY saga_id,version;
SELECT count(*) FROM saga_outbox WHERE published_at IS NULL;
-- expected, not run: committed transitions explain the current state;
-- unconfirmed outgoing commands remain eligible for relay/recovery.# In a configured Laravel 13 host application:
php artisan migrate
php artisan schedule:work
php artisan saga:consume-replies-redis
# expected, not run: expired running/compensating steps are retried or parked.
# To test the pure PHP decisions without Laravel:
php docs/snippets/messaging/saga-pattern/php/Tests/DefinitionTest.phpاثر پایدار مشارکتکننده را هم کنار ردیف ساگا بررسی کنید. آزمون state machine ثابت نمیکند درگاه payment tombstone را رعایت میکند، refund همتوان است یا تنظیم broker failover را تحمل میکند.
بدفهمیهای رایج
| باور | واقعیت |
|---|---|
| ساگا rollback توزیعشده است | پس از commitهای محلی تراکنش معنایی جدید اجرا میشود |
| جبران تاریخ را پاک میکند | refund و cancellation رویداد قابل مشاهدهاند |
| SERIALIZABLE محلی ساگا را serializable میکند | interleaving میان گامها باقی است |
| timeout یعنی شکست گام | اثر شاید commit شده باشد |
| هر شکست یعنی refund | سیاست پس از pivot ممکن است forward recovery بخواهد |
| redelivery جای ذخیرهٔ ساگا است | پیشرفت کسبوکار و ورودی جبران را بیان نمیکند |
| choreography coupling را حذف میکند | coupling را در قرارداد رویدادها پخش میکند |
| orchestrator باید یک process باشد | workerها میتوانند وضعیت پایدارِ سریشده را شریک شوند |
| ShouldBeUnique یعنی exactly-once | dispatch suppression محدود است، نه dedup اثر |
| publisher confirm یعنی سفارش تمام شد | پذیرش انتقال است، نه موفقیت کسبوکار |
| DLQ ساگای stuck را حل میکند | تحویل شکستخورده را نگه میدارد؛ بازیابی مالک میخواهد |
| با حذف ردیف incident حل میشود | شاید مدرک لازم برای تطبیق پول از بین برود |
چکیدهٔ کاربردی
| موضوع | به خاطر بسپارید |
|---|---|
| مرز | یک تراکنش محلی برای اثر مشارکتکننده |
| هویت | saga id ثابت و کلید جدا برای do/undo |
| وضعیت | step، جهت، attempts، deadline و version را ذخیره کنید |
| انتشار | state و outbox ترجیح دارد؛ gap بازیابیشونده با timer را صریح بگویید |
| پاسخ | commit گذار پیش از ack broker |
| timeout | outcome مبهم؛ رد کسبوکار نسازید |
| جبران | همتوان، دامنهمحور و شکستپذیر |
| pivot | مرز توقف بازگشت خودکار را تعیین کنید |
| جداسازی | قفل معنایی، delta، version و تاریخچهٔ عملیات |
| کار دیررس | وضعیت لغو پایدار جلوی do-after-undo را بگیرد |
| retention | افق replay، recovery و کلید provider پوشش داده شود |
| عملیات | سن open/stuck هشدار داشته باشد؛ با حقیقت مشارکتکننده تطبیق دهید |
| نسخهگذاری | تعریف لازم برای workflowهای باز حفظ شود |
| تست | شکست هر گام، تکرار و outcome مبهم را بررسی کنید |
خودآزمایی: پرسش و پاسخ
- حیاتی تقریباً در هر مصاحبه پرسیده میشود
- مهم پرتکرار؛ در سطح senior انتظار میرود
- تکمیلی عمق بیشتر؛ تمایز ایجاد میکند
۱ — چرا rollback محلی charge خارجی را برنمیگرداند؟ حیاتی
پاسخ
پاسخ: provider بیرون آن transaction commit کرده است؛ refund همتوان یا عملیات تطبیق جدا لازم است.
۲ — چرا باید reservation آزاد شود و نه عدد قدیمی stock برگردد؟ حیاتی
پاسخ
پاسخ: سفارشهای دیگر ممکن است stock را تغییر داده باشند. آزادسازی مقدار رزرو خودمان اثر همین ساگا را اصلاح میکند.
۳ — پرداخت ردشده و پرداخت timeoutشده چه تفاوتی دارند؟ مهم
پاسخ
پاسخ: رد قطعی نبود اثر forward را اعلام میکند. Timeout نتیجه را نامعلوم میگذارد و شاید استعلام، retry همان کلید یا لغو گام ساکت لازم باشد.
۴ — کدام سه فیلد پاسخ را به گذار جاری وصل میکنند؟ مهم
پاسخ
پاسخ: Saga id، step و action. operation key جدا retryها را به یک فرمان با payload ثابت متصل میکند.
۵ — چرا وقتی چیزی برای undo نیست باز هم tombstone لازم میشود؟ تکمیلی
پاسخ
پاسخ: فرمان forward ممکن است دیرتر برسد؛ وضعیت لغو پایدار از ساخت اثر پس از جبران جلوگیری میکند.
۶ — تراکنش Kafka آیا state در PostgreSQL و payment capture را اتمی میکند؟ حیاتی
پاسخ
پاسخ: خیر؛ محدودهٔ پشتیبانیشدهٔ Kafka شامل SQL دلخواه یا اثر provider خارجی نیست.
۷ — در نمونهٔ Laravel چه چیزی ارسال گمشدهٔ after-commit را بازیابی میکند؟ مهم
پاسخ
پاسخ: deadline ذخیرهشده و sweeper. این بازیابی با تأخیر است؛ afterCommit خودش outbox نیست.
۸ — پس از pivot اگر retry ارسال تمام شود چه میشود؟ مهم
پاسخ
پاسخ: ساگا Stuck و طبق سیاست از مسیر رو به جلو تطبیق میشود؛ refund خودکار امن فرض نشده است.
۹ — چرا گرفتن 23505 و commit همان transaction در PostgreSQL غلط است؟ مهم
پاسخ
پاسخ: تراکنش abort شده است؛ statement صریحِ conflict-safe یا rollback/retry لازم است.
۱۰ — آیا compensation همیشه دقیقاً به ترتیب معکوس اجرا میشود؟ تکمیلی
پاسخ
پاسخ: برای دنبالهٔ خطی وابسته مناسب است؛ وابستگی و ریسک واقعی شاید ترتیب دیگری بخواهد یا موازیسازی را مجاز کند.
واژهنامه
| اصطلاح | معنا |
|---|---|
| ساگا (Saga) | دنبالهٔ هماهنگ و بازیابیپذیر تراکنشهای محلی |
| تراکنش محلی (Local transaction) | commit اتمی در مرز یک مشارکتکننده |
| تراکنش بلندعمر (Long-lived transaction / LLT) | کاری که طول آن انگیزهٔ شکستن مرز تراکنش بود |
| مشارکتکننده (Participant) | مالک اثر محلی و قرارداد بازیابی آن |
| هماهنگسازی مرکزی (Orchestration) | انتخاب فرمان بعد توسط coordinator |
| هماهنگی رویدادی (Choreography) | اتصال واکنش مشارکتکنندهها با event |
| مدیر فرایند (Process Manager) | جزء دارای وضعیت که مسیر process را تصمیم میگیرد |
| جبران (Compensation) | تراکنش جدید برای اصلاح اثر قبلی |
| بازیابی رو به عقب (Backward recovery) | جبران پیشوند اجراشده |
| بازیابی رو به جلو (Forward recovery) | retry یا repair کارهای باقیمانده |
| جبرانپذیر (Compensable) | گامی با undo معنایی تعریفشده |
| نقطهٔ تعهد (Pivot) | مرز نیاز به forward recovery |
| قابل تلاش مجدد (Retryable) | سیاست اجرای تکراری با یک هویت عملیات |
| نتیجهٔ مبهم (Ambiguous outcome) | شاید اثر commit شده ولی نتیجه معلوم نیست |
| مهلت (Deadline) | زمان پایدار واجدشرایطشدن بازیابی |
| پایان انتظار (Timeout) | ندیدن completion در بودجهٔ زمان |
| قفل معنایی (Semantic lock) | وضعیت کسبوکار مانع گذار ناسازگار |
| تغییر جابجاپذیر (Commutative update) | delta با ترکیب حسابی مستقل از ترتیب |
| دید بدبینانه (Pessimistic view) | تعویق visibility پرریسک تا فاز retryable |
| بازخوانی مقدار (Reread values) | اعتبارسنجی خواندن قبلی پیش از write بعد |
| پروندهٔ نسخهها (Version file) | تاریخچهٔ عملیات برای اعمال ترتیب قانونی |
| بر پایهٔ ارزش (By value) | انتخاب قدرت هماهنگی بر اساس ریسک |
| بهروزرسانی گمشده (Lost update) | بازنویسی اثر یک عملیات توسط دیگری |
| خواندن کثیف ساگا (Dirty read at saga level) | خواندن وضعیت provisional که محلی commit شده |
| خواندن تکرارناپذیر (Nonrepeatable read) | مشاهدهٔ مقدار تغییرکرده در گامهای مختلف |
| کلید همتوانی (Idempotency key) | هویتی که retry را یک اثر منطقی میکند |
| صندوق ورودی (Inbox) | رکورد پایدار dedup و نتیجهٔ مشارکتکننده |
| صندوق خروجی (Outbox) | قصد انتشار پایدار همراه وضعیت محلی |
| نشان لغو (Tombstone) | واقعیت نگهداریشدهٔ لغو/پایان برای fencing دیررس |
| تاریخچهٔ هماهنگکننده (SEC log) | اطلاعات پایدار بازیابی اجرای ساگا |
| گیرکرده (Stuck) | توقف خودکار بازیابی و نیاز به مداخله |
| تطبیق (Reconciliation) | مقایسهٔ اثر مرجع مشارکتکننده با state فرایند |
| نسخهٔ تعریف (Definition version) | نسخهٔ قواعد گذار لازم برای کار باز |
| تأیید ناشر (Publisher confirm) | acknowledgement پذیرش سمت producer در RabbitMQ |
| تأیید مصرفکننده (Consumer acknowledgement) | settlement تحویل پس از پردازش |
| فهرست pending (PEL) | pending entries list در Redis Streams |
| پسگرفتن خودکار (XAUTOCLAIM) | انتقال مالکیت entryهای idle و pending در Redis |
| job یکتا (ShouldBeUnique) | قرارداد جلوگیری از dispatch تکراری با cache lock |
| مدت یکتایی (UniqueFor) | زمان قفل job یکتا در Laravel |
| پس از commit (afterCommit) | تعویق action تا commit؛ outbox نیست |
| قفل بهروزرسانی (FOR UPDATE) | قفل ردیف PostgreSQL برای سریسازی گذار |
| عبور از قفل (SKIP LOCKED) | ردشدن از ردیف قفلشده هنگام انتخاب کار |
منابع
- Garcia-Molina and Salem, Sagas (1987).
- Microsoft, Saga distributed transactions pattern and Compensating Transaction.
- Richardson, Saga pattern and developing sagas, part 1.
- EIP, Process Manager.
- PostgreSQL, SELECT and transaction isolation, explicit locking and SQLSTATE codes.
- RabbitMQ, confirms, Direct Reply-To and Go channel source.
- Apache Kafka, introduction and consumer configuration; franz-go consumer source.
- Redis, Streams and XAUTOCLAIM; phpredis command signatures.
- Laravel 13, queues, database, HTTP client, scheduling, Redis, UniqueFor source and queued handler source.
- RabbitMQ Laravel package, README and queue publisher source.
- Laravel Kafka, consumer builder, consumer and producer builder.