Skip to content

Service Communication: Sync vs Async, Contracts, Retries, Idempotency ​

"In general, our view is that APIs with side effects aren't safe to retry unless they provide idempotency." — Marc Brooker، Timeouts, retries, and backoff with jitter، Amazon Builders' Library

خلاصه (Summary): وقتی یک فراخوانی تابع به فراخوانی شبکه تبدیل می‌شود، هر تعامل چهار تصمیم لازم دارد: سبک (منتظر پاسخ بمانیم یا نه)، قرارداد (هر دو طرف چه قولی می‌دهند)، سیاست خطا (چقدر صبر کنیم و کی دوباره تلاش کنیم) و سیاست تکرار (اگر همان درخواست دو بار رسید چه شود). تمرکز (Focus): ماتریس سبک‌ها (sync request/response، async request/response، event notification، event-carried state transfer، stream)، ابعاد جفت‌شدگی، orchestration در برابر choreography، قراردادها (OpenAPI، Protobuf، AsyncAPI، Pact)، سازگاری و نسخه‌بندی، timeout و انتشار deadline، retry با backoff و jitter و بودجه، کلید idempotency، hedging، API composition و BFF، انتشار trace و معنای خطا، همراه با کد Go و Laravel و یک آزمایشگاه retry storm. هدف یادگیری (Learning goal): برای هر پیکان بین دو سرویس بتوانید سبک را انتخاب کنید و دلیلش را بگویید، قراردادش را بنویسید، به آن deadline و سیاست retry بدهید که طوفان نسازد، تکرارش را بی‌خطر کنید و همهٔ این‌ها را با contract test و تزریق خطا ثابت کنید.

این فصل در گروه Microservices in Practice است؛ بعد از مرزهای سرویس (کجا ببُریم) و پیش از API Gateway، BFF و Service Mesh (چه چیزی لبهٔ سیستم می‌نشیند). سطح این صفحه تصمیم معماری است و عمق را به صفحه‌های صاحب موضوع می‌سپارد: طراحی REST و gRPC و GraphQL در REST API Design، gRPC و Protobuf و GraphQL؛ brokerها، تضمین تحویل، outbox، DLQ و inbox در مسیر messaging، به‌خصوص تضمین‌های تحویل، Transactional Outbox، Idempotent Consumer و Inbox و Saga؛ سازوکار تاب‌آوری در Timeouts, Retries & Jitter، Circuit Breaker، Bulkheads و API Idempotency. این صفحه می‌گوید هر تعامل کدام‌یک از این ابزارها را لازم دارد و چطور کنار هم می‌نشینند.

نقشهٔ صفحه ​

دنبال چه هستیدبروید به
کل صفحه در سه جدولهمه‌چیز در یک دقیقه
چرا فراخوانی شبکه فراخوانی تابع نیستچرا وجود دارد
Postel، قرارداد مصرف‌کننده‌محور، jitter، Problem Detailsاز کجا آمده
پنج سبک، هر کدام یک بلوکSync، فرمان‌های async، Event notification، Event-carried state transfer، Stream
جفت‌شدگی زمانی، دسترس‌پذیری، تأخیر و سازگاریجفت‌شدگی
Orchestration در برابر choreographyOrchestration و choreography
OpenAPI، Protobuf، AsyncAPI، Pact، نسخه‌بندیقراردادها، قرارداد مصرف‌کننده‌محور، سازگاری
Timeout، deadline، retry، jitter، بودجهDeadline، Retry
طراحی Idempotency-Keyکلید idempotency
Circuit breaker، bulkhead، hedgingBreaker و bulkhead، Hedging
خواندن داده از چند سرویسAPI composition و BFF
mTLS، توکن، traceparent، قالب خطااحراز هویت، Tracing، خطاها
عددها، تنظیم‌ها، کدهای وضعیتسازوکار
کدGo، Laravel
خرابی‌های کلاسیک و راه‌حلشانحل مسئله‌های کلاسیک
Contract test، تست مصرف‌کننده، chaosتست
کدام سبک، کدام سیاستانتخاب
از monolith تا سیستم توزیع‌شدهدر معماری
Retry storm با عدد واقعیآزمایشگاه
باورهای غلط، چکیده، خودآزمایی، واژه‌هابدفهمی‌ها، چکیده، خودآزمایی، واژه‌نامه

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

سبک‌ها. کتاب Building Microservices (ویرایش دوم) نوشتهٔ Newman فصل ۴ را دقیقاً حول همین تقسیم چیده است: "asynchronous vs synchronous calls, request-response and event-driven collaboration styles".

سبکبه زبان سادهمثال کوچکچه کسی منتظر می‌ماندریسک اصلی
Sync request/responseصدا بزن و منتظر جواب بمانGET /customers/42 روی REST یا یک فراخوانی unary در gRPCفراخوان، برای کل زنجیرهیک وابستگی کند یا خاموش، فراخوان را هم متوقف می‌کند
Async request/response (فرمان، Command)از کسی بخواه کاری بکند؛ بعداً خبرش می‌رسدChargeOrder روی صف، PaymentSucceeded برمی‌گرددهیچ‌کس block نمی‌شود؛ گردش کار منتظر استپیام گم‌شده یا تکراری، debug سخت‌تر
Event notificationبه همه بگو چیزی رخ داد، با یک شناسهOrderPlaced {order_id}هیچ‌کسجریان پنهان؛ مصرف‌کننده‌ها برای جزئیات برمی‌گردند و صدا می‌زنند
Event-carried state transferبه همه بگو چه چیزی عوض شد، همراه با دادهCustomerChanged {id, name, tier, version}هیچ‌کسنسخه‌های متعدد از داده، کهنگی
Event streamواقعیت‌ها را به یک log پایدار و قابل بازپخش اضافه کنtopic کافکا به نام orders با retentionهیچ‌کس؛ هر مصرف‌کننده offset خودش را داردتکامل schema، ترتیب فقط به‌ازای هر کلید

جفت‌شدگی‌ای (Coupling) که هر سبک می‌سازد.

جفت‌شدگیبه چه سؤالی جواب می‌دهدSyncفرمان asyncرویدادها
زمانی (Temporal)آیا هر دو باید در یک لحظه بالا باشند؟بلهنه (broker نگه می‌دارد)نه
دسترس‌پذیری (Availability)اگر فراخوانده بیفتد، فراخوان هم می‌افتد؟بله، مگر با حالت تنزل‌یافتهنه، در صف می‌ماندنه
تأخیر (Latency)تأخیر فراخوانده به تأخیر کاربر اضافه می‌شود؟بله، به‌ازای هر hopنهنه
سازگاری (Consistency)نتیجه فوراً دیده می‌شود؟بله (read-your-write)در نهایت (eventually)در نهایت
شناخت (Knowledge)فرستنده گیرنده را می‌شناسد؟بلهبله (یک گیرندهٔ مشخص)نه

جعبه‌ابزار قابلیت اطمینان، به ترتیبی که به کار می‌رود.

ابزارقولهمراه ضروریصفحهٔ صاحب
Deadlineهیچ‌کس بعد از لحظه‌ای که کاربر بی‌خیال شد منتظر نمی‌ماندانتشار به همهٔ hopهاDeadline
Retry با backoff و jitterخطاهای گذرا دیده نمی‌شوندidempotency، بودجهRetry
کلید idempotencyدو بار انجام دادن برابر یک بار استذخیره با TTL، fingerprintکلید idempotency
Circuit breakerصدا زدن وابستگی‌ای که مدام خطا می‌دهد قطع می‌شودfallbackCircuit Breaker
Bulkheadیک وابستگی کند همهٔ threadها را نمی‌گیردpool جدا برای هر وابستگیBulkheads
Hedgingدنبالهٔ تأخیر خواندن‌های idempotent کوتاه می‌شودلغو، throttlingHedging
Contract testتغییر provider بی‌صدا مصرف‌کننده را نمی‌شکنددروازه در CIقرارداد مصرف‌کننده‌محور
Trace contextیک درخواست در همهٔ hopها دنبال‌شدنی استtraceparent روی هر فراخوانی و پیامTracing
Synchronous (blocking)Asynchronous (non-blocking)Request-responseEvent-drivenSync request/responseCaller waits for the answerREST, gRPC unary, GraphQL query"Is this card valid?" during checkoutCoupling: temporal + availabilityLatency adds up per hopUse: reads, needs answer nowAsync request/responseCommand on a queue, reply laterChargeOrder -> queue -> PaymentDoneReply queue, callback, 202 + pollCoupling: no temporal coupling;still knows the receiverUse: slow or retried workNot a real combinationEvents are not awaited: if thesender blocks on a handler result,it is request/response in disguise(in-process listeners that run inlineare synchronous, but stay insideone process)Event-driven (three variants)1 Event notificationOrderPlaced {id}; consumer may call back2 Event-carried state transferCustomerChanged {all fields, version}3 Event stream (log, replayable)Kafka topic, Redis Stream; consumerskeep their own offsetMore temporal coupling, simpler to followLess coupling, flow harder to see

تصویر، ماتریس سبک‌هاست. Request/response می‌تواند همگام (synchronous) یا ناهمگام (asynchronous) باشد؛ همکاری رویدادمحور (event-driven) ذاتاً ناهمگام است. هرچه به راست برویم جفت‌شدگی زمانی کمتر می‌شود و دیدن کل جریان سخت‌تر.

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

درون یک پردازه، فراخوانی چند نانوثانیه طول می‌کشد، نیمه‌کاره نمی‌ماند و یا برمی‌گردد یا exception می‌دهد. روی شبکه همان یک خط کد ممکن است کند باشد، پیش از ارسال شکست بخورد، بعد از اینکه طرف مقابل کار را انجام داد شکست بخورد، یا دو بار برسد. الگوی microservices.io برای فراخوانی همگام (Remote Procedure Invocation) هزینه را صریح می‌گوید: "Reduced availability since the client and the service must be available for the duration of the interaction". الگوی messaging همان سایت روی دیگر سکه را: "Additional complexity of message broker, which must be highly available". هر تصمیم ارتباط سرویس‌ها انتخاب بین این دو هزینه است، به‌علاوهٔ کاری که برای زنده ماندن در هر کدام باید اضافه کنید.

Request/response همگامMessaging ناهمگام
ساده برای نوشتن، خواندن و debugقطعه‌های متحرک بیشتر: broker، consumer، DLQ
پاسخ همین حالا؛ read-after-write قویپاسخ بعداً می‌رسد؛ UI باید «در انتظار» نشان دهد
دسترس‌پذیری ضرب می‌شود: ۳ سرویس با 99.9% حدود 99.7%broker نگه می‌دارد؛ producer وقتی consumer خاموش است بالا می‌ماند
تأخیر به‌ازای هر hop جمع می‌شودمسیر درخواست کوتاه می‌ماند
خطا فوراً دیده می‌شود (timeout، 503)خطا دیرتر دیده می‌شود (DLQ، saga گیرکرده)
Retry در فراخوان و زیر یک deadlineRetry در consumer و با redelivery
مناسب query و تصمیم‌هایی که کاربر منتظرشان استمناسب اثرهای جانبی، fan-out، کار کند یا پرنوسان

تشبیهی که در کل صفحه به کار می‌بریم: تلفن، نامه و تابلوی اعلانات. تماس تلفنی همگام است: هر دو باید در دسترس باشند و اگر وسط جمله خط قطع شود نمی‌دانید طرف چه شنیده. نامه یک فرمان ناهمگام است: گیرنده را نام می‌برید، نامه در صندوقش می‌ماند، جواب بعداً می‌آید و پست گاهی همان نامه را دو بار تحویل می‌دهد. تابلوی اعلانات یک رویداد است: «دفتر دوشنبه جابه‌جا می‌شود» را می‌چسبانید و نمی‌دانید و برایتان مهم نیست چه کسی می‌خواندش. Deadline یعنی «اگر پیش از حرکت قطارم نمی‌توانی جواب بدهی، زحمت نکش». کلید idempotency شمارهٔ ارجاع روی نامه است که به گیرنده اجازه می‌دهد بگوید «این یکی را قبلاً انجام داده‌ام».

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

  1. «Async همیشه بهتر است چون decouple می‌کند.» جفت‌شدگی زمانی را برمی‌دارد و هزینه‌های دیگری می‌آورد: کاربر منتظر نتیجهٔ «در نهایت» می‌ماند، پیام تکراری و جابه‌جا پیدا می‌شود و جریان دیگر در هیچ برنامه‌ای دیده نمی‌شود. Fowler هشدار می‌دهد که با event notification "it's very easy to make nicely decoupled systems with event notification, without realizing that you're losing sight of that larger-scale flow".
  2. «Retry سیستم را قابل‌اطمینان‌تر می‌کند.» Retry خطای گذرا را پنهان می‌کند و اضافه‌بار را بدتر. مقالهٔ AWS در یک کلمه می‌گوید: retryها "selfish" هستند.
  3. «Timeout یعنی فراخوانی انجام نشد.» Timeout یعنی شما دیگر منتظر نماندید. جدول کدهای وضعیت gRPC می‌گوید DEADLINE_EXCEEDED "may be returned even if the operation has completed successfully". هر طراحی retry از همین واقعیت شروع می‌شود.

از کجا آمده ​

مسئله به قدمت محاسبات توزیع‌شده است؛ واژگانی که امروز به کار می‌بریم بیشترش بعد از ۲۰۰۵ نوشته شد.

اصل استحکام Postel. Fowler در Tolerant Reader (۹ مه ۲۰۱۱) آن را قانون حاکم بر همکاری decoupled می‌داند: "be conservative in what you do, be liberal in what you accept from others" (Jon Postel). به زبان سرویس‌ها: فقط فیلدهایی را بخوان که لازم داری، بقیه را نادیده بگیر و هرگز بیشتر از آنچه قرارداد اجازه می‌دهد نفرست.

قراردادهای مصرف‌کننده‌محور (Consumer-driven contracts)، ۲۰۰۶. مقالهٔ Ian Robinson با عنوان Consumer-Driven Contracts: A Service Evolution (martinfowler.com، ۱۲ ژوئن ۲۰۰۶) قرارداد provider ("Closed and complete"، "Singular and authoritative") را از قراردادهای مصرف‌کننده ("Open and incomplete"، "Multiple and non-authoritative") جدا کرد. providerی که انتظارات همهٔ مصرف‌کننده‌هایش را می‌داند می‌تواند بدون شکستن آن‌ها تکامل پیدا کند. Pact این ایده را به ابزار تبدیل کرد: "Contract testing is a technique for testing an integration point by checking each application in isolation"، در برابر یک قرارداد مشترک و مستند.

تأخیر دنباله و hedging، ۲۰۱۳. مقالهٔ The Tail at Scale از Dean و Barroso (CACM، فوریهٔ ۲۰۱۳) اصطلاح "hedged requests" را ساخت و نشان داد که فرستادن درخواست دوم فقط وقتی اولی بیش از صدک ۹۵ تأخیر مورد انتظار معطل مانده "limits the additional load to approximately 5% while substantially shortening the latency tail".

میکروسرویس‌ها، ۲۰۱۴. مقالهٔ Lewis و Fowler (۲۵ مارس ۲۰۱۴) عبارت "smart endpoints and dumb pipes" را جا انداخت: منطق در سرویس‌ها، انتقال ساده.

Backoff نمایی و jitter، ۲۰۱۵. پست Marc Brooker در وبلاگ معماری AWS (۴ مارس ۲۰۱۵) سه روش "Full Jitter"، "Equal Jitter" و "Decorrelated Jitter" را مقایسه کرد و نتیجه گرفت "Equal Jitter" "the loser" است؛ با ۱۰۰ کلاینت رقیب، jitter "reduced our call count by more than half".

Google SRE، ۲۰۱۶. فصل‌های handling overload و cascading failures در کتاب SRE بودجهٔ retry (برای هر درخواست "up to three attempts"، برای هر کلاینت نسبت retry "below 10%")، قاعدهٔ ضرب ("64 attempts (4^3) on the database") و انتشار deadline را داد.

رویدادها، ۲۰۱۷. مقالهٔ Fowler با عنوان What do you mean by "Event-Driven"? (۷ فوریهٔ ۲۰۱۷) این واژه را به event notification، event-carried state transfer، event sourcing و CQRS شکست و "passive-aggressive command" را نام‌گذاری کرد.

کلیدهای idempotency، ۲۰۱۷. پست Brandur Leach در Stripe (۲۲ فوریهٔ ۲۰۱۷) هدر Idempotency-Key روی endpointهای تغییردهنده را توضیح داد، همراه با backoff نمایی و jitter در کتابخانه‌های کلاینت.

استانداردها، از ۲۰۲۰ تا امروز. W3C Trace Context به Recommendation رسید (۶ فوریهٔ ۲۰۲۰؛ ویرایش فعلی ۲۳ نوامبر ۲۰۲۱). RFC 9457 با عنوان Problem Details for HTTP APIs (ژوئیهٔ ۲۰۲۳) جای RFC 7807 را گرفت. OpenAPI 3.1.0 و AsyncAPI 3.0.0 قالب‌های توصیف فعلی‌اند. Idempotency-Key HTTP Header Field در IETF هنوز پیش‌نویس است (-09، ۲۱ نوامبر ۲۰۲۶)، نه RFC.

text
     Year   Idea                                      What changed in practice
1    -      Postel's principle (quoted by Fowler)      Tolerant readers, additive changes
2    2006   Consumer-driven contracts (Robinson)       Providers test against consumer expectations
3    2011   Tolerant Reader (Fowler)                   Ignore unknown fields by design
4    2013   Tail at Scale: hedged requests             Tail latency treated as a design input
5    2014   Microservices: smart endpoints, dumb pipes Every module boundary becomes a network hop
6    2015   Backoff + jitter (Brooker)                 Randomised retries become the default
7    2016   SRE: retry budgets, deadline propagation   Retries are rationed, deadlines shared
8    2017   Event-driven taxonomy; Stripe keys         Events named precisely; safe POST retries
9    2020   W3C Trace Context                          One traceparent header across vendors
10   2023   RFC 9457 Problem Details                   One error shape for HTTP APIs
11   2026   Idempotency-Key draft -09                  Header standardisation still in progress

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

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

Request/response همگام (Synchronous) حیاتی ​

به زبان ساده: فراخوان درخواست را می‌فرستد و روی آن مسیر هیچ کار دیگری نمی‌کند تا پاسخ، خطا یا deadline خودش برسد.

بدفهمی رایج: «gRPC یا HTTP/2 آن را ناهمگام می‌کند.» کتابخانهٔ کلاینت ممکن است non-blocking باشد (future، goroutine، promise در Guzzle)، اما تعامل همچنان همگام است: گام کاری فراخوان بدون بالا بودن فراخوانده در همین لحظه تمام نمی‌شود. I/O غیرمسدودکننده مصرف thread را عوض می‌کند، نه جفت‌شدگی را.

تعریف: تعاملی که در آن فراخوان برای ادامه به پاسخ نیاز دارد و فراخوانده باید در تمام مدت فراخوانی در دسترس باشد (microservices.io، Remote Procedure Invocation: "The client uses a request/reply-based protocol to make requests to a service.").

text
     Checkout (budget 800 ms)        Pricing                     Inventory
1    POST /checkout arrives
2    -> GET /quote  (deadline 780)   computes 40 ms
3    <- 200 {total: 4999}
4    -> POST /reservations (deadline 720, Idempotency-Key k1)
5                                                                 reserves, 60 ms
6    <- 201 {reservation_id}
7    responds 201 to the user at ~130 ms; any hop failing fails the whole request

سناریوی واقعی: بررسی قیمت و موجودی هنگام checkout (کاربر منتظر جواب است)؛ بررسی دسترسی («آیا کاربر ۷ می‌تواند فاکتور ۹ را ببیند؟»)؛ اپ موبایلی که پروفایل را می‌خواند؛ مجوز پرداختی که باید پیش از نمایش صفحهٔ سفارش موفق یا ناموفق شود.

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

محصولابزار همگامtimeout پیش‌فرضنکته
Go net/httphttp.Client.Doندارد (Timeout صفر یعنی بدون timeout)همیشه Timeout یا deadline روی context بگذارید
کلاینت HTTP لاراول (Guzzle)Http::get/post۳۰ ثانیه پاسخ، ۱۰ ثانیه اتصالtimeout()، connectTimeout()
gRPC (همهٔ زبان‌ها)RPC از نوع unaryبه‌طور پیش‌فرض deadline ندارد"always explicitly set a realistic deadline"
GraphQLquery روی HTTPهرچه کلاینت HTTP تعیین کندیک درخواست، چندین resolver پشتش
Envoy / Istio / Linkerdtimeout و retry در routeتنظیم per-routeببینید Service Mesh

راه درست: sync را برای خواندن‌ها و تصمیم‌هایی نگه دارید که کاربر واقعاً منتظرشان است؛ به هر فراخوانی deadline‌ای بدهید که از بودجهٔ کاربر می‌آید (Deadline)؛ زنجیره‌های sync را کوتاه نگه دارید (دو hop بویی است که باید بررسی شود، چهار hop مشکل طراحی است)؛ فقط فراخوانی‌های idempotent را retry کنید (Retry).

Request/response ناهمگام و فرمان‌ها (Commands) حیاتی ​

به زبان ساده: کاری را («این سفارش را شارژ کن») از طریق صف به گیرنده‌ای مشخص می‌سپارید و ادامه می‌دهید؛ نتیجه به‌صورت پیامی دیگر، callback یا وضعیتی که poll می‌کنید برمی‌گردد.

بدفهمی رایج: «اگر از صف عبور کند، رویداد است.» پیامی که به یک گیرندهٔ مشخص می‌گوید کاری انجام بده فرمان است، حتی اگر روی Kafka باشد. Fowler فرمانی را که لباس رویداد پوشیده "passive-aggressive command" می‌نامد: مبدأ "expects the recipient to carry out an action, and ought to use a command message to show that intention, but styles the message as an event instead."

تعریف: microservices.io گونه‌های ناهمگام را می‌شمارد: "Request/response - a service sends a request message to a recipient and expects to receive a reply message promptly"، "Request/asynchronous response - a service sends a request message to a recipient and expects to receive a reply message eventually" و "Notifications - a sender sends a message a recipient but does not expect a reply."

text
     Orders                          Broker (queue)              Payments
1    INSERT order (PENDING) + outbox row in one transaction
2    relay publishes ChargeOrder{msg_id, order_id}  ->  payments.commands
3    responds 202 Accepted + Location: /orders/1001
4                                                                 consumes ChargeOrder
5                                                                 charges (Idempotency-Key order-1001-charge)
6                                    <- PaymentSucceeded{order_id} on payments.events
7    consumes; UPDATE order SET status = PAID
8    user polls GET /orders/1001 or gets a push: "paid"

