Skip to content

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 و partitionKafka
پاسخ با channel یا streamRedis
تصمیم بر پایهٔ زمان و وابستگیانتخاب
کدهای کامل مشترک دو زبان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 وب
سرویسی فرمان می‌دهد و منتظر نیستپیام فرمان، در صورت نیاز رویداد پاسخجداسازی زمانی
تعداد بسیار زیاد کلاینت کوتاه‌عمر در RabbitMQDirect 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-1AMQP 1.0KafkaRedis Streams
نشانی بازگشت (Return Address)reply_toreply-toreply-topic و reply-partitionفیلد reply_to
همبستگی (Correlation)correlation_idcorrelation-idheader قراردادیفیلد قراردادی
هویت پیام (Message Identity)message_idmessage-idheader قراردادیentry id یا فیلد
انقضای درخواست (Expiry)expiration، رشتهٔ میلی‌ثانیهttldeadline برنامهdeadline برنامه
بافت ردیابی (Trace Context)header traceparentapplication propertyheaderفیلد
نوع محتوا (Content Type)content_typecontent-typeheader یا schema idفیلد

در قرارداد AMQP 1.0 مستند RabbitMQ، درخواست‌کننده message-id یکتا می‌سازد و پاسخ‌دهنده آن را در correlation-id جواب می‌گذارد. آموزش AMQP 0-9-1 مستقیماً correlation_id را کپی می‌کند. مهم، توافق دو سمت است؛ نباید شناسه‌ای را که broker بعد از ارسال تولید می‌کند پیشاپیش در جدول انتظار فرض کنید.

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

Requestor(client / web node)1. new id = c-422. pending[c-42] = waiterpending tablec-41 → waiter Ac-42 → waiter Bc-43 → waiter CReplier(worker)reads reply_todoes the workcopies id into replycorrelation_id = c-42request queueknown, long-lived namereply queue (reply_to)one per client, not per callrequestconsumereplymatchrequest carries: correlation_id=c-42, reply_to=client-7.replies, expiration=5000unknown id → drop (orphan)known id → complete waiter

نمودار، چند درخواست هم‌زمان و یک مصرف‌کنندهٔ پاسخ را نشان می‌دهد. جدول منتظرها (Pending Table) پاسخ را به caller درست وصل می‌کند؛ ترتیب رسیدن جواب‌ها اهمیتی ندارد.

text
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
text
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 -> delete
text
1 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 از چند تأمین‌کننده قیمت می‌گیرد و در پایان مهلت بهترین را انتخاب می‌کند.

محصولشکل پیاده‌سازی
RabbitMQpropertyهای reply_to و correlation_id، صف پاسخ یا Direct Reply-To
Kafkaheaderها و topic/partition پاسخ؛ قرارداد برنامه
Redis Streamsstream درخواست و stream خصوصی پاسخ یا Pub/Sub
NATShelper درخواست با inbox یکتا و timeout؛ multiplex زیر سلسله‌مراتب subject
Pulsartopic پاسخ و 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ها؛ نه تطبیق یک پاسخ
text
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 قرار می‌دهد.

text
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
Requesterone connection, one channel1. basic.consumeamq.rabbitmq.reply-to(no-ack, no declare)2. publish reply_to =amq.rabbitmq.reply-toResponder3. reads rewrittenreply_to4. publish to defaultexchange "", routing key =that nameRabbitMQ brokerrequest queuerewrites reply_to →no queue existschannel process → channel processat-most-once, dropped if gonereply_to = amq.rabbitmq.reply-to.<opaque-suffix>

در نمودار، ذخیره‌سازی صف فقط روی مسیر درخواست است. حذف صف پاسخ، هزینه را کم می‌کند و هم‌زمان ضمانت بازیابی آن مسیر را حذف می‌کند.

محدودیتپیامد
مصرف 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 پایدار، همین پاسخ باید با وضعیت ثبت‌شده تطبیق داده شود.

لایهتنظیمچه چیزی محدود می‌شود؟
callercontext.WithTimeout یا deadline حلقهٔ PHPانتظار پاسخ
پیام درخواستexpiration یا x-message-ttlماندن در صف، پیش از تحویل
replierheader مهلت مطلق + سقف محلی اجراشروع یا ادامهٔ کار بی‌فایده؛ با کنترل 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 داشته باشد.

text
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 را ثابت نمی‌کند.

