Routing Topologies: Fan-out, Topic & Content-Based
"The purpose of exchanges is to route all messages that flow through them to one or more queues, streams, or other exchanges." — RabbitMQ documentation, Exchanges guide
خلاصه: توپولوژی مسیریابی (Routing topology) تعیین میکند هر پیام به کدام اشتراک برسد؛ تعداد workerها مسئلهٔ دیگری است. تمرکز: مبادلهگر (Exchange) و اتصال (Binding) در RabbitMQ، طراحی موضوع (Topic) در Kafka، نام کلید جریان (Stream key) در Redis Streams و مسیریابی Laravel 13. هدف یادگیری: برای Sales، Fulfilment و Billing مسیرهایی تعریف کنید که افزودن مصرفکننده، ناشر را تغییر ندهد و خطای مسیر به گمشدن خاموش پیام تبدیل نشود.
این صفحه دربارهٔ مقصد پیام است. جزئیات ترتیب، مقیاس مصرفکننده، DLQ و الگوهای پیشرفته در صفحات جدا هستند. تفاوت ساختار داخلی brokerها را در RabbitMQ، Kafka و Redis Streams بخوانید.
نقشهٔ صفحه
| نیاز | بخش |
|---|---|
| مقایسهٔ سریع | یک دقیقه |
| دلیل وجود مسیریابی | چرا |
| سابقهٔ AMQP و EIP | تاریخچه |
| کلید و binding | اتصال |
| Direct و Fanout | Direct، Fanout |
| wildcardها | Topic |
| چند ویژگی مستقل | Headers |
| مبادلهگر پیشفرض | Default |
| چند لایهٔ مسیریابی | E2E |
| پیام بیمقصد و پیام مرده | AE، DLX |
| توزیع بر اساس hash | Hash |
| اندازهٔ موضوع Kafka | طراحی topic |
| نام و مجوز موضوع | نامگذاری |
| مستأجر و stream | Redis |
| محل تصمیمگیری | Content-Based Router |
| انتشار و تجمیع مسیرها | Fan-out/Fan-in |
| خطاها و تنظیمها | سازوکار |
| نمونهٔ Go و Laravel | Go، Laravel |
| اجرای هر broker | تفاوتها |
| مسائل عملی | راهحلها |
| انتخاب و ضدالگو | انتخاب، ضدالگو |
| از برنامهٔ واحد تا چند منطقه | معماری |
| تمرین | آزمایشگاه |
همهچیز در یک دقیقه
| پرسش | RabbitMQ | Kafka | Redis Streams |
|---|---|---|---|
| مقصد انتشار | exchange و routing key | topic و partition key | stream key |
| مالک انتخاب اشتراک | broker با binding | مصرفکننده با subscription | گروه روی هر stream |
| انتخاب بر اساس metadata | topic/headers exchange | کد مصرفکننده | کد مصرفکننده |
| انتشار چندگیرندهای (fan-out) | صف مستقل هر سرویس | consumer group مستقل | consumer group مستقل |
| چند ورودی (fan-in) | چند binding روی یک صف | چند topic یا regex | چند stream در XREADGROUP |
| پیام بیمقصد | drop، return یا AE | topic ناموجود خطا میدهد، مگر auto-create | XADD معمولاً کلید را میسازد |
| مرز ترتیب | یک صف با قیود تولید/مصرف | partition یک topic | یک stream |
| محدودیت نام | routing key تا 255 بایت | topic تا 249 نویسه | کلید binary-safe |
NATS روی subject، Pulsar روی topic/subscription و SNS روی انتشار به SQS کار میکنند؛ نقشهٔ آنها در Other Brokers آمده است.
| نوع exchange | قاعده | مثال کوچک | کاربرد |
|---|---|---|---|
| direct exchange | برابری کامل کلید | invoice.pdf به صفی با همین binding key | نوع job یا severity |
| fanout | همهٔ bindingها، بدون توجه به کلید | تغییر قیمت به صف هر cache node | audit و broadcast |
| topic exchange | واژههای نقطهجدا با * و # | sales.order.*.v1 رویداد sales.order.placed.v1 را میگیرد | رویداد دامنه و مشترک انتخابگر |
| headers exchange | مقدار header و x-match | channel=sms, tier=vip | ترکیب ویژگیهای مستقل |
| default exchange | کلید برابر نام صف | publish روی "" با key برابر emails | ارسال ساده به صف |
| x-consistent-hash، افزونه | حلقهٔ hash با وزن، روی key یا header | تقسیم order id میان 4 صف | affinity بین کلید و صف |
| x-modulus-hash، داخلی | hash modulo تعداد مقصد | shardهای ساختهشده توسط sharding plugin | shard کردن صف classic |
| local random، از RabbitMQ 4.0 | صف محلی تصادفی | انتخاب RPC server نزدیک | کاهش تأخیر Request-Reply |
| قاعدهٔ طراحی | دلیل |
|---|---|
| exchange یا خانوادهٔ topic متعلق به دامنهٔ ناشر | مالکیت و ACL هممرز با دامنه |
| صف مستقل برای هر مصرفکننده و هدف | backlog، DLQ و مقیاس مستقل؛ استقلال چرخهٔ استقرار |
| نام پیام توصیف اتفاق باشد | مصرفکنندهٔ جدید producer را تغییر ندهد |
| رویدادهای نیازمند ترتیب، topic و key مشترک داشته باشند | ترتیب بین topicها وجود ندارد |
| metadata را از payload جدا نگه دارید | router به مدل داخلی وابسته نشود |
| topology در کد یا definitions باشد | بازسازی و review ممکن شود |
| namespace جای authorization نیست | prefix بهتنهایی مرز امنیتی ایجاد نمیکند |
چرا توپولوژی لازم است؟
وقتی یک فرستنده فقط یک مقصد دارد، نوشتن نام صف کافی به نظر میرسد. با اضافهشدن حسابداری و انبار، سؤال عوض میشود: کدام تیم باید بداند چه کسی نسخهای از سفارش میخواهد؟ اگر پاسخ «Sales» باشد، هر مشترک تازه یک تغییر در producer تحمیل میکند. توپولوژی (Topology) این وابستگی را به قرارداد انتشار و اشتراک منتقل میکند.
| تصمیم در producer | تصمیم در topology |
|---|---|
| فهرست تمام مقصدها داخل برنامه | producer فقط کانال خودش را میشناسد |
| افزودن subscriber نیازمند deploy است | subscriber صف یا گروه خودش را میسازد |
| دنبالکردن جریان محلی ساده است | نقشهٔ سراسری روشنتر میشود |
| چند ارسال مستقل و شکست جزئی | قواعد routing قابل review |
| شروع ارزانتر | هزینهٔ نامگذاری و مجوزدهی |
| وابستگی تیمها به تغییر producer | استقلال تیمها با قرارداد نامگذاری مشترک |
تصویر روزمره، دبیرخانهٔ شرکت است: روی پاکت آدرس مینویسید و دبیرخانه با جدول قواعد آن را در کازیهٔ واحدها میگذارد. دو کارمند پشت یک کازیه، دو نسخه از هر نامه نمیگیرند؛ برای نسخهٔ مستقل باید دو کازیه داشته باشید. Kafka بیشتر به بایگانی مشترک شبیه است: هر واحد نشانگر خواندن خودش را دارد.
سه بدفهمی اولیه
- Topic در RabbitMQ یک نوع router است؛ در Kafka محل نگهداری log است.
- چند worker روی یک صف، رقابت ایجاد میکند؛ fan-out ایجاد نمیکند.
- کوچکترین تعداد کانال الزاماً بهترین طراحی نیست؛ مالکیت، ترتیب و حجم تعیینکنندهاند.
از کجا آمده؟
AMQP 0-9-1 محل انتشار (Exchange) را از محل مصرف (Queue) جدا کرد و binding را واسطه گذاشت. RabbitMQ قابلیتهایی مانند اتصال exchange به exchange و مسیر جایگزین را به این مدل اضافه کرده است.
کتاب Enterprise Integration Patterns نوشتهٔ Hohpe و Woolf در سال ۲۰۰۳ برای تصمیمها اسم گذاشت: کانال انتشارـاشتراک (Publish-Subscribe Channel)، مسیریاب محتوامحور (Content-Based Router) و پالایهٔ پیام (Message Filter). اینها توصیف مسئلهاند؛ نگاشتشان به محصول باید جدا بررسی شود.
در Kafka خودِ مرزبندی topic بخشی از طراحی دامنه است. مقالهٔ Martin Kleppmann در سال ۲۰۱۸ توضیح میدهد چرا نیاز به ترتیب باید قبل از سلیقهٔ «یک topic برای هر event type» بررسی شود. Redis Streams نیز گروه مصرفکننده دارد، اما یک stream را خودکار میان چند node پارتیشن نمیکند.
فهرست مفهومها
کلید مسیریابی و اتصال حیاتی
به زبان ساده: ناشر آدرس را مینویسد؛ مصرفکننده اعلام میکند کدام آدرسها را میخواهد.
بدفهمی رایج: نام صف همیشه routing key است. این رابطه فقط برای default exchange برقرار است.
تعریف: اتصال (Binding) رابطهٔ source exchange با destination، نوع مقصد، binding key و آرگومانهای اختیاری است. دوام binding به دوام دو سر آن وابسته است.
1 Fulfilment declares fulfilment.sales-orders
2 bind sales.events -> fulfilment.sales-orders: sales.order.*.v1
3 Billing binds billing.sales-orders: sales.order.placed.v1
4 Sales publishes sales.order.placed.v1
5 broker -> one copy per matching queue
6 sales.order.cancelled.v1 -> Fulfilment onlyمثلاً Analytics میتواند صف analytics.sales را با sales.# اضافه کند، بیآنکه Sales تغییر کند. روی Kafka این استقلال با group تازه حاصل میشود و در Redis با XGROUP CREATE روی stream موجود.
مبادلهگر مستقیم حیاتی
به زبان ساده: direct exchange آدرس را دقیق مقایسه میکند.
بدفهمی رایج: Direct یعنی حتماً یک گیرنده. اگر سه صف با کلید یکسان bind شوند، هر سه نسخه میگیرند.
تعریف: binding key و routing key باید دقیقاً برابر باشند؛ amq.direct نمونهٔ ازپیشساخته است.
برای jobهای pdf.render و email.send یا سطح log مناسب است. وقتی گیرنده خانوادهای از آدرسها میخواهد، topic exchange بیان روشنتری دارد.
انتشار همگانی حیاتی
به زبان ساده: fanout از هر پیام برای همهٔ مقصدهای متصل نسخه میسازد.
بدفهمی رایج: برای broadcast همیشه fanout لازم است. binding برابر # روی topic هم تمام کلیدها را میگیرد.
تعریف: routing key در fanout نادیده گرفته میشود؛ وجود binding تعیینکننده است.
برای audit عمومی مناسب است. برای cache هر instance میتواند صف exclusive و auto-delete خودش را داشته باشد؛ آفلاینشدن آن instance در این طراحی یعنی نداشتن backlog پایدار.
Topic و دستور زبان کلید حیاتی
به زبان ساده: topic exchange آدرس را به واژههای جداشده با نقطه تقسیم میکند.
بدفهمی رایج: ord* همهٔ واژههای شروعشده با ord را میگیرد. wildcardهای این مدل فقط واژهٔ کاملاند.
تعریف: * یک واژه و # صفر یا چند واژه را میگیرد. سقف routing key برابر 255 بایت است؛ برای متن غیر ASCII، بایت با نویسه برابر نیست.
1 Q1 binding *.orange.*; Q2 bindings *.*.rabbit and lazy.#
2 quick.orange.rabbit -> Q1,Q2
3 lazy.pink.rabbit -> Q2 once
4 quick.orange.new.rabbit -> neither
5 lazy.orange.new.rabbit -> Q2
6 lazy -> Q2 because # matches zero wordsقرارداد این فصل <domain>.<entity>.<event>.v<N> است؛ این قانون broker نیست. مثلاً sales.order.item-added.v1. تعداد واژهها را ثابت نگه دارید تا sales.order.*.v1 قابل پیشبینی باشد. برای تمام نامهای چهارواژهای نسخهٔ یک، #.v1 مناسب است؛ *.v1 فقط دو واژه را میگیرد.
| Pattern | Match | No match |
|---|---|---|
sales.order.*.v1 | sales.order.placed.v1 | sales.order.item.added.v1 |
sales.# | sales.order.placed.v1 | billing.order.placed.v1 |
audit.events.# | audit.events | audit.users |
*.v1 | order.v1 | sales.order.placed.v1 |
Header و ترکیب ویژگیها مهم
به زبان ساده: headers exchange برچسبهای مستقل را مقایسه میکند، مثلاً channel و tier.
بدفهمی رایج: کلید routing هم در این نوع اثر دارد. اینجا تصمیم از headerها میآید.
تعریف: x-match=all همهٔ شرطها و any دستکم یکی را میخواهد؛ any-with-x و all-with-x headerهای شروعشده با x- را نیز وارد مقایسه میکنند. نوع مقدار نیز مهم است؛ عدد و رشته را یکسان فرض نکنید.
1 binding sms: x-match=all, channel=sms, tier=vip
2 message channel=sms,tier=vip -> sms
3 message channel=sms,tier=basic -> no match
4 message channel=email,tier=vip -> no matchبرای notification با channel × tier × locale، پردازش سند با format=pdf و size=large، یا صف مخصوص region=eu، چند ویژگی مستقل از یک رشتهٔ بلند خواناتر است. این تطبیق broker-side مخصوص RabbitMQ است؛ Kafka و Redis همان شرط را در filter مصرفکننده یا router اجرا میکنند.
شرط all برای «SMS و VIP» مناسب است. any متمم منطقی این شرط نیست؛ برای «هر چیز دیگری» AE یا router صریح بسازید.
مبادلهگر پیشفرض حیاتی
به زبان ساده: انتشار روی exchange با نام خالی، کلید را نام صف فرض میکند.
بدفهمی رایج: amq.default را باید هنگام publish بنویسیم. نام هدف انتشار در AMQP 0-9-1 همان "" است.
تعریف: صف هنگام ایجاد خودکار با نام خودش به default exchange متصل میشود. binding دلخواه و alternate exchange برای آن طراحی نشدهاند.
در package RabbitMQ لاراول بدون گزینهٔ exchange و در پاسخ RPC به صف اختصاصی client کاربرد دارد؛ amq.default نامِ مورد استفاده در permission است. برای task queue ساده مفید است؛ اگر استقلال مصرفکننده لازم دارید، یک direct یا topic exchange جدا تعریف کنید.
اتصال exchange به exchange مهم
به زبان ساده: یک جدول مسیر میتواند به جدول دیگری وصل شود.
بدفهمی رایج: دو مسیر به یک صف الزاماً دو نسخه میسازد. RabbitMQ در همان routing، مقصد صف را deduplicate میکند؛ این ربطی به dedup انتشار مجدد producer ندارد.
تعریف: exchange.bind یک رابطهٔ جهتدار است. نوع source و binding key همچنان اعمال میشوند. internal اجازهٔ publish مستقیم client را از مقصد میگیرد.
1 sales.events --#--> audit.all (internal fanout)
2 billing.events --#--> audit.all
3 audit.all -> audit.archive
4 sales.order.placed.v1 -> business queues + audit.archiveامضای Go برابر ExchangeBind(destination, key, source, noWait, args) و امضای php-amqplib برابر exchange_bind(destination, source, routing_key) است؛ جابهجایی source و destination خطای طراحی رایجی است. E2E انتشار مجدد نیست و نرخ ingress مقصد exchange لزوماً افزایش نمییابد؛ صفهای نهایی را مشاهده کنید.
E2E برای audit/analytics چند دامنه، exchange ورودی هر tenant و مهاجرت مشترک از exchange قدیمی به تازه مفید است. RabbitMQ چرخهٔ routing را تشخیص میدهد، ولی لایهها را کمعمق نگه دارید؛ binding فراموششده در هر لایه میتواند مسیر را قطع کند.
مسیر جایگزین مهم
به زبان ساده: alternate exchange یا AE برای پیام بدون مسیر، مقصد دیگری امتحان میکند.
بدفهمی رایج: publisher confirm ثابت میکند یک مصرفکنندهٔ کسبوکار پیام را گرفته است. پیام unroutable هم میتواند confirm شود.
تعریف: آرگومان یا policy با نام alternate-exchange مقصد جایگزین را مشخص میکند؛ آرگومان client مقدم است و میتوان زنجیرهٔ AE داشت. اگر AE پیام را route کند، شرط mandatory برآورده شده و return ندارید. اگر هیچ مقصدی نباشد، mandatory=true باعث 312 NO_ROUTE در basic.return میشود.
1 publish channel=push,tier=basic -> notifications.route
2 no headers binding matches
3 AE notifications.unmatched -> unmatched queue
4 confirm arrives; no basic.return because AE routed itCatch-all برابر # روی exchange اصلی هر پیام را به audit میرساند؛ پس AE دیگر تایپ اشتباه در مسیر کسبوکار را کشف نمیکند. برای هر subscription نرخ و backlog را بررسی کنید، نه فقط unroutable کل exchange.
مقصد مردهها تکمیلی
DLX نوع ویژهٔ exchange نیست. صف با policy به نام dead-letter-exchange و در صورت نیاز dead-letter-routing-key پیام ردشده یا منقضی را به exchange معمولی میفرستد. آرگومان سمت client پیشوند x- دارد. یک topic DLX میتواند با binding برابر # به dlq.all یا با کلید اصلی به DLQهای دامنه برسد. جزئیات x-death، poison message و parking در DLQ و زمانبندی retry در Retry است.
مسیریابی با hash تکمیلی
به زبان ساده: بهجای کپی به همه، یک مقصد بر اساس hash انتخاب میشود.
بدفهمی رایج: چهار صف با binding برابر # بار را تقسیم میکنند. آنها چهار کپی میگیرند.
x-consistent-hash از routing key، header انتخابشده با hash-header یا property پشتیبانیشده hash میسازد؛ binding key وزن عددی است. وزن برابر معمولاً نقطهٔ شروع مناسبتری است. x-modulus-hash کلید binding را برای وزن استفاده نمیکند. rabbitmq_sharding روی این سازوکار صفهای classic را shard میکند؛ آن را برای quorum queue بهکار نبرید.
تغییر مجموعهٔ مقصدها affinity را تغییر میدهد. نتیجهٔ این تغییر بر ترتیب در Ordering بررسی شده است.
اندازهٔ topic در Kafka حیاتی
به زبان ساده: تعیین کنید کدام اتفاقها باید کنار هم در log باشند.
بدفهمی رایج: یک topic برای هر event type همیشه تمیزتر است. ممکن است address-changed قبل از customer-created پردازش شود.
| طرح | مثال | ترتیب بین نوع رویدادها | هزینهٔ مصرف | مرز ACL | زمان مناسب |
|---|---|---|---|---|---|
| per event type | sales.order.placed.v1 و sales.order.cancelled.v1 | بین topicها ندارد | فقط نوع لازم خوانده میشود؛ topic بیشتر | هر event type | جریان مستقل و پرتعداد مثل کلیک و بازدید |
| per aggregate | sales.order.events.v1، key برابر order id | هر سفارش در partition خودش | ردکردن نوع نامربوط، معمولاً ارزان | نوع entity | سرویس رویدادمحور و event sourcing |
| bounded context | sales.events.v1، key برابر aggregate id | هر aggregate در یک partition | خواندن و ردکردن دادهٔ بیشتر | دامنه | دامنهٔ کوچک با حجم کم |
تعریف: واحد ترتیب Kafka، partition داخل یک topic است. topic مشترک بدون key مناسب هم ترتیب هر aggregate را تضمین نمیکند. «per aggregate» در این فصل یعنی نوع aggregate؛ برای هر سفارش topic تازه نسازید.
رویدادهای placed، paid و cancelled یک سفارش در یک topic میمانند. کلیکهای پرتعداد سبد میتوانند topic جدا داشته باشند تا backlog پردازش سفارش را سنگین نکنند. چند schema در یک topic ممکن است subject strategy مثل TopicRecordNameStrategy یا RecordNameStrategy بخواهد؛ مرجع Schema Evolution است.
key باید واحد ترتیب، مثلاً order id یا account id، را مشخص کند. تعداد partition را با موازیسازی موردنیاز انتخاب کنید؛ کاهش آن ممکن نیست و افزایش آن میتواند نگاشت keyها را عوض کند. Ordering پیامد migration را توضیح میدهد.
نام، state و topic sprawl مهم
به زبان ساده: اسم topic هم قرارداد است و هم ورودی مجوزدهی.
بدفهمی رایج: نام و تعداد partition را هر وقت خواستیم برمیگردانیم. rename مستقیم و کاهش partition پشتیبانی نمیشود.
| مورد | قاعدهٔ Kafka |
|---|---|
| طول | حداکثر 249 نویسه |
| الفبا | ASCII alphanumeric و .، _، - |
| نام ممنوع | نام خالی، . و .. |
| برخورد metrics | sales.order و sales_order ممکن است برخورد کنند |
| auto-create | auto.create.topics.enable=false برای آشکارشدن typo |
| enforce نام | CreateTopicPolicy و create.topic.policy.class.name |
| مجوز prefix | --resource-pattern-type prefixed در KIP-290 |
| state | cleanup.policy=compact |
| حذف state | مقدار null بهعنوان tombstone |
| عمر tombstone | delete.retention.ms؛ پیشفرض 24 ساعت |
نام سلسلهمراتبی میتواند <organization>.<team>.<dataset>.<event-name> یا <project>.<product>.<event-name> باشد؛ نام consumer و تعداد partition را وارد آن نکنید. قرارداد این فصل <domain>.<entity>.<event>.v<N> برای هر نوع و <domain>.<entity>.events.v<N> برای تاریخچهٔ نوع aggregate است.
مصرفکنندهای که بیشتر از delete.retention.ms عقب بماند ممکن است tombstone لازم برای حذف state قدیمی را از دست بدهد. topic آخرین وضعیت را مثلاً ...state.v1 با cleanup.policy=compact بسازید و تاریخچه را با cleanup.policy=delete نگه دارید؛ ارتباطش با Event Sourcing جدا بررسی شده است.
تراکم موضوعها (Topic sprawl) از ضرب tenant، event type و environment حاصل میشود. هر topic به metadata، partition و ACL نیاز دارد. جایی که مرز دسترسی اجازه میدهد، tenant را در key/header بگذارید. برای log تاریخچه و آخرین state دو topic جدا انتخاب کنید؛ compaction پاککردن فوری تمام نسخههای قبلی نیست.
نام stream و shard مهم
به زبان ساده: stream یک کلید است؛ اسم همان آدرس است.
بدفهمی رایج: consumer group دادهٔ یک stream را بین چند node تقسیم میکند. تقسیم کار با تقسیم storage یکی نیست.
تعریف: Redis Cluster کلیدها را در 16384 شیار (Hash slot) میگذارد. برچسب hash یا Hash tag مثل {acme} ورودی hash را محدود میکند؛ t:{acme}:sales.order.events و t:{acme}:billing.invoice.events همslot میشوند.
محاسبهٔ slot برابر CRC16(key) mod 16384 است؛ با hash tag فقط بخش داخل brace هش میشود. پیشفرض، یک stream برای هر نوع aggregate مثل sales.order.events و event type در field است. برای shard صریح از کلیدی مثل sales.order.events:{3} و hash پایدار aggregate id استفاده کنید. Laravel گزینهٔ database.redis.options.prefix را قبل از نام کلید میگذارد.
این کار برای فرمان چندکلیدی مفید است، اما یک tenant بزرگ را روی همان node متمرکز میکند. برای hot tenant باید shard صریح اضافه کنید. نام tenant را از شناسهٔ معتبر داخلی بگیرید؛ ورودی دارای brace میتواند قرارداد slot را خراب کند. prefix خودکار Laravel نیز باید بدون hash tag ناخواسته باشد.
مسیریابی محتوامحور حیاتی
به زبان ساده: مقصد از یک ویژگی پیام انتخاب میشود.
بدفهمی رایج: broker حتماً JSON بدنۀ پیام را parse میکند. RabbitMQ بهصورت معمول key/header را میبیند؛ Kafka و Redis این router داخلی را ندارند.
تعریف: Content-Based Router کانال خروجی را از دادهٔ پیام انتخاب میکند. Message Filter فقط یک خروجی دارد و پیام نامربوط را رد میکند؛ Recipient List چند مقصد محاسبه میکند. جزئیات آنها در Advanced Routing است.
| محل تصمیم | RabbitMQ | Kafka | Redis Streams | هزینه |
|---|---|---|---|---|
| producer | انتخاب exchange و routing key | انتخاب topic و partition key | انتخاب stream key | producer مسیرها را میشناسد |
| broker | topic pattern، headers exchange و AE | موجود نیست | موجود نیست | نگهداری topology |
| router مستقل | consume و republish | برنامهٔ Kafka Streams یا worker در Go که consume/produce میکند | XREADGROUP سپس XADD | hop، سرویس و مرز شکست اضافه |
| consumer | اغلب binding محدودتر کافی است | ردکردن رکورد با header نوع | ردکردن entry با field | خواندن دادهٔ اضافه |
1 router reads source stream
2 choose target from channel field
3 XADD target with original source identity
4 only after successful XADD: XACK source
5 crash between 3 and 4 -> duplicate output; receiver deduplicatesTransaction در Redis rollback خطای runtime ندارد؛ در MULTI، شکست XADD الزاماً جلوی XACK را نمیگیرد. نمونهٔ این فصل عمداً publish-before-ack دارد و تکرار احتمالی را آشکار نگه میدارد.
Fan-out و Fan-in حیاتی
به زبان ساده: fan-out یک ورودی را به چند اشتراک مستقل میرساند؛ fan-in چند ورودی را کنار هم مصرف میکند.
بدفهمی رایج: fan-in نتیجهها را خودکار aggregate میکند. جمعکردن ورودی با کاملبودن یک نتیجه یکی نیست.
| رفتار | RabbitMQ | Kafka | Redis Streams |
|---|---|---|---|
| fan-out | صف مستقل | گروه مستقل | گروه مستقل |
| رقابت داخل اشتراک | workerهای یک صف | اعضای گروه روی partitionها | اعضای گروه روی entryها |
| fan-in | چند exchange یا binding key به یک صف | چند topic یا regex با ConsumeRegex | XREADGROUP ... STREAMS a b c؛ در Cluster باید همslot باشند |
| ترتیب چند ورودی | interleave بر اساس ورود به صف | تضمین بین topicها ندارد | فقط هر stream |
| تجمیع نتیجهها | Aggregator | join/aggregate در Stream Processing | کد برنامه |
1 OrderPlaced -> Fulfilment, Billing, Audit subscriptions
2 three Fulfilment workers share its subscription
3 Billing publishes PaymentCaptured
4 Fulfilment reads both sources
5 domain code correlates by order idسازوکار و تنظیمها
در RabbitMQ ابتدا exchange پیدا میشود، سپس مقصدهای binding و E2E محاسبه میشوند؛ اگر مقصدی نبود AE امتحان میشود. basic.return برای پیام mandatory بیمقصد قبل از confirm همان پیام میآید. ثبت callback کافی نیست؛ publisher باید تا نتیجه یا timeout منتظر بماند.
| تنظیم | محصول | معنا |
|---|---|---|
| طول routing key | RabbitMQ | حداکثر 255 بایت |
internal | اعلان exchange در RabbitMQ | client مستقیم publish نمیکند؛ مسیر ورودی E2E است |
auto-delete | exchange/queue در RabbitMQ | پس از رفتن آخرین binding برای exchange یا آخرین consumer برای queue، طبق شرایط lifecycle |
alternate-exchange | آرگومان exchange یا policy در RabbitMQ | نام AE؛ آرگومان client بر policy اولویت دارد |
x-match | headers binding در RabbitMQ | all، any، all-with-x و any-with-x |
hash-header | افزونهٔ x-consistent-hash | هشکردن header بهجای routing key |
dead-letter-exchange و dead-letter-routing-key | policy صف RabbitMQ؛ آرگومان client با پیشوند x- | مقصد پیام مرده و کلید اختیاری آن |
| نام topic | Kafka | حداکثر 249 نویسه از [a-zA-Z0-9._-] |
auto.create.topics.enable | broker در Kafka | با false، typo به topic ضمنی تبدیل نمیشود |
create.topic.policy.class.name | broker در Kafka | اتصال CreateTopicPolicy برای enforce قرارداد نام |
cleanup.policy | topic در Kafka | delete برای تاریخچه یا compact برای آخرین state هر key |
delete.retention.ms | topic در Kafka | زمان نگهداری tombstone؛ پیشفرض 24 ساعت |
--resource-pattern-type | CLI مجوز Kafka | literal بهصورت پیشفرض یا prefixed |
topic.metadata.refresh.interval.ms | librdkafka، زیرساخت laravel-kafka | زمان کشف topicهای تازهٔ مطابق regex |
| Hash slots | Redis Cluster | 16384 slot؛ {tag} ورودی hash را به tag محدود میکند |
MAXLEN | Redis Streams | حد نگهداری stream، مستقل از نیاز subscriber |
| خطا | محل | تشخیص | اقدام |
|---|---|---|---|
312 NO_ROUTE در basic.return | publish با mandatory در RabbitMQ | هیچ صفی حتی از مسیر AE نرسیده است | کلید، binding و AE را بررسی کنید |
404 NOT_FOUND | publish/bind در RabbitMQ | exchange یا queue موجود نیست | topology قبل از مصرف/انتشار |
406 PRECONDITION_FAILED | declare در RabbitMQ | نوع، flag یا آرگومان با تعریف قبلی متفاوت است | migration کنترلشده یا policy برای تنظیم mutable؛ retry کور نکنید |
403 ACCESS_REFUSED | RabbitMQ | configure/write/read یا topic authorisation اجازه نمیدهد | مجوز principal در vhost و کلید topic را اصلاح کنید |
invalid exchange type در exchange.declare | RabbitMQ | نوع افزونه فعال نیست | مثلاً rabbitmq-plugins enable rabbitmq_consistent_hash_exchange |
InvalidTopicException | create/produce در Kafka | نام غیرمجاز | اصلاح قرارداد نام |
TOPIC_ALREADY_EXISTS | ساخت topic در Kafka | setup دوباره | وجود را بپذیرید و config را بررسی کنید |
UNKNOWN_TOPIC_OR_PARTITION | produce در Kafka | topic/metadata آماده نیست؛ با auto-create خاموش topic خودکار ساخته نمیشود | provisioning در pipeline و تشخیص علت |
TOPIC_AUTHORIZATION_FAILED | Kafka | ACL به principal اجازه نمیدهد | مجوز topic یا prefix دامنه |
CROSSSLOT | Redis Cluster | فرمان چندکلیدی روی slotهای متفاوت | طراحی hash tag |
BUSYGROUP | Redis XGROUP CREATE | group از قبل هست | فقط همین خطا را قابلقبول بدانید |
تعریف توپولوژی بهصورت کد (Topology as code) جلوی drift را میگیرد. rabbitmqctl export_definitions ساختار را برای بازبینی ذخیره میکند؛ definitions جای backup پیامها نیست. export به management plugin وابسته نیست. سه روش قابل بازتولید، declaration توسط مالک resource هنگام startup، import فایل definitions در boot/CI و infrastructure-as-code هستند. consumer صف و binding خودش را میسازد و producer exchange خودش را. policy برای تنظیم mutable مثل DLX، AE، TTL و max-length است، ولی نوع exchange/queue را عوض نمیکند. در Kafka، admin client مثل kadm.CreateTopic یا pipeline پلتفرم topic را میسازد؛ در Redis اولین XADD کلید را ایجاد میکند و XGROUP CREATE ... MKSTREAM گروه و stream لازم را آماده میکند.
جدول outbox میتواند destination را کنار رویداد نگه دارد. query زیر فقط کار را بین relayها تقسیم میکند؛ SKIP LOCKED ترتیب aggregate میان چند relay را تضمین نمیکند. برای ترتیب، مالکیت ثابت shard یا serialization هر aggregate لازم است.
CREATE TABLE outbox (
id bigserial PRIMARY KEY,
aggregate_id text NOT NULL,
event_type text NOT NULL,
destination text NOT NULL,
routing_key text,
headers jsonb NOT NULL DEFAULT '{}',
payload jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
published_at timestamptz
);
SELECT id, destination, routing_key, aggregate_id, headers, payload
FROM outbox WHERE published_at IS NULL ORDER BY id
LIMIT 500 FOR UPDATE SKIP LOCKED;Go
نمونه
کتابخانههای amqp091-go، franz-go و go-redis primitiveهای متفاوت دارند. یک interface با متد Publish میتواند جزئیات اتصال را پنهان کند، اما binding، partition و consumer group را هممعنا نمیکند. نمونههای کامل در بخش brokerها وارد شدهاند.
// Command naming checks channel names against the rules each broker enforces
// and against our own convention. It needs no broker.
//
// - Kafka (clients/.../internals/Topic.java): at most 249 chars, only ASCII
// alphanumerics, '.', '_' and '-'; "." and ".." are invalid; names that
// differ only by '.' vs '_' collide in metric names.
// - Redis Cluster (cluster spec): slot = CRC16(key) mod 16384, and only the
// text inside the first non-empty {...} is hashed (hash tag).
// - Our convention (not a broker rule): <domain>.<entity>.<event>.v<N>.
package main
import (
"fmt"
"regexp"
"strings"
)
var legalKafka = regexp.MustCompile(`^[a-zA-Z0-9._-]+$`)
// ValidKafkaTopic mirrors Topic.detectInvalidTopic.
func ValidKafkaTopic(name string) error {
switch {
case name == "":
return fmt.Errorf("the empty string is not allowed")
case name == "." || name == "..":
return fmt.Errorf("%q is not allowed", name)
case len(name) > 249:
return fmt.Errorf("longer than 249 characters")
case !legalKafka.MatchString(name):
return fmt.Errorf("%q contains characters other than ASCII alphanumerics, '.', '_' and '-'", name)
}
return nil
}
// Collides mirrors Topic.hasCollision: '.' and '_' map to the same metric name.
func Collides(a, b string) bool {
return strings.ReplaceAll(a, ".", "_") == strings.ReplaceAll(b, ".", "_")
}
var convention = regexp.MustCompile(`^[a-z][a-z0-9-]*\.[a-z][a-z0-9-]*\.[a-z][a-z0-9-]*\.v[0-9]+$`)
// EventTopic builds <domain>.<entity>.<event>.v<N> and checks both rule sets.
func EventTopic(domain, entity, event string, version int) (string, error) {
name := fmt.Sprintf("%s.%s.%s.v%d", domain, entity, event, version)
if err := ValidKafkaTopic(name); err != nil {
return "", err
}
if !convention.MatchString(name) {
return "", fmt.Errorf("%q breaks the <domain>.<entity>.<event>.v<N> convention", name)
}
return name, nil
}
// crc16 is CRC-16/XMODEM (poly 0x1021, init 0), the Redis Cluster key hash.
func crc16(b []byte) uint16 {
var crc uint16
for _, c := range b {
crc ^= uint16(c) << 8
for i := 0; i < 8; i++ {
if crc&0x8000 != 0 {
crc = crc<<1 ^ 0x1021
} else {
crc <<= 1
}
}
}
return crc
}
// HashSlot applies the hash-tag rule from the Redis Cluster specification.
func HashSlot(key string) int {
if s := strings.IndexByte(key, '{'); s >= 0 {
if e := strings.IndexByte(key[s+1:], '}'); e > 0 {
key = key[s+1 : s+1+e]
}
}
return int(crc16([]byte(key)) % 16384)
}
// TenantStream is our per-tenant stream naming: the tenant is the hash tag,
// so every stream of one tenant lands in one slot (multi-key reads work).
func TenantStream(tenant, domain, entity string) string {
return fmt.Sprintf("t:{%s}:%s.%s.events", tenant, domain, entity)
}
func main() {
for _, n := range []string{"sales.order.placed.v1", "sales_order.placed.v1", "Sales Order Placed", "."} {
fmt.Printf("kafka %-24q valid=%v\n", n, ValidKafkaTopic(n) == nil)
}
fmt.Println("collide sales.order / sales_order:", Collides("sales.order", "sales_order"))
if _, err := EventTopic("sales", "order", "Placed", 1); err != nil {
fmt.Println("convention:", err)
}
for _, k := range []string{
TenantStream("acme", "sales", "order"), TenantStream("acme", "billing", "invoice"),
TenantStream("globex", "sales", "order"), "sales.order.events", "billing.invoice.events",
} {
fmt.Printf("slot %5d %s\n", HashSlot(k), k)
}
}نگاه Go
matcher خالص و محاسبهٔ slot بدون broker قابل تستاند. اعتبارسنجی نام قبل از I/O خطای طراحی را زود آشکار میکند. در Kafka، خطای handler باید قبل از commit batch باعث توقف شود؛ ادامهدادن و commit کردن offsetهای بعدی، رویداد شکستخورده را جا میاندازد. پس از restart، بخش موفق قبلی ممکن است دوباره اجرا شود؛ handler باید تکرارپذیر بدون اثر اضافی (Idempotent) باشد.
Laravel
نمونه
اتصال (Connection) backend را انتخاب میکند و صف (Queue) مسیر داخل آن اتصال است. onConnection و onQueue را با subscription مستقل اشتباه نگیرید. Laravel 13 با Queue::route قواعد پیشفرض را مرکزی میکند و Queue::forward مسیر صف را تغییر میدهد؛ تنظیم صریح job میتواند اولویت داشته باشد. Queue::route میتواند class، interface، trait یا parent class را پوشش دهد و queue:work --queue=high,default ترتیب polling صفها را مشخص میکند.
<?php
namespace App\Providers;
use App\Jobs\GenerateInvoicePdf;
use App\Jobs\ReserveStock;
use App\Jobs\SendOrderConfirmation;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\ServiceProvider;
/**
* Central routing table for in-process jobs (Laravel 13 Queue::route and
* Queue::forward). Jobs stay ignorant of where they run; ops changes routes
* here. A job's own onQueue()/onConnection() still overrides this.
*/
class QueueRoutingServiceProvider extends ServiceProvider
{
public function boot(): void
{
Queue::route([
ReserveStock::class => ['redis', 'fulfilment'], // connection, queue
GenerateInvoicePdf::class => ['redis', 'billing-slow'],
SendOrderConfirmation::class => 'notifications', // queue only
]);
// Move a whole queue to new infrastructure without touching jobs.
Queue::forward('billing-slow', 'billing-slow', 'sqs');
}
}فهرست درایورهای queue در مستندات Laravel 13 چنین آمده است:
"including the database, Amazon SQS, Redis, and Beanstalkd drivers" — Laravel 13, Queues
درایور sync برای اجرای فوری و null برای دورریختن job نیز وجود دارند. RabbitMQ و Kafka به package نیاز دارند. با laravel-queue-rabbitmq و exchange تنظیمشده، exchange_routing_key با %s نام queue انتخابشده را وارد routing key میکند؛ queue مصرف باید واقعاً bind شده باشد. package با exchange تنظیمشده binding را بهجای شما نمیسازد؛ command استقرار از php-amqplib استفاده میکند. pushRaw انتشار mandatory دارد، اما این معادل انتظار confirm نیست. مسیر failed job تنظیمهای مستقل reroute_failed، failed_exchange و failed_routing_key دارد.
<?php
// config/queue.php (excerpt). A Laravel "connection" picks the broker; with
// vladimir-yuldashev/laravel-queue-rabbitmq an exchange turns the Laravel
// "queue" name into a routing key: exchange_routing_key '%s' is replaced by
// the queue passed to onQueue() (package source: RabbitMQQueue::getRoutingKey).
return [
'default' => env('QUEUE_CONNECTION', 'redis'),
'connections' => [
// In-process jobs of the monolith: queue names are the routing.
'redis' => [
'driver' => 'redis',
'connection' => 'default',
'queue' => 'default',
'retry_after' => 90,
'block_for' => null,
],
// Integration events of the Sales domain, published to a topic exchange.
'sales-events' => [
'driver' => 'rabbitmq',
// Default key if a job forgets onQueue(): no business binding wants it.
'queue' => 'sales.missing-key',
'connection' => 'default',
'hosts' => [
[
'host' => env('RABBITMQ_HOST', '127.0.0.1'),
'port' => env('RABBITMQ_PORT', 5672),
'user' => env('RABBITMQ_USER', 'guest'),
'password' => env('RABBITMQ_PASSWORD', 'guest'),
'vhost' => env('RABBITMQ_VHOST', '/prod'),
],
],
'options' => [
'queue' => [
'exchange' => 'sales.events',
'exchange_type' => 'topic',
'exchange_routing_key' => '%s',
'reroute_failed' => true,
'failed_exchange' => 'dlx',
'failed_routing_key' => 'failed.%s',
],
],
],
// The consuming side: the worker reads a queue, not a routing key.
// php artisan queue:work fulfilment-in --queue=fulfilment.sales-orders
'fulfilment-in' => [
'driver' => 'rabbitmq',
'queue' => 'fulfilment.sales-orders',
'connection' => 'default',
'hosts' => [
[
'host' => env('RABBITMQ_HOST', '127.0.0.1'),
'port' => env('RABBITMQ_PORT', 5672),
'user' => env('RABBITMQ_FULFILMENT_USER', 'fulfilment'),
'password' => env('RABBITMQ_FULFILMENT_PASSWORD', 'secret'),
'vhost' => env('RABBITMQ_VHOST', '/prod'),
],
],
],
],
];<?php
namespace App\Jobs;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
/**
* Laravel-to-Laravel integration event. The payload is a serialised Laravel
* job, so only a Laravel consumer with this class can run it; for polyglot
* consumers publish plain JSON with php-amqplib or laravel-kafka instead.
*/
class OrderPlacedIntegrationEvent implements ShouldQueue
{
use Queueable;
public function __construct(
public string $orderId,
public string $tenant,
public int $totalCents,
) {
// Connection = broker, queue = routing key on the sales.events exchange.
$this->onConnection('sales-events');
$this->onQueue('sales.order.placed.v1');
}
public function handle(): void
{
// Runs in the Fulfilment worker that consumes fulfilment.sales-orders.
}
}<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Wire\AMQPTable;
/**
* php artisan messaging:topology
*
* Declares the Fulfilment side of the ordering topology with php-amqplib (the
* library laravel-queue-rabbitmq is built on). Declarations are idempotent;
* a declare with different arguments fails with 406 PRECONDITION_FAILED.
* Note php-amqplib defaults auto_delete to true, so pass false explicitly.
*/
class DeclareOrderingTopology extends Command
{
protected $signature = 'messaging:topology';
protected $description = 'Declare exchanges, queues and bindings owned by Fulfilment';
public function handle(): int
{
$conn = new AMQPStreamConnection(
config('services.rabbitmq.host'),
(int) config('services.rabbitmq.port'),
config('services.rabbitmq.user'),
config('services.rabbitmq.password'),
config('services.rabbitmq.vhost'),
);
$ch = $conn->channel();
// The publisher's exchange (declared here too so start order does not matter).
// exchange_declare(name, type, passive, durable, auto_delete)
$ch->exchange_declare('sales.events', 'topic', false, true, false);
$ch->exchange_declare('dlx', 'topic', false, true, false);
// One queue per consuming service and purpose.
// queue_declare(name, passive, durable, exclusive, auto_delete, nowait, arguments)
$ch->queue_declare('fulfilment.sales-orders', false, true, false, false, false, new AMQPTable([
'x-queue-type' => 'quorum',
'x-dead-letter-exchange' => 'dlx',
]));
// Topic binding: every v1 order event, whatever its name.
$ch->queue_bind('fulfilment.sales-orders', 'sales.events', 'sales.order.*.v1');
// Headers exchange for notifications: route on content, not on the key.
// Same arguments as the Go topology, so the declarations can coexist.
$ch->exchange_declare('notifications.unmatched', 'fanout', false, true, false);
$ch->exchange_declare('notifications.route', 'headers', false, true, false, false, false, new AMQPTable([
'alternate-exchange' => 'notifications.unmatched',
]));
$ch->queue_declare('notifications.unmatched', false, true, false, false, false, new AMQPTable([
'x-queue-type' => 'quorum',
]));
$ch->queue_bind('notifications.unmatched', 'notifications.unmatched');
$ch->queue_declare('notifications.sms-vip', false, true, false, false, false, new AMQPTable([
'x-queue-type' => 'quorum',
'x-dead-letter-exchange' => 'dlx',
]));
$ch->queue_bind('notifications.sms-vip', 'notifications.route', '', false, new AMQPTable([
'x-match' => 'all',
'channel' => 'sms',
'tier' => 'vip',
]));
// Exchange-to-exchange: exchange_bind(destination, source, routing_key).
$ch->exchange_declare('audit.all', 'fanout', false, true, false, true);
$ch->exchange_bind('audit.all', 'sales.events', '#');
$ch->close();
$conn->close();
$this->info('Fulfilment topology declared');
return self::SUCCESS;
}
}Redis facade برای Streams استفاده میشود؛ queue driver داخلی Redis روی list/sorted set کار میکند.
<?php
namespace App\Messaging;
use Illuminate\Support\Facades\Redis;
/**
* Redis Streams has no exchanges: the stream key is the route. Argument order
* below is phpredis (key, id, fields); predis differs. Laravel's
* database.redis.options.prefix is prepended to keys, which keeps the
* {tenant} hash tag intact because only the text inside braces is hashed.
*/
final class RedisStreamRouter
{
/** Trusted application identifiers only. Our convention: t:{tenant}:<domain>.<entity>.events */
public static function stream(string $tenant, string $domain, string $entity): string
{
return "t:{{$tenant}}:{$domain}.{$entity}.events";
}
/** Fan-out: one consumer group per subscribing service. */
public static function setupGroups(string $tenant): void
{
$orders = self::stream($tenant, 'sales', 'order');
foreach (['fulfilment', 'billing', 'notification-router'] as $group) {
try {
Redis::xgroup('CREATE', $orders, $group, '$', true); // MKSTREAM
} catch (\Throwable $e) {
if (! str_contains($e->getMessage(), 'BUSYGROUP')) {
throw $e;
}
}
}
}
public static function publish(string $tenant, array $fields): string
{
return Redis::xadd(self::stream($tenant, 'sales', 'order'), '*', $fields, 1000000, true);
}
/** Content-based router: read one stream, append to the matching one, ack. */
public static function routeOnce(string $tenant): void
{
$orders = self::stream($tenant, 'sales', 'order');
$batch = Redis::xreadgroup('notification-router', 'router-1', [$orders => '>'], 100, 2000) ?: [];
foreach ($batch as $entries) {
foreach ($entries as $id => $fields) {
$target = ($fields['channel'] ?? '') === 'sms'
? self::stream($tenant, 'notifications', 'sms')
: self::stream($tenant, 'notifications', 'email');
$fields['_source_stream'] = $orders;
$fields['_source_id'] = $id;
// Publish before ack; deduplicate retries using the source identity.
if (Redis::xadd($target, '*', $fields) === false) {
throw new \RuntimeException('Destination XADD failed; source remains pending');
}
Redis::xack($orders, 'notification-router', [$id]);
}
}
}
}نگاه Laravel
پاسخ phpredis ممکن است نام کلید prefixشده داشته باشد؛ روی مقدارهای پاسخ iterate کنید. فقط BUSYGROUP را هنگام setup نادیده بگیرید، نه خطای شبکه یا permission. router نمونه recovery کامل PEL ندارد؛ برای اجرای دائمی باید reclaim و idempotency اضافه شود.
تفاوتهای اجرا در brokerها
RabbitMQ
صف هر سرویس، backlog مستقل آن است. exchangeهای domain از نوع topic هستند؛ audit با E2E به fanout داخلی میرود و notification با headers و AE انتخاب میشود.
// Command topology declares the ordering domain (Sales, Fulfilment, Billing)
// on RabbitMQ. Without AMQP_URL it only prints the plan, so it runs anywhere.
//
// Rules it follows: one topic exchange per domain (the publisher's), one
// queue per consuming service and purpose, keys <domain>.<entity>.<event>.v<N>,
// a DLX pointer per queue, an audit fan-out built from exchange-to-exchange
// bindings, and a headers exchange for content-based routing of notifications
// whose alternate exchange is the "or else" branch.
//
// Gotcha: the audit binding uses "#", so every domain event is "routed". An
// alternate exchange (or the mandatory flag) on the domain exchanges could no
// longer tell you that no business consumer wanted a message.
package main
import (
"fmt"
"log"
"os"
amqp "github.com/rabbitmq/amqp091-go"
)
type exchange struct {
name, kind string
internal bool
args amqp.Table
}
type queue struct {
name string
args amqp.Table
}
type binding struct {
dest, key, source string
toExchange bool
args amqp.Table
}
// quorum returns queue arguments: replicated quorum queue plus a DLX pointer.
// Prefer policies for DLX in production; see the Dead-Letter Queue chapter.
func quorum(dlx string) amqp.Table {
return amqp.Table{"x-queue-type": "quorum", "x-dead-letter-exchange": dlx}
}
var exchanges = []exchange{
// One publishing exchange per domain, owned by that domain.
{name: "sales.events", kind: "topic"},
{name: "fulfilment.events", kind: "topic"},
{name: "billing.events", kind: "topic"},
{name: "dlx", kind: "topic"},
// Internal: only other exchanges may publish into it (exchange.bind).
{name: "audit.all", kind: "fanout", internal: true},
// Content-based routing on headers, not on the key. Messages no binding
// matches go to the alternate exchange (policy preferred in production).
{name: "notifications.route", kind: "headers", args: amqp.Table{"alternate-exchange": "notifications.unmatched"}},
{name: "notifications.unmatched", kind: "fanout"},
}
var queues = []queue{
{"fulfilment.sales-orders", quorum("dlx")},
{"billing.sales-orders", quorum("dlx")},
{"billing.fulfilment-shipments", quorum("dlx")},
{"fulfilment.billing-payments", quorum("dlx")},
{"notifications.unmatched", amqp.Table{"x-queue-type": "quorum"}},
{"dlq.all", amqp.Table{"x-queue-type": "quorum"}},
// A stream keeps history for replay; audit readers do not delete it.
{"audit.archive", amqp.Table{"x-queue-type": "stream", "x-max-age": "30D"}},
{"notifications.sms-vip", quorum("dlx")},
{"notifications.email", quorum("dlx")},
}
var bindings = []binding{
// Fulfilment needs every order lifecycle event of version 1.
{dest: "fulfilment.sales-orders", key: "sales.order.*.v1", source: "sales.events"},
// Billing needs only two event types: two exact bindings, same queue.
{dest: "billing.sales-orders", key: "sales.order.placed.v1", source: "sales.events"},
{dest: "billing.sales-orders", key: "sales.order.cancelled.v1", source: "sales.events"},
{dest: "billing.fulfilment-shipments", key: "fulfilment.shipment.dispatched.v1", source: "fulfilment.events"},
{dest: "fulfilment.billing-payments", key: "billing.payment.captured.v1", source: "billing.events"},
{dest: "notifications.unmatched", source: "notifications.unmatched"},
{dest: "dlq.all", key: "#", source: "dlx"},
// Exchange-to-exchange: every domain exchange feeds the audit fan-out.
{dest: "audit.all", key: "#", source: "sales.events", toExchange: true},
{dest: "audit.all", key: "#", source: "fulfilment.events", toExchange: true},
{dest: "audit.all", key: "#", source: "billing.events", toExchange: true},
{dest: "audit.archive", source: "audit.all"},
// Headers exchange: x-match all = every listed header must match.
{dest: "notifications.sms-vip", source: "notifications.route",
args: amqp.Table{"x-match": "all", "channel": "sms", "tier": "vip"}},
// x-match any = one matching header is enough.
{dest: "notifications.email", source: "notifications.route",
args: amqp.Table{"x-match": "any", "channel": "email", "fallback": "email"}},
}
func plan() {
for _, e := range exchanges {
fmt.Printf("exchange %-22s %-8s internal=%v args=%v\n", e.name, e.kind, e.internal, e.args)
}
for _, q := range queues {
fmt.Printf("queue %-30s args=%v\n", q.name, q.args)
}
for _, b := range bindings {
kind := "queue"
if b.toExchange {
kind = "exchange"
}
fmt.Printf("bind %-20s -[%s]-> %s %s %v\n", b.source, b.key, kind, b.dest, b.args)
}
}
func apply(ch *amqp.Channel) error {
for _, e := range exchanges {
// durable=true, autoDelete=false, noWait=false
if err := ch.ExchangeDeclare(e.name, e.kind, true, false, e.internal, false, e.args); err != nil {
return fmt.Errorf("exchange %s: %w", e.name, err)
}
}
for _, q := range queues {
// durable=true, autoDelete=false, exclusive=false, noWait=false
if _, err := ch.QueueDeclare(q.name, true, false, false, false, q.args); err != nil {
return fmt.Errorf("queue %s: %w", q.name, err)
}
}
for _, b := range bindings {
var err error
if b.toExchange {
// ExchangeBind(destination, key, source, ...): messages flow source -> destination.
err = ch.ExchangeBind(b.dest, b.key, b.source, false, b.args)
} else {
err = ch.QueueBind(b.dest, b.key, b.source, false, b.args)
}
if err != nil {
return fmt.Errorf("bind %s -> %s: %w", b.source, b.dest, err)
}
}
return nil
}
func main() {
url := os.Getenv("AMQP_URL")
if url == "" {
plan()
return
}
conn, err := amqp.Dial(url)
if err != nil {
log.Fatal(err)
}
defer conn.Close()
ch, err := conn.Channel()
if err != nil {
log.Fatal(err)
}
// A failed declare (e.g. 406 PRECONDITION_FAILED for changed arguments)
// closes the channel; topology code must stop, not continue.
if err := apply(ch); err != nil {
log.Fatal(err)
}
log.Println("topology declared")
}// Command publish shows the producer side of RabbitMQ routing: the routing
// key carries the event name, headers carry content for a headers exchange,
// and mandatory=true plus NotifyReturn surfaces messages no queue accepted.
package main
import (
"context"
"fmt"
"log"
"os"
"time"
amqp "github.com/rabbitmq/amqp091-go"
)
func main() {
url := os.Getenv("AMQP_URL")
if url == "" {
log.Println("AMQP_URL not set; nothing to do")
return
}
conn, err := amqp.Dial(url)
if err != nil {
log.Fatal(err)
}
defer conn.Close()
ch, err := conn.Channel()
if err != nil {
log.Fatal(err)
}
if err := ch.Confirm(false); err != nil {
log.Fatal(err)
}
returns := ch.NotifyReturn(make(chan amqp.Return, 16))
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// 1. Topic routing: the key is the event name, never the consumer name.
order := amqp.Publishing{
ContentType: "application/json",
DeliveryMode: amqp.Persistent,
Type: "sales.order.placed.v1",
MessageId: "evt-01J9Z",
Body: []byte(`{"order_id":"o-42","tenant":"acme","total":1990}`),
}
if err := publish(ctx, ch, returns, "sales.events", "sales.order.placed.v1", true, false, order); err != nil {
log.Fatal(err)
}
// 2. A typo in the key: no business binding matches. With the audit "#"
// binding it still counts as routed, which is why that binding hides typos.
if err := publish(ctx, ch, returns, "sales.events", "sales.oder.placed.v1", true, false, order); err != nil {
log.Fatal(err)
}
// 3. Headers routing: the key is ignored; x-match decides.
sms := amqp.Publishing{
DeliveryMode: amqp.Persistent,
Headers: amqp.Table{"channel": "sms", "tier": "vip"},
Body: []byte(`{"to":"+31...","text":"Your order shipped"}`),
}
if err := publish(ctx, ch, returns, "notifications.route", "", true, false, sms); err != nil {
log.Fatal(err)
}
}
func publish(ctx context.Context, ch *amqp.Channel, returns <-chan amqp.Return, exchange, key string, mandatory, immediate bool, msg amqp.Publishing) error {
dc, err := ch.PublishWithDeferredConfirmWithContext(ctx, exchange, key, mandatory, immediate, msg)
if err != nil {
return err
}
ack, err := dc.WaitContext(ctx)
if err != nil {
return err
}
if !ack {
return fmt.Errorf("broker rejected publish")
}
// amqp091-go dispatches basic.return before completing the matching confirm.
select {
case r, ok := <-returns:
if ok {
return fmt.Errorf("returned %d %s exchange=%s key=%s", r.ReplyCode, r.ReplyText, r.Exchange, r.RoutingKey)
}
default:
}
return nil
}برنامه بدون AMQP_URL فقط plan را چاپ میکند. declaration ناسازگار با 406 کانال را میبندد؛ consumerی که زودتر از producer بالا میآید باید exchange لازم را هم declare کند. نبود binding بدون mandatory، AE یا مشاهدهٔ unroutable میتواند خاموش باشد. publisher confirm را با deadline انتظار میکشد؛ return یعنی مسیر را اصلاح کنید. timeout نتیجهٔ نامعلوم است و retry با همان شناسه ممکن است duplicate بسازد. context در amqp091-go نوشتنِ شروعشده روی socket را قطع نمیکند؛ برای تولید واقعی، سیاست deadline اتصال و I/O هم لازم است.
Kafka
مسیریابی broker-side بر اساس payload ندارید؛ topic را producer انتخاب میکند و consumer با header به handler میرود. ConsumeRegex موضوعهای تازهٔ مطابق pattern را نیز وارد subscription میکند؛ ACL و قرارداد نام باید این دامنه را محدود کنند.
// Command topics creates the ordering domain's Kafka topics. Without
// KAFKA_BROKERS it prints the plan. Topic design rules used here:
//
// - one topic per aggregate stream when order matters across event types
// (sales.order.events.v1, key = order id), Kleppmann's rule;
// - one topic per event type only for independent, high-volume events;
// - a compacted topic for "latest state per key" (sales.order.state.v1);
// - names <domain>.<entity>.<stream>.v<N>: our convention, enforced with
// prefixed ACLs on "sales." and auto.create.topics.enable=false.
package main
import (
"context"
"fmt"
"log"
"os"
"sort"
"strings"
"github.com/twmb/franz-go/pkg/kadm"
"github.com/twmb/franz-go/pkg/kgo"
)
type topic struct {
name string
partitions int32
configs map[string]*string
}
func ptr(s string) *string { return &s }
var plan = []topic{
// All order lifecycle events, keyed by order id: placed, paid, cancelled.
{"sales.order.events.v1", 12, map[string]*string{
"cleanup.policy": ptr("delete"),
"retention.ms": ptr("604800000"), // 7 days
}},
// Latest order snapshot per key; a null value (tombstone) deletes it.
{"sales.order.state.v1", 12, map[string]*string{
"cleanup.policy": ptr("compact"),
"min.compaction.lag.ms": ptr("3600000"),
}},
{"fulfilment.shipment.events.v1", 6, nil},
{"billing.invoice.events.v1", 6, nil},
// High-volume, independent: its own topic so others need not skip it.
{"sales.cart.item-viewed.v1", 48, map[string]*string{"retention.ms": ptr("86400000")}},
}
func main() {
brokers := os.Getenv("KAFKA_BROKERS")
if brokers == "" {
for _, t := range plan {
fmt.Printf("%-32s partitions=%-3d configs=%s\n", t.name, t.partitions, show(t.configs))
}
return
}
cl, err := kgo.NewClient(kgo.SeedBrokers(strings.Split(brokers, ",")...))
if err != nil {
log.Fatal(err)
}
defer cl.Close()
adm := kadm.NewClient(cl)
for _, t := range plan {
// Replication factor 3; partitions can grow later but never shrink,
// and growing them remaps keys (see Ordering & Partitioning).
resp, err := adm.CreateTopic(context.Background(), t.partitions, 3, t.configs, t.name)
if err != nil {
log.Fatal(err)
}
if resp.Err != nil {
log.Printf("%s: %v", t.name, resp.Err) // e.g. TOPIC_ALREADY_EXISTS
continue
}
log.Printf("created %s", t.name)
}
}
func show(m map[string]*string) string {
var parts []string
for k, v := range m {
parts = append(parts, k+"="+*v)
}
sort.Strings(parts)
return strings.Join(parts, " ")
}// Command consume shows the two consumer-side routing tools Kafka has:
// fan-in through a regex subscription, and content-based dispatch on a
// header because the broker cannot filter. Each consumer group gets its own
// copy of every record (fan-out); members of one group split partitions.
package main
import (
"context"
"fmt"
"log"
"os"
"strings"
"github.com/twmb/franz-go/pkg/kgo"
)
type handler func(context.Context, *kgo.Record) error
// Fulfilment handles three of the order events; it ignores the rest cheaply.
var routes = map[string]handler{
"sales.order.placed.v1": reserveStock,
"sales.order.cancelled.v1": releaseStock,
"billing.payment.captured.v1": func(ctx context.Context, r *kgo.Record) error {
log.Printf("ship order %s", r.Key)
return nil
},
}
func reserveStock(_ context.Context, r *kgo.Record) error {
log.Printf("reserve stock for %s", r.Key)
return nil
}
func releaseStock(_ context.Context, r *kgo.Record) error {
log.Printf("release stock for %s", r.Key)
return nil
}
func header(r *kgo.Record, key string) string {
for _, h := range r.Headers {
if h.Key == key {
return string(h.Value)
}
}
return ""
}
func main() {
brokers := os.Getenv("KAFKA_BROKERS")
if brokers == "" {
log.Println("KAFKA_BROKERS not set; nothing to do")
return
}
cl, err := kgo.NewClient(
kgo.SeedBrokers(strings.Split(brokers, ",")...),
// The group id is the subscriber identity: one group per service.
kgo.ConsumerGroup("fulfilment.order-handler"),
// Fan-in: every <domain>.<entity>.events.v1 topic of sales and billing.
// New matching topics are picked up on the next metadata refresh.
kgo.ConsumeTopics(`^(sales|billing)\.[a-z-]+\.events\.v1$`),
kgo.ConsumeRegex(),
kgo.DisableAutoCommit(),
)
if err != nil {
log.Fatal(err)
}
defer cl.Close()
ctx := context.Background()
for {
fetches := cl.PollFetches(ctx)
if fetches.IsClientClosed() {
return
}
fetches.EachError(func(t string, p int32, err error) { log.Printf("fetch %s/%d: %v", t, p, err) })
if err := dispatchBatch(ctx, fetches.Records(), routes); err != nil {
log.Printf("%v; stop without committing this batch", err)
return // Restart replays the batch; handlers must be idempotent.
}
if err := cl.CommitUncommittedOffsets(ctx); err != nil {
log.Printf("commit: %v", err)
}
}
}
// A failure stops the whole batch: the caller must not commit past a gap.
func dispatchBatch(ctx context.Context, records []*kgo.Record, handlers map[string]handler) error {
for _, r := range records {
h, ok := handlers[header(r, "type")]
if !ok {
continue
} // Intentional Message Filter: safe to commit ignored types.
if err := h(ctx, r); err != nil {
return fmt.Errorf("handler %s at %s/%d/%d: %w", header(r, "type"), r.Topic, r.Partition, r.Offset, err)
}
}
return nil
}خطای handler به commit موفق تعبیر نمیشود. از ساخت خودکار topic در production اجتناب کنید تا typo آشکار باشد.
Redis Streams
گروهها باید قبل از رویداد نمونه ساخته شوند؛ ایجاد group در $ بعد از publish همان رویداد را رد میکند. برای replay گذشته از 0 استفاده کنید، به شرط اینکه داده هنوز trim نشده باشد.
// Command streams shows routing on Redis Streams, which has no exchanges:
// the stream key IS the route. It uses one stream per aggregate type,
// a per-tenant hash tag so one tenant's streams share a cluster slot, one
// consumer group per subscribing service (fan-out), and a small router
// process that reads one stream and XADDs to others (content-based router).
package main
import (
"context"
"errors"
"fmt"
"log"
"os"
"time"
"github.com/redis/go-redis/v9"
)
// Inputs here are trusted application constants, not user-supplied tenant IDs.
// Stream is our naming convention, not a Redis rule:
// t:{<tenant>}:<domain>.<entity>.events
func Stream(tenant, domain, entity string) string {
return fmt.Sprintf("t:{%s}:%s.%s.events", tenant, domain, entity)
}
func ensureGroup(ctx context.Context, rdb *redis.Client, stream, group string) error {
err := rdb.XGroupCreateMkStream(ctx, stream, group, "$").Err()
// BUSYGROUP means the group exists already: fine for idempotent setup.
if err != nil && err.Error() != "BUSYGROUP Consumer Group name already exists" {
return err
}
return nil
}
func main() {
addr := os.Getenv("REDIS_ADDR")
if addr == "" {
fmt.Println(Stream("acme", "sales", "order"))
fmt.Println(Stream("acme", "notifications", "sms"))
return
}
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{Addr: addr})
defer rdb.Close()
orders := Stream("acme", "sales", "order")
// Fan-out: each service has its own group, so each sees every entry.
for _, g := range []string{"fulfilment", "billing", "analytics", "notification-router"} {
if err := ensureGroup(ctx, rdb, orders, g); err != nil {
log.Fatal(err)
}
}
// Producer: the event type is a field; MAXLEN ~ bounds memory.
if err := rdb.XAdd(ctx, &redis.XAddArgs{
Stream: orders,
MaxLen: 1_000_000,
Approx: true,
Values: map[string]any{"type": "sales.order.placed.v1", "order_id": "o-42", "channel": "sms"},
}).Err(); err != nil {
log.Fatal(err)
}
// Router: a consumer group of its own that forwards by content.
if err := ensureGroup(ctx, rdb, orders, "notification-router"); err != nil {
log.Fatal(err)
}
res, err := rdb.XReadGroup(ctx, &redis.XReadGroupArgs{
Group: "notification-router", Consumer: "router-1",
Streams: []string{orders, ">"}, Count: 100, Block: 2 * time.Second,
}).Result()
if err != nil && !errors.Is(err, redis.Nil) {
log.Fatal(err)
}
for _, s := range res {
for _, m := range s.Messages {
target := Stream("acme", "notifications", "email")
if m.Values["channel"] == "sms" {
target = Stream("acme", "notifications", "sms")
}
// Publish first, then ack. A crash between them can duplicate output.
// MULTI does not roll back command errors; do not ack a failed XADD.
fields := make(map[string]any, len(m.Values)+2)
for k, v := range m.Values {
fields[k] = v
}
fields["_source_stream"], fields["_source_id"] = orders, m.ID
if err := rdb.XAdd(ctx, &redis.XAddArgs{Stream: target, Values: fields}).Err(); err != nil {
log.Fatal(err)
}
if err := rdb.XAck(ctx, orders, "notification-router", m.ID).Err(); err != nil {
log.Fatal(err)
}
}
}
}ارسال به مقصد و ack مبدأ دو مرحلهاند. _source_stream و _source_id برای dedup خروجی حفظ میشوند. همslot بودن کلیدها بهتنهایی تضمین exactly-once نیست.
در سیستمهای واقعی
- RabbitMQ bindings را در metadata نگه میدارد؛ restart به دوام هر دو سر وابسته است.
- Kafka prefix ACL را روی نام resource اعمال میکند؛ header tenant را خودکار به مرز امنیتی تبدیل نمیکند.
- Redis Cluster یک stream را میان slotها تقسیم نمیکند؛ نامگذاری shard تصمیم برنامه است.
- Laravel route/forward مسیر job را انتخاب میکند، ولی exchange binding خارجی را بهجای شما طراحی نمیکند.
راهحل مسئلههای کلاسیک
مشترک تازه
| راه | اقدام | سود | هزینه |
|---|---|---|---|
| RabbitMQ | queue.bind analytics.sales sales.events "sales.#" | producer ثابت و backlog مستقل | مدیریت binding |
| Kafka | group.id=analytics روی topicهای موجود | replay با offset مستقل | خواندن و filtering نوع نامربوط |
| Redis | XGROUP CREATE <stream> analytics $ MKSTREAM؛ برای تاریخچهٔ موجود 0 | setup کم | فقط دادهٔ trimنشده؛ MAXLEN تاریخچه را محدود میکند |
| Laravel محلی | listener جدید روی domain event | ساده در یک deploy | مرز سرویس نیست |
فقط بخشی از پیامها
در RabbitMQ binding را محدود کنید؛ در Kafka و Redis نوع رویداد را فیلتر کنید. در Kafka اگر تقریباً همهٔ حجم، مثلاً حدود 99.9٪، برای یک مشترک نامربوط است، توصیهٔ Kleppmann جداسازی جریان پرتعداد مستقل است؛ برای ردکردن چند نوع کمحجم، topicهای مرتبط را بیدلیل خرد نکنید. در laravel-kafka، withKafkaKey کلید و withHeaders نوع رویداد را تعیین میکند.
<?php
namespace App\Messaging;
use Junges\Kafka\Contracts\ConsumerMessage;
use Junges\Kafka\Facades\Kafka;
/**
* Kafka routing with mateusjunges/laravel-kafka: the topic is the channel,
* the key picks the partition (and so the order), the "type" header lets
* consumers route or skip without decoding the body.
*/
final class KafkaOrderEvents
{
public const TOPIC = 'sales.order.events.v1';
public static function publishPlaced(string $orderId, string $tenant, int $totalCents): void
{
Kafka::publish()
->onTopic(self::TOPIC)
->withKafkaKey($orderId)
->withHeaders([
'type' => 'sales.order.placed.v1',
'tenant' => $tenant,
])
->withBodyKey('order_id', $orderId)
->withBodyKey('total_cents', $totalCents)
->send();
}
/**
* Fulfilment's consumer group. Regex subscription (topics prefixed with ^)
* is fan-in from every matching topic; the handler is a content-based router.
*/
public static function consumeForFulfilment(): void
{
$routes = [
'sales.order.placed.v1' => fn (ConsumerMessage $m) => logger()->info('reserve', $m->getBody()),
'sales.order.cancelled.v1' => fn (ConsumerMessage $m) => logger()->info('release', $m->getBody()),
];
Kafka::consumer()
->subscribe('^sales\..*\.events\.v1$')
->withConsumerGroupId('fulfilment.order-handler')
->withHandler(function (ConsumerMessage $message) use ($routes): void {
$type = $message->getHeaders()['type'] ?? null;
if (! isset($routes[$type])) {
return; // not for Fulfilment: skip cheaply
}
$routes[$type]($message);
})
->build()
->consume();
}
}چندمستأجری
| طرح multi-tenant | RabbitMQ | Kafka | Redis Streams | مرز جداسازی | هزینه |
|---|---|---|---|---|---|
| کانال اشتراکی | header با نام tenant یا واژهٔ acme در key | tenant در header، key برابر tenant + aggregate | tenant field | فقط منطق برنامه | ارزان؛ همسایهٔ پرمصرف مزاحمت ایجاد میکند |
| prefix هر tenant | exchange با نام acme.sales.events | acme.sales.order.events.v1 با prefixed ACL | t:{acme}:... با مجوز key pattern | مجوز resource | sprawl با تعداد tenant رشد میکند |
| فضای مستقل | vhost هر tenant، در صورت نیاز cluster | cluster هر tenant | instance یا cluster؛ Redis Cluster فقط database 0 دارد | قویتر | هزینهٔ عملیات و نگهداری چندبرابر |
Redis Cluster فقط database صفر دارد؛ جداسازی با شمارهٔ database راهحل Cluster نیست. tenant بسیار بزرگ را با اندازهگیری workload جدا کنید. Kafka برای tenantهای یک cluster، prefix سلسلهمراتبی، prefixed ACL و quota را کنار هم میگذارد؛ quota اثر noisy neighbour را محدود میکند.
محیطها
staging و production بهتر است broker یا namespace و principal مجزا داشته باشند. # روی exchange مشترک میتواند دادهٔ production را به staging برساند. یک prefix بدون ACL این خطر را حل نمیکند. در RabbitMQ vhost هر محیط، در Kafka cluster مستقل یا دستکم prefix/ACL و auto-create خاموش، و در Redis instance مستقل انتخاب روشنی است؛ database جدا فقط در Redis غیرCluster مطرح است. کد topology ثابت میماند و تنظیم اتصال عوض میشود.
ترتیب
fan-out چند مسیر مستقل میسازد؛ fan-in ورودیها را interleave میکند. یک صف RabbitMQ ترتیب انتشار یک channel را حفظ میکند، ولی ورودی دو exchange interleave میشود. Kafka فقط در partition یک topic ترتیب دارد؛ Redis فقط در stream key. shard کردن Redis، ترتیب هر aggregate را فقط با hash پایدار شناسه حفظ میکند. تغییر partition count در Kafka میتواند کلید را به partition دیگری ببرد. شرح کامل در Ordering است.
امنیت
مجوز topic یا key را بر اساس مالکیت تعریف کنید. RabbitMQ علاوه بر configure/write/read در vhost، topic authorisation دارد؛ Kafka literal/prefixed ACL و Redis key pattern دارد. Messaging Security مرجع hardening است.
ضدالگوها
| ضدالگو | پیامد | جایگزین |
|---|---|---|
| یک صف یا topic برای همه | job کند جلوی سریع را میگیرد؛ failure domain و DLQ مشترک، مقیاس مستقل نداریم | صف بر اساس مصرفکننده و کار؛ topic بر اساس نوع aggregate |
| اسم مصرفکننده در event | وابستگی producer | نام اتفاق |
| JSON regex برای routing | شکست با schema change | metadata قراردادی |
| صف بهازای هر request یا session | هزاران صف، churn و مصرف حافظه | یک reply queue هر instance یا Direct Reply-To |
| exchange بهازای هر type | topology بزرگ | topic exchange دامنه |
| topic حاصل ضرب tenant × event type × environment | topic sprawl، بار controller و انفجار ACL | tenant/type در key/header؛ prefix فقط برای جداسازی لازم |
| catch-all همراه AE alarm | پنهانشدن typo | مشاهدهٔ subscription کسبوکار |
| eventهای aggregate در چند topic | ترتیب نامعتبر | topic و key مشترک |
| producer صف consumerها را میسازد | producer باید همهٔ مصرفکنندهها را بشناسد | هر consumer صف و binding خودش را declare کند |
| UI بهعنوان منبع حقیقت | drift میان محیطها | کد یا definitions در version control |
انتخاب توپولوژی
| وضعیت | پیشنهاد | تکنیک مکمل | دلیل |
|---|---|---|---|
| job پسزمینه داخل Laravel | queue نامدار و Queue::route | --queue=high,default برای اولویت polling | topology جداگانهٔ broker لازم نیست |
| event دامنه به چند سرویس با انتخاب زیاد | topic exchange هر دامنه و صف هر consumer در RabbitMQ | AE روی exchange انتخابگر، policy برای DLX | filtering در broker |
| چند ویژگی مستقل | headers exchange در RabbitMQ | x-match صریح و AE برای باقی موارد | ویژگیها مجبور نیستند ترتیب ثابتی در key داشته باشند |
| replay، مصرفکنندهٔ زیاد و throughput بالا | Kafka per aggregate با key برابر aggregate id | topic جدا برای state فشردهشده | ترتیب هر entity و ردکردن ارزان نوع نامربوط |
| firehose مستقل | Kafka topic هر event type | retention کوتاه | حجم بالا از بقیهٔ eventها جدا میماند |
| آخرین state هر entity | compacted topic در Kafka | tombstone برای حذف | بازسازی cache از log |
| تیم کوچک با Redis موجود | stream هر نوع aggregate، group مستقل هر سرویس | tenant hash tag و MAXLEN | اجزای عملیاتی کمتر |
| SaaS با tenantهای کوچک فراوان | کانال مشترک، tenant در key/header | انتقال tenant بزرگ به prefix یا فضای مستقل | جلوگیری از sprawl |
| tenant یا منطقه با الزام قانونی | vhost، cluster یا prefix همراه ACL | topic authorisation و prefixed ACL | جداسازی یک الزام است |
| پخش بار یک صف با affinity کلید | x-consistent-hash یا partitionهای Kafka | وزن برابر برای مقصدهای همظرفیت | موازیسازی با وابستگی پایدار کلید به مقصد |
| audit همهٔ eventها | E2E به fanout داخلی و stream queue؛ یا group audit در Kafka | retention مستقل | domain producer تغییر نمیکند |
در معماری: از یک پردازه تا سیستم توزیعشده
یکپارچه (Monolith)
در برنامهٔ واحد، ReserveStock به queue انبار و SendConfirmation به queue اعلان میرود. Queue::route() تصمیم را در service provider مرکزی میکند و queue:work redis --queue=fulfilment worker pool همان مقصد را اجرا میکند. اینها commandهای محلیاند. برای آمادهکردن مرز بیرونی، integration event را در outbox ثبت کنید؛ همهٔ eventهای درون دامنه نیازمند قرارداد نسخهدار بیرونی نیستند.
یکپارچهٔ ماژولار
Sales، Fulfilment و Billing هرکدام مالک زبان داخلی خود هستند. وقتی مرز ماژول از طریق قرارداد integration طی میشود، نام پایدار مثل sales.order.placed.v1 معنا دارد. هر ماژول اشتراک مستقل میگیرد؛ صف مشترک میان آنها نسخهٔ event را به رقابت تبدیل میکند.
میکروسرویسها
| جریان | RabbitMQ | Kafka | Redis Streams |
|---|---|---|---|
| Sales → Fulfilment | sales.events → fulfilment.sales-orders با sales.order.*.v1 | sales.order.events.v1، group fulfilment.order-handler | t:{acme}:sales.order.events، group fulfilment |
| Sales → Billing | sales.events → billing.sales-orders با دو کلید exact برای placed/cancelled | همان topic، group billing.order-handler؛ paid را رد میکند | همان stream، group billing |
| Fulfilment → Billing | fulfilment.events → billing.fulfilment-shipments | fulfilment.shipment.events.v1 | t:{acme}:fulfilment.shipment.events |
| Billing → Fulfilment | billing.events → fulfilment.billing-payments | billing.invoice.events.v1؛ payment نوع رویداد است | t:{acme}:billing.invoice.events |
| Audit | E2E با # → audit.all → stream به نام audit.archive | group audit روی همهٔ topicها با regex | group audit روی هر stream |
| Notification | notifications.route با headers و AE | router روی header با نام channel فیلتر میکند | router group به streamهای sms/email، XADD میکند |
1 Sales commits order + outbox
2 Relay publishes sales.order.placed.v1
3 Billing captures payment -> billing.payment.captured.v1
4 Fulfilment reserves stock and observes successful payment
5 Fulfilment dispatches shipment -> fulfilment.shipment.dispatched.v1
6 Billing observes shipment for reconciliationاین نمونه ترتیب تصمیم کسبوکار را از wiring جدا میکند؛ نباید payment به dispatched و dispatched به payment وابسته باشد. قرارداد نام event، key/header و مالکیت ناشر بر exchange/topic و مصرفکننده بر queue/group پس از جدایی سرویسها باقی میماند. recovery با پردازش at-least-once نیاز به idempotency دارد؛ retention و ازدسترفتن storage محدودیتهای جدا هستند. تفاوت Domain/Integration Events، Designing for Failure و گزینهٔ synchronous در Service Communication دنبال میشود. publish قابلاعتماد با Outbox و تکرار بیاثر با Inbox پوشش داده میشود.
دادهٔ توزیعشده و چند منطقه
Federation/Shovel در RabbitMQ میان clusterها پیام منتقل میکنند؛ این همان binding داخل یک vhost نیست. mirroring موضوع Kafka میان clusterها مرز شکست و lag جدید دارد؛ نام یکسان یا prefix منطقهٔ مبدأ به consumer میگوید چه دادهای میخواند، ولی تضمین ترتیب key فقط داخل partition همان cluster است. replication در Redis در سطح instance است؛ در Cluster هر stream با slot روی node قرار میگیرد و tenant hash tag در محل استقرار داده اثر دارد. topology مقصد باید از قبل آماده باشد؛ relay نباید برای ترتیب و تازگی outbox به replica عقبمانده تکیه کند.
مسیر مقیاس
| بار | RabbitMQ | Kafka | Redis Streams | هزینهٔ تازه |
|---|---|---|---|---|
| 1× | topic exchange هر دامنه و صف هر consumer | topic هر نوع aggregate؛ مثلاً 6–12 partition با توجه به نیاز واقعی | stream هر نوع aggregate | نام و قرارداد، مالکیت روشن |
| 10× | worker بیشتر، صف بر اساس هدف، quorum queue | افزایش زودهنگام partition با توجه به remap کلید؛ جداسازی firehose | N کلید برای stream داغ با hash aggregate | skew و monitoring |
| 100× | x-consistent-hash روی N صف، stream/super stream، vhost یا cluster مستقل دامنه | partition بیشتر، cluster هر دامنه و mirroring | Redis Cluster با tenant hash tag؛ انتقال tenant بزرگ به فضای مستقل | migration کلید و حفظ ordering هنگام انتقال |
آزمایشگاه؛ expected, not run
این مراحل و خروجیها انتظار آموزشیاند؛ broker یا Docker اجرا نشده است. lint و unit test کد با اجرای آزمایشگاه یکی نیست.
1. تطبیق topic
// Command topicmatch is a pure-Go model of RabbitMQ topic-exchange matching:
// keys are dot-separated words, "*" matches exactly one word and "#" matches
// zero or more words. It needs no broker, so you can run it in the lab.
package main
import (
"fmt"
"strings"
)
// Match reports whether a routing key matches a binding pattern.
func Match(pattern, key string) bool {
return match(strings.Split(pattern, "."), strings.Split(key, "."))
}
func match(p, k []string) bool {
if len(p) == 0 {
return len(k) == 0
}
switch p[0] {
case "#":
// "#" may swallow zero words, or one word and try again.
if match(p[1:], k) {
return true
}
return len(k) > 0 && match(p, k[1:])
case "*":
return len(k) > 0 && match(p[1:], k[1:])
default:
return len(k) > 0 && p[0] == k[0] && match(p[1:], k[1:])
}
}
func main() {
bindings := []string{"*.orange.*", "*.*.rabbit", "lazy.#", "sales.order.*.v1", "sales.#", "#"}
keys := []string{
"quick.orange.rabbit", "lazy.orange.elephant", "quick.orange.fox",
"lazy.brown.fox", "quick.brown.fox", "orange", "quick.orange.new.rabbit",
"lazy.orange.new.rabbit", "lazy", "sales.order.placed.v1", "sales.order.placed.v2",
}
for _, k := range keys {
var hits []string
for _, b := range bindings {
if Match(b, k) {
hits = append(hits, b)
}
}
fmt.Printf("%-26s -> %s\n", k, strings.Join(hits, ", "))
}
}$ go test ./topicmatch/ && go run ./topicmatch/
# expected, not run
quick.orange.rabbit -> *.orange.*, *.*.rabbit, #
lazy.orange.elephant -> *.orange.*, lazy.#, #
quick.orange.fox -> *.orange.*, #
lazy.brown.fox -> lazy.#, #
quick.brown.fox -> #
orange -> #
quick.orange.new.rabbit -> #
lazy.orange.new.rabbit -> lazy.#, #
lazy -> lazy.#, #
sales.order.placed.v1 -> sales.order.*.v1, sales.#, #
sales.order.placed.v2 -> sales.#, #2. نامها و slot
$ go test ./naming/ && go run ./naming/
# expected, not run
kafka "sales.order.placed.v1" valid=true
kafka "Sales Order Placed" valid=false
collide sales.order / sales_order: true
convention: "sales.order.Placed.v1" breaks the <domain>.<entity>.<event>.v<N> convention
slot 11304 t:{acme}:sales.order.events
slot 11304 t:{acme}:billing.invoice.events
slot 14041 t:{globex}:sales.order.events
slot 14303 sales.order.events
slot 4073 billing.invoice.events3. plan بدون broker
$ go run ./rabbitmq/topology/
# expected, not run
exchange sales.events topic
exchange audit.all fanout internal=true
queue fulfilment.sales-orders quorum
bind sales.events -[sales.order.*.v1]-> queue fulfilment.sales-orders
bind sales.events -[#]-> exchange audit.all4. RabbitMQ
روی broker آزمایشی ازپیشآماده، AMQP_URL را برای دو command تنظیم کنید: ابتدا topology و سپس publish. در حالت عادی audit پیام typo را هم میگیرد؛ بعد از حذف E2E catch-all همان typo باید NO_ROUTE بدهد. صف Fulfilment فقط یک placed میگیرد، نه typo.
برای نمونه، AMQP_URL را در shell همان terminal تنظیم و از ریشهٔ ماژول Go دستورهای زیر را اجرا کنید؛ نتیجه برای broker تازه و بدون consumer فعال است:
# expected, not run
go run ./rabbitmq/topology/
go run ./rabbitmq/publish/
rabbitmqctl list_queues name messages
fulfilment.sales-orders 1
billing.sales-orders 1
audit.archive 2
notifications.sms-vip 1
# After removing all three audit.all E2E bindings and publishing again:
returned 312 NO_ROUTE exchange=sales.events key=sales.oder.placed.v15. Kafka
با KAFKA_BROKERS ابتدا topics و سپس consume را اجرا کنید. یک record با header نوع placed و یک paid به topic مشترک بدهید؛ اولی handler انبار و دومی filter را طی میکند. topic جدید matching regex پس از metadata refresh دیده میشود. خطای handler باید بدون commit باعث توقف شود. kafka-topics.sh --describe --topic sales.order.state.v1 باید compact را نشان دهد؛ برای رکورد placed با key برابر o-42 انتظار reserve stock for o-42 داریم و paid خروجی ندارد. ایجاد billing.refund.events.v1 دامنهٔ regex fan-in را نشان میدهد.
6. Redis
با REDIS_ADDR نمونه را اجرا کنید؛ روی اجرای تازه، چهار group قبل از publish وجود دارند و stream پیامک یک entry میگیرد. با قطع بین XADD و XACK، منبع pending میماند؛ replay ممکن است دو خروجی با _source_id یکسان بسازد. recovery PEL را از فصل acknowledgment پیاده کنید؛ > بهتنهایی pending قدیمی را نمیخواند.
فرمانهای مشاهدهٔ گروه، مقصد و pending بهترتیب چنیناند؛ وضعیت pending به محل توقف نمونه بستگی دارد:
# expected, not run
XINFO GROUPS t:{acme}:sales.order.events
# fulfilment, billing, analytics, notification-router
XRANGE t:{acme}:notifications.sms.events - +
# forwarded entry with _source_stream and _source_id
XPENDING t:{acme}:sales.order.events notification-router
# successful ack: 0 pending; interruption before XACK: source remains pendingبدفهمیهای رایج
| باور | واقعیت |
|---|---|
| Topic همهجا یک چیز است | exchange type با log فرق دارد |
| worker بیشتر یعنی fan-out | اشتراک مستقل لازم است |
| Direct فقط unicast است | چند صف exact-match نسخه میگیرند |
| wildcard داخل واژه کار میکند | ستاره یک واژهٔ کامل است |
| confirm یعنی business consumer گرفت | unroutable هم confirm میشود |
| AE typo را همیشه میگیرد | catch-all مسیر audit آن را پنهان میکند |
| چند binding یعنی duplicate | در یک routing، صف deduplicate میشود |
| Kafka topic را rename یا کوچک میکنیم | rename مستقیم و کاهش partition ممکن نیست؛ topic تازه و migration لازم است |
| Redis group یعنی partition ذخیره | stream همچنان یک کلید است |
| MULTI خطا را rollback میکند | خطای runtime میتواند با اجرای فرمانهای بعدی همراه شود |
| SKIP LOCKED یعنی ترتیب aggregate | چند relay میتوانند از هم سبقت بگیرند |
| prefix یعنی امنیت | ACL و principal مستقل لازماند |
| پیام بیمقصد حتماً خطای publish میدهد | بدون mandatory یا AE مؤثر ممکن است silently drop شود |
| یک topic هر event type همیشه تمیزتر است | ترتیب بین نوعهای یک aggregate از دست میرود |
| Kafka برای هر consumer payload را filter میکند | broker partition را میدهد؛ filtering کار consumer است |
| onQueue در package RabbitMQ همیشه نام صف مصرف است | با exchange تنظیمشده، routing key میشود؛ worker صفی را میخواند که bind کرده است |
چکیده
| موضوع | یادآوری |
|---|---|
| fan-out | صف مستقل در RabbitMQ یا consumer group مستقل در Kafka/Redis |
| تقسیم کار (Load sharing) | چند consumer روی یک صف یا عضوهای یک group |
| fan-in | ورودیهای متعدد بدون ترتیب سراسری یا تجمیع ضمنی |
| topic exchange | واژههای نقطهجدا، حداکثر 255 بایت؛ * یک و # صفر یا چند واژه |
| direct | برابری کامل کلید، با امکان چند صف مطابق |
| قرارداد نام | <domain>.<entity>.<event>.v<N>؛ نام consumer وارد آن نمیشود |
| headers | key نادیده گرفته میشود؛ x-match برابر all/any یا گونههای with-x |
| Default exchange | key برابر نام صف؛ بدون binding دلخواه و بدون AE |
| E2E | exchange.bind؛ در یک routing هر صف یک نسخه، internal برای exchange داخلی |
| AE | فقط وقتی مسیر نهایی نیست؛ binding با # ممکن است نبود مصرفکنندهٔ کسبوکار را پنهان کند |
| mandatory | basic.return با 312 NO_ROUTE؛ handler و انتظار نتیجه لازم است، AE موفق آن را برآورده میکند |
| DLX | اشارهگر queue argument/policy؛ جزئیات در DLQ |
| Kafka | ترتیب در partition یک topic؛ eventهای نیازمند ترتیب مشترک، topic و key مشترک؛ per type برای firehose مستقل |
| نام Kafka | حداکثر 249 نویسهٔ [a-zA-Z0-9._-]؛ rename ندارد، ترکیب نامهای متناظر با dot/underscore خطر برخورد metrics دارد؛ auto-create خاموش |
| compact | cleanup.policy=compact برای آخرین state، نه حذف فوری تاریخچه؛ tombstone یعنی مقدار null |
| چندمستأجری Kafka | prefix سلسلهمراتبی، prefixed ACL با KIP-290 و quota |
| Redis | stream key مسیر است؛ stream هر نوع aggregate و shard به N کلید برای hot path |
| hash tag | t:{tenant}:... برای همslot کردن، با هزینهٔ hotspot |
| Laravel | onConnection اتصال، onQueue صف یا routing key؛ Queue::route و Queue::forward تصمیم را مرکزی میکنند |
| router | publish موفق، سپس ack؛ احتمال duplicate |
| topology | consumer مالک صف/binding است؛ policy برای تنظیم mutable و کد/definitions در version control |
خودآزمایی: پرسش و پاسخ
- حیاتی تقریباً در هر مصاحبه پرسیده میشود
- مهم پرتکرار؛ در سطح senior انتظار میرود
- تکمیلی عمق بیشتر؛ تمایز ایجاد میکند
۱ — دو binding مطابق روی یک صف چند کپی میدهند؟ حیاتی
پاسخ
پاسخ: در یک routing یک کپی؛ انتشار دوبارهٔ producer مسئلهٔ جداست.
۲ — آیا audit.events.# خود audit.events را میگیرد؟ حیاتی
پاسخ
پاسخ: بله؛ # میتواند صفر واژه باشد.
۳ — چرا AE روی sales.events با audit catch-all ساکت است؟ تکمیلی
پاسخ
پاسخ: پیام دستکم به audit route شده و unroutable نیست.
۴ — آیا x-match=any متمم SMS و VIP است؟ مهم
پاسخ
پاسخ: خیر؛ OR روی شرطهای نوشتهشده است. برای بقیه AE یا router صریح لازم است.
۵ — customer-created و address-changed چرا topic مشترک میخواهند؟ حیاتی
پاسخ
پاسخ: اگر ترتیب لازم باشد باید topic و key مشترک داشته باشند؛ ترتیب میان topicها وجود ندارد.
۶ — افزایش partition چه خطری برای key دارد؟ مهم
پاسخ
پاسخ: hash ممکن است به partition تازه برود؛ پیامهای قبل و بعد دیگر در یک ترتیب واحد نیستند.
۷ — نامگذاری چگونه enforce میشود؟ مهم
پاسخ
پاسخ: auto-create خاموش، CreateTopicPolicy و ACL مناسب؛ convention مکتوب بهتنهایی کافی نیست.
۸ — چرا group در $ بعد از publish پیام اول را نمیبیند؟ مهم
پاسخ
پاسخ: $ نشانگر را روی انتهای فعلی میگذارد؛ group را قبل از publish بسازید یا برای replay از 0 شروع کنید.
۹ — چرا شکست handler نباید با commit batch ادامه یابد؟ مهم
پاسخ
پاسخ: offset از پیام شکستخورده عبور میکند. توقف قبل از commit و handler تکرارپذیر لازم است.
۱۰ — خطای XADD داخل MULTI چه ارتباطی با XACK دارد؟ حیاتی
پاسخ
پاسخ: Redis rollback عمومی ندارد؛ XACK ممکن است اجرا شود. مثال این فصل publish-before-ack و dedup را انتخاب کرده است.
واژهنامه
| اصطلاح | معنا |
|---|---|
| Exchange / مبادلهگر | انتخاب مقصد RabbitMQ بدون ذخیرهٔ backlog |
| Binding / اتصال | رابطهٔ source و destination با binding key |
| Routing key / کلید مسیریابی | آدرس انتخابشده توسط ناشر |
| Binding key / کلید اتصال | کلید یا pattern ثبتشده در binding که با routing key مقایسه میشود |
| Direct exchange / مستقیم | تطبیق کامل کلید |
| Fanout / پخش همگانی | نسخه برای تمام مقصدهای bindشده |
| Topic exchange / موضوعی | تطبیق واژهها با * و # |
| Headers exchange / سرآیندی | انتخاب بر اساس ویژگیهای مستقل |
| x-match، any-with-x، all-with-x | ترکیب شرطهای header و تصمیم دربارهٔ نامهای x- |
| Default exchange / پیشفرض | exchange نامخالی با binding خودکار نام صف |
| amq.direct / amq.topic / amq.fanout / amq.headers | exchangeهای ازپیشساخته |
| exchange-to-exchange / exchange.bind | اتصال جهتدار exchangeها، بدون republication |
| Internal / داخلی | مقصدی که client مستقیم در آن publish نمیکند |
| Alternate exchange / alternate-exchange | مسیر جایگزین هنگام نبود مقصد |
| mandatory / NO_ROUTE | بازگشت پیام بیمقصد به publisher |
| dead-letter-exchange / DLX | مسیر صف برای پیام مرده؛ policy بدون x-، آرگومان با x- |
| x-consistent-hash / hash-header | انتخاب مقصد با hash و وزن binding |
| x-modulus-hash / rabbitmq_sharding | hash modulo مقصدها و مدیریت shardهای classic |
| Local random / تصادفی محلی | انتخاب یک صف روی node محلی |
| Vhost / فضای مجازی | namespace و محدودهٔ permission در RabbitMQ |
| Topic authorisation / مجوز کلید | بررسی routing key در topic exchange |
| Definitions / export_definitions | تعریف قابلخروجیگرفتن topology، نه محتوای پیامها |
| Policy / سیاست | تنظیم سروری mutable برای resourceهای matching |
| auto-delete / حذف خودکار | lifecycle وابسته به binding یا consumer با شرایط محصول |
| quorum / حدنصاب | نوع صف تکثیرشدهٔ RabbitMQ |
| per event type / بهازای نوع رویداد | topic جدا با استقلال ترتیب از نوع دیگر |
| per aggregate / بهازای نوع aggregate | eventهای مرتبط در topic مشترک و key شناسهٔ entity |
| bounded context / بافت محدود | مرز مدل و مالکیت دامنه |
| partition / پارتیشن | واحد ترتیب و تقسیم log در Kafka |
| cleanup.policy / compact | سیاست retention یا نگهداری آخرین state |
| Tombstone / نشان حذف | رکورد مقدار null برای حذف state کلید |
| prefixed ACL / KIP-290 | مجوز روی نام resourceهای دارای prefix |
| CreateTopicPolicy | افزونهٔ enforce قرارداد ساخت topic |
| auto.create.topics.enable | تنظیم ساخت ضمنی موضوع ناموجود |
| Topic sprawl / تراکم موضوع | تکثیر بیرویهٔ topicها و هزینهٔ عملیات |
| ConsumeRegex / اشتراک الگویی | خواندن موضوعهای matching regex |
| Kafka topic / موضوع Kafka | log نامدار، partitionشده و تکثیرشده |
| Redis stream / جریان Redis | log افزایشی ذخیرهشده در یک key |
| Consumer group / گروه مصرفکننده | اشتراک با cursor مستقل و تقسیم کار میان اعضا |
| Hash tag / برچسب hash | بخش braceدار کلید که slot را تعیین میکند |
| Hash slot / شیار | یکی از 16384 جایگاه Redis Cluster |
| CROSSSLOT | خطای فرمان چندکلیدی میان slotها |
| XREADGROUP / XADD / XACK | خواندن گروهی، افزودن entry، تأیید پردازش |
| Content-Based Router / مسیریاب محتوامحور | انتخاب کانال از metadata یا محتوای پیام |
| Message Filter / پالایهٔ پیام | حذف پیام نامربوط از مسیر مصرف |
| Publish-Subscribe Channel / انتشارـاشتراک | نسخهٔ مستقل برای هر subscriber |
| Recipient List / فهرست گیرندگان | انتخاب مجموعهای از مقصدها |
| Fan-out / انتشار چندگیرندهای | یک ورودی به چند اشتراک |
| Fan-in / چند ورودی | خواندن چند کانال بدون aggregation ضمنی |
| onQueue / onConnection | انتخاب مسیر و backend صف Laravel |
| Queue::route / Queue::forward | قواعد پیشفرض job و هدایت مجدد صف |
| exchange_routing_key | تبدیل queue انتخابی به کلید انتشار package RabbitMQ |
| laravel-kafka / withKafkaKey | package Kafka و تنظیم partition key |
| Multi-tenant / چندمستأجری | تقسیم routing و مجوز بر اساس tenant |
| PRECONDITION_FAILED | اعلان resource با مشخصات ناسازگار |
| Idempotent / تکرارپذیر بدون اثر اضافی | اجرای دوباره نتیجهٔ کسبوکار را دوباره اعمال نمیکند |
| محدودیت نام Kafka / Name limit | حداکثر 249 نویسهٔ مجاز برای نام topic |
منابع
- RabbitMQ, Exchanges (source markdown): https://github.com/rabbitmq/rabbitmq-website/blob/main/docs/exchanges.md
- RabbitMQ, AMQP 0-9-1 Model Explained: https://github.com/rabbitmq/rabbitmq-website/blob/main/tutorials/amqp-concepts/index.md
- RabbitMQ, Tutorial five: Topics (Go): https://github.com/rabbitmq/rabbitmq-website/blob/main/tutorials/tutorial-five-go.md
- RabbitMQ, Exchange to Exchange Bindings: https://github.com/rabbitmq/rabbitmq-website/blob/main/docs/e2e.md
- RabbitMQ, Alternate Exchanges: https://github.com/rabbitmq/rabbitmq-website/blob/main/docs/ae.md
- RabbitMQ, Publishers (unroutable messages): https://github.com/rabbitmq/rabbitmq-website/blob/main/docs/publishers/index.md
- RabbitMQ, Consumer Acknowledgements and Publisher Confirms: https://github.com/rabbitmq/rabbitmq-website/blob/main/docs/confirms.md
- RabbitMQ, Dead Letter Exchanges: https://github.com/rabbitmq/rabbitmq-website/blob/main/docs/dlx.md
- RabbitMQ, Definitions: https://github.com/rabbitmq/rabbitmq-website/blob/main/docs/definitions.md
- RabbitMQ, Virtual Hosts: https://github.com/rabbitmq/rabbitmq-website/blob/main/docs/vhosts.md
- RabbitMQ, Access Control (topic authorisation): https://github.com/rabbitmq/rabbitmq-website/blob/main/docs/access-control.md
- RabbitMQ, Local Random Exchange: https://github.com/rabbitmq/rabbitmq-website/blob/main/docs/local-random-exchange.md
- RabbitMQ consistent-hash exchange README: https://github.com/rabbitmq/rabbitmq-server/blob/main/deps/rabbitmq_consistent_hash_exchange/README.md
- RabbitMQ sharding plugin README: https://github.com/rabbitmq/rabbitmq-server/blob/main/deps/rabbitmq_sharding/README.md
- Apache Kafka, Multi-Tenancy: https://github.com/apache/kafka/blob/trunk/docs/operations/multi-tenancy.md
- Apache Kafka, Design (log compaction): https://github.com/apache/kafka/blob/trunk/docs/design/design.md
- Apache Kafka, Basic Kafka Operations: https://github.com/apache/kafka/blob/trunk/docs/operations/basic-kafka-operations.md
- Apache Kafka, Authorization and ACLs: https://github.com/apache/kafka/blob/trunk/docs/security/authorization-and-acls.md
- Apache Kafka,
Topic.java(name rules): https://github.com/apache/kafka/blob/trunk/clients/src/main/java/org/apache/kafka/common/internals/Topic.java - KIP-290, Support for Prefixed ACLs: https://cwiki.apache.org/confluence/display/KAFKA/KIP-290%3A+Support+for+Prefixed+ACLs
- Martin Kleppmann, Should You Put Several Event Types in the Same Kafka Topic? (2018): https://www.confluent.io/blog/put-several-event-types-kafka-topic/
- Redis, Redis Streams: https://redis.io/docs/latest/develop/data-types/streams/
- Redis, Cluster specification (hash tags): https://redis.io/docs/latest/operate/oss_and_stack/reference/cluster-spec/
- Enterprise Integration Patterns, Content-Based Router: https://www.enterpriseintegrationpatterns.com/patterns/messaging/ContentBasedRouter.html
- Enterprise Integration Patterns, Message Filter: https://www.enterpriseintegrationpatterns.com/patterns/messaging/Filter.html
- Enterprise Integration Patterns, Publish-Subscribe Channel: https://www.enterpriseintegrationpatterns.com/patterns/messaging/PublishSubscribeChannel.html
- Laravel 13, Queues: https://laravel.com/docs/13.x/queues
- vladimir-yuldashev/laravel-queue-rabbitmq README: https://github.com/vyuldashev/laravel-queue-rabbitmq
- mateusjunges/laravel-kafka docs: https://github.com/mateusjunges/laravel-kafka/tree/master/docs
- php-amqplib
AMQPChannel: https://github.com/php-amqplib/php-amqplib/blob/master/PhpAmqpLib/Channel/AMQPChannel.php - amqp091-go: https://github.com/rabbitmq/amqp091-go
- franz-go: https://github.com/twmb/franz-go
- go-redis: https://github.com/redis/go-redis
- Redis transactions, runtime errors: https://redis.io/docs/latest/develop/using-commands/transactions/