سناریوی واقعی: شارژ کارت بعد از checkout؛ ساخت PDF فاکتور؛ ارسال ایمیل؛ ساخت حساب در سیستم شخص ثالث؛ هر کار طولانی یا دارای محدودیت نرخ.

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

محصولانتقال فرمانسازوکار پاسخصفحهٔ عمیق
RabbitMQیک صف برای هر گیرندهreply_to + correlation id، direct reply-toRequest-Reply
Kafkaیک topic برای هر نوع فرمانtopic پاسخ با کلید correlation idKafka
Amazon SQSصفصف دوم یا URL برای callbackBrokerهای دیگر
صف‌های لاراولdispatch(new ChargeOrder(...))event یا job که پس از اتمام dispatch می‌شودLaravel Queue Internals
HTTP202 Accepted + URL وضعیتpoll یا webhookREST API Design

راه درست: از طریق transactional outbox منتشر کنید تا وقتی دیتابیس commit می‌کند و فراخوانی broker شکست می‌خورد، فرمان گم نشود؛ به هر فرمان شناسهٔ پیام پایدار بدهید؛ handler را idempotent کنید (کلید idempotency، Inbox)؛ در UI «در انتظار» نشان دهید به‌جای اینکه وانمود کنید کار تمام شده.

Event notification مهم ​

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

بدفهمی رایج: «رویدادها جفت‌شدگی را حذف می‌کنند.» شناخت فرستنده از گیرنده‌ها را حذف می‌کنند، اما گیرنده‌ای که برای جزئیات برمی‌گردد و صدا می‌زند دوباره به‌طور همگام به فرستنده وابسته است، و جریان سرتاسری دیگر هیچ‌جا نوشته نشده. Fowler: "Often the only way to figure out this flow is from monitoring a live system."

تعریف: Fowler: "This happens when a system sends event messages to notify other systems of a change in its domain. A key element of event notification is that the source system doesn't really care much about the response."

text
     Orders                   Broker                    Shipping                  Loyalty
1    publish OrderPlaced{order_id: 1001}
2                             fan-out to subscribers
3                                                       GET /orders/1001 (sync callback)
4                                                                                 adds points from event only
5    a change to OrderPlaced's meaning now affects two teams nobody listed

سناریوی واقعی: باطل کردن cache («محصول ۴۲ عوض شد»)؛ خوراک audit و analytics؛ راه انداختن index دوبارهٔ جستجو؛ webhook برای مشتری‌ها.

چه چیزی فراهمش می‌کند: exchangeهای fanout/topic در RabbitMQ، topicهای Kafka با consumer group، Redis Pub/Sub (بدون ماندگاری) و Redis Streams، SNS و Google Pub/Sub؛ و درون پردازه، eventهای لاراول و channelهای Go. جزئیات مسیریابی در Routing Topologies.

راه درست: نام رویدادها را به زمان گذشته بگذارید و payload را یک واقعیت نگه دارید، نه دستور؛ اگر مصرف‌کننده‌ها مدام برمی‌گردند و صدا می‌زنند، به event-carried state transfer بروید؛ جریان را مستند کنید (یک فایل AsyncAPI به‌علاوهٔ نمودار توالی) چون کد نشانش نمی‌دهد؛ آن را trace کنید (Tracing).

Event-carried state transfer حیاتی ​

به زبان ساده: رویداد دادهٔ تغییرکرده را با خودش می‌برد، پس گیرنده‌ها نسخهٔ خودشان را نگه می‌دارند و هیچ‌وقت لازم نیست از مبدأ بپرسند.

بدفهمی رایج: «نسخهٔ محلی یعنی دادهٔ غلط.» نسخه برای مدتی محدود کهنه است و بعد درست می‌شود، و این دقیقاً چیزی است که بیشتر خواندن‌ها لازم دارند (برچسب ارسال به نشانی زمان سفارش نیاز دارد، نه نشانی همین میلی‌ثانیه). چیزی که خرابش می‌کند تحویل بی‌ترتیب یا تکراری بدون بررسی نسخه است.

تعریف: Fowler: "This pattern shows up when you want to update clients of a system in such a way that they don't need to contact the source system in order to do further work." سودش: "greater resilience, since the recipient systems can function if the customer system is becomes unavailable" و "We reduce latency, as there's no remote call required". هزینه‌اش: "lots of data schlepped around and lots of copies" و پیچیدگی در سمت گیرنده.

text
     Customers                         Broker                 Orders (local customer_snapshots)
1    UPDATE customer 42 tier=gold, version 7
2    publish CustomerChanged{id 42, tier gold, version 7}
3    UPDATE customer 42 email=..., version 8
4    publish CustomerChanged{..., version 8}
5                                      v8 delivered first     upsert v8 (8 > 0)
6                                      v7 delivered late      ignored (7 < 8): WHERE version < EXCLUDED.version
7    customers is down for an hour     -                      orders still prices with tier gold

سناریوی واقعی: سرویس سفارش tier و نشانی مشتری را نگه می‌دارد؛ جستجو نام و قیمت محصول را؛ سرویس صورتحساب plan هر tenant را؛ BFF موبایل یک نمای denormalize شده.

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

محصولتناسب با ECSTنکته
Kafka با log compactionخیلی خوبآخرین مقدار هر کلید نگه داشته می‌شود؛ مصرف‌کنندهٔ جدید از روی topic بازسازی می‌کند
RabbitMQبرای به‌روزرسانی زنده خوبتاریخچه بازپخش نمی‌شود؛ مصرف‌کنندهٔ جدید را از API یا snapshot راه بیندازید
Redis Streamsخوب، محدود به MAXLENتاریخچه کوتاه می‌شود؛ راه‌اندازی اولیه را برنامه‌ریزی کنید
CDC (Debezium)خیلی خوبرویدادها از log دیتابیس ساخته می‌شوند (CDC)

راه درست: یک version صعودی (یا موقعیت commit مبدأ) بگذارید و فقط وقتی جدیدتر است upsert کنید؛ با tolerant reader بخوانید؛ مالک داده را مشخص کنید (مبدأ) و هرگز روی نسخهٔ محلی بازنویسی نکنید (مالکیت داده)؛ برنامه داشته باشید که مصرف‌کنندهٔ جدید حالت اولیه را از کجا بگیرد.

Event stream تکمیلی ​

به زبان ساده: یک log پایدار و مرتب از واقعیت‌ها که هر تعداد مصرف‌کننده با سرعت خودشان می‌خوانند و می‌توانند از اول دوباره بخوانند.

بدفهمی رایج: «stream فقط صفی است که پیام‌ها را نگه می‌دارد.» مالک موقعیت (offset) مصرف‌کننده است نه broker، پس بازپخش، projectionهای جدید و مصرف‌کنندهٔ دیرآمده عادی است؛ ترتیب به‌ازای هر partition (هر کلید) است، نه سراسری.

تعریف: یک log فقط‌افزودنی با retention که بر اساس کلید partition شده؛ مصرف‌کننده‌های یک گروه partitionها را تقسیم می‌کنند و offset را commit می‌کنند. Kafka، Redis Streams، Pulsar، Kinesis و NATS JetStream پیاده‌اش می‌کنند.

text
     Producer         Kafka topic orders (partition by order_id)   Analytics       Search (new)
1    append e1..e100  p0: e1 e4 ... | p1: e2 e5 ... | p2: ...
2                                                                  offset 100      -
3                                                                                  starts at offset 0, replays all
4    append e101      ordering holds per order_id only

سناریوی واقعی: تغذیهٔ analytics، جستجو و پیشنهاد از همان واقعیت‌ها؛ بازسازی read model بعد از یک باگ؛ ردپای audit. جزئیات: Kafka، Event Sourcing و CQRS، Stream Processing.

راه درست: کلید partition را از ترتیبی که لازم دارید انتخاب کنید (ترتیب و partition)؛ schema را نسخه‌بندی کنید (طراحی پیام و تکامل schema)؛ retention را برای طولانی‌ترین بازپخشی که لازم خواهید داشت اندازه بگیرید.

ابعاد جفت‌شدگی: زمانی، دسترس‌پذیری، تأخیر، سازگاری حیاتی ​

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

بدفهمی رایج: «جفت‌شدگی سست (loose coupling) یعنی استفاده از broker.» broker جفت‌شدگی زمانی (temporal coupling) و دسترس‌پذیری را برمی‌دارد، اما جفت‌شدگی معنایی را نه: اگر schema رویداد OrderPlaced عوض شود همهٔ مصرف‌کننده‌ها باز هم می‌شکنند. این را قراردادها حل می‌کنند (قراردادها).

تعریف:

بُعدکی جفت‌شده استمثالبا چه چیزی جدا می‌شود
زمانی (Temporal)هر دو باید در یک لحظه اجرا شوندCheckout قیمت‌گذاری را همگام صدا می‌زندصف، رویداد، نسخهٔ محلی
دسترس‌پذیری (Availability)خاموشی فراخوانده یعنی خاموشی فراخوانصفحهٔ پروفایل با خرابی سرویس پیشنهاد خراب می‌شودfallback، cache، async
تأخیر (Latency)تأخیر فراخوانده به فراخوان اضافه می‌شودپنج فراخوانی پشت‌سرهم هر کدام ۵۰ msفراخوانی موازی، دادهٔ محلی، async
سازگاری (Consistency)فراخوان آخرین حالت فراخوانده را لازم دارد«آیا صندلی هنوز آزاد است؟»حذف‌شدنی نیست؛ sync بماند یا مالکیت بازطراحی شود
معنایی (Semantic، قرارداد)هر دو به معنای فیلد وابسته‌اندamount به سنت یا یوروقرارداد نسخه‌دار، contract test
استقرار (Deployment)هر دو باید با هم deploy شوندکتابخانهٔ مشترک DTOتغییرات backward compatible
text
     Arrow                         Temporal  Availability  Latency  Consistency need
1    checkout -> pricing (sync)    yes       yes           yes      high (price shown = price charged)
2    checkout -> email (queue)     no        no            no       low (email may arrive later)
3    orders <- customers (ECST)    no        no            no       medium (tier may lag seconds)

سناریوی واقعی: distributed monolith کلاسیک: هر درخواست شش سرویس را همگام طی می‌کند، پس دسترس‌پذیری حاصل‌ضرب شش SLO است (SLO و بودجهٔ خطا).

راه درست: چهار جواب را کنار هر پیکان روی نمودار معماری بنویسید؛ هر پیکانی که نیاز سازگاری بالا دارد همگام می‌ماند یا داده‌اش به همان سرویس منتقل می‌شود؛ بقیه نامزد async یا نسخهٔ محلی‌اند.

Orchestration در برابر choreography حیاتی ​

به زبان ساده: در orchestration یک جزء قدم‌به‌قدم به بقیه می‌گوید چه کنند؛ در choreography هر سرویس به رویدادهای بقیه واکنش نشان می‌دهد و هیچ‌کس کل نقشه را ندارد.

بدفهمی رایج: «choreography بیشتر decouple است، پس بهتر است.» هماهنگ‌کنندهٔ مرکزی را حذف می‌کند و گردش کار را به فاصله‌های بین سرویس‌ها می‌برد. با بیش از سه یا چهار گام، هیچ‌کس بدون trace نمی‌تواند بگوید «سفارش ۱۰۰۱ کجا گیر کرده؟». Orchestration «یک monolith» نیست: orchestrator مالک فرایند است، نه دادهٔ شرکت‌کننده‌ها.

تعریف: microservices.io (Saga): "Choreography - each local transaction publishes domain events that trigger local transactions in other services"؛ "Orchestration - an orchestrator (object) tells the participants what local transactions to execute". همین دو سبک برای هر تعامل چندمرحله‌ای کاربرد دارد، نه فقط saga. Richards و Ford (Software Architecture: The Hard Parts) هماهنگی (coordination) را یکی از سه بُعد مستقل یک گردش کار توزیع‌شده می‌دانند، کنار ارتباط (sync یا async) و سازگاری (atomic یا eventual).

text
     Choreography                                   Orchestration
1    Orders: OrderCreated ->                        Orchestrator: create order PENDING
2    Payments: hears it, charges, PaymentDone ->    Orchestrator -> Payments: ChargeOrder (command)
3    Inventory: hears PaymentDone, reserves         Payments -> Orchestrator: Charged (reply)
4    Shipping: hears StockReserved, books           Orchestrator -> Inventory: Reserve (command)
5    failure: who compensates? each listener must   failure: orchestrator runs compensations in order

سناریوی واقعی: تکمیل سفارش (معمولاً orchestration می‌برد: گام‌های زیاد، جبران، صفحهٔ وضعیت)؛ پخش «کاربر ثبت‌نام کرد» به ایمیل، analytics و CRM (choreography می‌برد: واکنش‌های مستقل، بدون جبران).

چه چیزی فراهمش می‌کند: Temporal، AWS Step Functions، Camunda و Bus::chain لاراول برای orchestration (گردش‌کار پایدار)؛ هر brokerی برای choreography. جبران (compensation) و حالت saga در الگوی Saga درس داده می‌شود.

راه درست: از جدول تصمیم در انتخاب استفاده کنید؛ هر کدام را انتخاب کردید، به گردش کار یک شناسه بدهید، منتشرش کنید و هر گام را idempotent کنید.

قراردادها: OpenAPI، Protobuf، AsyncAPI، contract-first حیاتی ​

به زبان ساده: قرارداد (Contract) قول نوشته‌شدهٔ بین دو سرویس است: چه عملیاتی، چه فیلدهایی، چه خطاهایی، چه تضمین‌هایی. اگر فقط در کد وجود داشته باشد، تصادفی عوض می‌شود.

بدفهمی رایج: «schema همان قرارداد است.» Robinson چیزهای بیشتری می‌شمارد: schema سند، interfaceها، گفت‌وگوها (الگوی تبادل پیام)، سیاست (امنیت، تراکنش) و "Quality of service characteristics" مثل "availability, latency and throughput". تغییری که از نظر schema سازگار است اما endpoint را ده برابر کند می‌کند هم قرارداد را می‌شکند.

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

قالبچه چیزی را توصیف می‌کندنقل از مشخصهچه چیزی تولید می‌کند
OpenAPI 3.1.0APIهای HTTP"a standard, programming language-agnostic interface description for HTTP APIs"کلاینت، سرور، مستندات، mock server
Protocol Buffers (proto3) + gRPCسرویس‌های RPC و پیام‌هاشمارهٔ فیلد هویت روی سیم استstub برای Go/PHP/Java
AsyncAPI 3.0.0APIهای پیام‌محور"protocol-agnostic, so you can use it for APIs that work over any protocol (e.g., AMQP, MQTT, WebSockets, Kafka, STOMP, HTTP, Mercure, etc)"مستندات، کد، validator
JSON Schema / Avropayload پیامدر schema registryها استفاده می‌شودvalidator
GraphQL SDLAPIهای گرافیschema نوع‌دارکلاینت، resolver

Contract-first در برابر code-first: در contract-first تیم ابتدا openapi.yaml یا billing.proto را می‌نویسد، با مصرف‌کننده‌ها بازبینی می‌کند و کد را تولید می‌کند؛ در code-first قرارداد از annotationها ساخته می‌شود. وقتی چند تیم API را مصرف می‌کنند یا پیش از وجود provider به mock نیاز دارید، contract-first بهتر است؛ درون یک تیم code-first کافی است.

text
     Contract-first workflow
1    billing team drafts billing.proto (ChargeRequest, ChargeReply, errors)
2    orders team reviews: needs idempotency_key, currency
3    buf lint + breaking check in CI against main
4    generate Go server stub and PHP client
5    orders writes consumer contract test (Pact) against the mock
6    billing implements; provider verification runs in billing's CI

راه درست: قرارداد را در مخزن provider و هم‌نسخه با کد نگه دارید؛ در CI بررسی تغییر شکننده اجرا کنید (برای Protobuf قواعد سازگاری)؛ برای هر topic رویداد AsyncAPI منتشر کنید، چون رویدادها URLی ندارند که کسی مرورش کند.

Contract test مصرف‌کننده‌محور و Pact مهم ​

به زبان ساده: هر مصرف‌کننده دقیقاً درخواست‌هایی را که می‌فرستد و بخش‌هایی از پاسخ را که می‌خواند می‌نویسد؛ provider این انتظارات را در CI خودش اجرا می‌کند، بدون اینکه مصرف‌کننده اجرا شود. به این می‌گویند قرارداد مصرف‌کننده‌محور (consumer-driven contract).

بدفهمی رایج: «contract test جای integration test را می‌گیرد.» شکل هر تعامل را جداگانه بررسی می‌کند. درستی کل جریان سرتاسری یا کارایی را نه. مستندات Pact: "Without contract testing, the only way to ensure that applications will work correctly together is by using expensive and brittle integration tests." contract test بیشتر آن‌ها را غیرضروری می‌کند؛ چند smoke test باقی می‌ماند.

تعریف: تست مصرف‌کننده کلاینت واقعی را در برابر یک provider ساختگی (mock) اجرا می‌کند که از تعامل مورد انتظار ساخته شده؛ بعد Pact یک فایل pact می‌نویسد. در provider verification، "each request is sent to the provider, and the actual response it generates is compared with the minimal expected response described in the consumer test"، و اگر پاسخ "contains at least the data described" قبول می‌شود. حالت provider (provider state) پیش‌شرط‌ها را توصیف می‌کند («customer 42 has enough credit»).

text
     Orders CI (consumer)                         Billing CI (provider)
1    test: BillingClient.Charge vs Pact mock
2    pact file orders-billing.json written
3    published to a Pact Broker (or shared file)
4                                                 fetch pacts for billing
5                                                 set provider state "customer 42 has enough credit"
6                                                 replay POST /charges against real handler
7                                                 response has charge_id (string) and status "captured": pass
8                                                 billing renames status -> state: verification fails BEFORE deploy

چه چیزی فراهمش می‌کند: Pact (pact برای HTTP و پیام، زبان‌های زیاد، Pact Broker/PactFlow)، Spring Cloud Contract (JVM)، بررسی سازگاری schema registry برای رویدادها. کد این صفحه «Pact-style» است: همان فایل JSON را Go و لاراول بدون runtime خود Pact بررسی می‌کنند، پس همه‌جا اجرا می‌شود.

راه درست: مصرف‌کننده‌ها فقط فیلدهایی را assert کنند که واقعاً می‌خوانند (این provider را در اضافه کردن فیلد آزاد می‌گذارد)؛ برای مقدارهای تولیدی matcher نوعی به کار ببرید؛ وقتی pact هر مصرف‌کننده‌ای شکست می‌خورد، deploy provider را مسدود کنید. تست قرارداد پیام‌ها: تست سیستم‌های پیام‌رسانی.

سازگاری و نسخه‌بندی حیاتی ​

به زبان ساده: backward compatible یعنی providerهای جدید با مصرف‌کننده‌های قدیمی کار می‌کنند؛ forward compatible یعنی مصرف‌کننده‌های قدیمی با پیام producerهای جدید کار می‌کنند. استقرار مستقل هر دو را لازم دارد.

بدفهمی رایج: «/v2 اضافه کن و در امانی.» نسخهٔ جدید قرارداد جدیدی است که باید اجرا، پایش و بازنشسته شود. پیش‌فرض ارزان‌تر این است که هر تغییر افزایشی باشد و یک نسخه بماند؛ فقط وقتی مجبورید بشکنید، نسخهٔ جدید بسازید.

تعریف و قواعد:

تغییرJSON روی HTTPProtobuf (باینری)امن؟
افزودن فیلد اختیاریخواننده‌های قدیمی نادیده‌اش می‌گیرند (tolerant reader)"Adding new fields is safe"بله
حذف فیلدخواننده‌ای که استفاده‌اش می‌کند می‌شکند"Removing fields is safe" فقط اگر شماره هرگز دوباره استفاده نشود؛ reserved 2, 3;فقط وقتی هیچ مصرف‌کننده‌ای نمی‌خواندش
تغییر نام فیلدخواننده‌ها می‌شکنندروی سیم امن (شماره ثابت)، ProtoJSON و کد می‌شکنندنه (جدید اضافه، قدیمی منسوخ)
تغییر نوع یا شمارهٔ فیلدمی‌شکند"Changing field numbers for any existing field is not safe"نه
افزودن فیلد الزامیفرستنده‌های قدیمی می‌شکنند"Don’t Add a Required Field"نه
افزودن مقدار enumswitchهای کامل می‌شکنند"Adding additional values to an enum is safe" روی سیمروی سیم بله، در کد شاید
سخت‌تر کردن اعتبارسنجیفرستنده‌های قدیمی می‌شکنندهماننه
تغییر معنا (سنت به یورو)خرابی بی‌صداهمانهرگز؛ فیلد جدید
text
     Expand-and-contract (parallel change) for renaming amount -> amount_cents
1    v1: provider sends amount and amount_cents (expand)
2    consumers move to amount_cents, one deploy at a time; pacts show who still reads amount
3    pact verification: no consumer reads amount any more
4    provider stops sending amount; Protobuf: reserved its number (contract)

راهبردهای نسخه‌بندی: در URI (/v2/charges)، در هدر یا media type (Accept: application/vnd.example.v2+json)، نسخه‌های تاریخ‌دار (نسخهٔ API که به سبک Stripe برای هر حساب ثابت می‌شود)، نسخهٔ package در Protobuf (billing.v2) و نام topic یا نوع رویداد جدید برای پیام‌ها. جزئیات: نسخه‌بندی و تکامل API و طراحی پیام و تکامل schema.

راه درست: tolerant reader در هر مصرف‌کننده؛ تغییر افزایشی به‌عنوان پیش‌فرض؛ expand-and-contract برای تغییر نام؛ هدر deprecation یا changelog با تاریخ حذف؛ contract testهایی که می‌گویند آخرین مصرف‌کننده کی منتقل شد.

Timeout، بودجهٔ هر hop و انتشار deadline حیاتی ​

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

بدفهمی رایج: «به هر کلاینت یک timeout سخاوتمندانه مثل ۳۰ ثانیه بدهیم که خیالمان راحت باشد.» timeoutهای ثابت و طولانی خودشان علت تمام شدن threadها هستند. مثال latency دوقله‌ای (bimodal) در کتاب SRE: deadline‌ای "three orders of magnitude larger than the normal mean latency" وقتی ۵٪ درخواست‌ها هرگز تمام نشدند به تمام شدن threadها انجامید. و timeout جداگانهٔ هر hop که فراخوان را نادیده می‌گیرد کار را هدر می‌دهد: فراخوانده بعد از رفتن کاربر هنوز ادامه می‌دهد.