text
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 پس از اولین تکمیل
درخواست redeliveredunique constraint و inbox در تراکنش اثر
retry caller پس از timeoutکلید منطقی ثابت؛ correlation id تازه برای هر attempt
webhook دوبارهdedup روی event id یا Idempotency-Key
sql
-- 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 است.

request 1request 2GET /healthwaits for a slotweb workers (8)each: publish, thenBLOCK for the reply8 of 8 busynew requests queue uprequest queuegrows1 worker20 jobs/sweb workers, 202 variantpublish, return 202slot free in msrequest queueabsorbs the burst1 workercatches up laterclient polls or is pushedthe resultSync over async: capacity of the back-end becomes capacity of the front door

نمودار نشان می‌دهد صف بلند backend می‌تواند با تمام‌شدن workerهای frontend هم‌زمان شود. ظرفیت صف جای ظرفیت درخواست‌کننده را نمی‌گیرد.

منبع اشغال‌شدهمحدودیت نمونهنشانه
PHP-FPM workerpm.max_children502/504؛ حتی health معطل
thread در servletthread poolصف درخواست ورودی
goroutine در Goحافظه، socket و pending entryرشد حافظه و fd
promise در Node.jsحافظه و کار callbackهاافزایش latency؛ event loop با CPU هم مختل می‌شود
اتصال DB در تراکنش بازاندازهٔ pool و max_connectionsکمبود اتصال
reverse proxytimeout پیکربندی‌شده504 و retry caller
text
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 در handlerpoll سمت client یا pushانتظار خارج از worker درخواست
broker RPC برای خواندن فوریREST/gRPC با deadlineمسیر کم‌هزینه‌تر
broker RPC برای فرمان پایدارcommand + reply eventworkflow منتظر می‌ماند، نه 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 / running200 با state؛ فاصلهٔ poll اختیاریهنوز تمام نشده
done200 با نتیجه یا 303 به منبع نتیجهموفق
failed200 با state=failed و errorعملیات شکست خورده؛ خواندن وضعیت موفق بوده
expired410 Goneنتیجه طبق retention حذف شده
شناسهٔ ناشناخته404وجود ندارد
درخواست لغوDELETE با 202 یا 204 طبق قراردادلغو ممکن است ناهمگام باشد
text
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 + result
sql
CREATE 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 است.

راهجهتکاربردهزینه یا محدودیت
pollingclient به serverساده و سازگار با proxyبار تابع تعداد caller و فاصلهٔ poll
long pollingدرخواست باززیرساخت قدیمیاتصال باز و timeout proxy
SSEserver به browserپیشرفت و نتیجهٔ یک صفحهاتصال بلند، reconnect، غیرفعال‌کردن buffering
WebSocketدوطرفهتعامل و رویدادهای متعددپروتکل و backplane چندگرهی
webhookserver به serverB2Bامضا، retry، dedup و مقصد قابل‌دسترسی
reply event/queueservice به serviceworkflow داخلیcaller باید عضو messaging باشد
push موبایل یا emailserver به انسانکاربر صفحه را بستهجایگزین کانال دادهٔ معتبر نیست

Laravel با Reverb، Pusher یا Ably broadcast می‌کند؛ Mercure نیز مسیر SSE مستقلی دارد. در Go، net/http و Flusher برای شکل ساده کافی‌اند. کانال private باید مالک quote را authorize کند؛ دانستن UUID مجوز دسترسی نیست.

text
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-idspan جاریinstrumentationبا span فرزند عوض می‌شوددرخت اجرای توزیع‌شده
causation_idپیام علتpublisherبا زنجیرهٔ علتبازسازی زنجیرهٔ رویداد
business idaggregateدامنهثابتجست‌وجوی سفارش و مانند آن
text
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 شناخته‌شده
ترتیبفقط داخل partitioncorrelation؛ ترتیب
retentionقطع client پاسخ را حذف نمی‌کندretention کوتاه متناسب با recovery
latencybatching و fetch waitتنظیم با هزینهٔ throughput؛ اندازه‌گیری واقعی
partition برای هر callerهزینهٔ partition و هماهنگی مالکیتتعداد requester محدود و assignment معتبر
تکرارreplay و retry برنامهکلید منطقی ثابت؛ correlation هر attempt جدا
timeoutویژگی callercontext و 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 برای هر requesterXADD پاسخ، XREAD با cursorretention و replayاتصال مسدودشونده، EXPIRE و trim
stream مشترک با یک groupXREADGROUPتقسیم تحویلهمهٔ 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 یا meshcompeting consumerscompeting consumers
backpressure429/503 یا صف proxyصف رشد می‌کند، caller timeoutباید admission control داشته باشد
debugginglog، trace، curlbroker tooling و correlationهمان ابزارهای پیام
تراکنشتماس HTTP هم با DB اتمی نیستDB+publish اتمی نیست؛ outboxهمان شکاف
ترتیباجرای درخواست‌های هم‌زمان تضمین ترتیب نداردقواعد صف/partition و completion متفاوتقواعد صف/partition
امنیت و discoveryDNS، gateway، mTLSACL، vhost، مقصد پاسخهمان
خرابی شاخصcascade timeoutorphan، duplicate، starvationpoison message و backlog

