Request-Reply over Messaging & REST vs AMQP
"Send a pair of Request-Reply messages, each on its own channel." — Gregor Hohpe and Bobby Woolf، Enterprise Integration Patterns، Request-Reply
خلاصه (Summary): برای گرفتن پاسخ از میانافزار پیام، مسیر برگشت را خودتان طراحی میکنید: نشانی بازگشت (Return Address)، شناسهٔ همبستگی (Correlation Identifier)، صف پاسخ (Reply Queue) و مهلت (Deadline). وجود صف بهتنهایی وابستگی زمانی درخواستکننده را از بین نمیبرد. تمرکز (Focus): پاسخ دیررس، پاسخ تکراری، گمشدن پاسخ، تمامشدن ظرفیت درخواستکننده و انتخاب میان REST، gRPC، RPC روی پیام، یا 202 همراه منبع وضعیت. هدف یادگیری (Learning goal): یک RPC محدود در Go یا Laravel 13 بسازید، پنجرههای شکست آن را توضیح دهید، و وقتی جواب فوری لازم نیست، انتظار را با وضعیت پایدار و اعلان جایگزین کنید.
این فصل مالک گفتوگوی درخواستـپاسخ (Request-Reply)، Direct Reply-To، همبستگی پاسخها، دشواری RPC در Kafka و ضدالگوی همگام روی ناهمگام (Sync over Async) است. جزئیات مصرفکنندگان رقیب، تأیید پیام، مصرفکنندهٔ همتوان، تلاش مجدد و توپولوژی مسیریابی در فصلهای خودشان باقی میمانند. برای تنظیمات محصول به RabbitMQ، Kafka و Redis Streams & Pub/Sub بروید.
نقشهٔ صفحه
| دنبال چه هستید؟ | بخش |
|---|---|
| واژگان و انتخاب سریع | یک دقیقه |
| ریشهٔ الگو و دو شیوهٔ انتظار | پیشینه |
| فیلدهای درخواست، پاسخ و وضعیت درخواستکننده | سازوکار |
| مفهومها و سناریوهای واقعی | فهرست مفهومها |
| صف برای هر تماس، هر کلاینت یا مشترک | نشانی بازگشت |
| قواعد و محدودیتهای Direct Reply-To | پاسخ مستقیم |
| مهلت، پاسخ یتیم و تکرار | مهلت، تکرار |
| چرا worker وب تمام میشود؟ | همگام روی ناهمگام |
| پذیرش کار و نمایش پیشرفت | منبع وضعیت |
| SSE، WebSocket و webhook | پاسخ ناهمگام |
| traceparent در برابر correlation_id | همبستگی میان گامها |
| مشکلهای reply topic و partition | Kafka |
| پاسخ با channel یا stream | Redis |
| تصمیم بر پایهٔ زمان و وابستگی | انتخاب |
| کدهای کامل مشترک دو زبان | Go، Laravel |
| مقایسهٔ دقیق سه broker | تفاوت brokerها |
| از تکبرنامه تا چند منطقه | معماری |
| آزمایش و خروجی مورد انتظار | آزمایشگاه |
| مرور و سنجش فهم | بدفهمیها، خودآزمایی |
همهچیز در یک دقیقه
واژگان پایه.
| اصطلاح | معنای کاربردی | جای آن |
|---|---|---|
| درخواستـپاسخ (Request-Reply) | دو تحویل مستقل یک گفتوگو میسازند | الگوی EIP |
| درخواستکننده / پاسخدهنده (Requestor / Replier) | کسی که میپرسد / کسی که پاسخ میدهد | دو سمت گفتوگو |
| نشانی بازگشت (Return Address) | پاسخ را به این مقصد بفرست | reply_to در AMQP یا header قراردادی |
| شناسهٔ همبستگی (Correlation Identifier) | این پاسخ متعلق به کدام درخواست است؟ | correlation_id |
| صف پاسخ (Reply Queue) | جایی برای نگهداری جواب تا مصرف | صف اختصاصی، بلندعمر یا پاسخ مستقیم |
| پاسخ یتیم (Orphaned Reply) | دیگر کسی منتظر این شناسه نیست | پس از timeout یا restart |
| همگام روی ناهمگام (Sync over Async) | ارسال به صف و سپس متوقفکردن caller | ضدالگوی ظرفیت |
| پذیرش کار (202 Accepted) | دریافت شد؛ هنوز تمام نشده | HTTP و منبع وضعیت |
پنج گام مکانیسم.
| گام | عمل | مسئول |
|---|---|---|
| 1 | ساخت شناسه و ثبت منتظر در جدول | درخواستکننده |
| 2 | ارسال همراه نشانی پاسخ، شناسه، TTL و deadline | درخواستکننده |
| 3 | انجام کار و انتشار به مقصد پاسخ | پاسخدهنده |
| 4 | کپی شناسهٔ درخواست در پاسخ | پاسخدهنده |
| 5 | تکمیل منتظر شناختهشده؛ نادیدهگرفتن شناسهٔ ناشناخته | درخواستکننده |
انتخاب اولیه.
| موقعیت | انتخاب | دلیل |
|---|---|---|
| کاربر قیمت یا مجوز را همین حالا میخواهد | REST/gRPC با deadline | مسیر سادهتر برای جواب فوری |
| گزارش چند ثانیه یا چند دقیقه طول میکشد | 202 + وضعیت + poll یا push | آزادشدن worker وب |
| سرویسی فرمان میدهد و منتظر نیست | پیام فرمان، در صورت نیاز رویداد پاسخ | جداسازی زمانی |
| تعداد بسیار زیاد کلاینت کوتاهعمر در RabbitMQ | Direct Reply-To | حذف صف بهازای هر اتصال |
| پاسخ باید پس از اتصال دوباره باقی بماند | صف پاسخ پایدار + وضعیت همبستگی پایدار | پاسخ و معنی آن بازیابی میشوند |
| تنها بستر مجاز Kafka است | reply topic/partition با مهلت | شدنی، همراه پیچیدگی بیشتر |
| هیچ الزام مشخصی به broker RPC ندارید | RPC را به صف تحمیل نکنید | هزینهٔ مسیر برگشت بیدلیل ایجاد نشود |
پیشینهٔ الگو
کتاب Enterprise Integration Patterns گفتوگو را از دو پیام یکطرفه میسازد. الگوی درخواستـپاسخ (Request-Reply) دو مسیر را تعریف میکند؛ نشانی بازگشت (Return Address) مقصد جواب را داخل درخواست میگذارد؛ شناسهٔ همبستگی (Correlation Identifier) میگوید هر جواب به کدام سؤال مربوط است. هیچکدام بهتنهایی اثر جانبی را دقیقاً یکبار نمیکند.
در انتظار مسدودکننده (Synchronous Block)، یک thread ارسال میکند و میایستد. در فراخوان بازگشتی ناهمگام (Asynchronous Callback)، یک شنونده پاسخ را میگیرد و منتظر مناسب را تکمیل میکند. روش دوم اجازه میدهد چند درخواست از یک مسیر پاسخ استفاده کنند؛ اما اگر handler وب منتظر همان future بماند، وابستگی زمانی همچنان وجود دارد.
آموزش ششم RabbitMQ توصیه میکند هرجا خط لولهٔ ناهمگام مناسب است، RPC را کنار بگذارید. RFC 9110 نیز با 202 Accepted امکان اعلام پذیرش بدون ادعای تکمیل را فراهم میکند. Location و Retry-After در این فصل قرارداد API هستند؛ RFC آنها را برای همهٔ پاسخهای 202 اجباری نکرده است.
چرا این الگو وجود دارد؟
پیامرسانی (Messaging) اجازه میدهد فرستنده منتظر گیرنده نماند. بااینحال سؤالهایی مثل «قیمت این کالا چیست؟» یا «صندلی رزرو شد؟» جواب دارند. اگر تنها مسیر مجاز میان دو سامانه broker باشد، یا مسیریابی و توزیع کار آن لازم باشد، یک تماس را از دو پیام میسازیم.
| دستاورد | هزینه |
|---|---|
| تقسیم کار میان پاسخدهندههای رقیب | طراحی، مجوزدهی و پاکسازی مسیر پاسخ |
| نگهداری درخواست در غیبت کوتاه پاسخدهنده | غیبت هنوز به latency یا timeout caller تبدیل میشود |
| مسیریابی بر اساس صف، exchange یا header | جدول همبستگی و مدیریت پاسخ یتیم |
| یک بستر مشترک برای فرمان و پاسخ | broker روی مسیر تأخیر قرار میگیرد |
تمثیل رستوران. شمارهٔ سفارش، شناسهٔ همبستگی است؛ میز شما، نشانی بازگشت. آشپزخانه میتواند جدا از صندوق کار کند. اگر مشتری برود، آمادهشدن غذایش یک پاسخ یتیم میسازد. صفحهٔ پیگیری سفارش همان منبع وضعیت است. گرفتن شماره و همچنان ایستادن جلوی صندوق تا غذا آماده شود، همگام روی ناهمگام است: صف آشپزخانه آزاد است، ولی صندوق همچنان اشغال میشود.
سه سوءبرداشت را از همین ابتدا کنار بگذارید: وجود صف الزاماً caller را ناهمگام نمیکند؛ correlation id تضمین همتوانی نیست؛ Direct Reply-To صف معمولی سریعتر نیست، چون اصلاً پاسخ را ذخیره نمیکند.
سازوکار یک تماس
فیلدهای درخواست و پاسخ
| داده | AMQP 0-9-1 | AMQP 1.0 | Kafka | Redis Streams |
|---|---|---|---|---|
| نشانی بازگشت (Return Address) | reply_to | reply-to | reply-topic و reply-partition | فیلد reply_to |
| همبستگی (Correlation) | correlation_id | correlation-id | header قراردادی | فیلد قراردادی |
| هویت پیام (Message Identity) | message_id | message-id | header قراردادی | entry id یا فیلد |
| انقضای درخواست (Expiry) | expiration، رشتهٔ میلیثانیه | ttl | deadline برنامه | deadline برنامه |
| بافت ردیابی (Trace Context) | header traceparent | application property | header | فیلد |
| نوع محتوا (Content Type) | content_type | content-type | header یا schema id | فیلد |
در قرارداد AMQP 1.0 مستند RabbitMQ، درخواستکننده message-id یکتا میسازد و پاسخدهنده آن را در correlation-id جواب میگذارد. آموزش AMQP 0-9-1 مستقیماً correlation_id را کپی میکند. مهم، توافق دو سمت است؛ نباید شناسهای را که broker بعد از ارسال تولید میکند پیشاپیش در جدول انتظار فرض کنید.
وضعیت درخواستکننده
نمودار، چند درخواست همزمان و یک مصرفکنندهٔ پاسخ را نشان میدهد. جدول منتظرها (Pending Table) پاسخ را به caller درست وصل میکند؛ ترتیب رسیدن جوابها اهمیتی ندارد.
pending: correlation_id -> buffered waiter
one reply consumer -> lookup -> complete once -> delete
deadline -> delete -> later reply is orphan
consumer closed -> mark client closed -> fail all waitersپس از restart حافظه از دست میرود. باقیماندن پیام در صف پایدار کافی نیست؛ برای کار بلندمدت باید وضعیت عملیات و همبستگی را هم پایدار کنید. ثبت منتظر بعد از بستهشدن مصرفکننده نیز باید رد شود، وگرنه درخواست تازه تا آخر مهلت بیجهت میماند.
| شکست | آنچه caller میبیند | اقدام |
|---|---|---|
| پاسخدهنده خاموش است | درخواست در صف و بدون جواب | timeout؛ retry تنها با سیاست همتوانی |
| پاسخدهنده کند است | پاسخ پس از مهلت | حذف پاسخ یتیم؛ deadline کار را محدود کند |
| crash بعد از پاسخ و قبل از ack | جواب دوباره | تکمیل یکبارهٔ منتظر و dedup اثر |
| restart درخواستکننده | شناسههای ناشناخته | بازیابی وضعیت پایدار یا کنارگذاشتن پاسخ گذرا |
| حذف صف اختصاصی یا قطع Direct Reply-To | گمشدن جواب | اتصال دوباره؛ نتیجهٔ کسبوکار ممکن است نامعلوم باشد |
| broker در دسترس نیست | خطا یا توقف publish | محدودیت I/O جدا از timeout انتظار |
| درخواست مسموم | reject یا retryهای مکرر | DLQ و وضعیت شکست |
reply_to وجود ندارد | پاسخ ممکن نیست | reject بدون requeue |
1 requester: register c-42
2 requester: publish(reply_to=R, correlation_id=c-42, ttl=2s)
3 replier: receive; validate deadline; calculate
4 replier: publish reply c-42; wait broker confirm
5 replier: ack request
6 requester: reply c-42 -> complete waiter -> delete1 t=0.0 caller sends c-42; deadline=2s
2 t=0.1 worker starts work
3 t=2.0 caller removes pending[c-42]; returns timeout
4 t=3.0 reply c-42 arrives; no waiter -> drop
5 queue TTL cannot cancel work already delivered at t=0.1مفهومها، یکییکی
درخواستـپاسخ (Request-Reply) حیاتی
به زبان ساده (In plain words): پیام دوم، جواب پیام اول است؛ return value محلی نداریم.
بدفهمی رایج (Common misunderstanding): «همان تابع است که از صف رد میشود.» تحویل درخواست، اجرای کار، تحویل پاسخ و ثبت تکمیل چهار پنجرهٔ مستقل شکست دارند.
تعریف: درخواستکننده روی کانال درخواست ارسال میکند و پاسخ را از کانال برگشت میگیرد. درخواست میتواند یکبهیک یا fan-out باشد؛ پاسخ معمولاً به همان درخواستکننده میرود. در جمعآوری چند پاسخ (Scatter-gather)، یک شناسه با شمارندهٔ جوابها و deadline همراه میشود.
سناریوها: چند گره وب از Pricing قیمت میگیرند؛ عامل نصبشده در محل مشتری فقط به broker دسترسی دارد و مجوز میپرسد؛ یک aggregator از چند تأمینکننده قیمت میگیرد و در پایان مهلت بهترین را انتخاب میکند.
| محصول | شکل پیادهسازی |
|---|---|
| RabbitMQ | propertyهای reply_to و correlation_id، صف پاسخ یا Direct Reply-To |
| Kafka | headerها و topic/partition پاسخ؛ قرارداد برنامه |
| Redis Streams | stream درخواست و stream خصوصی پاسخ یا Pub/Sub |
| NATS | helper درخواست با inbox یکتا و timeout؛ multiplex زیر سلسلهمراتب subject |
| Pulsar | topic پاسخ و propertyهای پیام به قرارداد برنامه |
| SQS | صف پاسخ برای caller یا کتابخانهٔ صف موقت |
| Laravel queue | کانال پاسخ ذاتی ندارد؛ Job::dispatch() یک PendingDispatch میدهد، نه نتیجهٔ اجرای آینده |
شناسهٔ همبستگی (Correlation Identifier) حیاتی
به زبان ساده (In plain words): شمارهٔ روی برگهٔ سؤال باید روی برگهٔ جواب هم باشد.
بدفهمی رایج (Common misunderstanding): «offset یا message id خود broker کافی است.» offset پس از append معلوم میشود؛ RabbitMQ نیز message_id را بهجای شما نمیسازد. caller باید شناسه را پیش از ارسال بداند.
تعریف: یک درخواست، یک شناسهٔ تطبیق پاسخ دارد. درخواستهای همزمان برای یک سفارش باید correlation idهای جدا داشته باشند؛ کلید همتوانی منطقی میتواند بین retryهای همان عملیات ثابت بماند.
| نوع شناسه | ویژگی | کاربرد |
|---|---|---|
| UUIDv4 / تصادفی 128 بیت | یکتا و بیترتیب | انتخاب معمول |
| ULID / UUIDv7 | دارای ترتیب زمانی | جستوجو و وضعیت؛ تولید شناسه |
| کلید کسبوکار (Business Key) | ممکن است تکرار شود | بهتنهایی correlation نیست |
| شمارندهٔ کلاینت (Counter) | کوچک | نیازمند شناسهٔ instance و epoch پس از restart |
| شناسهٔ trace | چندین تماس را میپوشاند | برای اتصال spanها؛ نه تطبیق یک پاسخ |
1 pending[A]=caller1; pending[B]=caller2
2 worker finishes B first -> reply(B)
3 dispatcher completes caller2
4 worker finishes A -> reply(A)
5 dispatcher completes caller1ترتیب متفاوت پاسخها خطا نیست. خطا آن است که برنامه پاسخ اول را به caller اول بدهد، بدون اینکه شناسه را بررسی کند. channel منتظر در Go باید buffer یکتایی داشته باشد تا پاسخ پس از انصراف caller، dispatcher را متوقف نکند.
نشانی بازگشت و راهبرد صف پاسخ حیاتی
به زبان ساده (In plain words): نشانی بازگشت (Return Address) همان «جواب را اینجا بفرست» است.
بدفهمی رایج (Common misunderstanding): «پاسخدهنده باید آدرس همهٔ کلاینتها را تنظیم کرده باشد.» مقصد داخل درخواست میآید؛ البته باید با مجوز و allowlist محدود شود تا درخواستکننده نتواند به صف دلخواه دسترسی بگیرد.
تعریف: caller مقصد را انتخاب میکند و replier جواب را با شناسهٔ اصلی به آن میفرستد. عمر مقصد تعیین میکند پاسخ پس از قطع ارتباط چه میشود.
| راهبرد | عمر | هزینه | عبور از reconnect | مناسب |
|---|---|---|---|---|
| صف برای هر تماس | کوتاه و پرتکرار | declare/delete و metadata زیاد | خیر | حجم بسیار کم؛ معمولاً انتخاب بد |
| صف اختصاصی کلاینت (Exclusive) | عمر اتصال | یک declare در شروع | خیر | تماس کوتاه |
| صف نامدار بلندعمر (Durable) | مستقل از اتصال | نیازمند پاکسازی | بله، با بازیابی pending state | کار طولانی |
| یک صف مشترک برای همه | مشترک | صف کم | پیام بله؛ تطبیق وابسته به برنامه | dispatcher مشترک یا وضعیت مشترک لازم است |
| Direct Reply-To | بدون صف عادی | metadata کم | خیر | churn زیاد و پاسخ قابلتکرار |
در صف مشترک RabbitMQ، مصرفکنندگان رقیباند: هر پیام به یکی میرسد، نه به همه. فیلتر client-side راهحل نیست؛ کلاینت A ممکن است پاسخ B را بگیرد و حذف کند. صف مجزای هر درخواستکننده یا dispatcher آگاه از مالک منتظر لازم است.
| گزینهٔ RabbitMQ | اثر |
|---|---|
exclusive=true | تنها اتصال مالک مصرف میکند؛ با قطع آن حذف میشود |
auto-delete=true | پس از وجود مصرفکننده، با حذف آخرین consumer حذف میشود |
durable=false | پس از restart broker بازیابی نمیشود |
| نام خالی (Server-named) | نام amq.gen-... از declare-ok گرفته و در reply_to گذاشته میشود |
x-expires | صف پس از دورهٔ بیاستفادهبودن حذف میشود |
x-message-ttl | عمر پیام پاسخ در صف |
| نام client-defined | نامگذاری، مالکیت و سیاست پاکسازی با برنامه |
پاسخ مستقیم RabbitMQ مهم
به زبان ساده (In plain words): Direct Reply-To پاسخ را به کانال اتصال زنده میرساند؛ صفی برای نگهداری آن ندارد.
بدفهمی رایج (Common misunderstanding): «صف ویژهای است که میتوان بعداً از آن خواند.» نام amq.rabbitmq.reply-to در پروتکل مثل مقصد استفاده میشود، اما صف عادی قابلفهرستکردن یا حذفکردن نیست.
تعریف AMQP 0-9-1: ابتدا از نام ویژه با automatic acknowledgment مصرف کنید؛ روی همان channel درخواست را با همان reply_to منتشر کنید. broker نشانی را به مقصد تولیدشده با پسوند opaque تبدیل میکند. replier آن مقدار را بدون تغییر routing key در default exchange قرار میدهد.
1 consume amq.rabbitmq.reply-to, no_ack=true
2 publish request on SAME channel; correlation_id=c-42
3 broker rewrites reply_to -> generated opaque destination
4 replier publishes exchange="", routing_key=request.reply_to
5 broker delivers to requester channel; no queue buffer
6 requester matches c-42در نمودار، ذخیرهسازی صف فقط روی مسیر درخواست است. حذف صف پاسخ، هزینه را کم میکند و همزمان ضمانت بازیابی آن مسیر را حذف میکند.
| محدودیت | پیامد |
|---|---|
| مصرف automatic-ack | پاسخ unacked برای بازگرداندن به صف نداریم |
| اتصال و channel مشترک برای ارسال و مصرف | مصرف روی channel دیگر کافی نیست |
| یک consumer از این نوع در هر channel | تعداد تماسها با pending table multiplex میشود |
| تحویل حداکثر یکبار (At-most-once) | قطع requester میتواند پاسخ را حذف کند |
| بدون دوام، replication و buffer | کندی مصرفکننده میتواند به افت پاسخ تبدیل شود |
mandatory مقصد را routable حساب میکند | نبود requester با basic.return ثابت نمیشود |
در UI صف و list_queues دیده نمیشود | metric با queue_type="rabbit_volatile_queue" را ببینید |
| نرخ زیاد پاسخ به یک requester | صف معمولی برای buffer مناسبتر است |
| AMQP 1.0 و ارتباط میان دو پروتکل | capability rabbitmq:volatile-queue، settled و link-detach طبق مستند محصول |
برای کار پرهزینه میتوان روی یک channel موقت مقصد تولیدشده را passive declare کرد؛ موفقیت لحظهای حضور را نشان میدهد، نه تضمین حضور تا انتهای کار. در AMQP 1.0 نیز سازوکار HTTP GET روی AMQP مستند شده است. این بررسی جای idempotency یا deadline را نمیگیرد.
معیار افت پاسخ rabbitmq_global_messages_dead_lettered_maxlen_total{queue_type="rabbit_volatile_queue",dead_letter_strategy="disabled"} است. این افت میتواند پس از confirm انتشار نیز رخ دهد: پذیرش broker برابر دریافت caller نیست.
| انتخاب کنید وقتی | اجتناب کنید وقتی |
|---|---|
| کلاینتهای بسیار زیاد و تماس کوتاه دارید | از دسترفتن جواب پذیرفتنی نیست |
| اتصالها کوتاه و پرتغییرند | پاسخ باید reconnect را تحمل کند |
| retry با کلید منطقی ثابت امن است | یک requester باید burst بزرگ جواب را buffer کند |
| هزینهٔ metadata صف مهم است | کار بلندمدت و بازیابی نتیجه لازم است |
مهلت و پاسخ یتیم حیاتی
به زبان ساده (In plain words): مهلت (Deadline) زمان پایان انتظار است؛ پاسخ یتیم (Orphaned Reply) جوابی است که پس از پایان انتظار میرسد.
بدفهمی رایج (Common misunderstanding): «timeout caller یعنی کار لغو شده.» ممکن است اثر کسبوکار انجام شده باشد و فقط جواب گم شده باشد. retry کور میتواند اثر را دوباره اجرا کند.
تعریف: در کلاینت گذرا، پاسخی که شناسهاش در pending table نیست کنار گذاشته میشود. در workflow پایدار، همین پاسخ باید با وضعیت ثبتشده تطبیق داده شود.
| لایه | تنظیم | چه چیزی محدود میشود؟ |
|---|---|---|
| caller | context.WithTimeout یا deadline حلقهٔ PHP | انتظار پاسخ |
| پیام درخواست | expiration یا x-message-ttl | ماندن در صف، پیش از تحویل |
| replier | header مهلت مطلق + سقف محلی اجرا | شروع یا ادامهٔ کار بیفایده؛ با کنترل skew ساعت |
| پاسخ ذخیرهشده | message TTL، queue expiry، Redis EXPIRE، Kafka retention | انباشت جوابهای متروک |
| اتصال | heartbeat، TCP keepalive، write timeout | کشف اتصال مرده و نوشتن مسدود |
TTL صف را از زمان باقیماندهٔ caller بسازید؛ آن را مساوی زمان اجرای worker ندانید. مقدار expiration در پیام، بهتنهایی مدت سپریشده در شبکه و صف را به worker نمیگوید. header deadline_unix_ms نیازمند ساعتهای همگام و حاشیهٔ skew است؛ downstream نیز باید timeout داشته باشد.
1 caller deadline=2s; queued request TTL=2000ms
2 worker busy; request remains queued
3 caller timeout -> remove pending id
4 broker expires queued request (or dead-letters it)
5 worker never starts that stale requestوقتی consumer پاسخ بسته شد، تمام منتظرهای موجود را با خطا کامل کنید و client را بسته علامت بزنید. ثبت تماس تازه باید همان وضعیت را زیر lock بررسی کند. در amqp091-go v1.17.0، PublishWithContext فقط پیش از publish لغو را بررسی میکند؛ لغو context نوشتن درحالاجرای socket را قطع نمیکند. نمونهٔ Go سقف نوشتن transport را جداگانه نشان میدهد.
برای صف پاسخ معمولی، mandatory و NotifyReturn مقصد حذفشده را آشکار میکنند. برای Direct Reply-To این نتیجه برقرار نیست. بستن اتصال مشترک برای لغو یک call نیز همهٔ callهای دیگر را خراب میکند؛ لغو محلی باید منتظر خودش را حذف کند.
پاسخ تکراری و همتوانی مهم
به زبان ساده (In plain words): دریافت دوبارهٔ جواب و اجرای دوبارهٔ سؤال دو مسئلهٔ جدا هستند.
بدفهمی رایج (Common misunderstanding): «correlation id یعنی اجرای دقیقاً یکبار.» همبستگی فقط پاسخ را پیدا میکند؛ همتوانی (Idempotency) جلوی تکرار اثر را میگیرد.
تعریف: انتشار پاسخ و ack درخواست دو عمل مستقلاند. crash میان آنها باعث redelivery میشود. confirm پاسخ هم دریافت نهایی caller را ثابت نمیکند.
1 replier applies effect and publishes answer c-42
2 broker confirms reply
3 replier crashes before request ack
4 broker redelivers request
5 another replier runs; without dedup effect repeats
6 requester accepts first response; ignores duplicate c-42| منشأ تکرار | دفاع |
|---|---|
| پاسخ دوباره | حذف pending پس از اولین تکمیل |
| درخواست redelivered | unique constraint و inbox در تراکنش اثر |
| retry caller پس از timeout | کلید منطقی ثابت؛ correlation id تازه برای هر attempt |
| webhook دوباره | dedup روی event id یا Idempotency-Key |
-- Same transaction as the business effect; use a stable logical operation key.
CREATE TABLE processed_requests (
request_id uuid PRIMARY KEY,
reply_body jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO processed_requests(request_id, reply_body)
VALUES ($1, $2)
ON CONFLICT (request_id) DO NOTHING
RETURNING request_id;این SQL شکل ذخیرهسازی را نشان میدهد؛ درج نتیجه قبل از انجام اثر بدون تراکنش صحیح، dedup کامل نیست. در تعارض، نتیجهٔ ثبتشده را بخوانید و با correlation id تلاش فعلی بازگردانید. کلید منطقی، payload fingerprint و سیاست retention باید با پنجرهٔ retry سازگار باشند.
Stripe برای API v1 رفتار ذخیره و بازگرداندن نتیجه با کلید تکراری را مستند میکند و امکان حذف کلید پس از 24 ساعت را دارد؛ قرارداد API v2 را جدا بخوانید. RFC 9110 برای retry خودکار روشهای همتوان قواعد دارد؛ افزودن یک header بدون اجرای dedup در سرور، POST را امن نمیکند.
همگام روی ناهمگام حیاتی
به زبان ساده (In plain words): handler پیام را صف میکند، ولی تا جواب بیاید worker را نگه میدارد.
بدفهمی رایج (Common misunderstanding): «صف بار را صاف میکند، پس frontend هم امن است.» صف بار worker پشتصحنه را buffer میکند؛ callerهای منتظر هنوز حافظه، اتصال و slot مصرف میکنند.
تعریف: توقف، sleep یا poll در handler تا تغییر وضعیت یک کار صفشده، وابستگی زمانی را حفظ میکند. این همان Sync over Async است.
نمودار نشان میدهد صف بلند backend میتواند با تمامشدن workerهای frontend همزمان شود. ظرفیت صف جای ظرفیت درخواستکننده را نمیگیرد.
| منبع اشغالشده | محدودیت نمونه | نشانه |
|---|---|---|
| PHP-FPM worker | pm.max_children | 502/504؛ حتی health معطل |
| thread در servlet | thread pool | صف درخواست ورودی |
| goroutine در Go | حافظه، socket و pending entry | رشد حافظه و fd |
| promise در Node.js | حافظه و کار callbackها | افزایش latency؛ event loop با CPU هم مختل میشود |
| اتصال DB در تراکنش باز | اندازهٔ pool و max_connections | کمبود اتصال |
| reverse proxy | timeout پیکربندیشده | 504 و retry caller |
1 8 web slots; backend capacity 20 jobs/s
2 offered load=100 requests/s; callers wait on replies
3 all slots occupied; new callers rejected or queued
4 health endpoint waits for same slots
5 retries add load while old work remains queued| بهجای | انجام دهید | نتیجه |
|---|---|---|
| نگهداشتن worker تا جواب | 202 و status resource | آزادشدن slot |
| poll با while/sleep در handler | poll سمت client یا push | انتظار خارج از worker درخواست |
| broker RPC برای خواندن فوری | REST/gRPC با deadline | مسیر کمهزینهتر |
| broker RPC برای فرمان پایدار | command + reply event | workflow منتظر میماند، نه thread |
| انتظار بیحد | deadline، TTL، bulkhead و circuit breaker | محدودشدن دامنهٔ خرابی |
در ابزار داخلی کمحجم با دلیل روشن برای broker، مهلت کوتاه و سهمیهٔ مستقل worker، این انتخاب ممکن است قابلقبول باشد. جداساز ظرفیت (Bulkhead) باید واقعی باشد؛ صرف گذاشتن نام RPC روی یک صف، ظرفیت وب را رزرو نمیکند.
202 و منبع وضعیت حیاتی
به زبان ساده (In plain words): سرور رسید میدهد و نشانی پیگیری را برمیگرداند.
بدفهمی رایج (Common misunderstanding): «Accepted یعنی کار حتماً موفق میشود.» منبع وضعیت (Status Resource) باید شکست، انقضا و توقف را هم بیان کند.
تعریف: قرارداد این فصل POST /quotes را با 202، Location و وضعیت اولیه پاسخ میدهد. worker ردیف را تغییر میدهد؛ caller poll میکند یا اعلان میگیرد. این headerها قرارداد API هستند، نه الزام عمومی همهٔ 202ها.
| وضعیت | پاسخ endpoint وضعیت | معنی |
|---|---|---|
| queued / running | 200 با state؛ فاصلهٔ poll اختیاری | هنوز تمام نشده |
| done | 200 با نتیجه یا 303 به منبع نتیجه | موفق |
| failed | 200 با state=failed و error | عملیات شکست خورده؛ خواندن وضعیت موفق بوده |
| expired | 410 Gone | نتیجه طبق retention حذف شده |
| شناسهٔ ناشناخته | 404 | وجود ندارد |
| درخواست لغو | DELETE با 202 یا 204 طبق قرارداد | لغو ممکن است ناهمگام باشد |
1 POST /quotes -> logical key k-9
2 transaction: insert queued status + outbox command
3 return 202 Location:/quotes/q-1
4 relay publishes; worker updates result
5 GET /quotes/q-1 -> running
6 GET /quotes/q-1 -> done + resultCREATE TABLE quotes (
id uuid PRIMARY KEY,
sku text NOT NULL,
state text NOT NULL CHECK (state IN ('queued','running','done','failed')),
price_cents integer,
error text,
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX quotes_state_updated_idx ON quotes(state, updated_at);بازآشتی وضعیت (Reconciliation) ردیفهای queued/running که بیشازحد قدیمیاند را بررسی میکند؛ بنا بر علت، دوباره صف میکند یا failed میسازد. Outbox شکاف commit دیتابیس و publish را میبندد؛ afterCommit() فقط ترتیب را درست میکند، اتمیبودن دو سامانه نمیسازد. Workflow پایدار مالک recovery بلندمدت است.
پاسخ ناهمگام: SSE، WebSocket، webhook مهم
به زبان ساده (In plain words): وقتی کار تمام شد خبر میدهیم، بهجای اینکه client مدام بپرسد.
بدفهمی رایج (Common misunderstanding): «WebSocket همیشه از SSE بهتر است.» برای جریان یکطرفهٔ سرور به مرورگر، رویداد ارسالی سرور (Server-Sent Events) سادهتر است؛ ارتباط دوطرفه دلیل انتخاب WebSocket است.
| راه | جهت | کاربرد | هزینه یا محدودیت |
|---|---|---|---|
| polling | client به server | ساده و سازگار با proxy | بار تابع تعداد caller و فاصلهٔ poll |
| long polling | درخواست باز | زیرساخت قدیمی | اتصال باز و timeout proxy |
| SSE | server به browser | پیشرفت و نتیجهٔ یک صفحه | اتصال بلند، reconnect، غیرفعالکردن buffering |
| WebSocket | دوطرفه | تعامل و رویدادهای متعدد | پروتکل و backplane چندگرهی |
| webhook | server به server | B2B | امضا، retry، dedup و مقصد قابلدسترسی |
| reply event/queue | service به service | workflow داخلی | caller باید عضو messaging باشد |
| push موبایل یا email | server به انسان | کاربر صفحه را بسته | جایگزین کانال دادهٔ معتبر نیست |
Laravel با Reverb، Pusher یا Ably broadcast میکند؛ Mercure نیز مسیر SSE مستقلی دارد. در Go، net/http و Flusher برای شکل ساده کافیاند. کانال private باید مالک quote را authorize کند؛ دانستن UUID مجوز دسترسی نیست.
1 browser POST -> 202 + status URL
2 establish subscription / SSE connection
3 fetch current durable status AFTER subscription is ready
4 worker commits done then emits notification
5 browser reconciles version; duplicates ignored
6 reconnect -> subscribe again -> fetch status againاعلان push منبع حقیقت نیست. اگر ابتدا GET کنید و بعد subscribe، تکمیل میتواند میان آن دو گم شود. پس از اتصال، subscription را آماده کنید و سپس وضعیت پایدار را بخوانید؛ بعد از reconnect یا heartbeat ازدسترفته نیز بازآشتی کنید. شمارهٔ نسخه جلوی جایگزینشدن وضعیت جدید با اعلان قدیمی را میگیرد.
همبستگی میان گامها و Trace Context مهم
به زبان ساده (In plain words): correlation id جواب یک سؤال را پیدا میکند؛ trace id مسیر یک اقدام کاربر را در چند سرویس دنبال میکند.
بدفهمی رایج (Common misunderstanding): «یک شناسه برای همهٔ نیازها کافی است.» یک trace میتواند چندین درخواستـپاسخ، retry و پیام مستقل داشته باشد.
تعریف: بافت ردیابی (Trace Context) استاندارد W3C شامل traceparent و tracestate است. شکل نسخهٔ صفر version-trace-id-parent-id-flags است؛ شناسهٔ trace و span تمامصفر معتبر نیست. SDK tracing باید اعتبار، سیاست اعتماد و ایجاد span فرزند را مدیریت کند.
| شناسه | دامنه | سازنده | تغییر | کاربرد |
|---|---|---|---|---|
| correlation_id | یک زوج سؤال/جواب | requester | در جواب کپی | یافتن waiter |
| message_id | یک پیام | publisher | هر پیام تازه | log و dedup پیام |
| trace-id | اقدام توزیعشده | ریشهٔ trace | هنگام ادامه ثابت | اتصال spanها |
| parent-id | span جاری | instrumentation | با span فرزند عوض میشود | درخت اجرای توزیعشده |
| causation_id | پیام علت | publisher | با زنجیرهٔ علت | بازسازی زنجیرهٔ رویداد |
| business id | aggregate | دامنه | ثابت | جستوجوی سفارش و مانند آن |
1 browser -> api: trace T, parent s1
2 api -> broker: correlation c-42, trace T, producer span s2
3 worker: extract context; create consumer span s3
4 worker -> reply: correlation c-42; tracing context for reply leg
5 api: match c-42; record outcome in trace Tبافت معتبر را طبق SDK منتقل کنید؛ در AMQP metadata و در Redis فیلد قراردادی میتواند حامل باشد. هنگام رد traceparent نامعتبر، tracestate وابسته را هم ادامه ندهید. نمونهٔ سبک Go ساختار را نشان میدهد و جای instrumentation کامل نیست. جزئیات در مشاهدهپذیری پیام است.
دشواری request-reply در Kafka مهم
به زبان ساده (In plain words): Kafka دفتر ثبت مشترک است؛ صندوق شخصی caller نیست.
بدفهمی رایج (Common misunderstanding): «چون Kafka پیام دارد، همان قرارداد RabbitMQ کافی است.» مقصد پاسخ و TTL هر پیام primitive بومی Kafka نیستند. Spring با ReplyingKafkaTemplate این قرارداد را در client میسازد؛ headerهای CORRELATION_ID، REPLY_TOPIC و REPLY_PARTITION و reply timeout پیشفرض 5 ثانیه دارد.
| مشکل | علت | راهکار و هزینه |
|---|---|---|
| صندوق شخصی نیست | یک topic چند reader دارد | group مستقل برای هر instance، partition رزروشده یا topic جدا |
| topic برای هر کلاینت | metadata و controller | برای کلاینت کوتاهعمر زیاد اجتناب کنید |
| rebalance | عضویت group تغییر میکند | assignment دستی یا static membership؛ ثبات کامل تضمین نیست |
| موقعیت شروع | latest ممکن است پس از اولین reply resolve شود | آمادهشدن reader پیش از publish؛ یا replay از offset شناختهشده |
| ترتیب | فقط داخل partition | correlation؛ ترتیب |
| retention | قطع client پاسخ را حذف نمیکند | retention کوتاه متناسب با recovery |
| latency | batching و fetch wait | تنظیم با هزینهٔ throughput؛ اندازهگیری واقعی |
| partition برای هر caller | هزینهٔ partition و هماهنگی مالکیت | تعداد requester محدود و assignment معتبر |
| تکرار | replay و retry برنامه | کلید منطقی ثابت؛ correlation هر attempt جدا |
| timeout | ویژگی caller | context و deadline header |
در topic مشترک با group مستقل، هر instance همهٔ پاسخها را میخواند و شناسههای دیگر را کنار میگذارد. در یک group مشترک اعضا کار را تقسیم میکنند؛ owner پاسخ تضمین نمیشود. اشتراک partition با hash نیز dispatcher یا reader مستقل میخواهد، نه صرفاً یک فیلتر روی consumer رقیب.
اگر Kafka تنها بستر سازمان است و پاسخ تأخیر چندثانیهای را تحمل میکند، این طراحی قابلدفاع است. برای خواندن سریع قیمت، REST/gRPC معمولاً سادهتر است. snippet از ابتدای دادهٔ retained میخواند تا race مربوط به resolve شدن AtEnd نداشته باشد؛ هزینه، replay جوابهای قدیمی است. partition باید انحصار منطقی داشته باشد و در restart، state پایدار یا offset معتبر لازم است.
پاسخ در Redis Streams و Pub/Sub تکمیلی
به زبان ساده (In plain words): Pub/Sub یک اعلان لحظهای است؛ Stream دفتر ثبت قابلخواندن دوباره است.
بدفهمی رایج (Common misunderstanding): «چون جواب کوتاهعمر است، گمشدن آن مسئله نیست.» اگر caller منتظر همان پاسخ است، افت آن تا پایان مهلت ظرفیت میگیرد و outcome را نامعلوم میکند.
تعریف: در Pub/Sub ابتدا subscription را فعال کنید، سپس درخواست را بفرستید. در Streams، یک stream پاسخ برای requester دارید و با آخرین entry id خواندن را ادامه میدهید.
| روش | مکانیسم | مزیت | محدودیت |
|---|---|---|---|
| channel برای هر درخواست | SUBSCRIBE سپس ارسال درخواست | ساده و سریع | at-most-once؛ اشتراک باید واقعاً فعال شده باشد |
| stream برای هر requester | XADD پاسخ، XREAD با cursor | retention و replay | اتصال مسدودشونده، EXPIRE و trim |
| stream مشترک با یک group | XREADGROUP | تقسیم تحویل | همهٔ clientها همهٔ پاسخها را نمیبینند؛ dispatcher لازم است |
| reader مستقل یا group جدا | خواندن کامل توسط هر requester | فیلتر local ممکن | خواندن اضافه به نسبت تعداد caller |
| REST | حذف mailbox | پاسخ فوری سادهتر | وابستگی زمانی مستقیم |
با $ در هر XREAD شروع نکنید؛ entryهای میان دو فراخوانی ممکن است حذف منطقی شوند و خوانده نشوند. آخرین id را حفظ کنید. گروه درخواست را اگر باید backlog قبلی را بگیرد با 0 بسازید؛ $ فقط پیامهای بعد از ساخت گروه را میگیرد. نمونهٔ این فصل مسیر new-entry را نشان میدهد؛ بازیابی pending با XAUTOCLAIM، dedup و سیاست trim در Redis Streams تکمیل میشوند.
پیامرسانی در برابر REST و gRPC حیاتی
به زبان ساده (In plain words): پرسش اصلی این است که caller میتواند ادامه دهد یا باید همین حالا جواب بگیرد.
بدفهمی رایج (Common misunderstanding): «gRPC جای همهٔ messaging را میگیرد.» gRPC چارچوب RPC دارای قرارداد، streaming و deadline است؛ در فراخوان همگام، availability و latency وابستگی همچنان به caller منتقل میشود.
| بُعد | REST/gRPC همگام | پیام همراه پاسخ منتظَر | پیام بدون انتظار |
|---|---|---|---|
| latency | مسیر مستقیمتر | دو مسیر پیام و queueing | خارج از مسیر پاسخ اولیه |
| وابستگی زمانی | هر دو باید پاسخگو باشند | هر دو داخل deadline باید حاضر شوند | گیرنده میتواند بعداً اجرا کند |
| آشکارشدن شکست | خطا یا timeout مستقیم | timeout و outcome نامعلوم | از وضعیت/DLQ/monitoring |
| retry | با قرارداد همتوانی | redelivery و retry caller با هم | retry مصرفکننده |
| تقسیم کار | load balancer یا mesh | competing consumers | competing consumers |
| backpressure | 429/503 یا صف proxy | صف رشد میکند، caller timeout | باید admission control داشته باشد |
| debugging | log، trace، curl | broker tooling و correlation | همان ابزارهای پیام |
| تراکنش | تماس HTTP هم با DB اتمی نیست | DB+publish اتمی نیست؛ outbox | همان شکاف |
| ترتیب | اجرای درخواستهای همزمان تضمین ترتیب ندارد | قواعد صف/partition و completion متفاوت | قواعد صف/partition |
| امنیت و discovery | DNS، gateway، mTLS | ACL، vhost، مقصد پاسخ | همان |
| خرابی شاخص | cascade timeout | orphan، duplicate، starvation | poison message و backlog |
رفتار واقعی محصولات
| قابلیت | RabbitMQ | Kafka | Redis | Laravel queue |
|---|---|---|---|---|
| نشانی پاسخ | reply_to | header قراردادی | فیلد/نام channel | ذاتی ندارد |
| همبستگی | correlation_id | header | فیلد | package ممکن است id job را property کند؛ RPC نمیسازد |
| مقصد شخصی | صف یا Direct Reply-To | topic/partition | stream/channel | ردیف، cache، broadcast |
| پاسخ بدون ذخیره | Direct Reply-To | خیر | Pub/Sub | وابسته به روش اعلان |
| TTL درخواست | expiration و queue TTL | retention در سطح topic، نه پیام | deadline برنامه/trim | retryUntil و timeout شغل، نه TTL عمومی broker |
| buffer هنگام قطع | صف معمولی بله؛ مستقیم خیر | retention | stream بله؛ Pub/Sub خیر | وضعیت برنامه |
| کشف نبود requester | mandatory صف عادی؛ passive probe لحظهای | قرارداد برنامه | EXISTS حضور زنده را ثابت نمیکند | برنامه |
| پاسخدهندههای رقیب | consumerهای صف | consumer group | stream group | queue workers |
| latency | تابع queue و شبکه | تابع batch/fetch/group | تابع Redis و شبکه | تابع driver و worker |
| احتمال duplicate | redelivery | replay/rebalance | pending recovery | retry job |
| helper RPC | tutorial/clientهای AMQP | Spring ReplyingKafkaTemplate | باید ساخته شود | built-in ندارد |
راهحلها: محدودکردن، جایگزینی و اعلان
| مسئله | راهحل | مکانیسم | مزیت | هزینه یا مرز |
|---|---|---|---|---|
| انتظار همیشگی | deadline | context یا حلقهٔ محدود | پایان قطعی انتظار | socket I/O سقف جدا دارد |
| کار برای caller رفته | TTL + execution deadline | expiration و header | حذف stale work | اثر commitشده لغو نمیشود |
| orphan | pending table | حذف در timeout | پاسخ دیررس متوقف نمیکند | پهنای باند مصرف شده |
| duplicate reply | complete once | حذف اولین entry | جواب دوم بیاثر | اثر worker مستقل است |
| duplicate effect | idempotent replier | inbox و تراکنش | retry امن | storage و retention |
| صفهای بسیار زیاد | صف برای instance یا Direct Reply-To | reuse destination | metadata کمتر | پاسخ مستقیم lossy |
| بستهشدن consumer | fail pending و closed flag | خطای مشترک | توقف زودتر انتظار | تضمین outcome نیست |
| worker وب تمام | 202 + وضعیت | بازگشت سریع | ظرفیت frontend حفظ | poll/push و reconciliation |
| نتیجهٔ زنده | SSE/Reverb/webhook | اعلان پس از commit | تجربهٔ بهتر | push منبع حقیقت نیست |
| جواب فوری | REST/gRPC | timeout و budget retry | ساده | وابستگی زمانی |
| فرمان نباید گم شود | outbox + reply event | وضعیت پایدار | durability | eventual completion |
| صف جواب داغ | مقصد جدا برای requester | ownership روشن | routing درست | صف و connection بیشتر |
| trace شکسته | context propagation | inject/extract SDK | trace یکپارچه | instrumentation لازم |
| retry storm | backoff/jitter/budget | محدودیت تلاش | کاهش amplification | تنظیم سیاست |
انتخاب
نمودار از نیاز caller شروع میکند: اگر میتواند بعداً نتیجه را بگیرد، وضعیت و اعلان مناسبتر است. الزام به broker باید دلیل مستقلی داشته باشد.
| موقعیت | پیشنهاد | تکنیک همراه | دلیل |
|---|---|---|---|
| قیمت یا permission فوری | REST/gRPC | cache، deadline، breaker | خواندن سریع |
| upload و گزارش طولانی | 202 + status | reconciliation | worker دقیقهها اشغال نشود |
| فرمان شروع فرایند | command | outbox و dedup | جدایی زمانی |
| saga منتظر تأیید مرحله | reply event | timeout transition | saga منتظر است، نه thread |
| کلاینت edge بسیار زیاد | Direct Reply-To | TTL و retry امن | صف کمتر |
| نتیجه بعد از reconnect | صف نامدار پایدار | expiry و state پایدار | buffer جواب |
| Kafka تنها بستر | reply partition/topic | retention و assignment | هزینهٔ قرارداد پذیرفته میشود |
| Redis تنها broker و افت مجاز | Pub/Sub reply | subscribe-first | ساده ولی lossy |
| مرورگر نتیجهٔ زنده میخواهد | SSE/Reverb | subscribe سپس GET وضعیت | پوشش race و reconnect |
| شریک تجاری | webhook | امضا و idempotency | قرارداد B2B |
| چند پاسخ به یک سؤال | scatter-gather | counter و deadline | aggregation |
| یک process | فراخوان تابع | هیچ broker لازم نیست | هزینهٔ کمتر |
| بودجهٔ زمانی | مناسب | نامناسب |
|---|---|---|
| چند میلیثانیه یا کمتر | عملیات local | تضمین بدون اندازهگیری روی شبکه |
| دهها میلیثانیه | RPC مستقیم در منطقه | broker RPC سرد بدون آزمون |
| صدها میلیثانیه تا ثانیه | REST/gRPC یا RabbitMQ گرم | Kafka تنظیمنشده |
| ثانیه تا دقیقه | 202 و پاسخ ناهمگام | نگهداشتن worker |
| ساعت | workflow و اعلان | هر انتظار مسدودکنندهٔ طولانی |
| سؤال مالکیت و وابستگی | اگر بله | اگر خیر |
|---|---|---|
| پاسخ فوری با قرارداد مشترک لازم است؟ | RPC مستقیم قابلدفاع | command/event را بررسی کنید |
| callee باید بتواند خاموش باشد؟ | messaging بدون انتظار فوری | RPC با deadline |
| یک جواب یک تصمیم را کامل میکند؟ | request-reply | event برای چند مصرفکننده |
| routing broker از قبل لازم است؟ | broker RPC شاید مناسب | load-balanced REST سادهتر |
Go
قبل
handler زیر درخواست را منتشر میکند و بدون مهلت منتظر پاسخ میماند. شناسهٔ دستساز و channel بدون buffer باعث میشوند قطع caller یا پاسخ دیررس، منابع را نگه دارد.
// Package main shows "sync over async": an HTTP handler that publishes a
// request message and then blocks until some other goroutine delivers the
// reply. It compiles and works on a good day; it has no timeout.
package main
import (
"fmt"
"net/http"
"sync"
)
// Bus is whatever publishes the request message (RabbitMQ, Kafka, ...).
type Bus interface {
Publish(correlationID string, body []byte) error
}
var (
mu sync.Mutex
pending = map[string]chan []byte{} // correlation id -> waiting handler
nextID int
)
// onReply is called by the reply consumer for every reply message.
func onReply(correlationID string, body []byte) {
mu.Lock()
ch := pending[correlationID]
delete(pending, correlationID)
mu.Unlock()
if ch != nil {
ch <- body // blocks forever if the handler already left
}
}
func quoteHandler(bus Bus) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
nextID++
id := fmt.Sprintf("req-%d", nextID) // fine until you run two instances
ch := make(chan []byte)
pending[id] = ch
mu.Unlock()
if err := bus.Publish(id, []byte(r.URL.Query().Get("sku"))); err != nil {
http.Error(w, err.Error(), http.StatusBadGateway)
return
}
// No timeout, no r.Context(): if the worker is down or the reply is
// lost, this goroutine, its map entry and the client connection stay
// stuck until the server is restarted.
body := <-ch
_, _ = w.Write(body)
}
}
func main() {
http.Handle("/quote", quoteHandler(nil))
_ = http.ListenAndServe(":8080", nil)
}بعد
کلاینت Direct Reply-To مصرفکننده را پیش از ارسال آماده میکند، سقف 256 تماس همزمان دارد، deadline الزامی میگیرد و TTL را از زمان باقیمانده میسازد. با بستهشدن consumer، client بسته علامت میخورد؛ هیچ call تازهای ثبت نمیشود. سقف نوشتن transport جدا از انتظار پاسخ است.
// Package main is a RabbitMQ RPC client using Direct Reply-To and a context
// timeout. One consumer on one channel serves every concurrent call.
package main
import (
"context"
"errors"
"fmt"
"log"
"net"
"os"
"strconv"
"sync"
"time"
"github.com/google/uuid"
amqp "github.com/rabbitmq/amqp091-go"
)
const directReplyTo = "amq.rabbitmq.reply-to"
type Client struct {
ch *amqp.Channel
queue string
mu sync.Mutex
pending map[string]chan result
closed bool
}
type result struct {
body []byte
err error
}
// ErrReplyChannelLost is returned to every waiter when the reply consumer
// ends (channel or connection closed, consumer cancelled). Direct Reply-To
// replies are at-most-once. Retry only idempotent or deduplicated operations.
var ErrReplyChannelLost = errors.New("reply consumer closed; outcome may be unknown")
// NewClient consumes from the pseudo-queue in no-ack mode. The same channel
// must be used to publish requests (RabbitMQ Direct Reply-To rule).
func NewClient(ch *amqp.Channel, requestQueue string) (*Client, error) {
replies, err := ch.Consume(directReplyTo, "", true, false, false, false, nil)
if err != nil {
return nil, fmt.Errorf("consume reply-to: %w", err)
}
c := &Client{ch: ch, queue: requestQueue, pending: map[string]chan result{}}
go func() {
for d := range replies {
c.mu.Lock()
w, ok := c.pending[d.CorrelationId]
delete(c.pending, d.CorrelationId)
c.mu.Unlock()
if !ok {
continue // late or duplicate reply: nobody is waiting, drop it
}
w <- result{body: d.Body} // buffered, never blocks
}
// The deliveries channel closed: fail everyone instead of letting
// them wait for their full deadline.
c.mu.Lock()
c.closed = true
for id, w := range c.pending {
w <- result{err: ErrReplyChannelLost}
delete(c.pending, id)
}
c.mu.Unlock()
}()
return c, nil
}
// Call publishes a request and waits for the reply or ctx.Done().
func (c *Client) Call(ctx context.Context, body []byte) ([]byte, error) {
if _, ok := ctx.Deadline(); !ok {
return nil, errors.New("RPC requires a deadline")
}
if err := ctx.Err(); err != nil {
return nil, err
}
deadline, _ := ctx.Deadline()
id := uuid.NewString()
wait := make(chan result, 1)
c.mu.Lock()
if c.closed {
c.mu.Unlock()
return nil, ErrReplyChannelLost
}
if len(c.pending) >= 256 {
c.mu.Unlock()
return nil, errors.New("RPC in-flight limit reached")
}
c.pending[id] = wait
c.mu.Unlock()
defer func() {
c.mu.Lock()
delete(c.pending, id) // timed out: later replies become orphans
c.mu.Unlock()
}()
err := c.ch.PublishWithContext(ctx, "", c.queue, false, false, amqp.Publishing{
ContentType: "application/json",
CorrelationId: id,
ReplyTo: directReplyTo,
Expiration: strconv.FormatInt(max(1, time.Until(deadline).Milliseconds()), 10), // queue residence only
Headers: amqp.Table{"deadline_unix_ms": strconv.FormatInt(deadline.UnixMilli(), 10)},
Body: body,
})
if err != nil {
return nil, err
}
select {
case res := <-wait:
return res.body, res.err
case <-ctx.Done():
return nil, ctx.Err()
}
}
func main() {
url := os.Getenv("AMQP_URL")
if url == "" {
log.Fatal("set AMQP_URL, e.g. amqp://guest:guest@localhost:5672/")
}
conn, err := amqp.DialConfig(url, amqp.Config{
Dial: func(network, address string) (net.Conn, error) {
c, err := net.DialTimeout(network, address, time.Second)
if err != nil {
return nil, err
}
return &boundedWriteConn{Conn: c}, nil
},
})
if err != nil {
log.Fatal(err)
}
defer conn.Close()
ch, err := conn.Channel()
if err != nil {
log.Fatal(err)
}
client, err := NewClient(ch, "quotes.rpc")
if err != nil {
log.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
reply, err := client.Call(ctx, []byte(`{"sku":"A-1"}`))
log.Printf("reply=%s err=%v", reply, err)
}
// Reply is the responder side: publish to the default exchange using the
// request's ReplyTo as the routing key, and copy the correlation id.
func Reply(ctx context.Context, ch *amqp.Channel, req amqp.Delivery, body []byte) error {
return ch.PublishWithContext(ctx, "", req.ReplyTo, false, false, amqp.Publishing{
CorrelationId: req.CorrelationId,
ContentType: "application/json",
Body: body,
})
}
// Context cancellation cannot interrupt an amqp091-go socket write. This
// connection-wide cap bounds each write; it is separate from the RPC deadline.
// Shared connections must not be closed just to cancel one individual call.
type boundedWriteConn struct{ net.Conn }
func (c *boundedWriteConn) Write(p []byte) (int, error) {
if err := c.Conn.SetWriteDeadline(time.Now().Add(time.Second)); err != nil {
return 0, err
}
return c.Conn.Write(p)
}پاسخدهنده صف quorum و prefetch یک دارد. header مهلت را بررسی میکند و قبل از ack درخواست منتظر publisher confirm میماند. باز هم دریافت نهایی پاسخ تضمین نمیشود؛ mandatory فقط برای صف معمولی نبود route را گزارش میکند.
// Package main is the replier side of a RabbitMQ RPC: a competing consumer
// with prefetch 1, a per-request deadline, a mandatory reply publish so a
// vanished ordinary reply queue is noticed, and ack after broker confirmation.
// Direct Reply-To is considered routed even if its requester has disconnected.
package main
import (
"context"
"encoding/json"
"log"
"os"
"strconv"
"time"
amqp "github.com/rabbitmq/amqp091-go"
)
const requestQueue = "quotes.rpc"
type quoteRequest struct {
SKU string `json:"sku"`
}
func main() {
url := os.Getenv("AMQP_URL")
if url == "" {
log.Fatal("set AMQP_URL, e.g. amqp://guest:guest@localhost:5672/")
}
conn, err := amqp.Dial(url)
if err != nil {
log.Fatal(err)
}
defer conn.Close()
ch, err := conn.Channel()
if err != nil {
log.Fatal(err)
}
// Durable quorum queue for requests; replies never touch a queue we own.
if _, err := ch.QueueDeclare(requestQueue, true, false, false, false,
amqp.Table{amqp.QueueTypeArg: amqp.QueueTypeQuorum}); err != nil {
log.Fatal(err)
}
// One unacked request per worker: slow requests do not pile up in one process.
if err := ch.Qos(1, 0, false); err != nil {
log.Fatal(err)
}
if err := ch.Confirm(false); err != nil {
log.Fatal(err)
}
// Ordinary missing reply queues return basic.return. Direct Reply-To does not.
returns := ch.NotifyReturn(make(chan amqp.Return, 16))
go func() {
for r := range returns {
log.Printf("reply %s had no route (%d %s): requester is gone", r.CorrelationId, r.ReplyCode, r.ReplyText)
}
}()
deliveries, err := ch.Consume(requestQueue, "", false, false, false, false, nil)
if err != nil {
log.Fatal(err)
}
for d := range deliveries {
if err := handle(ch, d); err != nil {
log.Fatal(err)
}
}
}
func handle(ch *amqp.Channel, d amqp.Delivery) error {
if d.ReplyTo == "" || d.CorrelationId == "" {
// Reject: dead-letter only with a configured DLX; otherwise discard.
return d.Reject(false)
}
deadline := time.Now().Add(3 * time.Second)
if raw, ok := d.Headers["deadline_unix_ms"].(string); ok {
ms, err := strconv.ParseInt(raw, 10, 64)
if err != nil {
return d.Reject(false)
}
requested := time.UnixMilli(ms)
if requested.Before(deadline) {
deadline = requested
}
}
if !deadline.After(time.Now()) {
return d.Reject(false)
}
// Production requires monitored clock skew; queue TTL is not an execution timer.
ctx, cancel := context.WithDeadline(context.Background(), deadline)
defer cancel()
var req quoteRequest
if err := json.Unmarshal(d.Body, &req); err != nil {
return d.Reject(false)
}
body, _ := json.Marshal(map[string]any{"sku": req.SKU, "price_cents": 1999})
// mandatory detects missing ordinary queues, not vanished Direct Reply-To clients.
confirmation, err := ch.PublishWithDeferredConfirmWithContext(ctx, "", d.ReplyTo, true, false, amqp.Publishing{
ContentType: "application/json",
CorrelationId: d.CorrelationId, // copy the request id into the reply
Body: body,
})
if err != nil {
return d.Nack(false, true) // unknown publication outcome; dedup is required
}
confirmed, err := confirmation.WaitContext(ctx)
if err != nil || !confirmed {
return d.Nack(false, true)
}
return d.Ack(false) // broker accepted reply; requester receipt is still NOT guaranteed
}نمونهٔ metadata تفاوت correlation و trace را نشان میدهد. برای tracing واقعی از SDK استفاده کنید؛ حفظ tracestate، لینک spanهای batch و سیاست trust فراتر از این تابع کوچک است.
// Package main shows what travels with a request across hops: a business
// correlation id (one per request-reply pair) and a W3C traceparent (one per
// distributed trace). They answer different questions and both go in headers.
package main
import (
"crypto/rand"
"encoding/hex"
"fmt"
"regexp"
"strings"
amqp "github.com/rabbitmq/amqp091-go"
)
var traceparentRE = regexp.MustCompile(`^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$`)
func randHex(n int) string {
b := make([]byte, n)
_, _ = rand.Read(b)
return hex.EncodeToString(b)
}
// childTraceparent keeps the trace id and swaps in a new parent id, which is
// what a service does before it calls the next hop (W3C Trace Context).
func childTraceparent(parent string) string {
m := traceparentRE.FindStringSubmatch(parent)
if m == nil || m[1] == strings.Repeat("0", 32) || m[2] == strings.Repeat("0", 16) {
return "00-" + randHex(16) + "-" + randHex(8) + "-01" // start a new trace
}
return "00-" + m[1] + "-" + randHex(8) + "-" + m[3]
}
// Request builds an AMQP publishing for the request leg. CorrelationId matches
// reply to request; traceparent lets the tracing backend join the hops.
func Request(traceparent, replyTo string, body []byte) amqp.Publishing {
return amqp.Publishing{
ContentType: "application/json",
CorrelationId: randHex(16),
ReplyTo: replyTo,
MessageId: randHex(16), // identifies this message; useful for dedup
Headers: amqp.Table{"traceparent": childTraceparent(traceparent)},
Body: body,
}
}
// Reply copies the correlation id and continues the same trace.
func Reply(req amqp.Delivery, body []byte) amqp.Publishing {
tp, _ := req.Headers["traceparent"].(string)
return amqp.Publishing{
ContentType: "application/json",
CorrelationId: req.CorrelationId,
Headers: amqp.Table{"traceparent": childTraceparent(tp)},
Body: body,
}
}
func main() {
in := "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01" // example from the W3C spec
req := Request(in, "amq.rabbitmq.reply-to", []byte(`{}`))
fmt.Println("correlation_id:", req.CorrelationId)
fmt.Println("traceparent :", req.Headers["traceparent"])
}جایگزین HTTP، یک endpoint وضعیت و publisher محلی قابلاجرا دارد. این publisher آموزشی و حافظهای است؛ restart کارها را از بین میبرد. برای پذیرش پایدار، DB و outbox لازم است. ناشناختهبودن نتیجهٔ publish را با retry بیکلید حل نکنید.
// Package main is the alternative to blocking on a reply: accept the work,
// return 202 Accepted with a status resource, and let the client poll.
package main
import (
"encoding/json"
"net/http"
"sync"
"time"
"github.com/google/uuid"
)
type Job struct {
ID string `json:"id"`
State string `json:"state"` // queued | done | failed
Result string `json:"result,omitempty"`
}
// Store is the status table. In production this is a database row, not a map.
type Store struct {
mu sync.Mutex
jobs map[string]Job
}
func (s *Store) Put(j Job) {
s.mu.Lock()
defer s.mu.Unlock()
s.jobs[j.ID] = j
}
func (s *Store) Get(id string) (Job, bool) {
s.mu.Lock()
defer s.mu.Unlock()
j, ok := s.jobs[id]
return j, ok
}
// Publisher puts the command on a broker. The worker that consumes it calls
// Store.Put with state "done" when it finishes.
type Publisher interface {
Publish(jobID string, body []byte) error
}
func NewMux(store *Store, pub Publisher) *http.ServeMux {
mux := http.NewServeMux()
mux.HandleFunc("POST /quotes", func(w http.ResponseWriter, r *http.Request) {
if pub == nil {
http.Error(w, "publisher not configured", http.StatusServiceUnavailable)
return
}
id := uuid.NewString()
store.Put(Job{ID: id, State: "queued"})
if err := pub.Publish(id, []byte(r.URL.Query().Get("sku"))); err != nil {
store.Put(Job{ID: id, State: "failed"})
// A real publish error may have an unknown outcome: reconcile using a DB outbox.
http.Error(w, "broker unavailable", http.StatusServiceUnavailable)
return
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Location", "/quotes/"+id)
w.Header().Set("Retry-After", "1")
w.WriteHeader(http.StatusAccepted)
_ = json.NewEncoder(w).Encode(Job{ID: id, State: "queued"})
})
mux.HandleFunc("GET /quotes/{id}", func(w http.ResponseWriter, r *http.Request) {
job, ok := store.Get(r.PathValue("id"))
if !ok {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(job) // 200 with the current state
})
return mux
}
func main() {
store := &Store{jobs: map[string]Job{}}
_ = http.ListenAndServe(":8080", NewMux(store, localPublisher{store}))
}
// A runnable teaching substitute, NOT durable acceptance: process exit loses jobs.
// Production persists status + outbox atomically; a relay publishes and a worker
// updates the status. Neither afterCommit nor this goroutine closes that crash gap.
type localPublisher struct{ store *Store }
func (p localPublisher) Publish(id string, body []byte) error {
go func() {
time.Sleep(100 * time.Millisecond)
p.store.Put(Job{ID: id, State: "done", Result: "quote for " + string(body)})
}()
return nil
}Hub سادهٔ SSE فقط اعلان لحظهای را نشان میدهد. client باید پس از آمادهشدن اشتراک وضعیت پایدار را fetch کند؛ endpoint داخلی نمونه نیازمند احراز هویت در محصول واقعی است.
// Package main delivers an asynchronous reply to a browser with
// Server-Sent Events: POST returns 202, GET /quotes/{id}/events streams the
// result when a worker finishes. A WebSocket or Reverb channel plays the
// same role when the browser also needs to send.
package main
import (
"fmt"
"net/http"
"sync"
"time"
)
// Hub fans a finished result out to whoever is watching that id. In a real
// system the worker publishes to Redis/RabbitMQ and every web node has a hub.
type Hub struct {
mu sync.Mutex
subs map[string][]chan string
}
func NewHub() *Hub { return &Hub{subs: map[string][]chan string{}} }
func (h *Hub) Subscribe(id string) (<-chan string, func()) {
ch := make(chan string, 1) // buffered: Publish never blocks on a slow browser
h.mu.Lock()
h.subs[id] = append(h.subs[id], ch)
h.mu.Unlock()
return ch, func() {
h.mu.Lock()
defer h.mu.Unlock()
list := h.subs[id]
for i, c := range list {
if c == ch {
h.subs[id] = append(list[:i], list[i+1:]...)
break
}
}
}
}
func (h *Hub) Publish(id, payload string) {
h.mu.Lock()
defer h.mu.Unlock()
for _, c := range h.subs[id] {
select {
case c <- payload:
default: // already has a pending value
}
}
delete(h.subs, id)
}
func events(h *Hub) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
fl, ok := w.(http.Flusher)
if !ok {
http.Error(w, "streaming unsupported", http.StatusInternalServerError)
return
}
ch, cancel := h.Subscribe(r.PathValue("id"))
defer cancel()
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
fmt.Fprint(w, ": connected\n\n")
fl.Flush()
keepAlive := time.NewTicker(15 * time.Second) // comment lines keep proxies from idling out
defer keepAlive.Stop()
for {
select {
case msg := <-ch:
fmt.Fprintf(w, "event: quote.ready\ndata: %s\n\n", msg)
fl.Flush()
return
case <-keepAlive.C:
fmt.Fprint(w, ": ping\n\n")
fl.Flush()
case <-r.Context().Done(): // browser left: stop waiting
return
}
}
}
}
func main() {
hub := NewHub()
mux := http.NewServeMux()
mux.HandleFunc("GET /quotes/{id}/events", events(hub))
mux.HandleFunc("POST /internal/quotes/{id}/ready", func(w http.ResponseWriter, r *http.Request) {
hub.Publish(r.PathValue("id"), `{"price_cents":1999}`)
w.WriteHeader(http.StatusNoContent)
})
srv := &http.Server{Addr: ":8080", Handler: mux, ReadHeaderTimeout: 5 * time.Second}
_ = srv.ListenAndServe()
}برای webhook، کلید همتوانی در تمام تلاشها ثابت میماند؛ امضای payload و محدودکردن مقصد callback نیز مسئولیت استقرار واقعی است.
// Package main delivers a result to a caller's callback URL. The sender
// retries with backoff and sends a stable Idempotency-Key, because the
// receiver will see duplicates (a timeout does not mean the callback failed).
package main
import (
"bytes"
"context"
"fmt"
"net/http"
"time"
)
// Deliver POSTs payload to url, retrying on network errors and 5xx.
func Deliver(ctx context.Context, c *http.Client, url, requestID string, payload []byte) error {
backoff := 500 * time.Millisecond
var last error
for attempt := 1; attempt <= 5; attempt++ {
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(payload))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Idempotency-Key", requestID) // same key on every attempt
resp, err := c.Do(req)
if err == nil {
resp.Body.Close()
if resp.StatusCode < 300 {
return nil
}
if resp.StatusCode < 500 && resp.StatusCode != http.StatusTooManyRequests {
return fmt.Errorf("callback rejected with %d: do not retry", resp.StatusCode)
}
last = fmt.Errorf("callback returned %d", resp.StatusCode)
} else {
last = err
}
select {
case <-time.After(backoff):
backoff *= 2
case <-ctx.Done():
return ctx.Err()
}
}
return fmt.Errorf("giving up after 5 attempts: %w", last)
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
c := &http.Client{Timeout: 5 * time.Second}
// Compile-only example; nothing listens on this address.
_ = Deliver(ctx, c, "http://localhost:9999/hooks/quote", "req-123", []byte(`{"price_cents":1999}`))
}وقتی جواب فوری لازم است، HTTP client با timeout و retry محدود روی GET همتوان، مسیر سادهتری دارد.
// Package main is the plain alternative: when the caller needs the answer
// now, call the service over HTTP with a deadline, a bounded retry on an
// idempotent request, and the trace context forwarded.
package main
import (
"context"
"fmt"
"io"
"log"
"net/http"
"time"
)
var client = &http.Client{
Timeout: 2 * time.Second, // hard ceiling for one attempt, including reading the body
Transport: &http.Transport{
MaxIdleConnsPerHost: 50,
ResponseHeaderTimeout: 1500 * time.Millisecond,
},
}
// GetQuote retries only because GET is idempotent (RFC 9110 section 9.2.2).
// A POST needs an Idempotency-Key before it may be retried.
func GetQuote(ctx context.Context, traceparent, sku string) ([]byte, error) {
ctx, cancel := context.WithTimeout(ctx, 3*time.Second) // total budget for all attempts
defer cancel()
var last error
for attempt := 0; attempt < 3; attempt++ {
req, err := http.NewRequestWithContext(ctx, http.MethodGet,
"http://pricing.internal/quotes/"+sku, nil)
if err != nil {
return nil, err
}
req.Header.Set("traceparent", traceparent)
resp, err := client.Do(req)
if err == nil {
body, rerr := io.ReadAll(resp.Body)
resp.Body.Close()
if rerr == nil && resp.StatusCode == http.StatusOK {
return body, nil
}
if resp.StatusCode < 500 {
return nil, fmt.Errorf("pricing returned %d", resp.StatusCode)
}
last = fmt.Errorf("pricing returned %d", resp.StatusCode)
} else {
last = err
}
select {
case <-time.After(time.Duration(100<<attempt) * time.Millisecond):
case <-ctx.Done():
return nil, ctx.Err()
}
}
return nil, last
}
func main() {
_, err := GetQuote(context.Background(), "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01", "A-1")
log.Println("result:", err)
}نگاه Go
لغو context انتظار روی select را خاتمه میدهد؛ کار remote را جادویی لغو نمیکند. channel منتظر یک buffer دارد و dispatcher فقط اولین جواب را ارسال میکند. Consume هنگام بستهشدن channel/connection یا cancel مصرفکننده پایان مییابد؛ همان لحظه باید pendingها fail شوند. NotifyReturn برای mandatory و Confirm برای پذیرش انتشار دو سیگنال متفاوتاند. الگوهای ServeMux مانند GET /quotes/{id} و PathValue endpoint وضعیت را بدون router جانبی میسازند.
Laravel
قبل
controller پس از dispatch در حلقهٔ poll باقی میماند. شکست دائمی job یا قطع worker میتواند یک PHP-FPM worker را تا timeout زیرساخت نگه دارد.
<?php
namespace App\Http\Controllers;
use App\Jobs\BuildQuote;
use App\Models\Quote;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
class QuoteController
{
// Sync over async: dispatch a job, then hold the HTTP request open and
// poll the database until the worker has written the answer.
public function store(Request $request): JsonResponse
{
$quote = Quote::create([
'id' => (string) Str::uuid(),
'sku' => $request->string('sku'),
'state' => 'queued',
]);
BuildQuote::dispatch($quote->id);
// No deadline: this FPM worker is pinned for as long as the queue is
// slow, the worker is down, or the job has failed for good.
while (true) {
$quote->refresh();
if ($quote->state === 'done') {
return response()->json(['price' => $quote->price]);
}
usleep(200_000);
}
}
}بعد
controller وضعیت اولیه را ثبت میکند و 202 همراه نشانی پیگیری میدهد. این skeleton باید با validation، مالکیت رکورد و outbox تکمیل شود؛ afterCommit جای تراکنش توزیعشده نیست.
<?php
namespace App\Http\Controllers;
use App\Jobs\BuildQuote;
use App\Models\Quote;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
// routes/api.php
// Route::post('/quotes', [QuoteController::class, 'store']);
// Route::get('/quotes/{quote}', [QuoteController::class, 'show'])->name('quotes.show');
class QuoteController
{
// Teaching skeleton: authenticate/authorize the owner and validate SKU.
// Production needs status + transactional outbox for durable acceptance.
// afterCommit orders dispatch but does not make DB and broker commit atomic.
// Accept the work, answer 202 Accepted, point at a status resource.
public function store(Request $request): JsonResponse
{
$quote = Quote::create([
'id' => (string) Str::uuid(),
'sku' => $request->string('sku'),
'state' => 'queued',
]);
// Wait for the INSERT to commit before a worker can see the job.
BuildQuote::dispatch($quote->id)->afterCommit();
return response()
->json(['id' => $quote->id, 'state' => $quote->state], 202)
->header('Location', route('quotes.show', $quote))
->header('Retry-After', '1');
}
// The client polls this; it never blocks.
public function show(Quote $quote): JsonResponse
{
return response()->json([
'id' => $quote->id,
'state' => $quote->state,
'price' => $quote->price,
]);
}
}job نتیجه را ذخیره و رویداد را dispatch میکند. hook شکست نباید نتیجهٔ done را بهخاطر شکست بعدی در broadcast به failed برگرداند.
<?php
namespace App\Jobs;
use App\Events\QuoteReady;
use App\Models\Quote;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\Timeout;
use Illuminate\Queue\Attributes\Tries;
use Throwable;
#[Tries(3)]
#[Timeout(30)]
class BuildQuote implements ShouldQueue
{
use Queueable;
public function __construct(public string $quoteId) {}
public function handle(): void
{
$quote = Quote::findOrFail($this->quoteId);
// Idempotent write: a retry after a crash simply overwrites the row.
$quote->forceFill([
'state' => 'done',
'price' => $this->priceFor($quote->sku),
])->save();
// Push the reply to the browser; ShouldBroadcast queues the broadcast.
QuoteReady::dispatch($quote);
}
// Called after the last attempt: the status row is the reply channel,
// so failures must be written to it too.
public function failed(?Throwable $exception): void
{
// A retry can fail while broadcasting after the result was already saved.
Quote::whereKey($this->quoteId)->where('state', '!=', 'done')->update(['state' => 'failed']);
}
private function priceFor(string $sku): int
{
return 4200; // stand-in for the real work
}
}رویداد روی کانال خصوصی میرود. ShouldDispatchAfterCommit از دیدهشدن اعلان قبل از commit جلوگیری میکند؛ policy کانال باید کاربر مالک را بررسی کند.
<?php
namespace App\Events;
use App\Models\Quote;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Contracts\Events\ShouldDispatchAfterCommit;
use Illuminate\Foundation\Events\Dispatchable;
// The asynchronous "reply" for a browser: the job finishes, Reverb (or Pusher,
// Ably) pushes this event to the page that is waiting on the quote.
class QuoteReady implements ShouldBroadcast, ShouldDispatchAfterCommit
{
use Dispatchable, InteractsWithSockets;
public function __construct(public Quote $quote) {}
public function broadcastOn(): array
{
// Private channel: only the owner may listen (see routes/channels.php).
return [new PrivateChannel('quotes.'.$this->quote->id)];
}
public function broadcastAs(): string
{
return 'quote.ready';
}
public function broadcastWith(): array
{
return ['id' => $this->quote->id, 'state' => $this->quote->state, 'price' => $this->quote->price];
}
}<?php
use App\Models\Quote;
use Illuminate\Support\Facades\Broadcast;
// routes/channels.php. Echo asks this callback before it lets a browser
// subscribe to the private channel.
Broadcast::channel('quotes.{quoteId}', function ($user, string $quoteId) {
return Quote::whereKey($quoteId)->where('user_id', $user->id)->exists();
});notification با database و broadcast برای کاربری که صفحه را بسته نیز قابلاستفاده است؛ وضعیت عملیات همچنان منبع معتبر نتیجه است.
<?php
namespace App\Notifications;
use App\Models\Quote;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\BroadcastMessage;
use Illuminate\Notifications\Notification;
// Notification flavour of the same reply: stored for later (database) and
// pushed live (broadcast). A user who closed the tab still finds it later.
class QuoteReadyNotification extends Notification implements ShouldQueue
{
use Queueable;
public function __construct(public Quote $quote)
{
$this->afterCommit();
}
public function via(object $notifiable): array
{
return ['database', 'broadcast'];
}
public function toArray(object $notifiable): array
{
return ['quote_id' => $this->quote->id, 'price' => $this->quote->price];
}
public function toBroadcast(object $notifiable): BroadcastMessage
{
return new BroadcastMessage($this->toArray($notifiable));
}
}سه روش dispatch، اجرای local را از queued و انتظار روی queued جدا میکنند.
<?php
namespace App\Http\Controllers;
use App\Jobs\BuildQuote;
use App\Models\Quote;
use Illuminate\Http\JsonResponse;
// Three ways to run the same job; only the last one is request-reply.
class DispatchModes
{
// 1. In-process, in the web request. No queue, no broker: this is a
// function call that happens to be shaped like a job.
public function inline(Quote $quote): JsonResponse
{
BuildQuote::dispatchSync($quote->id);
return response()->json($quote->fresh());
}
// 2. Queued, fire and forget. The response cannot contain the result.
public function queued(Quote $quote): JsonResponse
{
BuildQuote::dispatch($quote->id)->afterCommit();
return response()->json(['state' => 'queued'], 202);
}
// 3. Queued and awaited: sync over async. Do not ship this; it is here to
// be recognised in code review.
public function blocking(Quote $quote): JsonResponse
{
BuildQuote::dispatch($quote->id)->afterCommit();
$deadline = microtime(true) + 5;
while (microtime(true) < $deadline) {
$quote->refresh();
if ($quote->state !== 'queued') {
return response()->json($quote);
}
usleep(200_000); // holds a PHP-FPM worker the whole time
}
return response()->json(['state' => 'timeout'], 504);
}
}HTTP client زیر timeout اتصال و هر attempt و retry محدود دارد. مجموع تلاشها میتواند از timeout یک attempt بیشتر شود؛ deadline کل باید در لایهٔ caller مدیریت شود. header idempotency فقط با پشتیبانی واقعی سرور مؤثر است.
<?php
namespace App\Clients;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
use Throwable;
// The synchronous alternative: when the caller needs the answer now, call
// the service over HTTP with a deadline and an idempotency key.
class HttpQuoteClient
{
public function create(string $sku, string $traceparent): array
{
// One key per logical request, reused by every retry of it.
$key = (string) Str::uuid();
return Http::baseUrl(config('services.pricing.url'))
->withHeaders([
'Idempotency-Key' => $key,
'traceparent' => $traceparent,
])
->connectTimeout(1)
->timeout(3)
// Retry connection errors and 5xx only; a 4xx is the caller's bug.
->retry(
[100, 300],
when: fn (Throwable $e) => $e instanceof ConnectionException
|| ($e instanceof RequestException && $e->response->serverError()),
throw: false,
)
->post('/quotes', ['sku' => $sku])
->throw()
->json();
}
}برای RPC واقعی، php-amqplib مستقیم استفاده شده است. این client سری است و یک درخواست outstanding دارد؛ آن را میان coroutineهای همزمان به اشتراک نگذارید. حلقه با ساعت monotonic انتظار را محدود میکند؛ socket write timeout باید روی connection تنظیم شود.
<?php
namespace App\Messaging;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Exception\AMQPTimeoutException;
use PhpAmqpLib\Message\AMQPMessage;
use RuntimeException;
use InvalidArgumentException;
use PhpAmqpLib\Wire\AMQPTable;
// Raw php-amqplib (the laravel-queue-rabbitmq package is a queue driver and
// exposes no request-reply client). Follows RabbitMQ tutorial 6 for PHP, with
// Direct Reply-To instead of a declared callback queue.
class RabbitRpcClient
{
private const REPLY_TO = 'amq.rabbitmq.reply-to';
private $channel;
private ?string $response = null;
private string $correlationId = '';
public function __construct(AMQPStreamConnection $connection, private string $requestQueue)
{
$this->channel = $connection->channel();
// Consume the pseudo-queue in no-ack mode on the SAME channel that
// will publish the requests.
$this->channel->basic_consume(
self::REPLY_TO,
'',
false,
true, // no_ack
false,
false,
function (AMQPMessage $reply): void {
if ($reply->get('correlation_id') === $this->correlationId) {
$this->response = $reply->getBody();
}
// Any other correlation id is a late reply to an abandoned call.
},
);
}
public function call(string $body, float $timeoutSeconds = 2.0): string
{
if ($timeoutSeconds <= 0 || ! is_finite($timeoutSeconds)) {
throw new InvalidArgumentException('positive finite timeout required');
}
$deadline = hrtime(true) + (int) ($timeoutSeconds * 1_000_000_000);
$this->response = null;
$this->correlationId = bin2hex(random_bytes(16));
$this->channel->basic_publish(new AMQPMessage($body, [
'correlation_id' => $this->correlationId,
'reply_to' => self::REPLY_TO,
'expiration' => (string) max(1, (int) ($timeoutSeconds * 1000)),
'application_headers' => new AMQPTable([
'deadline_unix_ms' => (string) (int) ((microtime(true) + $timeoutSeconds) * 1000),
]),
]), '', $this->requestQueue);
// The connection must also have bounded socket read/write timeouts.
// This loop deadline cannot interrupt a socket write already in progress.
while ($this->response === null) {
$remaining = ($deadline - hrtime(true)) / 1_000_000_000;
if ($remaining <= 0) {
throw new RuntimeException('RPC timed out');
}
try {
$this->channel->wait(null, false, $remaining);
} catch (AMQPTimeoutException) {
throw new RuntimeException('RPC timed out');
}
}
return $this->response;
}
}پاسخدهنده command مستقل Artisan است؛ driver صف Laravel بهجای شما reply_to مصرف نمیکند. confirm پیش از ack درخواست گرفته میشود؛ exception باید موجب توقف/بازیابی تحت supervisor شود و request unacked برای redelivery باقی میماند.
<?php
namespace App\Console\Commands;
use App\Services\PricingService;
use Illuminate\Console\Command;
use PhpAmqpLib\Channel\AMQPChannel;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
use PhpAmqpLib\Wire\AMQPTable;
use RuntimeException;
use JsonException;
// php artisan rpc:serve
// The replier of a RabbitMQ RPC, written against php-amqplib. The
// laravel-queue-rabbitmq driver consumes Laravel jobs and sets no reply_to,
// so a request-reply server is a separate long-running command.
class RpcServeCommand extends Command
{
protected $signature = 'rpc:serve {--queue=quotes.rpc}';
protected $description = 'Answer RabbitMQ RPC requests using reply_to and correlation_id';
public function handle(PricingService $pricing): int
{
$connection = new AMQPStreamConnection(
config('queue.connections.rabbitmq.hosts.0.host', 'localhost'),
(int) config('queue.connections.rabbitmq.hosts.0.port', 5672),
config('queue.connections.rabbitmq.hosts.0.user', 'guest'),
config('queue.connections.rabbitmq.hosts.0.password', 'guest'),
);
$channel = $connection->channel();
$queue = (string) $this->option('queue');
$channel->queue_declare($queue, false, true, false, false, false, new AMQPTable(['x-queue-type' => 'quorum']));
$channel->confirm_select();
$channel->set_nack_handler(static function (): void { throw new RuntimeException('reply rejected by broker'); });
$channel->set_return_listener(function (): void { $this->warn('ordinary reply queue has no route'); });
$channel->basic_qos(null, 1, null); // one unacked request per worker
$channel->basic_consume($queue, '', false, false, false, false,
function (AMQPMessage $request) use ($pricing, $channel): void {
$this->reply($channel, $request, $pricing);
});
while ($channel->is_consuming()) {
$channel->wait();
}
return self::SUCCESS;
}
private function reply(AMQPChannel $channel, AMQPMessage $request, PricingService $pricing): void
{
if (! $request->has('reply_to') || ! $request->has('correlation_id')) {
$request->nack(false); // no return address: reject; DLX if configured, otherwise discard
return;
}
// Require a usable, unexpired deadline before expensive work. Monitor clock skew.
$headers = $request->has('application_headers') ? $request->get('application_headers')->getNativeData() : [];
$deadline = filter_var($headers['deadline_unix_ms'] ?? null, FILTER_VALIDATE_INT);
if ($deadline === false || $deadline <= (int) (microtime(true) * 1000)) {
$request->nack(false);
return;
}
try {
$payload = json_decode($request->getBody(), true, flags: JSON_THROW_ON_ERROR);
} catch (JsonException) {
$request->nack(false);
return;
}
if (! is_array($payload) || ! is_string($payload['sku'] ?? null)) {
$request->nack(false);
return;
}
$sku = $payload['sku'] ?? '';
// PricingService must also bound downstream I/O; the check cannot cancel committed effects.
$body = json_encode(['sku' => $sku, 'price_cents' => $pricing->priceFor($sku)]);
$channel->basic_publish(
new AMQPMessage($body, [
'content_type' => 'application/json',
'correlation_id' => $request->get('correlation_id'),
]),
'',
$request->get('reply_to'),
true, // missing ordinary queue; Direct Reply-To is always considered routed
);
$channel->wait_for_pending_acks_returns(3.0);
$request->ack(); // broker acceptance, NOT proof the requester received the reply
}
}نگاه Laravel
صف Laravel برای اجرای job است. Job::dispatch() یک PendingDispatch میدهد و APIهای دیگر dispatch ممکن است شناسه یا نتیجهٔ dispatch بدهند؛ هیچکدام نتیجهٔ آیندهٔ worker remote را برنمیگردانند.
| قابلیت Laravel 13 | رفتار | کاربرد این فصل |
|---|---|---|
afterCommit() | dispatch پس از commit | job رکورد هنوز commitنشده را نبیند |
after_commit اتصال | همان سیاست برای اتصال | تنظیم عمومی |
dispatchSync() | اجرای فعلی در process | جای RPC نیست |
#[Tries] و #[Timeout] | سقف تلاش و زمان job | پایان شکست قابلردیابی |
failed() | مسیر شکست نهایی | ثبت failure بدون بازگرداندن done |
ShouldBroadcast و PrivateChannel | job broadcast و authorization | اعلان مرورگر |
ShouldDispatchAfterCommit | رویداد پس از commit | ترتیب مشاهده |
| notification database/broadcast | ذخیره و push | کاربر offline |
| Reverb | WebSocket first-party | push خودمیزبان |
| Http timeout/connectTimeout/retry | زمان هر attempt و retry | REST محدود |
| Http withHeaders | idempotency و trace | قرارداد retry و tracing |
ShouldBroadcast معمولاً worker صف نیاز دارد؛ ShouldBroadcastNow استثنای همگام است. منبع بستهٔ laravel-queue-rabbitmq بررسیشده، id payload را در correlation_id میگذارد ولی reply_to تنظیم نمیکند. این property بهتنهایی client RPC نمیسازد. RabbitMQ و Kafka driver داخلی Laravel نیستند؛ نمونهٔ raw client از semantics jobهای Laravel جداست.
تفاوتهای اجرا در brokerها
RabbitMQ
نشانی بازگشت (Return Address) و شناسهٔ همبستگی (Correlation Identifier) property استاندارد پیاماند. default exchange بر اساس نام صف مسیر میدهد. صف درخواست quorum با consumerهای رقیب مستقل از مقصد پاسخ است. صف اختصاصی، صف نامدار بلندعمر و Direct Reply-To هرکدام عمر و تضمین متفاوت دارند؛ deadline caller و TTL صف و deadline اجرای کار سه کنترل جدا هستند.
// Package main is a RabbitMQ RPC client using Direct Reply-To and a context
// timeout. One consumer on one channel serves every concurrent call.
package main
import (
"context"
"errors"
"fmt"
"log"
"net"
"os"
"strconv"
"sync"
"time"
"github.com/google/uuid"
amqp "github.com/rabbitmq/amqp091-go"
)
const directReplyTo = "amq.rabbitmq.reply-to"
type Client struct {
ch *amqp.Channel
queue string
mu sync.Mutex
pending map[string]chan result
closed bool
}
type result struct {
body []byte
err error
}
// ErrReplyChannelLost is returned to every waiter when the reply consumer
// ends (channel or connection closed, consumer cancelled). Direct Reply-To
// replies are at-most-once. Retry only idempotent or deduplicated operations.
var ErrReplyChannelLost = errors.New("reply consumer closed; outcome may be unknown")
// NewClient consumes from the pseudo-queue in no-ack mode. The same channel
// must be used to publish requests (RabbitMQ Direct Reply-To rule).
func NewClient(ch *amqp.Channel, requestQueue string) (*Client, error) {
replies, err := ch.Consume(directReplyTo, "", true, false, false, false, nil)
if err != nil {
return nil, fmt.Errorf("consume reply-to: %w", err)
}
c := &Client{ch: ch, queue: requestQueue, pending: map[string]chan result{}}
go func() {
for d := range replies {
c.mu.Lock()
w, ok := c.pending[d.CorrelationId]
delete(c.pending, d.CorrelationId)
c.mu.Unlock()
if !ok {
continue // late or duplicate reply: nobody is waiting, drop it
}
w <- result{body: d.Body} // buffered, never blocks
}
// The deliveries channel closed: fail everyone instead of letting
// them wait for their full deadline.
c.mu.Lock()
c.closed = true
for id, w := range c.pending {
w <- result{err: ErrReplyChannelLost}
delete(c.pending, id)
}
c.mu.Unlock()
}()
return c, nil
}
// Call publishes a request and waits for the reply or ctx.Done().
func (c *Client) Call(ctx context.Context, body []byte) ([]byte, error) {
if _, ok := ctx.Deadline(); !ok {
return nil, errors.New("RPC requires a deadline")
}
if err := ctx.Err(); err != nil {
return nil, err
}
deadline, _ := ctx.Deadline()
id := uuid.NewString()
wait := make(chan result, 1)
c.mu.Lock()
if c.closed {
c.mu.Unlock()
return nil, ErrReplyChannelLost
}
if len(c.pending) >= 256 {
c.mu.Unlock()
return nil, errors.New("RPC in-flight limit reached")
}
c.pending[id] = wait
c.mu.Unlock()
defer func() {
c.mu.Lock()
delete(c.pending, id) // timed out: later replies become orphans
c.mu.Unlock()
}()
err := c.ch.PublishWithContext(ctx, "", c.queue, false, false, amqp.Publishing{
ContentType: "application/json",
CorrelationId: id,
ReplyTo: directReplyTo,
Expiration: strconv.FormatInt(max(1, time.Until(deadline).Milliseconds()), 10), // queue residence only
Headers: amqp.Table{"deadline_unix_ms": strconv.FormatInt(deadline.UnixMilli(), 10)},
Body: body,
})
if err != nil {
return nil, err
}
select {
case res := <-wait:
return res.body, res.err
case <-ctx.Done():
return nil, ctx.Err()
}
}
func main() {
url := os.Getenv("AMQP_URL")
if url == "" {
log.Fatal("set AMQP_URL, e.g. amqp://guest:guest@localhost:5672/")
}
conn, err := amqp.DialConfig(url, amqp.Config{
Dial: func(network, address string) (net.Conn, error) {
c, err := net.DialTimeout(network, address, time.Second)
if err != nil {
return nil, err
}
return &boundedWriteConn{Conn: c}, nil
},
})
if err != nil {
log.Fatal(err)
}
defer conn.Close()
ch, err := conn.Channel()
if err != nil {
log.Fatal(err)
}
client, err := NewClient(ch, "quotes.rpc")
if err != nil {
log.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
reply, err := client.Call(ctx, []byte(`{"sku":"A-1"}`))
log.Printf("reply=%s err=%v", reply, err)
}
// Reply is the responder side: publish to the default exchange using the
// request's ReplyTo as the routing key, and copy the correlation id.
func Reply(ctx context.Context, ch *amqp.Channel, req amqp.Delivery, body []byte) error {
return ch.PublishWithContext(ctx, "", req.ReplyTo, false, false, amqp.Publishing{
CorrelationId: req.CorrelationId,
ContentType: "application/json",
Body: body,
})
}
// Context cancellation cannot interrupt an amqp091-go socket write. This
// connection-wide cap bounds each write; it is separate from the RPC deadline.
// Shared connections must not be closed just to cancel one individual call.
type boundedWriteConn struct{ net.Conn }
func (c *boundedWriteConn) Write(p []byte) (int, error) {
if err := c.Conn.SetWriteDeadline(time.Now().Add(time.Second)); err != nil {
return 0, err
}
return c.Conn.Write(p)
}confirm انتشار جواب، ack درخواست و دریافت requester سه اتفاقاند. retry پس از ابهام فقط با کلید منطقی یا عملیات طبیعی همتوان امن است. جزئیات broker در RabbitMQ.
Kafka
مقصد پاسخ (Reply Destination) قرارداد header است. topic مشترک با group مستقل، مصرف تکراری جوابها میسازد؛ group مشترک جوابها را تقسیم میکند و ممکن است caller غلط آن را بگیرد. partition رزروشده و ManualPartitioner ownership روشن میخواهند. مثال از retained start میخواند؛ production باید offset بازیابیشده، ظرفیت pending و lifecycle reader را مدیریت کند.
// Package main sketches Kafka request-reply with franz-go. Kafka has no
// reply-to primitive, so the requester claims one partition of a shared
// reply topic and says so in a header; the replier produces back to it.
package main
import (
"context"
"errors"
"log"
"os"
"strconv"
"sync"
"time"
"github.com/google/uuid"
"github.com/twmb/franz-go/pkg/kgo"
)
const (
requestTopic = "quotes.requests"
replyTopic = "quotes.replies"
)
type Requester struct {
cl *kgo.Client
partition int32
mu sync.Mutex
pending map[string]chan []byte
}
func NewRequester(brokers []string, partition int32) (*Requester, error) {
cl, err := kgo.NewClient(
kgo.SeedBrokers(brokers...),
// Read our assigned partition from its retained start, filtering old ids.
// AtEnd resolved asynchronously can skip a reply produced before offset lookup.
// No consumer group:
// a rebalance here would add seconds of latency to every call.
kgo.ConsumePartitions(map[string]map[int32]kgo.Offset{
replyTopic: {partition: kgo.NewOffset().AtStart()},
}),
)
if err != nil {
return nil, err
}
r := &Requester{cl: cl, partition: partition, pending: map[string]chan []byte{}}
go r.pump(context.Background())
return r, nil
}
func (r *Requester) pump(ctx context.Context) {
for {
fetches := r.cl.PollFetches(ctx)
if fetches.IsClientClosed() || ctx.Err() != nil {
return
}
fetches.EachRecord(func(rec *kgo.Record) {
var corr string
for _, h := range rec.Headers {
if h.Key == "correlation-id" {
corr = string(h.Value)
}
}
r.mu.Lock()
w, ok := r.pending[corr]
delete(r.pending, corr)
r.mu.Unlock()
if ok {
w <- rec.Value // orphans (timed out calls) are skipped
}
})
}
}
func (r *Requester) Call(ctx context.Context, key, body []byte) ([]byte, error) {
if _, ok := ctx.Deadline(); !ok {
return nil, errors.New("RPC requires a deadline")
}
id := uuid.NewString()
wait := make(chan []byte, 1)
r.mu.Lock()
r.pending[id] = wait
r.mu.Unlock()
defer func() {
r.mu.Lock()
delete(r.pending, id)
r.mu.Unlock()
}()
rec := &kgo.Record{
Topic: requestTopic,
Key: key,
Value: body,
Headers: []kgo.RecordHeader{
{Key: "correlation-id", Value: []byte(id)},
{Key: "reply-topic", Value: []byte(replyTopic)},
{Key: "reply-partition", Value: []byte(strconv.Itoa(int(r.partition)))},
},
}
if err := r.cl.ProduceSync(ctx, rec).FirstErr(); err != nil {
return nil, err
}
select {
case v := <-wait:
return v, nil
case <-ctx.Done():
return nil, ctx.Err()
}
}
// Reply runs on the replier: copy the correlation header and produce to the
// partition named in the request. The producer must use ManualPartitioner.
func Reply(ctx context.Context, cl *kgo.Client, req *kgo.Record, body []byte) error {
var corr, topic, part []byte
for _, h := range req.Headers {
switch h.Key {
case "correlation-id":
corr = h.Value
case "reply-topic":
topic = h.Value
case "reply-partition":
part = h.Value
}
}
p, err := strconv.ParseInt(string(part), 10, 32)
if err != nil || p < 0 || string(topic) != replyTopic || len(corr) == 0 {
return errors.New("request has no usable reply headers")
}
return cl.ProduceSync(ctx, &kgo.Record{
Topic: string(topic),
Partition: int32(p),
Value: body,
Headers: []kgo.RecordHeader{{Key: "correlation-id", Value: corr}},
}).FirstErr()
}
// NewReplierClient builds the replier's producer with manual partitioning.
func NewReplierClient(brokers []string) (*kgo.Client, error) {
return kgo.NewClient(
kgo.SeedBrokers(brokers...),
kgo.RecordPartitioner(kgo.ManualPartitioner()),
)
}
func main() {
broker := os.Getenv("KAFKA_BROKER")
if broker == "" {
log.Fatal("set KAFKA_BROKER, e.g. localhost:9092")
}
r, err := NewRequester([]string{broker}, 0)
if err != nil {
log.Fatal(err)
}
defer r.cl.Close()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
reply, err := r.Call(ctx, []byte("A-1"), []byte(`{"sku":"A-1"}`))
log.Printf("reply=%s err=%v", reply, err)
}در Laravel، mateusjunges/laravel-kafka بستهٔ producer/consumer است؛ برای reply باید topic و header همبستگی را خودتان طبق قرارداد منتشر کنید. این فصل API undocumented RPC به package نسبت نمیدهد. Kafka و Ordering جزئیات را دارند.
Redis Streams
اشتراک (Subscription) Pub/Sub باید قبل از ارسال درخواست آماده باشد. جواب Pub/Sub replay ندارد؛ stream پاسخ با cursor و retention قابلبازیابی است. EXPIRE روی کل کلید اعمال میشود؛ موفقیت XADD و شکست EXPIRE میتواند leak بسازد و باید error آن دیده شود.
// Package main uses Redis Pub/Sub for a reply. It works only because the
// requester SUBSCRIBES FIRST: Pub/Sub keeps nothing, so a reply published
// before the subscription is active is gone (at-most-once).
package main
import (
"context"
"log"
"os"
"time"
"github.com/google/uuid"
"github.com/redis/go-redis/v9"
)
// Call puts the request on a durable stream and waits for one Pub/Sub reply
// on a per-request channel. If it times out the caller decides what to do.
func Call(ctx context.Context, rdb *redis.Client, body string) (string, error) {
id := uuid.NewString()
replyChan := "reply:" + id
sub := rdb.Subscribe(ctx, replyChan)
defer sub.Close()
if _, err := sub.Receive(ctx); err != nil { // wait for the SUBSCRIBE confirmation
return "", err
}
err := rdb.XAdd(ctx, &redis.XAddArgs{
Stream: "quotes:requests",
MaxLen: 10_000, Approx: true,
Values: map[string]any{"correlation_id": id, "reply_to": replyChan, "body": body},
}).Err()
if err != nil {
return "", err
}
select {
case msg := <-sub.Channel():
return msg.Payload, nil
case <-ctx.Done():
return "", ctx.Err()
}
}
func main() {
addr := os.Getenv("REDIS_ADDR")
if addr == "" {
log.Fatal("set REDIS_ADDR, e.g. localhost:6379")
}
rdb := redis.NewClient(&redis.Options{Addr: addr})
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
reply, err := Call(ctx, rdb, `{"sku":"A-1"}`)
log.Printf("reply=%s err=%v", reply, err)
}// Package main sketches request-reply on Redis Streams: a shared request
// stream with a consumer group, and one reply stream per requester instance.
package main
import (
"context"
"errors"
"fmt"
"log"
"os"
"strings"
"sync"
"time"
"github.com/google/uuid"
"github.com/redis/go-redis/v9"
)
const requestStream = "quotes:requests"
type Requester struct {
rdb *redis.Client
replyStream string
mu sync.Mutex
pending map[string]chan string
}
func NewRequester(rdb *redis.Client) *Requester {
r := &Requester{
rdb: rdb,
replyStream: "quotes:replies:" + uuid.NewString(),
pending: map[string]chan string{},
}
go r.pump(context.Background())
return r
}
// pump tails our private reply stream, remembering the last id it saw so no
// reply is missed between two blocking reads.
func (r *Requester) pump(ctx context.Context) {
last := "0"
for ctx.Err() == nil {
streams, err := r.rdb.XRead(ctx, &redis.XReadArgs{
Streams: []string{r.replyStream, last},
Block: time.Second,
}).Result()
if err != nil {
if !errors.Is(err, redis.Nil) {
select {
case <-ctx.Done():
return
case <-time.After(200 * time.Millisecond):
}
}
continue // no busy-spin during an outage
}
for _, msg := range streams[0].Messages {
last = msg.ID
corr, _ := msg.Values["correlation_id"].(string)
body, _ := msg.Values["body"].(string)
r.mu.Lock()
w, ok := r.pending[corr]
delete(r.pending, corr)
r.mu.Unlock()
if ok {
w <- body
}
}
// Orphaned replies must not live forever.
r.rdb.Expire(ctx, r.replyStream, 5*time.Minute)
}
}
func (r *Requester) Call(ctx context.Context, body string) (string, error) {
if _, ok := ctx.Deadline(); !ok {
return "", errors.New("RPC requires a deadline")
}
id := uuid.NewString()
wait := make(chan string, 1)
r.mu.Lock()
r.pending[id] = wait
r.mu.Unlock()
defer func() {
r.mu.Lock()
delete(r.pending, id)
r.mu.Unlock()
}()
err := r.rdb.XAdd(ctx, &redis.XAddArgs{
Stream: requestStream,
MaxLen: 10000,
Approx: true,
Values: map[string]any{
"correlation_id": id,
"reply_to": r.replyStream,
"body": body,
},
}).Err()
if err != nil {
return "", err
}
select {
case v := <-wait:
return v, nil
case <-ctx.Done():
return "", ctx.Err()
}
}
// Serve is the replier: read as a group member, answer on the stream named in
// the request, then XACK the request.
// This sketch only consumes new entries. Add pending recovery (XAUTOCLAIM),
// stable logical deduplication, and atomic reply/expiry policy before production.
func Serve(ctx context.Context, rdb *redis.Client, consumer string) error {
err := rdb.XGroupCreateMkStream(ctx, requestStream, "repliers", "0").Err()
if err != nil && err.Error() != "BUSYGROUP Consumer Group name already exists" {
return err
}
for ctx.Err() == nil {
res, err := rdb.XReadGroup(ctx, &redis.XReadGroupArgs{
Group: "repliers",
Consumer: consumer,
Streams: []string{requestStream, ">"},
Count: 10,
Block: time.Second,
}).Result()
if err != nil {
if errors.Is(err, redis.Nil) {
continue
}
return err
}
for _, msg := range res[0].Messages {
replyTo, _ := msg.Values["reply_to"].(string)
corr, _ := msg.Values["correlation_id"].(string)
if !strings.HasPrefix(replyTo, "quotes:replies:") || corr == "" {
return errors.New("invalid reply address or correlation id")
}
answer := fmt.Sprintf("quote for %v", msg.Values["body"])
if err := rdb.XAdd(ctx, &redis.XAddArgs{
Stream: replyTo,
MaxLen: 1000,
Approx: true,
Values: map[string]any{"correlation_id": corr, "body": answer},
}).Err(); err != nil {
return err
}
if err := rdb.Expire(ctx, replyTo, 5*time.Minute).Err(); err != nil {
return err
}
if err := rdb.XAck(ctx, requestStream, "repliers", msg.ID).Err(); err != nil {
return err
}
}
}
return ctx.Err()
}
func main() {
addr := os.Getenv("REDIS_ADDR")
if addr == "" {
log.Fatal("set REDIS_ADDR, e.g. localhost:6379")
}
rdb := redis.NewClient(&redis.Options{Addr: addr})
r := NewRequester(rdb)
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
reply, err := r.Call(ctx, "A-1")
log.Printf("reply=%q err=%v", reply, err)
}snippet Streams فقط مسیر پیامهای جدید را آموزش میدهد؛ pending recovery، atomic expiry، ACL مقصد و dedup را برای production از فصل محصول اضافه کنید. driver داخلی Redis queue در Laravel از list و sorted set استفاده میکند، نه Streams؛ استفاده از Redis::xadd و Redis::xread قرارداد جداگانه است. Redis Streams و Redis.
در سامانههای واقعی
| مرجع عملی | نکتهٔ قابلاستفاده |
|---|---|
| RabbitMQ Direct Reply-To | metric نوع rabbit_volatile_queue؛ پاسخ بدون buffer و امکان افت |
| آموزش ششم RabbitMQ | صف callback برای client و فهرست timeout/errorهای حلنشده |
| Spring ReplyingKafkaTemplate | headerهای پاسخ، timeout و assignment آمادگی reader |
| HTTP API طولانی | semantics پذیرش RFC 9110، قرارداد status monitor |
| Stripe idempotency | قرارداد retry و retention نتیجه باید صریح باشد |
| Laravel Broadcasting/Reverb | worker broadcast میتواند اعلان را عقب بیندازد |
| W3C Trace Context | بافت استاندارد میان سرویسها؛ اعتبارسنجی و trust لازم است |
metricها را به pending count، timeout rate، orphan count، duplicate count، callback latency و accepted-work age وصل کنید. کمشدن صف broker همراه رشد timeout caller الزاماً موفقیت نیست؛ شاید درخواستها TTL شدهاند یا پاسخ مستقیم افتاده است.
در معماری: از یک فرایند تا سامانهٔ توزیعشده
تکبرنامه (Monolith)
اگر Pricing داخل همان process است، method return یا dispatchSync کافی است. برای PDF طولانی job و status row بسازید؛ request وب منتظر PDF نمیماند. شناسهٔ وضعیت، هویت عملیات است و notification فقط رسید تکمیل را میرساند.
1 POST /reports -> status + outbox -> 202
2 worker -> build PDF -> update status done
3 browser -> poll or subscribe + reconcile -> downloadتکبرنامهٔ ماژولار (Modular Monolith)
Billing میتواند قرارداد PricingGateway::quote(): Money داشته باشد و Catalog آن را local اجرا کند. اگر نتیجه دیگر فوری نیست، قرارداد را به operation id یا future تغییر دهید؛ تعویض binding به صف با همان return type پول، تغییر semantics را پنهان میکند. مالکیت status table با ماژول تولیدکنندهٔ عملیات روشن باشد. معماری رویدادمحور الگوی ارتباط ماژولها را ادامه میدهد.
ریزسرویسها (Microservices)
Checkout سه انتخاب دارد: REST با deadline برای قیمت فوری؛ command و QuoteReady برای کار دیرتر؛ RabbitMQ RPC فقط وقتی الزام broker و بودجهٔ انتظار روشن است. در حالت سوم bulkhead و idempotency لازماند. اگر چند مرحله منتظر هم هستند، saga صاحب انتظار و timeout transition است.
1 checkout: insert order pending + outbox QuoteRequested
2 return 202 to browser
3 pricing: dedup operation -> compute -> publish QuoteReady
4 checkout consumer: idempotently update order
5 notify browser; browser reconciles statusمرز رویدادهای دامنه و یکپارچهسازی، طراحی برای شکست و ارتباط سرویسها را رعایت کنید. request-reply پنهان همچنان وابستگی همگام است.
دادهٔ توزیعشده (Distributed Data)
| مسئله | مثال | پاسخ طراحی |
|---|---|---|
| replica lag | worker done نوشته، poll هنوز queued میبیند | خواندن primary یا نسخهٔ monotonic |
| مرز cluster | request quorum است، reply مستقیم volatile | تضمین دو leg را جدا تحلیل کنید |
| چند منطقه | request و reply WAN را طی میکنند | حداقل یک RTT اضافه و hopهای دیگر؛ منطقهای نگه دارید |
| push چندگرهی | اتصال browser روی node دیگری است | backplane و status پایدار |
| clock skew | deadline مطلق زود/دیر تفسیر میشود | ساعت پایششده، حاشیه و سقف محلی |
| dedup چندمنطقهای | دو region همان اثر را میپذیرند | کلید و اثر در consistency domain مشترک |
TTL نسبی نگهداری صف را محدود میکند؛ deadline مطلق اجرای remote را با فرض clock skew محدود میکند. هیچیک اثر commitشده را پس نمیگیرد. مباحث replication و consensus این مرزها را توضیح میدهند.
مسیر رشد (Scaling Path)
| مقیاس | طراحی | تغییر اصلی |
|---|---|---|
| دهها call/s | REST با مهلت یا job+status | یک مسیر پاسخ ساده |
| صدها call/s | replierهای رقیب، bulkhead، TTL | محدودکردن pending و backlog |
| هزاران call/s و client زیاد | Direct Reply-To یا مقصد هر instance، backplane | churn، queue count، metric افت |
| چند region | pool منطقهای و replication وضعیت | پرهیز از call طولانی میان منطقهها |
آزمایشگاه
تمام آزمایشهای broker، latency و starvation این بخش مورد انتظار، اجرا نشده (expected, not run) هستند. Docker اجرا نشده و هیچ عدد benchmark بهعنوان مشاهدهٔ این نوبت ادعا نمیشود. ابزارهای lint، vet و unit test صرفاً QA کدند و نتیجهٔ رفتار broker را ثابت نمیکنند.
# expected, not run: educational load model; no broker required
cd docs/snippets/messaging/request-reply-rest-amqp/go
go run ./starvation -mode sync
go run ./starvation -mode 202مدل هشت slot وب و backend با ظرفیت 20 job/s را مقابل بار حدود 100 request/s قرار میدهد. انتظار میرود در sync، timeout و رد درخواست و معطلی health بیشتر شود؛ در 202، پذیرش سریعتر ولی backlog بیشتر شود. تعداد دقیق و percentile تابع scheduler است؛ خودتان اندازه بگیرید. 202 بدون admission control صف نامحدود میسازد؛ وقتی سن کار یا backlog از حد گذشت، 429/503 بدهید.
| # | آزمایش | روش | expected, not run |
|---|---|---|---|
| 1 | baseline HTTP | بار ثابت روی Pricing | p50/p99 واقعی محیط ثبت شود |
| 2 | RPC با صف اختصاصی | client tutorial، concurrency ثابت | queue برای هر client، هزینهٔ مسیر broker |
| 3 | Direct Reply-To | همان بار و consumer گرم | صف جواب فهرست نمیشود؛ metric volatile رشد میکند |
| 4 | قطع requester وسط کار | بستن فرایند client | صف عادی ممکن است basic.return؛ مستقیم ممکن است drop بدون return |
| 5 | کار 3s، caller 2s | تأخیر عمدی worker | timeout و orphan؛ TTL فقط درخواست هنوز صفشده را حذف میکند |
| 6 | crash قبل از request ack | بعد از reply confirm متوقف کنید | redelivery و duplicate؛ dedup اثر لازم |
| 7 | 202 در برابر blocking | بار بالاتر از ظرفیت backend | 202 slot را زودتر آزاد، ولی backlog را حذف نمیکند |
expected, not run — qualitative classes, NOT measured results
HTTP direct response; no reply queue
exclusive reply queue buffer while connection lives
Direct Reply-To zero reply queues; lossy after disconnect
long-lived reply queue reconnect buffer + persistent correlation needed
Kafka reply partition retained log + explicit assignment/offset managementثبت کنید: latency هر attempt و کل عملیات، timeout، orphan، duplicate، pending high-water mark، تعداد صف، سن backlog و تأخیر health. برای publish error نامعلوم بررسی کنید آیا اثر انجام شده بود؛ این آزمایش نشان میدهد timeout چرا معادل شکست کسبوکار نیست.
بدفهمیهای رایج
| باور | واقعیت |
|---|---|
| صف caller را ناهمگام میکند | تنها اگر caller منتظر نتیجه نماند |
| correlation id retry را امن میکند | تطبیق پاسخ با dedup اثر متفاوت است |
| Direct Reply-To صف سریع است | buffer و recovery صف را ندارد |
| timeout کار را لغو میکند | نتیجه ممکن است انجامشده ولی نامعلوم باشد |
| 202 موفقیت نهایی است | تنها پذیرش است؛ status میتواند failed شود |
| هر reply برای تماس فعال است | دیررس و duplicate طبیعیاند |
| Kafka همان mailbox RabbitMQ است | قرارداد topic/group/partition باید ساخته شود |
| Pub/Sub پاسخ قابلبازیابی دارد | at-most-once و بدون replay است |
| trace id همان correlation id است | یک trace چندین گفتوگو دارد |
| gRPC همهٔ messaging را جایگزین میکند | RPC همگام هنوز وابستگی زمانی دارد |
| WebSocket نتیجه را پایدار میکند | status منبع حقیقت باقی میماند |
| dispatch نتیجهٔ worker را میدهد | PendingDispatch/metadata است، نه نتیجهٔ آینده |
| mandatory حضور Direct Reply-To را ثابت میکند | مقصد حتی بدون requester routable حساب میشود |
| publisher confirm یعنی caller جواب را گرفت | تنها پذیرش broker را نشان میدهد |
| اعضای یک consumer group همهٔ replyها را میبینند | پیامها بین اعضا تقسیم میشوند |
چکیدهٔ عملی
| موضوع | به خاطر بسپارید |
|---|---|
| الگو | دو پیام مستقل و دو مسیر |
| correlation | requester میسازد، replier کپی میکند |
| idempotency | کلید عملیات بین retryها ثابت؛ correlation هر attempt جدا |
| reply queue | معمولاً یک مقصد برای هر requester، نه هر call |
| Direct Reply-To | same channel، no-ack، یک consumer، lossy |
| deadline | انتظار، queue TTL و execution deadline جدا |
| socket write | context ممکن است نوشتن آغازشده را قطع نکند |
| orphan | pending را در timeout حذف کنید |
| duplicate | caller یکبار complete؛ worker dedup effect |
| sync over async | slot caller با latency remote اشغال میشود |
| 202 | پذیرش + status + admission control |
| push | subscribe سپس fetch؛ reconnect سپس reconcile |
| trace | SDK معتبر؛ all-zero id را ادامه ندهید |
| Kafka | ownership partition و readiness/offset پیش از ارسال |
| Redis | subscribe-first؛ cursor آخرین id؛ EXPIRE و pending recovery |
| Laravel | afterCommit ترتیب است؛ outbox دوام پذیرش را میسازد |
| انتخاب | برای جواب فوری، ابتدا RPC مستقیم را بررسی کنید |
خودآزمایی: پرسش و پاسخ
- حیاتی تقریباً در هر مصاحبه پرسیده میشود
- مهم پرتکرار؛ در سطح senior انتظار میرود
- تکمیلی عمق بیشتر؛ تمایز ایجاد میکند
۱ — سه الگوی EIP چه کاری میکنند؟ مهم
پاسخ
پاسخ: Request-Reply دو leg را میسازد؛ Return Address مقصد جواب را میگوید؛ Correlation Identifier جواب را به سؤال وصل میکند.
۲ — چرا پاسخ پنجم ممکن است پیش از پاسخ اول برسد؟ حیاتی
پاسخ
پاسخ: مدت کار workerها متفاوت است. pending table بر اساس شناسه تطبیق میدهد، نه ترتیب ورود.
۳ — چهار محدودیت Direct Reply-To را نام ببرید. تکمیلی
پاسخ
پاسخ: مصرف no-ack، اتصال و channel مشترک، یک consumer در هر channel، نبود buffer و at-most-once. mandatory نیز زندهبودن requester را ثابت نمیکند.
۴ — timeout در 2s و جواب در 3s چه میسازد؟ مهم
پاسخ
پاسخ: جواب orphan میشود. TTL فقط کار هنوز تحویلنشده را حذف میکند؛ execution deadline و timeout downstream کار آغازشده را تا حد همکاری آن محدود میکنند.
۵ — crash پس از reply confirm و قبل از ack چه نتیجهای دارد؟ حیاتی
پاسخ
پاسخ: درخواست ممکن است دوباره تحویل شود. caller duplicate را کنار میگذارد؛ replier باید اثر را با کلید منطقی ثابت dedup کند.
۶ — صف چگونه میتواند همراه starvation وب باشد؟ حیاتی
پاسخ
پاسخ: صف backend را buffer میکند اما handler منتظر هنوز slot و اتصال دارد. با افزایش زمان پاسخ همهٔ slotها اشغال میشوند؛ bulkhead و 202 دو راه محدودکردن این اثرند.
۷ — پاسخ 202 این فصل چه قراردادی دارد؟ حیاتی
پاسخ
پاسخ: وضعیت اولیه، Location منبع پیگیری و Retry-After اختیاری. این headerها قرارداد این API هستند؛ RFC تنها با 202 موفقیت نهایی را تضمین نمیکند.
۸ — چرا GET وضعیت و بعد subscribe ممکن است نتیجه را گم کند؟ مهم
پاسخ
پاسخ: کار میتواند بین آن دو تمام شود. ابتدا subscription را آماده کنید و سپس وضعیت پایدار را بخوانید؛ نسخه و reconciliation reconnect لازماند.
۹ — فرق trace id و correlation id چیست؟ مهم
پاسخ
پاسخ: trace چند سرویس و چند گفتوگو را میپوشاند؛ correlation یک پاسخ را به یک منتظر وصل میکند. span id هنگام ایجاد span فرزند تغییر میکند.
۱۰ — سه دشواری Kafka RPC را بگویید. حیاتی
پاسخ
پاسخ: مالکیت reply partition/group، race موقعیت شروع و rebalance؛ همچنین retention و batching. group مشترک mailbox شخصی نمیسازد.
۱۱ — چرا در Redis قبل از درخواست subscribe میکنیم و XREAD را با آخرین id ادامه میدهیم؟ مهم
پاسخ
پاسخ: Pub/Sub پیش از اشتراک پیام را نگه نمیدارد. استفادهٔ تکراری از $ در XREAD نیز entryهای بین دو read را از دست میدهد.
۱۲ — afterCommit و publisher confirm چه چیزهایی را تضمین نمیکنند؟ مهم
پاسخ
پاسخ: afterCommit اتمیبودن DB و broker را نمیسازد؛ outbox لازم است. confirm نیز دریافت نهایی requester یا دقیقاً یکبار بودن اثر را تضمین نمیکند.
واژهنامه
| اصطلاح | معنی |
|---|---|
| درخواستـپاسخ (Request-Reply) | گفتوگو از دو تحویل مستقل |
| درخواستکننده / پاسخدهنده (Requestor / Replier) | دو نقش گفتوگو |
| نشانی بازگشت (Return Address) | مقصد جواب داخل درخواست |
| شناسهٔ همبستگی (Correlation Identifier) | کلید تطبیق پاسخ با منتظر |
| هویت پیام (Message ID) | شناسهٔ یک پیام مستقل |
| کلید همتوانی (Idempotency Key) | هویت ثابت عملیات در تلاشهای مجدد |
| جدول منتظرها (Pending Table) | نگاشت شناسه به waiter |
| انتظار مسدودکننده (Synchronous Block) | توقف caller تا جواب |
| فراخوان بازگشتی ناهمگام (Asynchronous Callback) | تکمیل منتظر از listener مستقل |
| صف پاسخ (Reply Queue) | محل ذخیرهٔ جواب |
| صف اختصاصی (Exclusive Queue) | وابسته به اتصال مالک |
| صف خودحذفشونده (Auto-delete Queue) | حذف پس از خروج آخرین consumer طبق چرخهٔ صف |
| پاسخ مستقیم (Direct Reply-To) | مسیر volatile بدون buffer پاسخ |
| صف فرّار (rabbit_volatile_queue) | نوع داخلی پیادهسازی پاسخ مستقیم |
| انتشار الزامی (mandatory) | درخواست اطلاع از route نشدن پیام |
| بازگشت انتشار (basic.return) | پیام به route مناسب نرسیده است |
| تأیید انتشار (Publisher Confirm) | پذیرش انتشار توسط broker |
| پیشواکشی (Prefetch) | تعداد تحویلهای unacked مجاز |
| عمر پیام (TTL / expiration) | زمان مجاز اقامت در صف |
| مهلت (Deadline) | نقطهٔ پایان انتظار یا بودجهٔ اجرا |
| پاسخ یتیم (Orphaned Reply) | جواب بدون منتظر فعال |
| همگام روی ناهمگام (Sync over Async) | انتظار مسدود روی کار صفشده |
| جداساز ظرفیت (Bulkhead) | pool محدود برای مهار خرابی وابستگی |
| پذیرش (202 Accepted) | دریافت کار بدون ادعای تکمیل |
| منبع وضعیت (Status Resource) | گزارش پیشرفت، نتیجه و شکست |
| فاصلهٔ تلاش (Retry-After) | راهنمای زمان درخواست بعدی طبق قرارداد |
| رویداد ارسالی سرور (SSE) | stream یکطرفهٔ HTTP به مرورگر |
| اتصال دوطرفه (WebSocket) | ارتباط زندهٔ دوطرفه؛ Reverb پیادهسازی Laravel |
| فراخوان وب (Webhook) | callback میان سرورها |
| بافت ردیابی (Trace Context) | metadata اتصال spanهای توزیعشده |
| والد trace (traceparent) | version، trace id، parent id و flags |
| وضعیت trace (tracestate) | metadata وابسته به vendor |
| شناسهٔ علت (Causation ID) | پیام یا رویداد علت |
| قالب پاسخ Kafka (ReplyingKafkaTemplate) | helper Spring برای قرارداد request-reply |
| پارتیشن پاسخ (Reply Partition) | partition تخصیصیافته به requester |
| نگهداری topic (retention.ms) | سیاست زمانی retention، نه deadline هر call |
| پارتیشنگذار دستی (ManualPartitioner) | انتخاب partition تعیینشده در رکورد |
| پخش و جمعآوری (Scatter-gather) | یک سؤال و چند پاسخ قابلتجمیع |
| مسیر پشتیبان اعلان (Backplane) | رساندن اعلان به node دارای اتصال client |
| بازآشتی (Reconciliation) | تطبیق وضعیت پایدار پس از افت یا قطع |
| کنترل پذیرش (Admission Control) | رد بار تازه پیش از رشد نامحدود backlog |
منابع
Hohpe & Woolf, Enterprise Integration Patterns: Request-Reply, Return Address, Correlation Identifier
RabbitMQ: Direct Reply-To, RPC tutorial (Go), RPC tutorial (PHP), Consumers, TTL
IETF: RFC 9110, HTTP Semantics, section 15.3.3 "202 Accepted" and section 9.2.2 "Idempotent Methods"; Idempotency-Key header (Internet-Draft)
W3C: Trace Context
Apache Kafka: KIP-82 Add Record Headers, Design, Topic configs; Spring for Apache Kafka: Sending messages, ReplyingKafkaTemplate
Stripe: Idempotent requests
gRPC: Introduction
Laravel 13: Queues, HTTP Client, Broadcasting, Reverb, Events, Notifications, Redis
Clients: amqp091-go, franz-go kgo, go-redis, php-amqplib, laravel-queue-rabbitmq, laravel-kafka
NATS: Request-Reply semantics; Laravel source: Dispatchable.
RabbitMQ: Publisher confirms; Redis: XREADGROUP.