تعریف: gRPC: "A deadline is used to specify a point in time past which a client is unwilling to wait for a response from a server." انتشار deadline (Deadline propagation) در Google SRE: "a deadline is set high in the stack (e.g., in the frontend). The tree of RPCs emanating from an initial request will all have the same absolute deadline." gRPC آن را به‌صورت timeout باقی‌مانده می‌فرستد تا از اختلاف ساعت در امان بماند: "gRPC converts the deadline to a timeout from which the already elapsed time is already deducted."

With deadline propagation: one budget, shrinking at every hopClientbudget 1000 msEdgespends 50 msOrdersspends 200 msBilling -> Paymentspends 100 ms, sends 620timeout 1000Timeout-Ms: 940Timeout-Ms: 7300 ms: client startsabout 380 ms: Payment starts with 620 ms left and can refuse work it cannot finish1000 ms: everyone stops togetherWithout propagation: every hop invents its own timeoutClient: gives up at 1000 ms and maybe retries (a second copy starts)Orders: own 1000 ms timeout, still waiting after the client leftPayment:own 1000 ms timeout, runs until about 1370 msRed = work after the client stopped listening: it costs capacity, its result is thrown away,and if the client retried, two copies of the side effect may now be running.gRPC does this per call (grpc-timeout, DEADLINE_EXCEEDED); for HTTP, Request-Timeout-Ms is our convention.

تصویر یک بودجهٔ ۱۰۰۰ میلی‌ثانیه‌ای را نشان می‌دهد که در هر hop کوچک‌تر می‌شود، و پایینش حالتی که هر hop timeout ثابت خودش را دارد و Payment بعد از رفتن کاربر هنوز کار می‌کند (کار هدررفته، قرمز).

text
     Hop          Receives budget   Spends   Sends on (minus 10 ms margin)
1    client       1000 ms           -        1000
2    edge         1000              50       940
3    orders       940               200      730
4    billing      730               100      620
5    payment      620               -        refuses work it knows takes longer than 620 ms

عددها را چطور انتخاب کنیم: AWS از تأخیر فراخوانده شروع می‌کند: "we choose an acceptable rate of false timeouts (such as 0.1%). Then, we look at the corresponding latency percentile on the downstream service (p99.9 in this example)." بودجهٔ سطح بالا از محصول می‌آید (صفحه باید در ۱ ثانیه رندر شود) یا از SLO (SLOها، بودجهٔ تأخیر). کتاب SRE اضافه می‌کند که deadline خروجی را "a few hundred milliseconds" برای انتقال کم کنید و برای هر وابستگی سقف بگذارید.

سناریوی واقعی: صفحهٔ جستجو با بودجهٔ ۳۰۰ ms که به پنج backend پخش می‌شود؛ API پرداختی که شریکش ۲ ثانیه قول داده؛ job دسته‌ای که با بودجهٔ ۳۰ ثانیه یک API را صدا می‌زند (بودجه بسته به فراخوان فرق دارد، پس باید همراه درخواست سفر کند).

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

محصولابزار deadlineخودکار منتشر می‌شود؟خطا هنگام عبور
gRPC Gocontext.WithTimeout؛ grpc-timeout روی سیمبله، وقتی ctx ورودی را به فراخوانی خروجی بدهید (مستندات: در Java و Go پیش‌فرض فعال است)codes.DeadlineExceeded؛ سمت سرور CANCELLED
gRPC C++ClientContext::set_deadlineباید صریحاً فعال شودDEADLINE_EXCEEDED
Go net/httphttp.NewRequestWithContext(ctx, ...)هدری ندارد؛ خودتان اضافه می‌کنید (این صفحه: Request-Timeout-Ms، یک قرارداد داخلی)context deadline exceeded
کلاینت HTTP لاراولHttp::timeout($seconds) (نوع int|float)نه؛ از یک بودجهٔ scoped حساب کنیدConnectionException
Envoyهدر x-envoy-expected-rq-timeout-ms، timeout در routeدرون mesh504، upstream request timeout

راه درست: در Go middleware callbudget به‌علاوهٔ Outgoing؛ در لاراول middleware PropagateCallBudget به‌علاوهٔ CallBudget::outgoingHeaders()؛ سرورها پیش از هر مرحلهٔ گران زمان باقی‌مانده را بررسی کنند و وقتی context تمام شد بایستند.

Retry: backoff، jitter، طوفان و بودجه حیاتی ​

به زبان ساده: فقط وقتی دوباره تلاش کن که خطا احتمالاً موقتی است، فقط اگر دو بار انجام دادن بی‌ضرر است، بعد از یک انتظار تصادفی، تعداد محدود، در یک لایه، و فقط تا وقتی بیشتر فراخوانی‌ها موفق‌اند.

بدفهمی رایج: «سه retry همه‌جا پیش‌فرض امنی است.» سه retry در هر یک از چند لایه ضرب می‌شود. Google SRE: اگر "the backend, frontend, and JavaScript layers all issue 3 retries (4 attempts), then a single user action may create 64 attempts (4^3) on the database." AWS نسخهٔ پنج‌لایه را می‌دهد: "the load on the database will increase 243x". به این می‌گویند طوفان retry (retry storm).

تعریف: سیاست retry شش جزء دارد:

جزءقاعدهمنبع
چه چیزی را retry کنیمفقط خطای گذرا: شکست اتصال، 503، 429، UNAVAILABLEgRPC: UNAVAILABLE "most likely a transient condition"
پیش‌شرطعملیات idempotent، یا کلید idempotencyAWS: "APIs with side effects aren't safe to retry unless they provide idempotency"
چند باربرای هر درخواست حداکثر ۳ تلاشSRE: "per-request retry budget of up to three attempts"
کیbackoff نمایی (exponential backoff) با jitterSRE: "Always use randomized exponential backoff when scheduling retries"
کجایک لایه، همان که درست بالای لایهٔ خراب استSRE: "retried at the layer immediately above the layer that is rejecting them"؛ AWS: "retry at a single point in the stack"
روی‌هم‌رفته چقدربودجه (retry budget): retryها کمتر از حدود ۱۰٪ درخواست‌ها، یا token bucketنسبت per-client در SRE "below 10%"؛ retryThrottling در gRPC
Naive: every layer retries 3 timesBudgeted: retry at one layer, with a budgetBrowser / appFrontendBackendDatabase (overloaded)Browser / appFrontendBackendDatabase (overloaded)4 attemptsx 4 attempts = 16x 4 attempts = 6464 attempts per click1 attempt (no retry)up to 3 attempts, jitteredonly while tokens > max/21 attempt (no retry)≈ 1 attempt per clickwhen the budget is spentGoogle SRE: 3 retries (4 attempts) at three layers -> "64 attempts (4^3) on the database".This page's lab, two retrying layers, db down: naive 1600 db attempts for 100 requests (16.00x);budgeted 103 attempts (1.03x); all 100 fail either way, budgeted in 30 ms instead of 2.5 s.

سمت چپ تصویر سه لایه را نشان می‌دهد که هر کدام چهار تلاش می‌کنند و ۶۴ تلاش روی دیتابیس می‌سازند؛ سمت راست فقط یک لایه retry می‌کند و بودجه وقتی خطاها غالب‌اند جلوی retry را می‌گیرد. عددهای پایین تصویر از آزمایشگاه همین صفحه است.

text
     t (ms)  Naive clients (no jitter)              Full-jitter clients
1    0       1000 clients fail together             1000 clients fail together
2    100     1000 retry at exactly 100 ms           retries spread over 0..100 ms
3    300     1000 retry at exactly 300 ms           spread over 0..200 ms; server drains between
4    700     same spike again; recovery delayed      most succeeded; few remain

سناریوی واقعی: یک deploy نیمی از podهای صورتحساب را برای ۲۰ ثانیه ری‌استارت می‌کند؛ failover دیتابیس ۳۰ ثانیه طول می‌کشد؛ API یک شریک با 429 و Retry-After: 2 محدودیت نرخ می‌گذارد؛ یک اختلال شبکه برای ۲۰۰ ms اتصال‌ها را قطع می‌کند. هر چهار ارزش retry دارند؛ 400، 422، PERMISSION_DENIED یا timeout روی فراخوانی غیر idempotent نه.

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

محصولسازوکار retryJitterبودجه
gRPC (Java، C++، Go)retryPolicy در service config برای هر متد±20% خودکارretryThrottling {maxTokens, tokenRatio}
AWS SDKهاحالت‌های retry داخلیبلهtoken bucket، "added this behavior to the AWS SDK in 2016"
کلاینت HTTP لاراولHttp::retry($times, $sleepMs|closure, $when, throw:)فقط اگر closure شما اضافه کندندارد؛ RateLimiter اضافه کنید
صف‌های لاراول#[Tries]، #[Backoff([1, 5, 15])]، release()نه (فهرست ثابت)به‌ازای هر job؛ ببینید Retry و Backoff
Envoy / Istioretry_policy در route، retryOnبلهretry_budget روی cluster
کتابخانهٔ استاندارد Goندارد-- (بستهٔ retry این صفحه)

راه درست: full jitter به شکل sleep = random(0, min(cap, base * 2^attempt))؛ احترام به Retry-After و pushback سرور در gRPC (grpc-retry-pushback-ms)؛ توقف وقتی deadline جای تلاش دیگری ندارد؛ شمردن retryها در metricها؛ سازوکار کامل در Timeouts, Retries & Jitter.

کلید idempotency: ذخیره، TTL، بازپخش، تکراری‌های هم‌زمان حیاتی ​

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

بدفهمی رایج: «POST ما بررسی می‌کند سفارش وجود دارد یا نه، پس idempotent است.» بررسی-سپس-درج (check-then-insert) یک race است: دو retry که ۵ ms فاصله دارند هر دو «وجود ندارد» می‌بینند. idempotency یک ادعای اتمی (کلید یکتا)، نتیجهٔ ذخیره‌شده و قاعده‌ای برای تکراری‌ای که در حین اجرای اولی می‌رسد لازم دارد.

تعریف: Stripe: "A client generates an idempotency key, which is a unique key that the server uses to recognize subsequent retries of the same request." قواعد Stripe (API v1): کلیدها "up to 255 characters long"، "we suggest using V4 UUIDs"، کلیدها ممکن است "after they’re at least 24 hours old" حذف شوند، و "The idempotency layer compares incoming parameters to those of the original request and errors if they’re not the same". پیش‌نویس IETF (-09) کدهای وضعیت را اضافه می‌کند: 400 وقتی کلید الزامی نیامده، 422 وقتی کلید با payload دیگری دوباره استفاده شده، و 409 وقتی "the request is retried, while the original request is still being processed".

Key not seenPOST + Idempotency-KeyIn progressrow inserted, handler runsCompletedstatus + body storedDeletedhandler returned 5xxExpiredafter TTL (e.g. 24 h)INSERT ok2xx / 4xx5xx (retry allowed)same payload while running -> 409same fingerprint -> replay stored responseother payload, any state-> 422The unique (scope, key) row is the lock; the fingerprint catches key reuse.Missing key on aPOST that needs one-> 400 (IETF draft -09)

تصویر چرخهٔ عمر یک کلید را نشان می‌دهد: درج ردیف و حالت «در حال اجرا»، ذخیرهٔ پاسخ و حالت «کامل»، حذف ردیف وقتی handler خطای 5xx داد، و انقضا بعد از TTL؛ به‌علاوهٔ سه پاسخ به تکراری‌ها (409، بازپخش، 422).

text
     Client A (retrying)                          Billing (idempotency_keys has PK (scope, key))
1    POST /charges  Idempotency-Key: k1           INSERT (cust-7, k1, fp, in progress) -> 1 row
2    ...network times out at 2 s                  still charging the card
3    POST /charges  Idempotency-Key: k1 (retry)   INSERT -> 0 rows; row in progress -> 409 Conflict
4    backs off 400 ms                             charge done; UPDATE row SET status 201, body
5    POST /charges  Idempotency-Key: k1 (retry)   INSERT -> 0 rows; fingerprint equal -> replay 201 (Idempotent-Replayed: true)
6    POST /charges  Idempotency-Key: k1, amount changed   fingerprint differs -> 422

تصمیم‌های طراحی:

تصمیمگزینه‌هاپیشنهاد
چه کسی کلید را می‌سازدکلاینت (UUID v4) یا از هویت کسب‌وکاری (order-1001-charge)از هویت کسب‌وکاری وقتی یک کار کسب‌وکاری به یک فراخوانی نگاشت می‌شود؛ وگرنه UUID
دامنه (Scope)سراسری، برای هر کلاینت، برای هر endpointبرای هر کلاینت احرازشده و endpoint، تا tenantها با هم برخورد نکنند
ذخیرههمان دیتابیس اثر جانبی، Redis، جدول جداهمان دیتابیس و همان تراکنش اثر جانبی در صورت امکان؛ Redis فقط با ماندگاری و پذیرفتن یک شکاف
ادعا (Claim)constraint یکتا / INSERT ... ON CONFLICT DO NOTHING، SET NX در Redisconstraint یکتا؛ اتمی است و از ری‌استارت جان سالم به در می‌برد
چه چیزی ذخیره شودوضعیت، هدرهای لازم، بدنه، fingerprintبه اندازه‌ای که بازپخش بایت‌به‌بایت ممکن باشد
خطا (5xx)ذخیره کن (Stripe v1 بازپخش می‌کند "including 500 errors") یا ادعا را حذف کنانتخاب و مستند کنید؛ این صفحه حذف می‌کند تا retry تمیز ممکن باشد
نگه‌دارندهٔ crash‌کردهقفل ابدی، یا تصاحب بعد از leaselease (locked_at قدیمی‌تر از N دقیقه)
TTLساعت تا روزدست‌کم طولانی‌ترین پنجرهٔ retry کلاینت؛ Stripe: دست‌کم ۲۴ ساعت
Fingerprinthash متد، مسیر و بدنهبرای کشف استفادهٔ دوباره از کلید (422) لازم است

سناریوی واقعی: شارژ و بازپرداخت، ساخت سفارش از شبکهٔ موبایل ناپایدار، انتقال بین حساب‌ها، ارسال SMS پولی، ساخت منبع ابری (RunInstances در EC2 "explicit token-based mechanisms to provide idempotency" دارد).

راه درست: SQL در حل مسئله‌های کلاسیک است؛ middleware idempotency در Go و RequireIdempotencyKey در لاراول در ادامه؛ کلید روی retryهای کلاینت سفر می‌کند و همین سرویس وقتی ارائه‌دهندهٔ پرداخت را صدا می‌زند باید همان کلید را پایین‌دست بفرستد. مصرف‌کننده‌های پیام همین ایده را با شناسهٔ پیام به کار می‌برند (Inbox). عمیق‌تر: API Idempotency.

Circuit breaker و bulkhead مهم ​

به زبان ساده: circuit breaker صدا زدن وابستگی‌ای را که مدام خطا می‌دهد قطع می‌کند و برای مدتی سریع شکست می‌خورد؛ bulkhead به هر وابستگی pool محدود خودش را می‌دهد تا یک وابستگی کند همهٔ threadها یا اتصال‌ها را نگیرد.

بدفهمی رایج: «circuit breaker راه‌حل retry storm است.» کمک می‌کند، اما AWS می‌گوید breakerها "introduce modal behavior into systems that can be difficult to test, and can introduce significant addition time to recovery"؛ AWS ترجیح می‌دهد "limiting retries locally using a token bucket". هر دو را آگاهانه به کار ببرید، نه پیش‌فرض.

تعریف: microservices.io: "When the number of consecutive failures crosses a threshold, the circuit breaker trips, and for the duration of a timeout period all attempts to invoke the remote service will fail immediately. After the timeout expires the circuit breaker allows a limited number of test requests to pass through."

text
     t      Calls to recommendations       Breaker state
1    0 s    5 consecutive timeouts         closed -> open
2    0-30 s calls fail in 0 ms; page shows "popular items" fallback
3    30 s   one trial call                 half-open
4    30 s   trial succeeds                 closed

چه چیزی فراهمش می‌کند: Resilience4j (JVM)، Polly (.NET)، sony/gobreaker (Go)، outlier detection در Envoy و DestinationRule در Istio، و در لاراول با package یا شمارندهٔ مبتنی بر Cache. سازوکار: Circuit Breaker، Bulkheads و تنزل نرم، Load Shedding، Cascading Failures.

راه درست: یک breaker برای هر وابستگی (نه برای هر نمونهٔ فراخوان)، همیشه با fallbackی که تیم محصول قبولش دارد؛ bulkhead به شکل worker pool یا connection pool محدود برای هر وابستگی.

Request hedging تکمیلی ​

به زبان ساده: اگر نسخهٔ اول یک خواندن از معمول کندتر است، نسخهٔ دوم را به replica دیگری بفرست و هر کدام زودتر جواب داد را بردار.

بدفهمی رایج: «hedging همان retry است.» retry بعد از خطا می‌آید؛ hedge هم‌زمان با درخواست کند اجرا می‌شود. کار آن درخواست را دو برابر می‌کند، پس فقط برای خواندن‌های idempotent است و باید throttle شود.

تعریف: gRPC: "With hedging, a gRPC client sends multiple copies of the same request to different backends and uses the first response it receives. Subsequently, the client cancels any outstanding requests". Dean و Barroso: تا صدک ۹۵ تأخیر صبر کن و بعد نسخهٔ دوم را بفرست، که "limits the additional load to approximately 5%".

text
     t (ms)  Replica A                 Replica B                Client
1    0       request 1 starts                                   waits
2    40      (p95 = 40 ms passed)      request 2 starts         hedge sent
3    55                                answers                  uses B's answer, cancels A
4    300     (A was in a GC pause)                              tail cut from 300 to 55 ms

چه چیزی فراهمش می‌کند: hedgingPolicy در gRPC (maxAttempts با سقف ۵، hedgingDelay، nonFatalStatusCodes) در Java؛ مستندات gRPC برای Go "Not yet supported" و برای C++ "Not yet available" نوشته‌اند، پس بستهٔ hedge این صفحه آن را دستی انجام می‌دهد؛ Envoy روی timeout هر تلاش hedging پشتیبانی می‌کند.

راه درست: فقط خواندن، تأخیر حدود p95، لغو بازنده‌ها، سقف تعداد نسخه‌ها، و پایش بار backend.

API composition و Backend-for-Frontend برای خواندن مهم ​

به زبان ساده: وقتی یک صفحه داده‌ای می‌خواهد که مالکش پنج سرویس است، یک جزء آن‌ها را (موازی) صدا می‌زند و جواب‌ها را join می‌کند؛ BFF چنین جزئی است که برای یک نوع کلاینت ساخته شده.

بدفهمی رایج: «composition مجانی است چون فراخوانی‌ها موازی‌اند.» تأخیر برابر کندترین فراخوانی است، دسترس‌پذیری حاصل‌ضرب همه، و microservices.io هشدار می‌دهد "Some queries would result in inefficient, in-memory joins of large datasets." برای فهرست‌ها و جستجو، read modelی که با رویداد تغذیه می‌شود (ECST، CQRS) معمولاً جواب درست است.

تعریف: microservices.io: "Implement a query by defining an API Composer, which invoking the services that own the data and performs an in-memory join of the results." الگوی Backends for Frontends "defines a separate API gateway for each kind of client".

text
     Mobile BFF (budget 400 ms)        Orders     Customers    Shipping
1    GET /app/orders/1001 arrives
2    parallel: GET order, GET customer, GET shipment (each deadline 380 ms)
3                                      60 ms      30 ms        timeout at 380 ms
4    responds with order + customer, shipment: null, "tracking unavailable"

سناریوی واقعی: صفحهٔ جزئیات سفارش؛ صفحهٔ خانهٔ اپ موبایل؛ داشبورد مدیریت. جای قرارگیری و قابلیت‌های gateway: API Gateway، BFF و Service Mesh.

راه درست: فراخوانی موازی (errgroup در Go، Http::pool در لاراول)، یک deadline برای کل composition، نتیجهٔ ناقص برای بخش‌های غیرحیاتی، و read model وقتی join بزرگ یا داغ است.

احراز هویت سرویس‌به‌سرویس تکمیلی ​

به زبان ساده: هر سرویس باید بداند کدام سرویس صدایش می‌زند (احراز هویت) و آیا اجازه دارد (مجوز)؛ درون شبکه بودن هیچ‌کدام را ثابت نمی‌کند.

بدفهمی رایج: «ترافیک داخلی قابل‌اعتماد است.» شبکهٔ zero-trust شبکه را خصمانه فرض می‌کند؛ یک pod نفوذشده نباید بتواند API پرداخت را صدا بزند.

تعریف: دو سازوکار مکمل: TLS دوطرفه (mTLS؛ هر طرف گواهی ارائه می‌دهد و هویت، workload است، مثلاً یک SPIFFE ID که mesh صادر کرده) و توکن (JWT یا توکن client-credentials در OAuth 2.0 که سرویس فراخوان و در صورت نیاز کاربر نهایی را حمل می‌کند).

text
     orders pod                     billing pod
1    TLS handshake: presents cert spiffe://prod/ns/orders/sa/orders
2                                   verifies cert; presents its own (mutual)
3    POST /charges  Authorization: Bearer <token aud=billing, sub=orders>
4                                   policy: orders may POST /charges; reporting may not

چه چیزی فراهمش می‌کند: Istio و Linkerd (mTLS خودکار)، SPIFFE/SPIRE، IAM ابری، client credentials در OAuth 2.0، client credentials در Laravel Passport، crypto/tls در Go با ClientAuth: tls.RequireAndVerifyClientCert. عمیق‌تر: mTLS و امنیت سرویس، OAuth 2.0 و OIDC، امنیت پیام‌رسانی.

راه درست: mTLS برای هر hop (اغلب از mesh)، توکنی با audience و فراخوان برای مجوز، و پیام‌هایی که در broker امضا یا احراز می‌شوند.

همبستگی و انتشار trace (W3C traceparent) حیاتی ​

به زبان ساده: هر درخواست و پیام یک trace ID را از لبه تا آخرین مصرف‌کننده حمل می‌کند، تا یک کار کند یا شکست‌خوردهٔ کاربر در همهٔ سرویس‌ها پیدا شود.

بدفهمی رایج: «هر سرویس request ID خودش را log می‌کند، پس همبستگی داریم.» شناسه‌های جدا در هر hop به هم وصل نمی‌شوند. trace ID باید منتشر شود، از جمله از میان صف‌ها که هدر HTTP در آن‌ها گم می‌شود.

تعریف: W3C Trace Context هدر traceparent را تعریف می‌کند ("describes the position of the incoming request in its trace graph in a portable, fixed-length format") و tracestate (دادهٔ فروشنده). قالب: version-traceid-parentid-flags، مثلاً traceparent: 00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01. جزئی که در trace شرکت نمی‌کند دست‌کم باید "propagate the traceparent and tracestate headers".

text
     edge                  orders                         queue message            payments
1    traceparent 00-T-A-01 (new trace T)
2                          reads T; logs trace_id=T; outbound parent-id B
3                          publishes ChargeOrder with header traceparent 00-T-C-01
4                                                         stored with message
5                                                                                  consumes; continues trace T