رفتار واقعی محصولات ​

قابلیتRabbitMQKafkaRedisLaravel queue
نشانی پاسخreply_toheader قراردادیفیلد/نام channelذاتی ندارد
همبستگیcorrelation_idheaderفیلدpackage ممکن است id job را property کند؛ RPC نمی‌سازد
مقصد شخصیصف یا Direct Reply-Totopic/partitionstream/channelردیف، cache، broadcast
پاسخ بدون ذخیرهDirect Reply-ToخیرPub/Subوابسته به روش اعلان
TTL درخواستexpiration و queue TTLretention در سطح topic، نه پیامdeadline برنامه/trimretryUntil و timeout شغل، نه TTL عمومی broker
buffer هنگام قطعصف معمولی بله؛ مستقیم خیرretentionstream بله؛ Pub/Sub خیروضعیت برنامه
کشف نبود requestermandatory صف عادی؛ passive probe لحظه‌ایقرارداد برنامهEXISTS حضور زنده را ثابت نمی‌کندبرنامه
پاسخ‌دهنده‌های رقیبconsumerهای صفconsumer groupstream groupqueue workers
latencyتابع queue و شبکهتابع batch/fetch/groupتابع Redis و شبکهتابع driver و worker
احتمال duplicateredeliveryreplay/rebalancepending recoveryretry job
helper RPCtutorial/clientهای AMQPSpring ReplyingKafkaTemplateباید ساخته شودbuilt-in ندارد

راه‌حل‌ها: محدودکردن، جایگزینی و اعلان ​

مسئلهراه‌حلمکانیسممزیتهزینه یا مرز
انتظار همیشگیdeadlinecontext یا حلقهٔ محدودپایان قطعی انتظارsocket I/O سقف جدا دارد
کار برای caller رفتهTTL + execution deadlineexpiration و headerحذف stale workاثر commit‌شده لغو نمی‌شود
orphanpending tableحذف در timeoutپاسخ دیررس متوقف نمی‌کندپهنای باند مصرف شده
duplicate replycomplete onceحذف اولین entryجواب دوم بی‌اثراثر worker مستقل است
duplicate effectidempotent replierinbox و تراکنشretry امنstorage و retention
صف‌های بسیار زیادصف برای instance یا Direct Reply-Toreuse destinationmetadata کمترپاسخ مستقیم lossy
بسته‌شدن consumerfail pending و closed flagخطای مشترکتوقف زودتر انتظارتضمین outcome نیست
worker وب تمام202 + وضعیتبازگشت سریعظرفیت frontend حفظpoll/push و reconciliation
نتیجهٔ زندهSSE/Reverb/webhookاعلان پس از commitتجربهٔ بهترpush منبع حقیقت نیست
جواب فوریREST/gRPCtimeout و budget retryسادهوابستگی زمانی
فرمان نباید گم شودoutbox + reply eventوضعیت پایدارdurabilityeventual completion
صف جواب داغمقصد جدا برای requesterownership روشنrouting درستصف و connection بیشتر
trace شکستهcontext propagationinject/extract SDKtrace یکپارچهinstrumentation لازم
retry stormbackoff/jitter/budgetمحدودیت تلاشکاهش amplificationتنظیم سیاست

انتخاب ​

Does the caller need the answer to continue?(a user is waiting, or a decision depends on it)Fast (under ~1 s) and reads data?yes: it is a queryWork is slow or can wait?no: a command or an eventREST or gRPCdeadline, retries,idempotency key202 + status resourcepoll, SSE, WebSocket,webhook for the resultCommand + reply eventno caller waiting; broker RPConly with a deadlineyesno / laterdefault: avoid broker RPC; RabbitMQ: "When in doubt avoid RPC"