چه چیزی فراهمش می‌کند: SDKهای OpenTelemetry (در Go otelhttp و otelgrpc؛ PHP)، Envoy و meshها هدرها را جلو می‌برند؛ انتشار در پیام‌ها در مشاهده‌پذیری پیام‌رسانی؛ Context::add('trace_id', ...) در لاراول که مستندات می‌گویند "automatically appended as metadata to any log entries" و با jobهای صف هم به اشتراک گذاشته می‌شود. پشته: مشاهده‌پذیری.

راه درست: trace را در لبه بپذیرید یا شروع کنید، trace ID را در هر خط log بگذارید، traceparent را در هدر پیام‌ها کپی کنید، و deadline و criticality را هم به همین شکل منتشر کنید.

معنای خطا بین سرویس‌ها: Problem Details و کدهای وضعیت gRPC مهم ​

به زبان ساده: خطاها بخشی از قراردادند؛ فراخوان باید بدون تجزیهٔ متن انگلیسی بتواند «بعداً دوباره تلاش کن» را از «درخواستت غلط است» و از «شاید انجام شده باشد» تشخیص دهد.

بدفهمی رایج: «500 با یک پیام برگردان، فراخوان خودش می‌فهمد.» 500 برای خطای اعتبارسنجی باعث می‌شود هر کلاینتی درخواستی را retry کند که هرگز موفق نمی‌شود؛ 200 با {"error": ...} خطا را از هر proxy، metric و سیاست retry پنهان می‌کند.

تعریف: در HTTP، RFC 9457 یک "problem detail" تعریف می‌کند "to carry machine-readable details of errors in HTTP response content"، با عضوهای type، status، title، detail، instance و media type application/problem+json. در gRPC یک کد وضعیت به‌علاوهٔ پیام؛ کتابخانه‌ها برخی کدها را خودشان تولید می‌کنند (DEADLINE_EXCEEDED، UNAVAILABLE، CANCELLED...) و کدهایی مثل INVALID_ARGUMENT، NOT_FOUND، ALREADY_EXISTS، FAILED_PRECONDITION، ABORTED، OUT_OF_RANGE، DATA_LOSS "are never generated by the library"، پس دیدنشان یعنی برنامه آن‌ها را انتخاب کرده.

text
     Billing returns                       Orders (caller) does
1    422 problem+json "Invalid amount"     no retry; surface to user
2    409 "outstanding for this key"        back off, retry same key
3    503 Retry-After: 2                    retry after 2 s if budget allows
4    504 / DEADLINE_EXCEEDED               unknown outcome: retry only with the same idempotency key
5    UNAVAILABLE                           retry with backoff (idempotent only)

چه چیزی فراهمش می‌کند: رندر exception در bootstrap/app.php لاراول ($exceptions->render(...))، encoding/json در Go با application/problem+json، google.golang.org/grpc/status و codes، و جزئیات غنی‌تر google.rpc.Status. جدول کامل retry در سازوکار است.

راه درست: هر خطای دامنه را به یک وضعیت و یک URL ثابت type نگاشت کنید، در OpenAPI مستندشان کنید، هرگز stack trace بیرون ندهید، و trace ID را در بدنهٔ problem بگذارید تا پشتیبانی پیدایش کند.

سازوکار (Mechanics) ​

حساب بودجه ​

کمیتفرمولمثال
بودجهٔ باقی‌مانده در hop شمارهٔ kB - sum(time spent before k) - k * margin1000 - 350 - 3 x 10 = 620 ms
timeout هر فراخوانی (از AWS)صدک تأخیری که با نرخ پذیرفته‌شدهٔ timeout کاذب جور است0.1% timeout کاذب -> p99.9
دسترس‌پذیری زنجیرهٔ همگامحاصل‌ضرب دسترس‌پذیری هر hop0.999^4 = 0.996 (حدود ۳۵ ساعت قطعی در سال)
تأخیر زنجیرهٔ پشت‌سرهمجمع hopها4 x 50 ms = 200 ms
تأخیر fan-out موازیبیشینهٔ فراخوانی‌ها؛ دنباله با fan-out رشد می‌کندp99 صد فراخوانی نزدیک p99.99 یکی است

ضرب شدن retry ​

چیدمانتلاش روی پایین‌ترین لایه به‌ازای هر کار کاربرمنبع
بدون retry1-
۳ retry (۴ تلاش) در یک لایه4-
۴ تلاش در ۳ لایه4^3 = 64Google SRE، cascading failures
۳ تلاش در ۵ لایه3^5 = 243AWS Builders' Library
بودجهٔ ۳ تلاش برای هر درخواست، یک لایهحداکثر ۳؛ در بدترین حالت "just below 3X"Google SRE، handling overload
به‌علاوهٔ نسبت per-client زیر ۱۰٪وقتی بیشتر فراخوانی‌ها شکست می‌خورند حدود 1.1Google SRE
retryThrottling در gRPC با {10, 0.1}وقتی tokenها به ۵ برسد retry متوقف می‌شودراهنمای retry در gRPC

فرمول‌های backoff و jitter ​

راهبردانتظار پیش از تلاش nداوری (Brooker 2015)
ثابتbaseکلاینت‌ها را هم‌گام می‌کند؛ پرهیز کنید
نماییmin(cap, base * 2^n)retryها را در زمان پخش می‌کند اما کلاینت‌ها هنوز خوشه می‌شوند
Full jitterrandom(0, min(cap, base * 2^n))کمترین کار؛ پیش‌فرض این صفحه
Equal jittert/2 + random(0, t/2) که t = min(cap, base * 2^n)"the loser"
Decorrelated jittermin(cap, random(base, previous * 3))کمی سریع‌تر، فراخوانی بیشتر
داخلی gRPCنمایی با "Jitter of plus or minus 20%"در retryهای service config خودکار

تنظیم‌های gRPC ​

تنظیمکجامعنا
retryPolicy.maxAttemptsservice config، برای هر متدشامل فراخوانی اول؛ مقدار بیش از ۵ همان ۵ حساب می‌شود (gRFC A6)
initialBackoff، maxBackoff، backoffMultiplierservice configbackoff نمایی، به‌علاوهٔ ۲۰٪ jitter
retryableStatusCodesservice configمعمولاً ["UNAVAILABLE"]؛ بقیه را فقط اگر متد idempotent است اضافه کنید
retryThrottling.maxTokens، tokenRatioservice configهر RPC ناموفق ۱- token، هر موفق +tokenRatio؛ زیر نصف، retry متوقف
hedgingPolicy.maxAttempts، hedgingDelay، nonFatalStatusCodesservice configنسخه‌های موازی؛ Go پشتیبانی نمی‌کند
timeoutmethodConfig در service configdeadline پیش‌فرض هر متد
grpc-timeoutmetadata درخواستdeadline باقی‌مانده روی سیم
grpc-retry-pushback-msmetadata پاسخسرور می‌گوید کلاینت چقدر صبر کند، یا retry نکند
grpc-previous-rpc-attemptsmetadata درخواستچند تلاش پیش از این یکی بوده
Transparent retryهمیشه روشنفقط وقتی RPC "never leaves the client" یا هرگز به برنامه نرسیده

gRPC همچنین می‌گوید: "Once the response header is received, the RPC is committed. No further retries will be attempted".

کدهای وضعیت و کاری که فراخوان می‌کند ​

سیگنالمعناRetry؟کار فراخوان
HTTP 400، gRPC INVALID_ARGUMENTدرخواست غلط استنهدرخواست را درست کن؛ خطا را نشان بده
401 / UNAUTHENTICATEDاعتبارنامه نیست یا بد استیک بار، بعد از تازه کردن توکنمستندات لاراول همین را با withToken در callback retry نشان می‌دهد
403 / PERMISSION_DENIEDاجازه نداردنهنشان بده
404 / NOT_FOUNDوجود نداردنه (مگر تأخیر replica مورد انتظار باشد)نشان بده یا صبر کن
409 (idempotency)همان کلید هنوز در حال اجراستبله، همان کلید، بعد از backoffکلید تازه نساز
409 / ALREADY_EXISTS، ABORTEDتعارض یا لغو به‌خاطر هم‌روندیبستگی دارد؛ ABORTED معمولاً در سطح بالاتردوباره بخوان و کل گام را تکرار کن
422 (idempotency)کلید با payload دیگری دوباره استفاده شدهنهباگ در کلاینت
429 / RESOURCE_EXHAUSTEDمحدودیت نرخ یا سهمیهبله، با احترام به Retry-Afterآهسته کن
500 / INTERNAL، UNKNOWNباگ یا ناوردای شکستهفقط با کلید idempotency، به‌ندرتهشدار
502، 503 / UNAVAILABLEگذرابله، با backoffgRPC: "not always safe to retry non-idempotent operations"
504 / DEADLINE_EXCEEDEDمنتظر ماندن رها شد؛ نتیجه نامعلومفقط idempotent یا کلیدداروضعیت را بررسی کن یا با همان کلید retry کن
رد اتصال پیش از ارسالچیزی به سرور نرسیدبلهحتی برای POST امن است
reset اتصال بعد از ارسالنتیجه نامعلومفقط idempotent یا کلیددارمثل 504

پیام‌های خطایی که واقعاً می‌بینید ​

کجاپیاممعنا
Go net/httpcontext deadline exceeded (Client.Timeout exceeded while awaiting headers)http.Client.Timeout فعال شد
Gocontext deadline exceededdeadline context خودتان رسید
Go gRPCrpc error: code = DeadlineExceeded desc = context deadline exceededdeadline در gRPC
Go gRPCrpc error: code = Unavailable desc = connection errorخطای انتقال؛ قابل retry
لاراولIlluminate\Http\Client\ConnectionException (cURL error 28: Operation timed out)از timeout() گذشت
لاراولIlluminate\Http\Client\RequestExceptionهمهٔ retryها با پاسخ خطا شکست خوردند
Envoyupstream request timeout (504)timeout مسیر در proxy
Problem Details{"type": ..., "title": "A request is outstanding for this Idempotency-Key", "status": 409}تکراری هم‌زمان

Go ​

ماژول Go (academy/service-communication) برای هر ایده یک package دارد. همه‌اش کتابخانهٔ استاندارد است جز کلاینت gRPC.

Before ​

نسخهٔ اول رایج: یک کلاینت مشترک بدون timeout، یک حلقهٔ retry با مکث ثابت دور یک POST، بدون کلید، بدون deadline از فراخوان.

go
// Command before is the version NOT to copy: a client without a timeout,
// a fixed-pause retry loop around a POST, no idempotency key and no
// deadline from the caller.
package main

import (
	"errors"
	"fmt"
	"net/http"
	"strings"
	"time"
)

const billingURL = "http://billing.internal"

var client = &http.Client{} // no Timeout: waits forever

func charge(orderID string, cents int64) error {
	body := fmt.Sprintf(`{"order_id":%q,"amount_cents":%d}`, orderID, cents)
	for i := 0; i < 3; i++ { // every layer above does the same: 3 x 3 x 3
		resp, err := client.Post(billingURL+"/charges", "application/json", strings.NewReader(body))
		if err == nil && resp.StatusCode < 500 {
			resp.Body.Close()
			return nil
		}
		time.Sleep(100 * time.Millisecond) // all clients wake up together
	} // a timeout after billing charged the card -> a second charge
	return errors.New("billing failed")
}

func main() {
	if err := charge("1001", 4999); err != nil {
		fmt.Println(err)
	}
}

After ​

انتشار deadline و trace. middleware هدر Request-Timeout-Ms را به deadline روی context تبدیل می‌کند و trace مربوط به W3C را نگه می‌دارد یا شروع می‌کند؛ Outgoing روی هر فراخوانی خروجی «آنچه مانده منهای یک حاشیه» را می‌نویسد و از فرستادن فراخوانی محکوم‌به‌شکست خودداری می‌کند.

go
// Package callbudget propagates a request deadline and W3C trace context
// across HTTP hops. HTTP has no standard deadline header (gRPC has
// grpc-timeout); Request-Timeout-Ms is this codebase's convention.
package callbudget

import (
	"context"
	"crypto/rand"
	"encoding/hex"
	"errors"
	"net/http"
	"strconv"
	"strings"
	"time"
)

const (
	HeaderTimeout     = "Request-Timeout-Ms" // convention, not a standard
	HeaderTraceparent = "traceparent"        // W3C Trace Context
)

type ctxKey struct{}

// ErrBudgetSpent means there is no time left to make a useful call.
var ErrBudgetSpent = errors.New("callbudget: remaining budget below safety margin")

// Middleware turns the caller's remaining budget into a context deadline.
// A missing header gets defaultBudget; anything above maxBudget is capped.
func Middleware(defaultBudget, maxBudget time.Duration, next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		budget := defaultBudget
		if v := r.Header.Get(HeaderTimeout); v != "" {
			if ms, err := strconv.Atoi(v); err == nil && ms > 0 {
				budget = time.Duration(ms) * time.Millisecond
			}
		}
		if budget > maxBudget {
			budget = maxBudget
		}
		ctx, cancel := context.WithTimeout(r.Context(), budget)
		defer cancel()

		tp := r.Header.Get(HeaderTraceparent)
		if !valid(tp) {
			tp = "00-" + randHex(16) + "-" + randHex(8) + "-01"
		}
		ctx = context.WithValue(ctx, ctxKey{}, tp)
		next.ServeHTTP(w, r.WithContext(ctx))
	})
}

// Outgoing stamps the remaining budget (minus a margin for the network and
// for our own post-processing) and a child traceparent on an outbound request.
// It fails fast when the budget is already spent: a doomed call is not sent.
func Outgoing(req *http.Request, margin time.Duration) error {
	ctx := req.Context()
	if dl, ok := ctx.Deadline(); ok {
		left := time.Until(dl) - margin
		if left < time.Millisecond {
			return ErrBudgetSpent
		}
		req.Header.Set(HeaderTimeout, strconv.FormatInt(left.Milliseconds(), 10))
	}
	if tp, ok := ctx.Value(ctxKey{}).(string); ok {
		// Same trace-id, new parent-id: this hop becomes the parent span.
		parts := strings.Split(tp, "-")
		req.Header.Set(HeaderTraceparent, parts[0]+"-"+parts[1]+"-"+randHex(8)+"-"+parts[3])
	}
	return nil
}

// TraceID returns the trace-id for logs, or "" when none is known.
func TraceID(ctx context.Context) string {
	if tp, ok := ctx.Value(ctxKey{}).(string); ok {
		return strings.Split(tp, "-")[1]
	}
	return ""
}

// valid checks the version-00 shape: 2-32-16-2 lowercase hex fields.
func valid(tp string) bool {
	p := strings.Split(tp, "-")
	if len(p) != 4 || len(p[0]) != 2 || len(p[1]) != 32 || len(p[2]) != 16 || len(p[3]) != 2 {
		return false
	}
	for _, s := range p {
		if _, err := hex.DecodeString(s); err != nil || strings.ToLower(s) != s {
			return false
		}
	}
	return p[1] != strings.Repeat("0", 32) && p[2] != strings.Repeat("0", 16)
}

func randHex(n int) string {
	b := make([]byte, n)
	_, _ = rand.Read(b)
	return hex.EncodeToString(b)
}

Retry با full jitter، بررسی idempotency و بودجهٔ retry. Do فقط متدهای idempotent یا درخواست‌های دارای Idempotency-Key را retry می‌کند، به Retry-After احترام می‌گذارد، وقتی deadline جای تلاش دیگری ندارد می‌ایستد، و وقتی بودجهٔ مشترک تمام شد هم.

go
// Package retry is an HTTP retry loop that is safe by construction: it only
// retries idempotent requests, waits with full jitter, respects the caller's
// deadline and Retry-After, and stops when a client-wide retry budget is spent.
package retry

import (
	"context"
	"errors"
	"io"
	"math/rand/v2"
	"net/http"
	"strconv"
	"sync"
	"time"
)

// Budget is a client-side retry budget modelled on gRPC retry throttling:
// failures cost 1 token, successes earn tokenRatio, and retries pause while
// tokens are at or below half of maxTokens.
type Budget struct {
	mu            sync.Mutex
	tokens, max   float64
	ratio         float64
	Denied, Spent int
}

func NewBudget(maxTokens int, tokenRatio float64) *Budget {
	return &Budget{tokens: float64(maxTokens), max: float64(maxTokens), ratio: tokenRatio}
}

func (b *Budget) record(ok bool) {
	b.mu.Lock()
	defer b.mu.Unlock()
	if ok {
		b.tokens = min(b.max, b.tokens+b.ratio)
	} else {
		b.tokens = max(0, b.tokens-1)
	}
}

func (b *Budget) allow() bool {
	b.mu.Lock()
	defer b.mu.Unlock()
	if b.tokens > b.max/2 {
		b.Spent++
		return true
	}
	b.Denied++
	return false
}

// Policy configures Do. Zero Rand means math/rand/v2.
type Policy struct {
	MaxAttempts int           // total attempts, including the first
	Base, Cap   time.Duration // exponential backoff base and ceiling
	Budget      *Budget       // optional, shared by all calls to one dependency
	Rand        func(n int64) int64
}

// FullJitter returns a random wait in [0, min(cap, base*2^attempt)].
func FullJitter(base, cap time.Duration, attempt int, rnd func(int64) int64) time.Duration {
	d := cap
	if attempt < 30 && base<<attempt < cap {
		d = base << attempt
	}
	return time.Duration(rnd(int64(d) + 1))
}

// ErrNotIdempotent is returned when a retry would be unsafe.
var ErrNotIdempotent = errors.New("retry: request is not idempotent and has no Idempotency-Key")

// Do sends the request built by newReq, retrying transient failures.
// newReq is called once per attempt so the body can be rebuilt.
func Do(ctx context.Context, c *http.Client, p Policy, newReq func(context.Context) (*http.Request, error)) (*http.Response, error) {
	rnd := p.Rand
	if rnd == nil {
		rnd = rand.Int64N
	}
	for attempt := 0; ; attempt++ {
		req, err := newReq(ctx)
		if err != nil {
			return nil, err
		}
		maxAttempts := p.MaxAttempts
		if !idempotent(req) {
			maxAttempts = 1 // one attempt only: a retry could double the side effect
		}
		resp, err := c.Do(req)
		retryable, after := classify(ctx, resp, err)
		if p.Budget != nil {
			p.Budget.record(!retryable)
		}
		if !retryable || attempt+1 >= maxAttempts {
			if retryable && maxAttempts == 1 && p.MaxAttempts > 1 && err != nil {
				return resp, errors.Join(err, ErrNotIdempotent)
			}
			return resp, err
		}
		if p.Budget != nil && !p.Budget.allow() {
			return resp, err // budget spent: fail fast instead of adding load
		}
		wait := max(after, FullJitter(p.Base, p.Cap, attempt, rnd))
		if dl, ok := ctx.Deadline(); ok && time.Until(dl) <= wait {
			return resp, err // the next attempt could not finish in time
		}
		if resp != nil {
			_, _ = io.Copy(io.Discard, resp.Body)
			resp.Body.Close()
		}
		t := time.NewTimer(wait)
		select {
		case <-ctx.Done():
			t.Stop()
			return nil, ctx.Err()
		case <-t.C:
		}
	}
}

// idempotent: RFC 9110 idempotent methods, or any request carrying a key.
func idempotent(r *http.Request) bool {
	switch r.Method {
	case http.MethodGet, http.MethodHead, http.MethodOptions, http.MethodPut, http.MethodDelete:
		return true
	}
	return r.Header.Get("Idempotency-Key") != ""
}

// classify decides whether a result is worth another attempt.
func classify(ctx context.Context, resp *http.Response, err error) (bool, time.Duration) {
	if err != nil {
		return ctx.Err() == nil, 0 // our own deadline or cancel: never retry
	}
	switch resp.StatusCode {
	case http.StatusTooManyRequests, http.StatusBadGateway, http.StatusServiceUnavailable, http.StatusGatewayTimeout:
		if s, e := strconv.Atoi(resp.Header.Get("Retry-After")); e == nil && s >= 0 {
			return true, time.Duration(s) * time.Second
		}
		return true, 0
	}
	return false, 0
}

کلید idempotency سمت سرور، با یک تست برای چهار نتیجه (اجرای اول، 409 در حین اجرا، بازپخش، 422 برای استفادهٔ دوباره):

go
// Package idempotency is server-side Idempotency-Key handling: first request
// runs, a completed duplicate gets the stored response replayed, a concurrent
// duplicate gets 409, and a key reused with a different payload gets 422.
// The in-memory map stands in for a table with a unique key (see the SQL on
// the page); the state machine is the same.
package idempotency

import (
	"bytes"
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"io"
	"net/http"
	"sync"
	"time"
)

type record struct {
	fingerprint string
	done        bool
	status      int
	header      http.Header
	body        []byte
	expires     time.Time
}

// Store keeps keys for ttl (Stripe prunes v1 keys after at least 24 hours).
type Store struct {
	mu  sync.Mutex
	m   map[string]*record
	ttl time.Duration
	now func() time.Time
}

func NewStore(ttl time.Duration) *Store {
	return &Store{m: map[string]*record{}, ttl: ttl, now: time.Now}
}

// Middleware enforces keys on POST and PATCH.
func (s *Store) Middleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.Method != http.MethodPost && r.Method != http.MethodPatch {
			next.ServeHTTP(w, r)
			return
		}
		key := r.Header.Get("Idempotency-Key")
		if key == "" || len(key) > 255 {
			Problem(w, http.StatusBadRequest, "Idempotency-Key is missing", "This operation requires an Idempotency-Key header of at most 255 characters.")
			return
		}
		body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
		if err != nil {
			Problem(w, http.StatusBadRequest, "Unreadable body", err.Error())
			return
		}
		r.Body = io.NopCloser(bytes.NewReader(body))
		sum := sha256.Sum256(append([]byte(r.Method+" "+r.URL.Path+"\n"), body...))
		fp := hex.EncodeToString(sum[:])
		// Scope keys per caller so two clients cannot collide.
		scoped := r.Header.Get("X-Client-Id") + "|" + r.URL.Path + "|" + key

		s.mu.Lock()
		rec, seen := s.m[scoped]
		if seen && s.now().After(rec.expires) {
			delete(s.m, scoped)
			seen = false
		}
		switch {
		case seen && rec.fingerprint != fp:
			s.mu.Unlock()
			Problem(w, http.StatusUnprocessableEntity, "Idempotency-Key is already used", "The key was used with a different payload.")
			return
		case seen && !rec.done:
			s.mu.Unlock()
			Problem(w, http.StatusConflict, "A request is outstanding for this Idempotency-Key", "Retry after the first request finishes.")
			return
		case seen:
			s.mu.Unlock()
			for k, v := range rec.header {
				w.Header()[k] = v
			}
			w.Header().Set("Idempotent-Replayed", "true")
			w.WriteHeader(rec.status)
			_, _ = w.Write(rec.body)
			return
		}
		s.m[scoped] = &record{fingerprint: fp, expires: s.now().Add(s.ttl)}
		s.mu.Unlock()

		cw := &capture{ResponseWriter: w, status: http.StatusOK}
		next.ServeHTTP(cw, r)

		s.mu.Lock()
		defer s.mu.Unlock()
		if cw.status >= 500 {
			delete(s.m, scoped) // our choice: let the client retry a server failure
			return
		}
		rec = s.m[scoped]
		rec.done, rec.status, rec.header, rec.body = true, cw.status, w.Header().Clone(), cw.buf.Bytes()
	})
}