نمودار از نیاز caller شروع می‌کند: اگر می‌تواند بعداً نتیجه را بگیرد، وضعیت و اعلان مناسب‌تر است. الزام به broker باید دلیل مستقلی داشته باشد.

موقعیتپیشنهادتکنیک همراهدلیل
قیمت یا permission فوریREST/gRPCcache، deadline، breakerخواندن سریع
upload و گزارش طولانی202 + statusreconciliationworker دقیقه‌ها اشغال نشود
فرمان شروع فرایندcommandoutbox و dedupجدایی زمانی
saga منتظر تأیید مرحلهreply eventtimeout transitionsaga منتظر است، نه thread
کلاینت edge بسیار زیادDirect Reply-ToTTL و retry امنصف کمتر
نتیجه بعد از reconnectصف نام‌دار پایدارexpiry و state پایدارbuffer جواب
Kafka تنها بسترreply partition/topicretention و assignmentهزینهٔ قرارداد پذیرفته می‌شود
Redis تنها broker و افت مجازPub/Sub replysubscribe-firstساده ولی lossy
مرورگر نتیجهٔ زنده می‌خواهدSSE/Reverbsubscribe سپس GET وضعیتپوشش race و reconnect
شریک تجاریwebhookامضا و idempotencyقرارداد B2B
چند پاسخ به یک سؤالscatter-gathercounter و deadlineaggregation
یک processفراخوان تابعهیچ broker لازم نیستهزینهٔ کمتر
بودجهٔ زمانیمناسبنامناسب
چند میلی‌ثانیه یا کمترعملیات localتضمین بدون اندازه‌گیری روی شبکه
ده‌ها میلی‌ثانیهRPC مستقیم در منطقهbroker RPC سرد بدون آزمون
صدها میلی‌ثانیه تا ثانیهREST/gRPC یا RabbitMQ گرمKafka تنظیم‌نشده
ثانیه تا دقیقه202 و پاسخ ناهمگامنگه‌داشتن worker
ساعتworkflow و اعلانهر انتظار مسدودکنندهٔ طولانی
سؤال مالکیت و وابستگیاگر بلهاگر خیر
پاسخ فوری با قرارداد مشترک لازم است؟RPC مستقیم قابل‌دفاعcommand/event را بررسی کنید
callee باید بتواند خاموش باشد؟messaging بدون انتظار فوریRPC با deadline
یک جواب یک تصمیم را کامل می‌کند؟request-replyevent برای چند مصرف‌کننده
routing broker از قبل لازم است؟broker RPC شاید مناسبload-balanced REST ساده‌تر

Go ​

قبل ​

handler زیر درخواست را منتشر می‌کند و بدون مهلت منتظر پاسخ می‌ماند. شناسهٔ دست‌ساز و channel بدون buffer باعث می‌شوند قطع caller یا پاسخ دیررس، منابع را نگه دارد.

go
// 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 جدا از انتظار پاسخ است.

go
// 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 را گزارش می‌کند.

go
// 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 فراتر از این تابع کوچک است.

go
// 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 بی‌کلید حل نکنید.

go
// 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 داخلی نمونه نیازمند احراز هویت در محصول واقعی است.

go
// 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 نیز مسئولیت استقرار واقعی است.

go
// 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 هم‌توان، مسیر ساده‌تری دارد.

go
// 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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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 پس از commitjob رکورد هنوز commit‌نشده را نبیند
after_commit اتصالهمان سیاست برای اتصالتنظیم عمومی
dispatchSync()اجرای فعلی در processجای RPC نیست
#[Tries] و #[Timeout]سقف تلاش و زمان jobپایان شکست قابل‌ردیابی
failed()مسیر شکست نهاییثبت failure بدون بازگرداندن done
ShouldBroadcast و PrivateChanneljob broadcast و authorizationاعلان مرورگر
ShouldDispatchAfterCommitرویداد پس از commitترتیب مشاهده
notification database/broadcastذخیره و pushکاربر offline
ReverbWebSocket first-partypush خودمیزبان
Http timeout/connectTimeout/retryزمان هر attempt و retryREST محدود
Http withHeadersidempotency و 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 اجرای کار سه کنترل جدا هستند.

go
// 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 را مدیریت کند.

go
// 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 آن دیده شود.