type capture struct {
	http.ResponseWriter
	status int
	buf    bytes.Buffer
}

func (c *capture) WriteHeader(code int) { c.status = code; c.ResponseWriter.WriteHeader(code) }
func (c *capture) Write(b []byte) (int, error) {
	c.buf.Write(b)
	return c.ResponseWriter.Write(b)
}

// Problem writes an RFC 9457 problem details response.
func Problem(w http.ResponseWriter, status int, title, detail string) {
	w.Header().Set("Content-Type", "application/problem+json")
	w.WriteHeader(status)
	_ = json.NewEncoder(w).Encode(map[string]any{
		"type":   "https://errors.example.com/idempotency",
		"title":  title,
		"status": status,
		"detail": detail,
	})
}
go
package idempotency

import (
	"net/http"
	"net/http/httptest"
	"strings"
	"sync/atomic"
	"testing"
	"time"
)

func TestKeyStates(t *testing.T) {
	var runs atomic.Int32
	release := make(chan struct{})
	h := NewStore(24 * time.Hour).Middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if runs.Add(1) == 1 {
			<-release // keep the first request in flight
		}
		w.WriteHeader(http.StatusCreated)
		_, _ = w.Write([]byte(`{"charge_id":"ch_1"}`))
	}))
	send := func(key, body string) *httptest.ResponseRecorder {
		req := httptest.NewRequest(http.MethodPost, "/charges", strings.NewReader(body))
		req.Header.Set("Idempotency-Key", key)
		rec := httptest.NewRecorder()
		h.ServeHTTP(rec, req)
		return rec
	}

	first := make(chan *httptest.ResponseRecorder)
	go func() { first <- send("k1", `{"amount":10}`) }()
	for runs.Load() == 0 {
		time.Sleep(time.Millisecond)
	}
	if c := send("k1", `{"amount":10}`).Code; c != http.StatusConflict {
		t.Fatalf("concurrent duplicate: want 409 got %d", c)
	}
	close(release)
	if c := (<-first).Code; c != http.StatusCreated {
		t.Fatalf("first: want 201 got %d", c)
	}
	replay := send("k1", `{"amount":10}`)
	if replay.Code != http.StatusCreated || replay.Header().Get("Idempotent-Replayed") != "true" {
		t.Fatalf("replay: got %d %v", replay.Code, replay.Header())
	}
	if c := send("k1", `{"amount":99}`).Code; c != http.StatusUnprocessableEntity {
		t.Fatalf("payload mismatch: want 422 got %d", c)
	}
	if c := send("", `{"amount":10}`).Code; c != http.StatusBadRequest {
		t.Fatalf("missing key: want 400 got %d", c)
	}
	if runs.Load() != 1 {
		t.Fatalf("handler ran %d times, want 1", runs.Load())
	}
}

کلاینت gRPC با سیاست retry، throttling و deadline (از health service استاندارد استفاده می‌کند، پس تولید کد لازم نیست):

go
// Command grpcclient shows a gRPC client with a per-method retry policy,
// retry throttling (a client-side retry budget) and a deadline taken from
// the caller's context. It uses the standard health service so that no
// generated code is needed.
package main

import (
	"context"
	"log"
	"os"
	"time"

	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/credentials/insecure"
	healthpb "google.golang.org/grpc/health/grpc_health_v1"
	"google.golang.org/grpc/status"
)

// serviceConfig is normally delivered by the name resolver; a default is set
// here so the client still behaves well without it.
const serviceConfig = `{
  "methodConfig": [{
    "name": [{"service": "grpc.health.v1.Health", "method": "Check"}],
    "timeout": "0.8s",
    "retryPolicy": {
      "maxAttempts": 3,
      "initialBackoff": "0.05s",
      "maxBackoff": "0.5s",
      "backoffMultiplier": 2,
      "retryableStatusCodes": ["UNAVAILABLE"]
    }
  }],
  "retryThrottling": {"maxTokens": 10, "tokenRatio": 0.1}
}`

func main() {
	addr := os.Getenv("BILLING_ADDR")
	if addr == "" {
		log.Println("BILLING_ADDR not set; nothing to call")
		return
	}
	conn, err := grpc.NewClient(addr,
		grpc.WithTransportCredentials(insecure.NewCredentials()), // use mTLS credentials in production
		grpc.WithDefaultServiceConfig(serviceConfig),
	)
	if err != nil {
		log.Fatalf("new client: %v", err)
	}
	defer conn.Close()

	// The deadline comes from the caller. In a server handler you would pass
	// the incoming ctx unchanged so grpc-go propagates the remaining budget.
	ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
	defer cancel()

	resp, err := healthpb.NewHealthClient(conn).Check(ctx, &healthpb.HealthCheckRequest{Service: "billing"})
	switch status.Code(err) {
	case codes.OK:
		log.Printf("billing status: %s", resp.GetStatus())
	case codes.DeadlineExceeded:
		log.Printf("budget spent; the call may still have run on the server: %v", err)
	case codes.Unavailable:
		log.Printf("still unavailable after retries: %v", err)
	default:
		log.Printf("non-retryable error: %v", err)
	}
}

خواندن hedge‌شده به‌صورت دستی (grpc-go hedgingPolicy ندارد):

go
// Package hedge sends a backup request when the first one is slower than
// delay (pick roughly the p95 latency) and returns the first success.
// grpc-go does not support hedgingPolicy, so this is done by hand.
// Use it only for idempotent reads.
package hedge

import (
	"context"
	"time"
)

type result[T any] struct {
	v   T
	err error
}

// First runs call up to maxCalls times, starting a new one every delay
// (or immediately after a failure), and cancels the losers.
func First[T any](ctx context.Context, delay time.Duration, maxCalls int, call func(context.Context) (T, error)) (T, error) {
	ctx, cancel := context.WithCancel(ctx)
	defer cancel() // cancels every outstanding copy when we return

	results := make(chan result[T], maxCalls)
	launch := func() {
		go func() {
			v, err := call(ctx)
			results <- result[T]{v, err}
		}()
	}
	launch()
	launched, failed := 1, 0
	timer := time.NewTimer(delay)
	defer timer.Stop()

	var zero T
	var lastErr error
	for {
		select {
		case r := <-results:
			if r.err == nil {
				return r.v, nil
			}
			failed, lastErr = failed+1, r.err
			if failed == launched && launched == maxCalls {
				return zero, lastErr
			}
			if launched < maxCalls {
				launch()
				launched++
			}
		case <-timer.C:
			if launched < maxCalls {
				launch()
				launched++
				timer.Reset(delay)
			}
		case <-ctx.Done():
			return zero, ctx.Err()
		}
	}
}

یک فرمان ناهمگام با handler idempotent. تحویل اول شارژ می‌کند و بعد تأییدش (ack) گم می‌شود؛ تحویل دوباره نادیده گرفته می‌شود. خروجی: nack msg-1001 attempt=1، skip msg-1001 (duplicate)، charge msg-1002، ledger: map[1001:4999 1002:1500].

go
// Command asynccmd sends a ChargeOrder command through a queue with
// at-least-once delivery and shows that an idempotent handler charges once
// even when the broker redelivers. The channel stands in for the broker and
// the map for a processed_messages table (see the SQL on the page).
package main

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

// ChargeOrder is a command: one named receiver, imperative name, an ID the
// producer chooses so every redelivery carries the same identity.
type ChargeOrder struct {
	MessageID   string
	OrderID     string
	AmountCents int64
	Traceparent string
}

// Inbox records processed message IDs. In SQL this is an INSERT ... ON
// CONFLICT DO NOTHING in the same transaction as the side effect.
type Inbox struct {
	mu   sync.Mutex
	seen map[string]bool
}

func (i *Inbox) FirstTime(id string) bool {
	i.mu.Lock()
	defer i.mu.Unlock()
	if i.seen[id] {
		return false
	}
	i.seen[id] = true
	return true
}

type Ledger struct {
	mu      sync.Mutex
	charges map[string]int64
}

func (l *Ledger) Charge(orderID string, cents int64) {
	l.mu.Lock()
	defer l.mu.Unlock()
	l.charges[orderID] += cents
}

var errTransient = errors.New("payment gateway timeout")

func handle(ctx context.Context, in *Inbox, l *Ledger, m ChargeOrder, failOnce *bool) error {
	if err := ctx.Err(); err != nil {
		return err
	}
	if !in.FirstTime(m.MessageID) {
		fmt.Printf("skip  %s (duplicate)\n", m.MessageID)
		return nil // ack: already done
	}
	// In production the inbox row and the charge commit in ONE transaction,
	// so a failed charge also rolls back the mark.
	l.Charge(m.OrderID, m.AmountCents)
	if *failOnce {
		*failOnce = false
		return errTransient // charged, but the ack is lost: broker redelivers
	}
	fmt.Printf("charge %s order=%s amount=%d\n", m.MessageID, m.OrderID, m.AmountCents)
	return nil
}

func main() {
	queue := make(chan ChargeOrder, 8)
	in := &Inbox{seen: map[string]bool{}}
	ledger := &Ledger{charges: map[string]int64{}}
	failOnce := true

	queue <- ChargeOrder{MessageID: "msg-1001", OrderID: "1001", AmountCents: 4999}
	queue <- ChargeOrder{MessageID: "msg-1002", OrderID: "1002", AmountCents: 1500}
	close(queue)

	ctx := context.Background()
	for m := range queue {
		for attempt := 1; ; attempt++ { // the broker redelivers until acked
			if err := handle(ctx, in, ledger, m, &failOnce); err != nil {
				fmt.Printf("nack  %s attempt=%d err=%v\n", m.MessageID, attempt, err)
				continue
			}
			break
		}
	}
	fmt.Println("ledger:", ledger.charges)
}

Contract test به سبک Pact. یک فایل JSON قرارداد است؛ تست مصرف‌کننده کلاینت واقعی را در برابر mockی که از آن ساخته شده اجرا می‌کند و تست provider آن را روی handler واقعی بازپخش می‌کند.

json
{
  "consumer": { "name": "orders" },
  "provider": { "name": "billing" },
  "interactions": [
    {
      "description": "a charge for a pending order",
      "providerState": "customer 42 has enough credit",
      "request": {
        "method": "POST",
        "path": "/charges",
        "headers": { "Content-Type": "application/json", "Idempotency-Key": "order-1001-charge" },
        "body": { "order_id": "1001", "customer_id": "42", "amount_cents": 4999, "currency": "EUR" }
      },
      "response": {
        "status": 201,
        "headers": { "Content-Type": "application/json" },
        "body": { "charge_id": "ch_example", "status": "captured" },
        "matchingRules": { "$.body.charge_id": { "match": "type" } }
      }
    }
  ],
  "metadata": { "pactSpecification": { "version": "2.0.0" } }
}
go
// Package contract is a Pact-style consumer-driven contract between the
// orders service (consumer) and billing (provider), using only the standard
// library. The JSON file is the contract both sides test against; with the
// real Pact tools it would be generated by the consumer test and published
// to a Pact Broker.
package contract

import (
	_ "embed"
	"encoding/json"
)

//go:embed pacts/orders-billing.json
var pactJSON []byte

type Pact struct {
	Consumer     struct{ Name string } `json:"consumer"`
	Provider     struct{ Name string } `json:"provider"`
	Interactions []Interaction         `json:"interactions"`
}

type Interaction struct {
	Description   string `json:"description"`
	ProviderState string `json:"providerState"`
	Request       struct {
		Method  string            `json:"method"`
		Path    string            `json:"path"`
		Headers map[string]string `json:"headers"`
		Body    map[string]any    `json:"body"`
	} `json:"request"`
	Response struct {
		Status        int                          `json:"status"`
		Headers       map[string]string            `json:"headers"`
		Body          map[string]any               `json:"body"`
		MatchingRules map[string]map[string]string `json:"matchingRules"`
	} `json:"response"`
}

func Load() (Pact, error) {
	var p Pact
	err := json.Unmarshal(pactJSON, &p)
	return p, err
}

// Matches checks that actual contains at least the expected fields
// ("provider verification passes if each request generates a response that
// contains at least the data described"); type rules relax exact values.
func Matches(expected, actual map[string]any, rules map[string]map[string]string) []string {
	var problems []string
	for k, want := range expected {
		got, ok := actual[k]
		if !ok {
			problems = append(problems, "missing field "+k)
			continue
		}
		if rules["$.body."+k]["match"] == "type" {
			if _, same := got.(string); same != isString(want) {
				problems = append(problems, "wrong type for "+k)
			}
			continue
		}
		wj, _ := json.Marshal(want)
		gj, _ := json.Marshal(got)
		if string(wj) != string(gj) {
			problems = append(problems, "field "+k+": want "+string(wj)+" got "+string(gj))
		}
	}
	return problems
}

func isString(v any) bool { _, ok := v.(string); return ok }
go
package contract

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"net/http"
)

// ChargeRequest is what orders sends to billing.
type ChargeRequest struct {
	OrderID     string `json:"order_id"`
	CustomerID  string `json:"customer_id"`
	AmountCents int64  `json:"amount_cents"`
	Currency    string `json:"currency"`
}

// ChargeResult holds only the fields orders reads (Tolerant Reader:
// unknown fields from billing are ignored, so billing may add fields freely).
type ChargeResult struct {
	ChargeID string `json:"charge_id"`
	Status   string `json:"status"`
}

type BillingClient struct {
	BaseURL string
	HTTP    *http.Client
}

func (c BillingClient) Charge(ctx context.Context, in ChargeRequest, idempotencyKey string) (ChargeResult, error) {
	body, err := json.Marshal(in)
	if err != nil {
		return ChargeResult{}, err
	}
	req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.BaseURL+"/charges", bytes.NewReader(body))
	if err != nil {
		return ChargeResult{}, err
	}
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Idempotency-Key", idempotencyKey)
	resp, err := c.HTTP.Do(req)
	if err != nil {
		return ChargeResult{}, err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusCreated && resp.StatusCode != http.StatusOK {
		return ChargeResult{}, fmt.Errorf("billing: unexpected status %d", resp.StatusCode)
	}
	var out ChargeResult
	err = json.NewDecoder(resp.Body).Decode(&out)
	return out, err
}
go
package contract

import (
	"encoding/json"
	"net/http"
	"strconv"
	"sync/atomic"
	"time"
)

// NewBillingHandler is the provider. It returns more fields than orders
// reads (created_at, amount_cents); that is a compatible extension.
func NewBillingHandler() http.Handler {
	var seq atomic.Int64
	mux := http.NewServeMux()
	mux.HandleFunc("POST /charges", func(w http.ResponseWriter, r *http.Request) {
		var in ChargeRequest
		if err := json.NewDecoder(r.Body).Decode(&in); err != nil || in.AmountCents <= 0 {
			w.Header().Set("Content-Type", "application/problem+json")
			w.WriteHeader(http.StatusUnprocessableEntity)
			_ = json.NewEncoder(w).Encode(map[string]any{"type": "about:blank", "title": "Invalid charge", "status": 422})
			return
		}
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusCreated)
		_ = json.NewEncoder(w).Encode(map[string]any{
			"charge_id":    "ch_" + strconv.FormatInt(seq.Add(1), 10),
			"status":       "captured",
			"amount_cents": in.AmountCents,
			"created_at":   time.Now().UTC().Format(time.RFC3339),
		})
	})
	return mux
}
go
package contract

import (
	"context"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"reflect"
	"testing"
)

// TestConsumerAgainstContract plays the Pact mock provider: it checks that
// the real BillingClient sends exactly the request in the contract and can
// read the contracted response.
func TestConsumerAgainstContract(t *testing.T) {
	p, err := Load()
	if err != nil {
		t.Fatal(err)
	}
	for _, it := range p.Interactions {
		t.Run(it.Description, func(t *testing.T) {
			mock := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
				if r.Method != it.Request.Method || r.URL.Path != it.Request.Path {
					t.Errorf("request line: got %s %s", r.Method, r.URL.Path)
				}
				for k, v := range it.Request.Headers {
					if r.Header.Get(k) != v {
						t.Errorf("header %s: want %q got %q", k, v, r.Header.Get(k))
					}
				}
				var body map[string]any
				_ = json.NewDecoder(r.Body).Decode(&body)
				if !reflect.DeepEqual(body, it.Request.Body) {
					t.Errorf("body: want %v got %v", it.Request.Body, body)
				}
				for k, v := range it.Response.Headers {
					w.Header().Set(k, v)
				}
				w.WriteHeader(it.Response.Status)
				_ = json.NewEncoder(w).Encode(it.Response.Body)
			}))
			defer mock.Close()

			c := BillingClient{BaseURL: mock.URL, HTTP: mock.Client()}
			res, err := c.Charge(context.Background(), ChargeRequest{
				OrderID: "1001", CustomerID: "42", AmountCents: 4999, Currency: "EUR",
			}, "order-1001-charge")
			if err != nil {
				t.Fatal(err)
			}
			if res.Status != "captured" || res.ChargeID == "" {
				t.Fatalf("unexpected result %+v", res)
			}
		})
	}
}
go
package contract

import (
	"bytes"
	"encoding/json"
	"net/http/httptest"
	"testing"
)

// TestProviderHonoursContract replays every contracted request against the
// real billing handler (no orders service running) and checks the response.
func TestProviderHonoursContract(t *testing.T) {
	p, err := Load()
	if err != nil {
		t.Fatal(err)
	}
	h := NewBillingHandler()
	for _, it := range p.Interactions {
		t.Run(it.Description, func(t *testing.T) {
			// Provider state "customer 42 has enough credit" would be set up here.
			body, _ := json.Marshal(it.Request.Body)
			req := httptest.NewRequest(it.Request.Method, it.Request.Path, bytes.NewReader(body))
			for k, v := range it.Request.Headers {
				req.Header.Set(k, v)
			}
			rec := httptest.NewRecorder()
			h.ServeHTTP(rec, req)

			if rec.Code != it.Response.Status {
				t.Fatalf("status: want %d got %d", it.Response.Status, rec.Code)
			}
			var got map[string]any
			if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil {
				t.Fatal(err)
			}
			for _, problem := range Matches(it.Response.Body, got, it.Response.MatchingRules) {
				t.Error(problem)
			}
			if ct := rec.Header().Get("Content-Type"); ct != it.Response.Headers["Content-Type"] {
				t.Errorf("content type %q", ct)
			}
		})
	}
}

نگاه Go ​

قابلیت Goکاربرد در ارتباط سرویس‌هانکته
context.Contextdeadline، لغو و مقدارهای درخواست در همهٔ فراخوانی‌هامقالهٔ context در وبلاگ Go: آن را آرگومان اول بدهید
http.Client.Timeoutسقف کل تبادل: زمان اتصال، redirectها و خواندن بدنهٔ پاسخ (طبق توضیح خود فیلد)صفر یعنی بدون timeout؛ http.DefaultClient ندارد
http.NewRequestWithContextدرخواست را به deadline فراخوان گره می‌زندلغو context درخواست را قطع می‌کند
net/http/httptestprovider ساختگی و recorder برای contract testشبکه لازم نیست
math/rand/v2Jitterrand.Int64N
golang.org/x/sync/errgroupcomposition موازی با یک deadlineاولین خطا بقیه را لغو می‌کند
google.golang.org/grpcgrpc.NewClient، WithDefaultServiceConfig، status.Code(err)وقتی ctx ورودی را بدهید deadline منتشر می‌شود
go.opentelemetry.io/contrib/.../otelhttpمدیریت خودکار traceparentجای کد trace دست‌نویس این صفحه را می‌گیرد

Laravel ​

Before ​

php
<?php

namespace App\Actions;

use App\Models\Order;
use Illuminate\Support\Facades\Http;

/**
 * Before: do not copy. Retries 4xx as well as 5xx with a fixed 100 ms pause
 * (and every layer above may do the same), keeps the default 30 s timeout,
 * and sends no Idempotency-Key, so a timeout after billing charged the card
 * leads to a second charge.
 */
final class ChargeOrderBefore
{
    public function __invoke(Order $order): void
    {
        Http::retry(3, 100)
            ->post(config('services.billing.url').'/charges', [
                'order_id' => $order->id,
                'amount_cents' => $order->total_cents,
            ]);
    }
}

After ​

بودجهٔ هر درخواست که با $this->app->scoped(CallBudget::class) ثبت می‌شود (مستندات container: "one time within a given Laravel request / job lifecycle" resolve می‌شود)، و middlewareی که آن را از Request-Timeout-Ms و traceparent پر می‌کند:

php
<?php

namespace App\Support;

use RuntimeException;

/**
 * The time left for the current request, and its W3C trace context.
 * Registered with $this->app->scoped(CallBudget::class) so each request
 * (or queued job) gets a fresh instance.
 */
final class CallBudget
{
    public const HEADER_TIMEOUT = 'Request-Timeout-Ms'; // our convention, not a standard

    private ?float $deadline = null; // monotonic seconds, from hrtime()

    private ?string $traceparent = null;

    public function start(float $seconds, ?string $traceparent): void
    {
        $this->deadline = hrtime(true) / 1e9 + $seconds;
        $this->traceparent = $traceparent;
    }

    public function remainingSeconds(): ?float
    {
        return $this->deadline === null ? null : $this->deadline - hrtime(true) / 1e9;
    }

    public function traceparent(): ?string
    {
        return $this->traceparent;
    }

    /**
     * Headers for an outbound call: remaining budget minus a safety margin,
     * and a child traceparent (same trace-id, new parent-id).
     *
     * @return array<string, string>
     */
    public function outgoingHeaders(float $marginSeconds = 0.005): array
    {
        $headers = [];
        $left = $this->remainingSeconds();
        if ($left !== null) {
            $left -= $marginSeconds;
            if ($left < 0.001) {
                throw new RuntimeException('Call budget spent; not sending a doomed request.');
            }
            $headers[self::HEADER_TIMEOUT] = (string) (int) floor($left * 1000);
        }
        if ($this->traceparent !== null) {
            [$version, $traceId, , $flags] = explode('-', $this->traceparent);
            $headers['traceparent'] = "{$version}-{$traceId}-".bin2hex(random_bytes(8))."-{$flags}";
        }

        return $headers;
    }
}
php
<?php