go
// 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)
}
go
// 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-Tometric نوع rabbit_volatile_queue؛ پاسخ بدون buffer و امکان افت
آموزش ششم RabbitMQصف callback برای client و فهرست timeout/errorهای حل‌نشده
Spring ReplyingKafkaTemplateheaderهای پاسخ، timeout و assignment آمادگی reader
HTTP API طولانیsemantics پذیرش RFC 9110، قرارداد status monitor
Stripe idempotencyقرارداد retry و retention نتیجه باید صریح باشد
Laravel Broadcasting/Reverbworker 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 فقط رسید تکمیل را می‌رساند.

text
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 است.

text
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 lagworker done نوشته، poll هنوز queued می‌بیندخواندن primary یا نسخهٔ monotonic
مرز clusterrequest quorum است، reply مستقیم volatileتضمین دو leg را جدا تحلیل کنید
چند منطقهrequest و reply WAN را طی می‌کنندحداقل یک RTT اضافه و hopهای دیگر؛ منطقه‌ای نگه دارید
push چندگرهیاتصال browser روی node دیگری استbackplane و status پایدار
clock skewdeadline مطلق زود/دیر تفسیر می‌شودساعت پایش‌شده، حاشیه و سقف محلی
dedup چندمنطقه‌ایدو region همان اثر را می‌پذیرندکلید و اثر در consistency domain مشترک

TTL نسبی نگهداری صف را محدود می‌کند؛ deadline مطلق اجرای remote را با فرض clock skew محدود می‌کند. هیچ‌یک اثر commit‌شده را پس نمی‌گیرد. مباحث replication و consensus این مرزها را توضیح می‌دهند.

مسیر رشد (Scaling Path) ​

مقیاسطراحیتغییر اصلی
ده‌ها call/sREST با مهلت یا job+statusیک مسیر پاسخ ساده
صدها call/sreplierهای رقیب، bulkhead، TTLمحدودکردن pending و backlog
هزاران call/s و client زیادDirect Reply-To یا مقصد هر instance، backplanechurn، queue count، metric افت
چند regionpool منطقه‌ای و replication وضعیتپرهیز از call طولانی میان منطقه‌ها

آزمایشگاه ​

تمام آزمایش‌های broker، latency و starvation این بخش مورد انتظار، اجرا نشده (expected, not run) هستند. Docker اجرا نشده و هیچ عدد benchmark به‌عنوان مشاهدهٔ این نوبت ادعا نمی‌شود. ابزارهای lint، vet و unit test صرفاً QA کدند و نتیجهٔ رفتار broker را ثابت نمی‌کنند.

sh
# 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
1baseline HTTPبار ثابت روی Pricingp50/p99 واقعی محیط ثبت شود
2RPC با صف اختصاصیclient tutorial، concurrency ثابتqueue برای هر client، هزینهٔ مسیر broker
3Direct Reply-Toهمان بار و consumer گرمصف جواب فهرست نمی‌شود؛ metric volatile رشد می‌کند
4قطع requester وسط کاربستن فرایند clientصف عادی ممکن است basic.return؛ مستقیم ممکن است drop بدون return
5کار 3s، caller 2sتأخیر عمدی workertimeout و orphan؛ TTL فقط درخواست هنوز صف‌شده را حذف می‌کند
6crash قبل از request ackبعد از reply confirm متوقف کنیدredelivery و duplicate؛ dedup اثر لازم
7202 در برابر blockingبار بالاتر از ظرفیت backend202 slot را زودتر آزاد، ولی backlog را حذف نمی‌کند
text
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ها را می‌بینندپیام‌ها بین اعضا تقسیم می‌شوند

چکیدهٔ عملی ​

موضوعبه خاطر بسپارید
الگودو پیام مستقل و دو مسیر
correlationrequester می‌سازد، replier کپی می‌کند
idempotencyکلید عملیات بین retryها ثابت؛ correlation هر attempt جدا
reply queueمعمولاً یک مقصد برای هر requester، نه هر call
Direct Reply-Tosame channel، no-ack، یک consumer، lossy
deadlineانتظار، queue TTL و execution deadline جدا
socket writecontext ممکن است نوشتن آغازشده را قطع نکند
orphanpending را در timeout حذف کنید
duplicatecaller یک‌بار complete؛ worker dedup effect
sync over asyncslot caller با latency remote اشغال می‌شود
202پذیرش + status + admission control
pushsubscribe سپس fetch؛ reconnect سپس reconcile
traceSDK معتبر؛ all-zero id را ادامه ندهید
Kafkaownership partition و readiness/offset پیش از ارسال
Redissubscribe-first؛ cursor آخرین id؛ EXPIRE و pending recovery
LaravelafterCommit ترتیب است؛ 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

منابع ​

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