namespace App\Http\Middleware;

use App\Support\CallBudget;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Context;
use Symfony\Component\HttpFoundation\Response;

/**
 * Turns the caller's Request-Timeout-Ms into this request's budget and
 * keeps (or starts) the W3C trace so every log line and outbound call
 * carries the same trace-id.
 */
final class PropagateCallBudget
{
    private const DEFAULT_SECONDS = 2.0;

    private const MAX_SECONDS = 10.0;

    public function __construct(private CallBudget $budget) {}

    public function handle(Request $request, Closure $next): Response
    {
        $ms = (int) $request->header(CallBudget::HEADER_TIMEOUT, '0');
        $seconds = $ms > 0 ? min($ms / 1000, self::MAX_SECONDS) : self::DEFAULT_SECONDS;

        $traceparent = (string) $request->header('traceparent', '');
        if (preg_match('/^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$/', $traceparent) !== 1) {
            $traceparent = '00-'.bin2hex(random_bytes(16)).'-'.bin2hex(random_bytes(8)).'-01';
        }

        $this->budget->start($seconds, $traceparent);
        Context::add('trace_id', explode('-', $traceparent)[1]); // appears in every log entry

        return $next($request);
    }
}

کلاینت HTTP: timeout() از روی بودجه، retry() با closure از نوع full jitter و callback when که فقط خطاهای گذرا را تا وقتی زمان و بودجهٔ RateLimiter اجازه می‌دهد retry می‌کند، و همان Idempotency-Key در هر تلاش:

php
<?php

namespace App\Clients;

use App\Support\CallBudget;
use Exception;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\RateLimiter;
use Throwable;

/**
 * Synchronous call from orders to billing: deadline from the incoming
 * request, retries only for transient failures, full jitter, an
 * Idempotency-Key so a retried POST cannot charge twice, and a
 * cluster-wide retry budget (at most 60 retries per minute, via the cache).
 */
final class BillingClient
{
    public function __construct(private CallBudget $budget) {}

    /** @return array{charge_id: string, status: string} */
    public function charge(string $orderId, string $customerId, int $amountCents, string $currency): array
    {
        $headers = $this->budget->outgoingHeaders(); // throws when the budget is already spent
        $remaining = $this->budget->remainingSeconds() ?? 2.0;

        $response = Http::baseUrl(config('services.billing.url'))
            ->acceptJson()
            ->connectTimeout(min(0.5, $remaining))
            ->timeout($remaining)
            ->withHeaders($headers + [
                'Idempotency-Key' => "order-{$orderId}-charge", // same key on every attempt
            ])
            ->retry(
                3,
                fn (int $attempt, Exception $e): int => random_int(0, min(1000, 100 * 2 ** ($attempt - 1))),
                function (Throwable $e, PendingRequest $request): bool {
                    $transient = $e instanceof ConnectionException
                        || ($e instanceof RequestException && in_array($e->response->status(), [429, 502, 503, 504], true));
                    $left = $this->budget->remainingSeconds() ?? 2.0;
                    // increment() is atomic on redis, memcached and database stores.
                    if (! $transient || $left < 0.05 || RateLimiter::increment('retry-budget:billing') > 60) {
                        return false; // not transient, no time left, or budget spent
                    }
                    $request->timeout($left)->withHeaders($this->budget->outgoingHeaders());

                    return true;
                },
            )
            ->post('/charges', [
                'order_id' => $orderId,
                'customer_id' => $customerId,
                'amount_cents' => $amountCents,
                'currency' => $currency,
            ]);

        // Tolerant Reader: read only the two fields we need, ignore the rest.
        return [
            'charge_id' => (string) $response->json('charge_id'),
            'status' => (string) $response->json('status'),
        ];
    }
}

Idempotency سمت سرور با جدولی که کلید اصلی‌اش قفل است:

php
<?php

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

return new class extends Migration
{
    public function up(): void
    {
        // Provider side: one row per (caller, key); the primary key is the lock.
        Schema::create('idempotency_keys', function (Blueprint $table) {
            $table->string('scope', 100);
            $table->string('key', 255);
            $table->char('fingerprint', 64);
            $table->unsignedSmallInteger('response_status')->nullable();
            $table->longText('response_body')->nullable();
            $table->string('response_content_type', 100)->nullable();
            $table->timestamp('locked_at')->nullable();
            $table->timestamp('expires_at')->index();
            $table->timestamp('created_at');
            $table->primary(['scope', 'key']);
        });

        // Consumer side: one row per handled message (inbox / dedup table).
        Schema::create('processed_messages', function (Blueprint $table) {
            $table->string('message_id', 100);
            $table->string('handler', 100);
            $table->timestamp('processed_at');
            $table->primary(['message_id', 'handler']);
        });

        // Local copy of another service's data (event-carried state transfer).
        Schema::create('customer_snapshots', function (Blueprint $table) {
            $table->string('customer_id', 64)->primary();
            $table->string('name');
            $table->string('email');
            $table->string('tier', 20);
            $table->unsignedBigInteger('version');
            $table->timestamp('updated_at');
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('customer_snapshots');
        Schema::dropIfExists('processed_messages');
        Schema::dropIfExists('idempotency_keys');
    }
};
php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpFoundation\Response;

/**
 * Server side of Idempotency-Key: the (scope, key) primary key is the lock.
 * First request runs; a finished duplicate is replayed; a concurrent one
 * gets 409; a key reused with another payload gets 422 (IETF draft -09).
 */
final class RequireIdempotencyKey
{
    public function handle(Request $request, Closure $next): Response
    {
        if (! in_array($request->method(), ['POST', 'PATCH'], true)) {
            return $next($request);
        }

        $key = (string) $request->header('Idempotency-Key', '');
        if ($key === '' || strlen($key) > 255) {
            return $this->problem(400, 'Idempotency-Key is missing', 'Send an Idempotency-Key header of at most 255 characters.');
        }

        $scope = (string) ($request->user()?->getAuthIdentifier() ?? $request->header('X-Client-Id', 'anonymous'));
        $fingerprint = hash('sha256', $request->method().' '.$request->path()."\n".$request->getContent());
        $row = ['scope' => $scope, 'key' => $key];

        $inserted = DB::table('idempotency_keys')->insertOrIgnore($row + [
            'fingerprint' => $fingerprint,
            'locked_at' => now(),
            'expires_at' => now()->addDay(),
            'created_at' => now(),
        ]);

        if ($inserted === 0) {
            $existing = DB::table('idempotency_keys')->where($row)->first();

            if (! hash_equals($existing->fingerprint, $fingerprint)) {
                return $this->problem(422, 'Idempotency-Key is already used', 'The key was used with a different payload.');
            }

            if ($existing->response_status === null) {
                // Take over only if the first attempt crashed long ago.
                $takenOver = DB::table('idempotency_keys')->where($row)
                    ->whereNull('response_status')
                    ->where('locked_at', '<', now()->subMinutes(5))
                    ->update(['locked_at' => now()]);

                if ($takenOver === 0) {
                    return $this->problem(409, 'A request is outstanding for this Idempotency-Key', 'Retry after the first request finishes.');
                }
            } else {
                return response($existing->response_body, (int) $existing->response_status, [
                    'Content-Type' => $existing->response_content_type,
                    'Idempotent-Replayed' => 'true',
                ]);
            }
        }

        $response = $next($request);

        if ($response->getStatusCode() >= 500) {
            DB::table('idempotency_keys')->where($row)->delete(); // our choice: allow a clean retry

            return $response;
        }

        DB::table('idempotency_keys')->where($row)->update([
            'response_status' => $response->getStatusCode(),
            'response_body' => $response->getContent(),
            'response_content_type' => $response->headers->get('Content-Type'),
            'locked_at' => null,
        ]);

        return $response;
    }

    private function problem(int $status, string $title, string $detail): Response
    {
        return response()->json([
            'type' => 'https://errors.example.com/idempotency',
            'title' => $title,
            'status' => $status,
            'detail' => $detail,
        ], $status, ['Content-Type' => 'application/problem+json']);
    }
}

خطاها به شکل Problem Details و ثبت middleware:

php
<?php

use App\Http\Middleware\PropagateCallBudget;
use App\Http\Middleware\RequireIdempotencyKey;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Context;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        api: __DIR__.'/../routes/api.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {
        $middleware->api(prepend: [PropagateCallBudget::class]);
        $middleware->alias(['idempotent' => RequireIdempotencyKey::class]);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        // Errors leave this service as RFC 9457 Problem Details, so every
        // caller can tell "retry later" from "your request is wrong".
        $exceptions->render(function (Throwable $e, Request $request) {
            if (! $request->is('api/*')) {
                return null; // default rendering
            }
            [$status, $title, $headers] = match (true) {
                $e instanceof ConnectionException => [503, 'A dependency is unavailable', ['Retry-After' => '1']],
                $e instanceof HttpExceptionInterface => [$e->getStatusCode(), 'Request failed', $e->getHeaders()],
                default => null,
            } ?? [null, null, []];
            if ($status === null) {
                return null; // validation, auth etc. keep Laravel's handling
            }

            return response()->json([
                'type' => 'about:blank',
                'title' => $title,
                'status' => $status,
                'detail' => $e->getMessage(),
                'instance' => $request->path(),
                'trace_id' => Context::get('trace_id'),
            ], $status, $headers + ['Content-Type' => 'application/problem+json']);
        });
    })
    ->create();

یک فرمان ناهمگام با ShouldBeUnique و handler idempotent. مستندات صف ShouldBeUnique را قفلی در زمان dispatch توصیف می‌کنند: "If the lock is already held, the job is not dispatched. This lock is released when the job completes processing or fails all of its retry attempts." این جلوی صف شدن تکراری را می‌گیرد، نه اجرای تکراری بعد از crash، پس handler همچنان شناسهٔ پیام را در همان تراکنش ثبت می‌کند:

php
<?php

namespace App\Contracts;

interface PaymentGateway
{
    /** Returns the gateway's charge id; the same key always yields the same charge. */
    public function charge(string $orderId, int $amountCents, string $idempotencyKey): string;
}
php
<?php

namespace App\Jobs;

use App\Contracts\PaymentGateway;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\Backoff;
use Illuminate\Queue\Attributes\Tries;
use Illuminate\Queue\Attributes\UniqueFor;
use Illuminate\Support\Facades\DB;

/**
 * An asynchronous command. ShouldBeUnique stops a second ChargeOrder for the
 * same order from being QUEUED while one is pending (a dispatch-time lock).
 * It does not make the handler idempotent: a worker can still crash after
 * charging and the job runs again. The processed_messages row does that.
 */
#[Tries(5)]
#[Backoff([1, 5, 15, 60])]
#[UniqueFor(3600)]
final class ChargeOrder implements ShouldBeUnique, ShouldQueue
{
    use Queueable;

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

    public function uniqueId(): string
    {
        return $this->orderId;
    }

    public function handle(PaymentGateway $gateway): void
    {
        DB::transaction(function () use ($gateway) {
            $first = DB::table('processed_messages')->insertOrIgnore([
                'message_id' => $this->messageId,
                'handler' => self::class,
                'processed_at' => now(),
            ]);
            if ($first === 0) {
                return; // already handled: finish so the job is acknowledged
            }

            // If this transaction rolls back, the retry calls the gateway
            // again with the SAME key and gets the same charge back.
            $chargeId = $gateway->charge($this->orderId, $this->amountCents, "order-{$this->orderId}-charge");

            DB::table('orders')->where('id', $this->orderId)
                ->update(['status' => 'paid', 'charge_id' => $chargeId]);
        });
    }
}

مصرف‌کنندهٔ event-carried state transfer. مصرف‌کنندهٔ broker (ببینید Laravel Queue Internals و packageهای RabbitMQ/Kafka در مسیر messaging) JSON را با tolerant reader باز می‌کند و CustomerChanged را dispatch می‌کند؛ listener صف‌دار فقط نسخه‌های جدیدتر را upsert می‌کند:

php
<?php

namespace App\Events;

use Illuminate\Foundation\Events\Dispatchable;

/**
 * Integration event published by the customers service and decoded here by
 * the broker consumer. It carries the state (event-carried state transfer),
 * so orders never has to call customers to read a name or a tier.
 */
final class CustomerChanged
{
    use Dispatchable;

    public function __construct(
        public string $customerId,
        public string $name,
        public string $email,
        public string $tier,
        public int $version,
    ) {}

    /** Tolerant Reader: take what we need, ignore unknown fields, default new optional ones. */
    public static function fromMessage(array $payload): self
    {
        return new self(
            customerId: (string) $payload['customer_id'],
            name: (string) ($payload['name'] ?? ''),
            email: (string) ($payload['email'] ?? ''),
            tier: (string) ($payload['tier'] ?? 'standard'),
            version: (int) $payload['version'],
        );
    }
}
php
<?php

namespace App\Listeners;

use App\Events\CustomerChanged;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\DB;

/**
 * Keeps orders' local copy of customer data. Idempotent and order-tolerant:
 * a duplicate or an older event (lower version) changes nothing.
 */
final class StoreCustomerSnapshot implements ShouldQueue
{
    public function handle(CustomerChanged $event): void
    {
        DB::statement(<<<'SQL'
            INSERT INTO customer_snapshots (customer_id, name, email, tier, version, updated_at)
            VALUES (?, ?, ?, ?, ?, now())
            ON CONFLICT (customer_id) DO UPDATE
               SET name = EXCLUDED.name, email = EXCLUDED.email, tier = EXCLUDED.tier,
                   version = EXCLUDED.version, updated_at = now()
             WHERE customer_snapshots.version < EXCLUDED.version
            SQL, [$event->customerId, $event->name, $event->email, $event->tier, $event->version]);
    }
}

Contract testها روی همان فایل JSON تست‌های Go (فایل go/contract/pacts/orders-billing.json را در هر دو اپ به contracts/ کپی کنید، یا از Pact Broker بگیرید):

php
<?php

namespace Tests\Contract;

use App\Clients\BillingClient;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;

/**
 * Runs in the ORDERS app. Plays the provider from the shared contract file
 * (the same JSON the Go tests use) and checks that BillingClient sends
 * exactly the contracted request and can read the contracted response.
 */
final class BillingConsumerContractTest extends TestCase
{
    public function test_orders_sends_the_contracted_charge_request(): void
    {
        $pact = json_decode(file_get_contents(base_path('contracts/orders-billing.json')), true, flags: JSON_THROW_ON_ERROR);
        $it = $pact['interactions'][0];

        config(['services.billing.url' => 'https://billing.test']);
        Http::preventStrayRequests();
        Http::fake([
            'billing.test/*' => Http::response($it['response']['body'], $it['response']['status'], $it['response']['headers']),
        ]);

        $result = app(BillingClient::class)->charge('1001', '42', 4999, 'EUR');

        $this->assertSame('captured', $result['status']);
        $this->assertNotSame('', $result['charge_id']);
        Http::assertSent(fn (Request $request): bool => $request->method() === $it['request']['method']
            && $request->url() === 'https://billing.test'.$it['request']['path']
            && $request->hasHeader('Idempotency-Key', $it['request']['headers']['Idempotency-Key'])
            && $request->data() == $it['request']['body']);
    }
}
php
<?php

namespace Tests\Contract;

use Illuminate\Support\Facades\DB;
use Illuminate\Testing\Fluent\AssertableJson;
use Tests\TestCase;

/**
 * Runs in the BILLING app. Replays every contracted request against the real
 * routes and checks the response contains at least the contracted fields
 * (extra fields are allowed: that is what keeps additions compatible).
 */
final class BillingProviderContractTest extends TestCase
{
    public function test_billing_honours_the_orders_contract(): void
    {
        $pact = json_decode(file_get_contents(base_path('contracts/orders-billing.json')), true, flags: JSON_THROW_ON_ERROR);

        foreach ($pact['interactions'] as $it) {
            $this->givenProviderState($it['providerState']);

            $response = $this->json($it['request']['method'], $it['request']['path'], $it['request']['body'], $it['request']['headers']);

            $response->assertStatus($it['response']['status']);
            $response->assertJson(function (AssertableJson $json) use ($it) {
                $rules = $it['response']['matchingRules'] ?? [];
                foreach ($it['response']['body'] as $field => $value) {
                    ($rules["$.body.{$field}"]['match'] ?? null) === 'type'
                        ? $json->whereType($field, gettype($value))
                        : $json->where($field, $value);
                }
                $json->etc();
            });
        }
    }

    private function givenProviderState(string $state): void
    {
        match ($state) {
            'customer 42 has enough credit' => DB::table('credit_limits')
                ->updateOrInsert(['customer_id' => '42'], ['available_cents' => 100_000]),
            default => $this->fail("Unknown provider state: {$state}"),
        };
    }
}

نگاه Laravel ​

قابلیت Laravel 13کاربردنکته
Http::timeout() / connectTimeout()سقف هر فراخوانیپیش‌فرض ۳۰ و ۱۰ ثانیه؛ امضا int|float می‌پذیرد
Http::retry($times, $sleep, $when, throw:)Retrycallback $when می‌تواند درخواست را عوض کند (توکن تازه، timeout تازه)
Http::pool()composition موازییک درخواست برای هر backend، هم‌زمان
Http::globalRequestMiddleware()افزودن traceparent به هر فراخوانی خروجیدر AppServiceProvider::boot ثبت کنید
Http::fake()، Http::preventStrayRequests()، Http::assertSent()contract test مصرف‌کنندهبدون شبکه
Context::add()trace ID در هر خط log و در jobهای صف"across the HTTP request / queued job boundary" به اشتراک گذاشته می‌شود
ShouldBeUnique، #[UniqueFor]، uniqueId()یک job در انتظار برای هر کلیدcache با قابلیت قفل لازم است (redis، memcached، dynamodb، database، file، array)
ShouldBeUniqueUntilProcessingباز شدن قفل با شروع پردازشاجازهٔ dispatch تازه در حین اجرای اولی
middleware WithoutOverlapping برای jobیک job در حال اجرا برای هر کلیدقفل با expireAfter()
#[Tries]، #[Backoff]، #[RetryFor]، #[MaxExceptions]سیاست retry سمت مصرف‌کنندهRetry و Backoff
ShouldQueueAfterCommitdispatch فقط بعد از commit تراکنشoutbox کامل نیست؛ ببینید Outbox
RateLimiter::increment()بودجهٔ retry در سطح cluster (اینجا ۶۰ retry در دقیقه)روی storeهای redis، memcached و database اتمی است

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

طوفان retry هنگام قطعی ​

text
     t      Event                                                Load on billing
1    0 s    billing slows down (GC, failover)                    100%
2    1 s    frontends, orders and gateway each retry 3x          up to 64x on the slowest path
3    5 s    billing recovers capacity, but the queue of retries  still above 100%: no recovery
4    fix    retry at one layer, jittered, budgeted               about 1.1x; recovers in seconds
راه‌حلچطورمزیتهزینه / محدودیت
Retry در یک لایهفقط لایهٔ درست بالای لایهٔ خراب retry می‌کند؛ بقیه خطا را بالا می‌دهندضرب شدن را می‌کشدتیم‌ها باید توافق کنند؛ کتابخانه‌ها پیش‌فرض retry دارند
بودجهٔ retryنسبت per-client زیر ۱۰٪ (SRE) یا token bucket (retryThrottling، AWS SDK)بار را در قطعی محدود می‌کندوقتی خطاها تصادفی و زیادند موفقیت کمتر (ببینید آزمایشگاه)
Full jitterrandom(0, min(cap, base * 2^n))موج هم‌گام نمی‌سازدمیانگین انتظار کمی بیشتر
سیگنال «اضافه‌بار؛ retry نکن»سرور خطای جدا یا grpc-retry-pushback-ms برمی‌گرداندretry را از منبع متوقف می‌کندقرارداد پروتکلی لازم دارد
Circuit breakerسریع شکست خوردن برای یک دورهٔ خنک شدنبه وابستگی فضا می‌دهدرفتار حالت‌دار، تست سخت‌تر

شارژ دوباره بعد از timeout ​

text
     Client                               Billing
1    POST /charges (no key)               charges card
2    timeout at 2 s (response was slow)
3    retry POST /charges (no key)         charges card again: customer charged twice
راه‌حلچطورمزیتهزینه / محدودیت
کلید idempotency با پاسخ ذخیره‌شده(scope, key) یکتا، fingerprint، بازپخشretry امن برای هر POSTذخیره‌سازی، TTL، مسیر 409
idempotency طبیعیPUT /charges/{order_id} یا upsert روی کلید کسب‌وکاریجدول اضافه لازم نیستکلید کسب‌وکاری یکتا برای هر کار لازم است
حذف تکرار در مصرف‌کنندهشناسهٔ پیام در جدول inboxبرای صف‌ها کار می‌کندبرای هر مصرف‌کننده جدا، ببینید Inbox
POST را retry نکنیک تلاش، بعد تطبیق (reconcile)سادهدسترس‌پذیری بدتر؛ پیگیری دستی

جدول سمت provider و ادعای اتمی در PostgreSQL (migration لاراول بالا همین شکل را می‌سازد):

sql
CREATE TABLE idempotency_keys (
  scope                 varchar(100) NOT NULL,          -- caller identity (tenant, client id)
  key                   varchar(255) NOT NULL,          -- Stripe allows up to 255 characters
  fingerprint           char(64)     NOT NULL,          -- sha256(method, path, body)
  response_status       smallint,                       -- NULL while in progress
  response_body         text,
  response_content_type varchar(100),
  locked_at             timestamptz,                    -- lease for crashed holders
  expires_at            timestamptz  NOT NULL,
  created_at            timestamptz  NOT NULL DEFAULT now(),
  PRIMARY KEY (scope, key)
);
CREATE INDEX idempotency_keys_expires_at ON idempotency_keys (expires_at);

-- 1. Claim: exactly one concurrent request gets a row back.
INSERT INTO idempotency_keys (scope, key, fingerprint, locked_at, expires_at)
VALUES ($1, $2, $3, now(), now() + interval '24 hours')
ON CONFLICT (scope, key) DO NOTHING
RETURNING key;

-- 2. No row returned: read the existing claim and decide 422 / 409 / replay.
SELECT fingerprint, response_status, response_body, response_content_type, locked_at
FROM idempotency_keys WHERE scope = $1 AND key = $2;

-- 3. Success: store the outcome in the SAME transaction as the business change.
UPDATE idempotency_keys
SET response_status = $3, response_body = $4, response_content_type = $5, locked_at = NULL
WHERE scope = $1 AND key = $2;

-- 4. Housekeeping (scheduled): drop expired keys.
DELETE FROM idempotency_keys WHERE expires_at < now();

-- Consumer side: the inbox claim for a message, inside the handler's transaction.
INSERT INTO processed_messages (message_id, handler, processed_at)
VALUES ($1, $2, now())
ON CONFLICT (message_id, handler) DO NOTHING;

کار هدررفته بعد از رفتن فراخوان ​

راه‌حلچطورمزیتهزینه / محدودیت
انتشار deadlinegrpc-timeout، یا Request-Timeout-Ms به‌علاوهٔ contextهمهٔ hopها با هم می‌ایستندHTTP به یک قرارداد داخلی نیاز دارد
بررسی پیش از هر مرحلهif ctx.Err() != nil یا بودجهٔ باقی‌مانده پیش از کار گرانکار محکوم‌به‌شکست زود متوقف می‌شودانضباط در کد
انتشار لغو (cancellation)لغو فراخوانی‌های خروجی وقتی ورودی لغو شدمنابع سریع آزاد می‌شوندهمهٔ کلاینت‌ها پشتیبانی نمی‌کنند (PHP-FPM مسدودکننده است)
timeout کوتاه و واقع‌بینانهp99.9 فراخوانده، نه «۳۰ ثانیه»threadها تمام نمی‌شونددادهٔ تأخیر لازم است

تغییر provider مصرف‌کننده را در production می‌شکند ​

راه‌حلچطورمزیتهزینه / محدودیت
contract test مصرف‌کننده‌محورفایل‌های pact که در CI provider بررسی می‌شوندشکستن پیش از deploy پیدا می‌شودمصرف‌کننده‌ها باید pact بنویسند و منتشر کنند
Tolerant readerفیلد ناشناخته را نادیده بگیر، اختیاری‌های غایب را پیش‌فرض بدهتغییر افزایشی مجانی استممکن است تغییر معنا را پنهان کند
بررسی تغییر شکننده روی schemaقواعد شکستن Protobuf، سازگاری schema registry، diff روی OpenAPIمکانیکی و ارزانفقط شکل، نه معنا
Expand-and-contractجدید را اضافه کن، مصرف‌کننده‌ها را منتقل کن، قدیمی را حذف کنبدون روز سرنوشت (flag day)مدتی دو فیلد

صفحهٔ کندی که از چند سرویس ساخته می‌شود ​

راه‌حلچطورمزیتهزینه / محدودیت
composition موازی با یک deadlineerrgroup / Http::pool، نتیجهٔ ناقصتأخیر = کندترین، محدوددسترس‌پذیری همچنان حاصل‌ضرب
read model (ECST یا CQRS)نسخهٔ denormalize شده که با رویداد تغذیه می‌شودیک query محلیکهنگی، فضای بیشتر
Hedging برای دنبالهنسخهٔ دوم بعد از p95p99 را کم می‌کندبار اضافه؛ فقط خواندن idempotent
BFF برای هر کلاینتداده را برای یک صفحه شکل بدهرفت‌وبرگشت کمتر از موبایلیک سرویس دیگر برای اجرا

هیچ‌کس نمی‌تواند یک درخواست را دنبال کند ​

راه‌حلچطورمزیتهزینه / محدودیت
W3C traceparent همه‌جاmiddleware، کلاینت‌های HTTP، هدر پیام‌هاtraceهای مستقل از فروشندههر hop باید جلو ببرد
trace ID در logهاContext در لاراول، slog در Go با attributeهای tracelogها به traceها وصل می‌شوندانضباط در محل log
شناسهٔ گردش کار برای جریان‌های asyncشناسهٔ saga یا سفارش در هر پیامجریان گیرکرده پیدا می‌شودیک فیلد دیگر در قراردادها

خطاهایی که از هم تشخیص داده نمی‌شوند ​

راه‌حلچطورمزیتهزینه / محدودیت
Problem Details (RFC 9457)application/problem+json با URL ثابت typeماشین‌خوان، مستندهر exception باید نگاشت شود
کدهای دقیق gRPCINVALID_ARGUMENT در برابر FAILED_PRECONDITION در برابر UNAVAILABLEسیاست‌های retry می‌توانند به کدها تکیه کنندتیم‌ها باید روی نگاشت توافق کنند
هرگز 200 با بدنهٔ خطااز خط وضعیت استفاده کنproxyها، metricها و retryها خطا را می‌بینندکلاینت‌های قدیمی شاید shim لازم داشته باشند

تست ارتباط سرویس‌ها ​

تستچه چیزی را ثابت می‌کندابزارکجا اجرا می‌شود
contract test مصرف‌کنندهکلاینت من همان را می‌فرستد که قرارداد می‌گوید و آنچه لازم دارد را می‌خواندPact، Http::fake، httptestCI مصرف‌کننده
Provider verificationAPI من هنوز قرارداد همهٔ مصرف‌کننده‌ها را برآورده می‌کندPact verifier، feature testهای لاراول، httptest.NewRecorderCI provider، deploy را مسدود می‌کند
سازگاری schemaschema جدید backward/forward compatible استبررسی شکستن Protobuf، schema registryCI
تست جزء با fakeمنطق retry، timeout و fallback کار می‌کندhttptest.Server که 503 می‌دهد یا می‌خوابدCI در سطح واحد
تزریق خطا (Fault injection)سیستم همان‌طور که طراحی شده تنزل می‌کندToxiproxy ("a framework for simulating network conditions")، fault injection در Istio (fixedDelay: 7s، abort در HTTP)staging، game day
آزمایش chaosفرضیه دربارهٔ حالت پایدار زیر خرابی واقعی برقرار استروش chaos engineeringproduction، با شعاع انفجار کوچک (Chaos Engineering)
smoke test سرتاسریمسیر خوش با سرویس‌های واقعی کار می‌کندچند فراخوانی اسکریپتیبعد از deploy
text
     Fault-injection run for orders -> billing (staging)
1    hypothesis: with billing at 30% 503s, checkout success stays above 99% and billing load stays below 1.2x
2    inject: Istio abort 30% on billing, or Toxiproxy latency 500 ms
3    observe: checkout success, retries per request, billing RPS, p99, breaker state
4    example outcome to look for: success above 99%, load near 1.1x; at 80% failures the budget stops retries

انتخاب ​

کدام سبک ​

موقعیتسبکتکنیک اضافهدلیل
کاربر منتظر جوابی است که فقط سرویس دیگری دارد (قیمت، مجوز، موجودی)Sync request/responsedeadline، retry برای خواندن idempotent، fallbackجواب همین حالا لازم است
اثر جانبی‌ای که کاربر لازم نیست منتظرش بماند (ایمیل، فاکتور، analytics)فرمان async یا رویدادoutbox، مصرف‌کنندهٔ idempotentبدون جفت‌شدگی زمانی
کار طولانی یا محدودشده (شارژ، خروجی، راه‌اندازی)فرمان async + وضعیت202 Accepted، poll یا pushاتصال را نگه ندار
چند سرویس باید به یک واقعیت واکنش نشان دهندEvent notificationAsyncAPI، tracingproducer مصرف‌کننده‌ها را نمی‌شناسد
یک سرویس مدام دادهٔ دیگری را می‌خواندEvent-carried state transferupsert نسخه‌دار، tolerant readerوابستگی زمان اجرا حذف می‌شود
بازپخش، audit، مصرف‌کننده‌های بعدیEvent streamretention، کلید partition، schema registryتاریخچه خودش محصول است
سازگاری قوی بین دو سرویسمعمولاً مشکل مرز استادغام مالکیت، یا saga با جبرانACID ارزان بین سرویس‌ها نداریم
صفحه دادهٔ چند سرویس را می‌خواهدAPI composition / BFFفراخوانی موازی، نتیجهٔ ناقصیک رفت‌وبرگشت برای کلاینت
تأخیر دنباله روی خواندن‌های داغSync + hedgingتأخیر در p95، لغو بازنده‌هاp99 را کم می‌کند

Orchestration یا choreography ​

عاملorchestration را ترجیح بدهchoreography را ترجیح بده
تعداد گام‌هابیش از ۳-۴، یا شاخه‌دار۱ تا ۳ واکنش مستقل
نیاز به جبرانبله، به ترتیب مشخصنه، یا هر واکنش خودبسنده است
دیدن «سفارشم کجاست؟»لازم (پشتیبانی، SLA)لازم نیست
مالکیت تیمییک تیم مالک فرایند استهر واکنش مال تیمی دیگر است
بسامد تغییر جریانزیاد (یک جا برای تغییر)کم
جفت‌شدگی‌ای که می‌پذیریدorchestrator فرمان‌های شرکت‌کننده‌ها را می‌شناسدشرکت‌کننده‌ها نام رویدادها را می‌شناسند
ابزارهای رایجTemporal، Step Functions، Camunda، Bus::chaintopicهای broker، eventهای لاراول

کدام سیاست خطا ​

text
1  Does the operation change state?
2    no  -> retry transient errors (UNAVAILABLE, 503, 429, connect errors), jitter, budget
3    yes -> is it naturally idempotent (PUT by id, upsert, "set status = paid where status = pending")?
4            yes -> same as reads
5            no  -> add an Idempotency-Key (stored response, 409 while running, 422 on reuse); then retry
6  Which layer retries?  the one directly above the failing dependency; the others pass the error up
7  How long?             the propagated deadline; never a fixed 30 s
8  What if it keeps failing?  budget stops retries; breaker or fallback; async + DLQ for commands

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

یک تعامل ثابت، «بعد از checkout مشتری را شارژ کن و به ارسال خبر بده»، با رشد سیستم شکلش عوض می‌شود. چهار تصمیم (سبک، قرارداد، سیاست خطا، سیاست تکرار) ثابت می‌مانند؛ چیزی که عوض می‌شود این است که زیرساخت چقدر از هر کدام را مجانی می‌دهد.

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

چطور دیده می‌شود: یک فراخوانی متد. CheckoutService درون یک DB::transaction (ACID) متد PaymentService::charge() را صدا می‌زند؛ تنها فراخوانی شبکه به ارائه‌دهندهٔ پرداخت بیرونی است.

ساده‌ترین استفادهٔ درست: حتی اینجا فراخوانی ارائه‌دهندهٔ پرداخت timeout، کلید idempotency (order-1001-charge) و retry فقط برای خطاهای گذرا لازم دارد. رویدادهای درون پردازه (eventهای لاراول، callbackهای Go) همگام‌اند مگر در صف بروند.

مثال (ساده): فروشگاهی با یک اپ لاراول: action به نام PlaceOrder، فراخوانی Http::timeout(5)->retry(...)->withHeaders(['Idempotency-Key' => ...]) به Stripe، و job صف‌دار SendOrderEmail.

مثال (در اندازهٔ production): همان اپ با workerهای Horizon: jobهای ایمیل و فاکتور فرمان‌های ناهمگام‌اند؛ پرداخت همگام است چون کاربر منتظر است؛ یک job شبانهٔ تطبیق، سفارش‌ها را با شارژهای ارائه‌دهنده مقایسه می‌کند.

Modular monolith: مرز بدون شبکه ​

چطور دیده می‌شود: ماژول‌ها از طریق facade یا رویداد درون پردازه حرف می‌زنند؛ پس قرارداد وجود دارد (interface، DTO) اما خطاها هنوز محلی‌اند. اینجا جای تمرین قراردادهاست: اگر Billing\Api\ChargeRequest تنها راه ورود باشد، بیرون کشیدن billing بعدها تغییر انتقال است، نه بازطراحی (Modular Monolith).

مثال: orders رویداد OrderPlaced را روی گذرگاه درون پردازه منتشر می‌کند؛ billing و shipping گوش می‌دهند. بیرون بردن billing یعنی: listener مصرف‌کنندهٔ broker می‌شود، facade کلاینت HTTP/gRPC می‌شود و outbox جای «dispatch بعد از commit» را می‌گیرد.

دغدغهالان درون پردازهوقتی بیرون کشیده شد
قراردادinterface در PHP / Go + DTOOpenAPI / Protobuf / AsyncAPI
خطاExceptionTimeout، 503، نتیجهٔ نامعلوم
تکراری‌هاناممکنکلید و inbox لازم است
تراکنشیک BEGIN ... COMMITSaga، outbox

Microservices: هر پیکان یک تصمیم است ​

چطور دیده می‌شود: هر پیکان روی نمودار سبک، قرارداد، deadline، سیاست retry و سیاست تکرار لازم دارد. یک جریان مشخص:

text
     Client -> Gateway -> Orders (sync, budget 1 s)
1    Orders: INSERT order PENDING + outbox ChargeOrder (one transaction); reply 202 + /orders/1001
2    Relay -> payments.commands: ChargeOrder{msg_id, order_id, traceparent}
3    Payments: inbox claim msg_id; POST provider /charges (Idempotency-Key order-1001-charge, deadline 5 s)
4    Payments -> payments.events: PaymentSucceeded{order_id, version}
5    Orders: consumes, marks PAID; Shipping: consumes, books courier (choreography for the reactions)
6    Customers -> customers.events: CustomerChanged (ECST) -> Orders keeps customer_snapshots
7    Contract tests: orders<->payments (commands/events, AsyncAPI), gateway<->orders (OpenAPI)

چه چیزی از مرز عبور می‌کند: trace ID، deadline (برای hopهای همگام)، کلید idempotency و شناسهٔ پیام. چه چیزی عبور نمی‌کند: تراکنش‌ها (saga به کار ببرید)، exceptionها (Problem Details و کد وضعیت به کار ببرید) و نوع‌های مشترک (قرارداد منتشرشده به کار ببرید). دغدغه‌های لبه (احراز هویت، محدودیت نرخ، BFF) مال API Gateway، BFF و Service Mesh است؛ پیدا کردن نمونه‌ها مال Service Discovery.

داده توزیع‌شده (Distributed data): replica، cache، region ​

چطور دیده می‌شود: یک خواندن همگام ممکن است به replicaی بخورد که عقب است، پس «تازه پرداخت کردم و صفحهٔ سفارش می‌گوید در انتظار» یک مشکل ارتباطی است، نه فقط دیتابیسی (Replication). cache جلوی یک سرویس، کهنگی شبیه ECST را پیش‌فرض می‌کند. بین regionها، بودجهٔ ۱ ثانیه فقط برای یک hop بین‌منطقه‌ای (حدود ۷۰ تا ۱۵۰ ms رفت‌وبرگشت) جا دارد و نه خیلی بیشتر، پس فراخوانی‌های بین‌منطقه‌ای به replication ناهمگام منتقل می‌شوند.

اثرکجا درد داردچاره
تأخیر replicaread-your-writes بعد از یک فرمانتا N ثانیه از primary بخوان، یا حالت جدید را در پاسخ فرمان برگردان
cache کهنهنسخه‌های ECST، cacheهای BFFنسخه در رویداد، TTL کوتاه، باطل کردن با رویداد
تأخیر بین‌منطقه‌ایزنجیره‌های همگامی که چند region را می‌پوشانندفراخوانی همگام را درون region نگه دار؛ داده را async تکثیر کن
اختلاف ساعتdeadlineهای مطلقزمان باقی‌مانده بفرست، نه timestamp (همان کاری که gRPC می‌کند)
تکثیر انبار idempotencyدو region یک کلید را می‌پذیرندکلیدها را به region خانگی محدود کن، یا انبار با سازگاری قوی

مسیر مقیاس (Scaling path): ۱×، ۱۰×، ۱۰۰× ​

بارچه عوض می‌شودمثال
1xفراخوانی همگام با timeout و retry کلیددار؛ یک صف برای اثرهای جانبییک اپ لاراول + worker، یک سرویس Go
10xانتشار deadline، بودجهٔ retry، breaker برای هر وابستگی، نسخه‌های ECST جای خواندن‌های همگام داغ را می‌گیرند، contract test در CI۵ تا ۱۵ سرویس؛ Kafka یا RabbitMQ؛ Pact Broker
100xservice mesh (mTLS، retry، outlier detection)، hedging روی خواندن‌های داغ، انتشار criticality همراه درخواست (Google SRE)، load shedding در لبه، streamها به‌عنوان ستون فقرات یکپارچگیصدها سرویس؛ service config هر متد gRPC از resolver

آزمایشگاه: retry storm در برابر retry بودجه‌دار، با عدد ​

دو راهبرد را در برابر خطا و تأخیر تزریق‌شدهٔ یکسان اجرا می‌کنید و باری را که به سرویس پایینی می‌رسد مقایسه می‌کنید. همه‌چیز بدون اینترنت روی loopback اجرا می‌شود.

راه‌اندازی.

bash
cd docs/snippets/architecture/service-communication/go
go vet ./... && go test ./...
go run ./asynccmd     # duplicate delivery, single charge

برنامهٔ lab/stormlab سه سرویس HTTP روی loopback راه می‌اندازد، edge -> api -> db، و خطا (-fail، کسری از پاسخ‌های 503 در db با seed ثابت) و تأخیر (-latency، زمانی که db برای هر تلاش صرف می‌کند) تزریق می‌کند. حالت naive: edge و api هر کدام تا ۴ تلاش با مکث ثابت ۱ ms و timeout ثابت خودشان می‌کنند؛ db به deadline اعتنا نمی‌کند. حالت budgeted: فقط edge retry می‌کند (۳ تلاش، full jitter، بودجه به سبک gRPC با {10, 0.1})، یک deadline با Request-Timeout-Ms منتشر می‌شود و db وقتی deadline بگذرد کار را متوقف می‌کند.

go
// Command stormlab runs three HTTP services on loopback, edge -> api -> db,
// injects failures and latency at db, and compares two client strategies:
//
//	naive:    every hop retries 4 times with a fixed pause and its own
//	          fixed timeout; db does not watch the deadline.
//	budgeted: only the edge retries (3 attempts, full jitter, retry budget),
//	          one deadline is propagated with Request-Timeout-Ms, db stops
//	          work when the caller's deadline passes.
//
// Failures are drawn from a seeded generator and requests are sequential,
// so the counts are reproducible.
package main

import (
	"context"
	"flag"
	"fmt"
	"io"
	"math/rand/v2"
	"net/http"
	"net/http/httptest"
	"sync"
	"sync/atomic"
	"time"

	"academy/service-communication/callbudget"
	"academy/service-communication/retry"
)

var (
	mode      = flag.String("mode", "naive", "naive or budgeted")
	failRate  = flag.Float64("fail", 0.0, "fraction of db attempts rejected with 503")
	dbLatency = flag.Duration("latency", 2*time.Millisecond, "db work per attempt")
	n         = flag.Int("n", 100, "user requests")
	edgeTotal = flag.Duration("budget", 300*time.Millisecond, "edge deadline (budgeted) / per-attempt timeout x4 (naive)")
)

var (
	dbAttempts, dbOrphans, dbCancelled atomic.Int64
	rngMu                              sync.Mutex
	rng                                = rand.New(rand.NewPCG(1, 2))
	inflight                           sync.WaitGroup
)

func shouldFail() bool {
	rngMu.Lock()
	defer rngMu.Unlock()
	return rng.Float64() < *failRate
}

func db(budgeted bool) http.Handler {
	h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		inflight.Add(1)
		defer inflight.Done()
		dbAttempts.Add(1)
		if shouldFail() {
			w.WriteHeader(http.StatusServiceUnavailable)
			return
		}
		if budgeted {
			select {
			case <-time.After(*dbLatency):
			case <-r.Context().Done():
				dbCancelled.Add(1) // stopped doomed work early
				w.WriteHeader(http.StatusGatewayTimeout)
				return
			}
		} else {
			time.Sleep(*dbLatency) // deadline-unaware work
		}
		_, _ = io.WriteString(w, "ok")
	})
	if budgeted {
		return callbudget.Middleware(time.Second, 5*time.Second, h)
	}
	return h
}

func api(dbURL string, budgeted bool) http.Handler {
	if budgeted {
		client := &http.Client{}
		return callbudget.Middleware(time.Second, 5*time.Second, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			req, _ := http.NewRequestWithContext(r.Context(), http.MethodGet, dbURL, nil)
			if err := callbudget.Outgoing(req, 2*time.Millisecond); err != nil {
				w.WriteHeader(http.StatusGatewayTimeout)
				return
			}
			resp, err := client.Do(req) // no retry here: retry at one layer only
			if err != nil {
				w.WriteHeader(http.StatusGatewayTimeout)
				return
			}
			defer resp.Body.Close()
			w.WriteHeader(resp.StatusCode)
		}))
	}
	client := &http.Client{Timeout: time.Second} // fixed per-hop timeout
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		inflight.Add(1)
		defer inflight.Done()
		for attempt := 0; attempt < 4; attempt++ {
			resp, err := client.Get(dbURL) // context not propagated
			if err == nil {
				resp.Body.Close()
				if resp.StatusCode == http.StatusOK {
					if r.Context().Err() != nil {
						dbOrphans.Add(1) // the edge gave up: this work was for nobody
					}
					return
				}
			}
			time.Sleep(time.Millisecond)
		}
		w.WriteHeader(http.StatusServiceUnavailable)
	})
}

func main() {
	flag.Parse()
	budgeted := *mode == "budgeted"
	dbSrv := httptest.NewServer(db(budgeted))
	defer dbSrv.Close()
	apiSrv := httptest.NewServer(api(dbSrv.URL, budgeted))
	defer apiSrv.Close()

	budget := retry.NewBudget(10, 0.1)
	ok := 0
	start := time.Now()
	for i := 0; i < *n; i++ {
		if budgeted {
			ctx, cancel := context.WithTimeout(context.Background(), *edgeTotal)
			resp, err := retry.Do(ctx, http.DefaultClient, retry.Policy{
				MaxAttempts: 3, Base: 5 * time.Millisecond, Cap: 50 * time.Millisecond, Budget: budget,
			}, func(ctx context.Context) (*http.Request, error) {
				req, err := http.NewRequestWithContext(ctx, http.MethodGet, apiSrv.URL, nil)
				if err == nil {
					err = callbudget.Outgoing(req, 2*time.Millisecond)
				}
				return req, err
			})
			if err == nil {
				if resp.StatusCode == http.StatusOK {
					ok++
				}
				resp.Body.Close()
			}
			cancel()
			continue
		}
		c := &http.Client{Timeout: *edgeTotal / 4} // a timeout per attempt, not per request
		for attempt := 0; attempt < 4; attempt++ {
			resp, err := c.Get(apiSrv.URL)
			if err == nil {
				resp.Body.Close()
				if resp.StatusCode == http.StatusOK {
					ok++
					break
				}
			}
			time.Sleep(time.Millisecond)
		}
	}
	elapsed := time.Since(start)
	inflight.Wait()
	fmt.Printf("mode=%-8s fail=%.2f latency=%-6v requests=%d ok=%d db_attempts=%d amplification=%.2fx orphaned=%d cancelled=%d budget_denied=%d elapsed=%v\n",
		*mode, *failRate, *dbLatency, *n, ok, dbAttempts.Load(),
		float64(dbAttempts.Load())/float64(*n), dbOrphans.Load(), dbCancelled.Load(), budget.Denied, elapsed.Round(10*time.Millisecond))
}

گام ۱: خطا، بدون تأخیر. هر دو حالت را با چهار نرخ خطا اجرا کنید:

bash
for m in naive budgeted; do for f in 0 0.1 0.5 1; do go run ./lab/stormlab -mode $m -fail $f; done; done

خروجی روی دستگاه نویسنده (شمارش‌ها قطعی‌اند؛ زمان‌ها فرق می‌کنند):

text
mode=naive    fail=0.00 latency=2ms    requests=100 ok=100 db_attempts=100 amplification=1.00x orphaned=0 cancelled=0 budget_denied=0 elapsed=250ms
mode=naive    fail=0.10 latency=2ms    requests=100 ok=100 db_attempts=112 amplification=1.12x orphaned=0 cancelled=0 budget_denied=0 elapsed=260ms
mode=naive    fail=0.50 latency=2ms    requests=100 ok=100 db_attempts=174 amplification=1.74x orphaned=0 cancelled=0 budget_denied=0 elapsed=350ms
mode=naive    fail=1.00 latency=2ms    requests=100 ok=0 db_attempts=1600 amplification=16.00x orphaned=0 cancelled=0 budget_denied=0 elapsed=2.53s
mode=budgeted fail=0.00 latency=2ms    requests=100 ok=100 db_attempts=100 amplification=1.00x orphaned=0 cancelled=0 budget_denied=0 elapsed=250ms
mode=budgeted fail=0.10 latency=2ms    requests=100 ok=100 db_attempts=112 amplification=1.12x orphaned=0 cancelled=0 budget_denied=0 elapsed=290ms
mode=budgeted fail=0.50 latency=2ms    requests=100 ok=65 db_attempts=105 amplification=1.05x orphaned=0 cancelled=0 budget_denied=35 elapsed=180ms
mode=budgeted fail=1.00 latency=2ms    requests=100 ok=0 db_attempts=103 amplification=1.03x orphaned=0 cancelled=0 budget_denied=99 elapsed=30ms
نرخ خطاتلاش db در naiveتلاش db در budgetedموفق naiveموفق budgetedبرداشت
0%100 (1.00x)100 (1.00x)100100در حالت سالم فرقی نیست
10%112112100100خطای گذرای سبک: هر دو retry می‌کنند و موفق‌اند
50%17410510065بودجه موفقیت را با بار معاوضه می‌کند: برای اضافه‌بار درست، برای گم‌شدن تصادفی بیش از حد سخت‌گیر
100% (قطعی)1600 (16.00x = 4 x 4)103 (1.03x)00طوفان: naive بار را در حاصل‌ضرب تلاش‌های هر لایه ضرب می‌کند

گام ۲: تأخیر، بدون خطا. db ۱۵۰ ms طول می‌کشد؛ edge روی‌هم ۴۰۰ ms دارد (naive آن را به ۴ تلاش ۱۰۰ میلی‌ثانیه‌ای تقسیم می‌کند):

bash
go run ./lab/stormlab -mode naive    -n 20 -latency 150ms -budget 400ms
go run ./lab/stormlab -mode budgeted -n 20 -latency 150ms -budget 400ms
go run ./lab/stormlab -mode budgeted -n 20 -latency 150ms -budget 100ms
text
mode=naive    fail=0.00 latency=150ms  requests=20 ok=0 db_attempts=80 amplification=4.00x orphaned=80 cancelled=0 budget_denied=0 elapsed=8.16s
mode=budgeted fail=0.00 latency=150ms  requests=20 ok=20 db_attempts=20 amplification=1.00x orphaned=0 cancelled=0 budget_denied=0 elapsed=3.03s
mode=budgeted fail=0.00 latency=150ms  requests=20 ok=0 db_attempts=20 amplification=1.00x orphaned=0 cancelled=20 budget_denied=17 elapsed=1.91s

برداشت مورد انتظار: timeout هر تلاش که از تأخیر عادی فراخوانده کمتر است همهٔ درخواست‌ها را شکست می‌دهد و باز هم کل کار را چهار بار انجام می‌دهد (۸۰ تکمیل یتیم: db کار را تمام کرد و کسی گوش نمی‌داد). یک deadline منتشرشده که با تأخیر جور است ۲۰ از ۲۰ موفق می‌شود با ۲۰ تلاش. وقتی بودجه واقعاً کم است، db کار محکوم‌به‌شکست را لغو می‌کند (cancelled=20) به‌جای تمام کردنش، و بودجه جلوی retry را می‌گیرد (budget_denied ممکن است بین اجراها یکی دو واحد فرق کند چون به زمان‌بندی وابسته است).

گام ۳: بودجه را با نوع خطا جور کنید. در main.go مقدار retry.NewBudget(10, 0.1) را به retry.NewBudget(10, 1.0) تغییر دهید و -mode budgeted -fail 0.5 و -fail 1 را دوباره اجرا کنید. نتیجهٔ مشاهده‌شده: با ۵۰٪ خطا ok=79 db_attempts=136 (1.36x، در برابر ۶۵ و 1.05x)؛ با ۱۰۰٪ همچنان db_attempts=103 (1.03x)، چون بودجه فقط با موفقیت پر می‌شود. بنویسید برای وابستگی‌ای که به‌خاطر اضافه‌بار شکست می‌خورد کدام تنظیم را انتخاب می‌کنید و برای وابستگی‌ای که به‌خاطر شبکهٔ پرتلفات.

گام ۴: ترتیب بررسی‌ها را بسنجید. تستی اضافه کنید که در حالی که درخواست اول با کلید k1 هنوز در جریان است، (الف) همان کلید با بدنهٔ {"amount":99} و (ب) همان کلید و همان بدنه را بفرستد. نتیجهٔ مشاهده‌شده: (الف) 422 و (ب) 409 می‌گیرد: middleware پیش از نگاه به حالت «در حال اجرا» fingerprint را مقایسه می‌کند، پس باگ کلاینت (کلید تکراری) حتی وسط race هم همان‌طور گزارش می‌شود. دو خط case را در idempotency.go جابه‌جا کنید تا (الف) 409 شود؛ تصمیم بگیرید API شما کدام رفتار را مستند می‌کند.

گام ۵: قرارداد را بشکنید. در contract/provider.go فیلد JSON به نام status را به state تغییر دهید و go test ./contract را اجرا کنید. انتظار: TestProviderHonoursContract با missing field status شکست می‌خورد، در حالی که تست مصرف‌کننده هنوز قبول می‌شود. نکته همین است: provider شکستن را در CI خودش می‌فهمد.

گام ۶ (لاراول، اختیاری). فایل‌های PHP را در یک اپ Laravel 13 با PostgreSQL کپی کنید، migration را اجرا کنید، CallBudget را به‌صورت scoped ثبت کنید، POST /api/charges را از middleware idempotent عبور دهید و همان درخواست را دو بار با curl -H 'Idempotency-Key: k1' بفرستید. انتظار: پاسخ دوم Idempotent-Replayed: true دارد و handler یک بار اجرا شده.

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

باورواقعیت
Async همیشه decoupleتر استجفت‌شدگی زمانی را برمی‌دارد؛ جفت‌شدگی معنایی و جریان‌های پنهان می‌مانند (Fowler دربارهٔ event notification)
Timeout یعنی فراخوانی شکست خوردیعنی شما منتظر نماندید؛ DEADLINE_EXCEEDED در gRPC "may be returned even if the operation has completed successfully"
Retry قابلیت اطمینان را بالا می‌بردفقط برای خطای گذرا؛ زیر اضافه‌بار "selfish" هستند و بار را ضرب می‌کنند (۶۴ برابر، ۲۴۳ برابر)
سه retry پیش‌فرض امنی استدر سه لایه می‌شود ۶۴ تلاش؛ در یک لایه با بودجه retry کنید
Backoff نمایی کافی استبدون jitter کلاینت‌ها هم‌گام می‌مانند؛ full jitter فراخوانی‌ها را "by more than half" کم کرد
Circuit breaker طوفان را حل می‌کندکمک می‌کند اما رفتار حالت‌دار می‌آورد؛ بودجهٔ retry ساده‌تر و همیشه روشن است
ShouldBeUnique job لاراول را idempotent می‌کندجلوی dispatch تکراری را در حالی که یکی در انتظار است می‌گیرد؛ worker که crash کند job را دوباره اجرا می‌کند
بررسی «وجود دارد؟» پیش از درج POST را idempotent می‌کندcheck-then-insert مسابقه دارد؛ ادعا با کلید یکتا لازم است
رویدادها هرگز نباید داده حمل کنندevent-carried state transfer عمداً داده حمل می‌کند تا وابستگی زمان اجرا را حذف کند
راه تکامل API ساختن /v2 استتغییر افزایشی، tolerant reader و expand-and-contract بیشتر نسخه‌های جدید را غیرضروری می‌کنند
Contract test کاملاً جای integration test را می‌گیردبیشترشان را؛ چند smoke test سرتاسری بماند
فراخوانی داخلی احراز هویت نمی‌خواهدZero trust: mTLS به‌علاوهٔ توکنی با فراخوان و audience
request ID هر سرویس برای tracing کافی استفقط trace ID منتشرشده بین hopها و صف‌ها به هم وصل می‌شود
gRPC همه‌چیز را خودش retry می‌کندسیاست retry پیش‌فرض ندارد؛ فقط transparent retry برای RPCهایی که به برنامه نرسیده‌اند

چکیده (Cheat sheet) ​

موضوعبه خاطر بسپار
سبک‌هاSync req/resp، async req/resp (فرمان)، event notification، event-carried state transfer، stream
سؤال‌های جفت‌شدگیزمانی، دسترس‌پذیری، تأخیر، سازگاری، معنایی، استقرار
کی syncکاربر منتظر جوابی است که فقط سرویس دیگری دارد
کی asyncاثر جانبی، کار کند یا پرنوسان، پخش به واکنش‌های زیاد
Orchestrationگام‌های زیاد، جبران، نیاز به دیدن وضعیت
Choreographyچند واکنش مستقل که مال تیم‌های مختلف‌اند
قراردادهاOpenAPI (HTTP)، Protobuf (gRPC)، AsyncAPI (پیام)؛ بین تیم‌ها contract-first
سازگاریتغییر افزایشی، tolerant reader، شمارهٔ فیلد Protobuf را هرگز دوباره استفاده نکن، expand-and-contract
Pactمصرف‌کننده انتظار را می‌نویسد؛ provider در CI خودش بررسی می‌کند؛ provider state برای داده
Deadlineیک بار در لبه تعیین کن؛ باقی‌مانده منهای حاشیه را بفرست؛ وقتی گذشت کار را متوقف کن
مقدار timeoutصدک تأخیر فراخوانده در نرخ پذیرفته‌شدهٔ timeout کاذب (AWS: 0.1% -> p99.9)
قاعدهٔ retryفقط گذرا، فقط idempotent، حداکثر ۳ تلاش، یک لایه، full jitter، بودجه
Full jitterrandom(0, min(cap, base * 2^n))
کلید idempotencyساختهٔ کلاینت، دامنه‌دار، ادعای یکتا، fingerprint، پاسخ ذخیره‌شده، 409 در حین اجرا، 422 برای استفادهٔ دوباره، TTL >= 24 h
Hedgingخواندن idempotent، بعد از p95، لغو بازنده‌ها؛ در gRPC-Go دستی
خطاهاProblem Details در RFC 9457؛ کدهای دقیق gRPC؛ هرگز 200 با خطا
TracingW3C traceparent روی هر درخواست و پیام؛ trace ID در هر خط log

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

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

۱ — پنج سبک ارتباطی را نام ببرید و برای هر کدام یک مثال بزنید. حیاتی ​

پاسخ

پاسخ: Sync request/response (GET /customers/42)، async request/response یا فرمان (ChargeOrder روی صف و PaymentSucceeded برگشتی)، event notification (OrderPlaced {id})، event-carried state transfer (CustomerChanged همراه داده و نسخه)، event stream (topic کافکا که مصرف‌کننده‌ها بازپخشش می‌کنند). ببینید فهرست مفاهیم.

۲ — سرویسی سه وابستگی را پشت‌سرهم صدا می‌زند که هر کدام 99.9% در دسترس‌اند. دسترس‌پذیری آن درخواست در بهترین حالت چقدر است و دو راه بهبودش چیست؟ حیاتی ​

پاسخ

پاسخ: حدود 0.999^3 = 99.7%. فراخوانی‌های غیرضروری را ناهمگام یا اختیاری با fallback کنید، یا یک خواندن زمان اجرا را با نسخهٔ محلی که با رویداد تغذیه می‌شود (ECST) جایگزین کنید. ببینید جفت‌شدگی.

۳ — POST شما به billing بعد از ۲ ثانیه timeout شد. می‌توانید retry کنید؟ پیش از آن چه چیزی باید برقرار باشد؟ حیاتی ​

پاسخ

پاسخ: فقط اگر idempotent باشد: در retry همان Idempotency-Key را بفرستید و سرور باید کلیدها را اتمی ادعا کند و پاسخ ذخیره‌شده را بازپخش کند. Timeout یعنی شارژ انجام نشده نیست. ببینید کلید idempotency.

۴ — frontend، backend و سرویس داده هر کدام هنگام خطا ۳ بار retry می‌کنند. دیتابیس زیر اضافه‌بار است. یک کار کاربر چند تلاش می‌سازد و چه چیزی را عوض می‌کنید؟ حیاتی ​

پاسخ

پاسخ: 4 x 4 x 4 = 64 (مثال Google SRE). فقط در لایهٔ درست بالای لایهٔ خراب retry کنید و full jitter و بودجهٔ retry (نسبت per-client زیر ۱۰٪ یا token bucket) اضافه کنید. ببینید Retry.

۵ — edge بودجهٔ ۱۰۰۰ ms دارد، ۵۰ ms مصرف می‌کند و هر hop حاشیهٔ ۱۰ ms دارد. orders پیش از صدا زدن billing ۲۰۰ ms مصرف می‌کند. billing چه timeoutی دریافت می‌کند؟ مهم ​

پاسخ

پاسخ: 1000 - 50 - 10 = 940 به orders؛ 940 - 200 - 10 = 730 به billing. ببینید Deadline.

۶ — لایهٔ idempotency برای این‌ها چه برمی‌گرداند: (الف) تکراری در حین اجرای اولی، (ب) تکراری بعد از تکمیل، (ج) همان کلید با بدنهٔ دیگر؟ مهم ​

پاسخ

پاسخ: (الف) 409 Conflict، (ب) بازپخش پاسخ ذخیره‌شده، (ج) 422 Unprocessable Content (پیش‌نویس IETF نسخهٔ -09؛ Stripe هم پارامترهای ناهمخوان را رد می‌کند).

۷ — آیا ShouldBeUnique در لاراول handler job را idempotent می‌کند؟ توضیح دهید. حیاتی ​

پاسخ

پاسخ: نه. از dispatch تا وقتی job تمام شود یا همهٔ retryهایش شکست بخورد قفل نگه می‌دارد، پس dispatch دوم با همان uniqueId صف نمی‌شود. workerی که بعد از اثر جانبی crash کند job را دوباره اجرا می‌کند؛ handler به ردیف inbox یا نوشتن idempotent طبیعی نیاز دارد.

۸ — کی orchestration را به choreography ترجیح می‌دهید؟ مهم ​

پاسخ

پاسخ: وقتی جریان بیش از چند گام دارد، جبران‌های مرتب لازم دارد، یا کسی باید بتواند بگوید «این سفارش کجا گیر کرده؟». choreography برای چند واکنش مستقل که مال تیم‌های مختلف‌اند مناسب است. ببینید انتخاب.

۹ — billing می‌خواهد status را در پاسخ JSON به state تغییر نام دهد. چطور بدون شکستن orders؟ مهم ​

پاسخ

پاسخ: Expand-and-contract: هر دو فیلد را بفرست، بگذار مصرف‌کننده‌ها منتقل شوند (pact verification نشان می‌دهد چه کسی هنوز status را می‌خواند)، بعد فرستادن status را قطع کن. هرگز معنا را درجا عوض نکن. ببینید سازگاری.

۱۰ — چرا gRPC روی سیم به‌جای deadline مطلق، timeout باقی‌مانده می‌فرستد؟ تکمیلی ​

پاسخ

پاسخ: چون ساعت سرورها ممکن است فرق کند؛ "gRPC converts the deadline to a timeout from which the already elapsed time is already deducted. This shields your system from any clock skew issues."

۱۱ — در آزمایشگاه با ۵۰٪ خطای تصادفی، کلاینت budgeted ۶۵ بار و naive ۱۰۰ بار موفق شد. آیا بودجه غلط است؟ تکمیلی ​

پاسخ

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

۱۲ — کدام هدر trace را بین سرویس‌ها حمل می‌کند و جزئی که trace نمی‌کند باز هم باید با آن چه کند؟ حیاتی ​

پاسخ

پاسخ: traceparent (با tracestate اختیاری)، از W3C Trace Context. حتی جزء غیرشرکت‌کننده "MUST propagate the traceparent and tracestate headers".

واژه‌نامه (Glossary) ​

واژهمعنا
request/response همگام (Synchronous request/response)فراخوان منتظر پاسخ می‌ماند؛ فراخوانده باید در تمام مدت بالا باشد
request/response ناهمگام (Asynchronous request/response)درخواست به شکل پیام؛ پاسخ بعداً به شکل پیام دیگر یا callback
فرمان (Command)پیامی که از یک گیرندهٔ مشخص می‌خواهد کاری بکند
رویداد (Event)پیامی که واقعیتی رخ‌داده را بیان می‌کند؛ هر تعداد گیرنده
Event notificationرویداد فقط با شناسه؛ گیرنده‌ها ممکن است برای جزئیات صدا بزنند (Fowler)
Event-carried state transfer (ECST)رویداد دادهٔ تغییرکرده را حمل می‌کند تا گیرنده‌ها نسخهٔ محلی نگه دارند (Fowler)
فرمان منفعل-پرخاشگر (Passive-aggressive command)فرمانی که لباس رویداد پوشیده (Fowler)
Event streamlog پایدار، partition‌شده و قابل بازپخش؛ مصرف‌کننده‌ها مالک offsetاند
جفت‌شدگی زمانی (Temporal coupling)هر دو طرف باید هم‌زمان در دسترس باشند
Orchestrationیک هماهنگ‌کننده به شرکت‌کننده‌ها می‌گوید چه کنند
Choreographyشرکت‌کننده‌ها به رویدادهای هم واکنش نشان می‌دهند؛ بدون هماهنگ‌کننده
Sagaدنباله‌ای از تراکنش‌های محلی با جبران (Saga)
Contract-firstتوصیف API پیش از کد نوشته و بازبینی می‌شود
OpenAPIقالب توصیف APIهای HTTP (3.1.0)
Protocol Buffersschema و IDL باینری gRPC؛ فیلدها با شماره شناخته می‌شوند
AsyncAPIقالب توصیف APIهای پیام‌محور (3.0.0)
قرارداد مصرف‌کننده‌محور (Consumer-driven contract)انتظارات مصرف‌کننده که provider بررسی‌شان می‌کند
Pactابزار contract testing؛ فایل pact، provider state، Pact Broker
حالت provider (Provider state)پیش‌شرطی که provider پیش از بررسی یک تعامل آماده می‌کند
Tolerant Readerفقط آنچه لازم داری بخوان؛ فیلد ناشناخته را نادیده بگیر (Fowler، Postel)
Backward compatibleprovider جدید با مصرف‌کنندهٔ قدیمی کار می‌کند
Forward compatibleمصرف‌کنندهٔ قدیمی با دادهٔ producer جدید کار می‌کند
Expand-and-contractشکل جدید را اضافه کن، منتقل کن، بعد قدیمی را حذف کن
Deadlineلحظهٔ مطلقی که بعد از آن فراخوان منتظر نمی‌ماند
انتشار deadline (Deadline propagation)فرستادن بودجهٔ باقی‌مانده به هر فراخوانی پایین‌دست
Request-Timeout-Msقرارداد هدر HTTP این صفحه برای بودجهٔ باقی‌مانده (استاندارد نیست)
grpc-timeoutنمایش deadline باقی‌مانده روی سیم در gRPC
DEADLINE_EXCEEDEDوضعیت ۴ در gRPC: deadline گذشت؛ عملیات شاید انجام شده باشد
UNAVAILABLEوضعیت ۱۴ در gRPC: گذرا؛ اگر امن است با backoff دوباره تلاش کن
Backoff نمایی (Exponential backoff)انتظار به شکل base x 2^attempt تا یک سقف رشد می‌کند
Jitterتصادفی کردن انتظار برای ناهمگام کردن کلاینت‌ها
Full jitterانتظار تصادفی یکنواخت بین صفر و مقدار نمایی
طوفان retry (Retry storm)retry در لایه‌ها یا کلاینت‌های زیاد که بار روی وابستگی خراب را ضرب می‌کند
بودجهٔ retry (Retry budget)سقف retry برای هر درخواست یا به‌صورت سهمی از ترافیک (SRE: زیر ۱۰٪)
Retry throttlingtoken bucket در gRPC که وقتی خطاها غالب‌اند retry را متوقف می‌کند
Transparent retryretry در gRPC برای RPCهایی که به برنامهٔ سرور نرسیده‌اند
Idempotencyدو بار انجام دادن یک عملیات همان اثر یک بار را دارد
کلید idempotency (Idempotency key)شناسه‌ای که کلاینت برای یک عملیات می‌سازد و در هر تلاش می‌فرستد (Idempotency-Key)
Fingerprinthash درخواست برای کشف کلیدی که با payload دیگر دوباره استفاده شده
Inbox / پیام‌های پردازش‌شدهجدول سمت مصرف‌کننده از شناسه‌های پیام پردازش‌شده
Circuit breakerبعد از خطاهای پیاپی سریع شکست می‌خورد، بعد آزمایش می‌کند (half-open)
Bulkheadpool منابع جدا و محدود برای هر وابستگی
Hedged requestنسخهٔ دوم یک درخواست idempotent کند؛ اولین پاسخ برنده است
API compositionجزئی که سرویس‌های مالک را صدا می‌زند و نتیجه‌ها را در حافظه join می‌کند
BFFBackend for Frontend: یک gateway برای هر نوع کلاینت
mTLSTLS دوطرفه: هر دو طرف گواهی ارائه می‌دهند
traceparentهدر W3C: version، trace-id، parent-id، flags
Problem Detailsقالب خطای JSON در RFC 9457، application/problem+json
تزریق خطا (Fault injection)افزودن عمدی تأخیر یا خطا (Toxiproxy، Istio) برای تست تاب‌آوری

منابع (References) ​

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