Skip to content

Broker Comparison & Decision Guide ​

"Many systems claim to provide “exactly-once” delivery semantics, but it is important to read the fine print, because sometimes these claims are misleading (i.e. they don’t translate to the case where consumers or producers can fail, cases where there are multiple consumer processes, or cases where data written to disk can be lost)." — مستندات Apache Kafka، Design، بخش "Message Delivery Semantics" (4.2)

خلاصه: یک ماتریس کنار‌هم برای RabbitMQ، Kafka و Redis Streams (به‌علاوهٔ NATS JetStream، Pulsar، SQS/SNS، Google Pub/Sub و driverهای database و sqs در Laravel) و یک راهنمای تصمیم که روی آن سوار است. تمرکز: انتخاب، مهاجرت و برگشت‌پذیر نگه‌داشتن انتخاب، نه اینکه هر broker از درون چطور کار می‌کند. هدف یادگیری: بعد از این صفحه می‌توانید در پنج دقیقه برای یک بار کاری broker انتخاب کنید، با ماتریس از انتخابتان دفاع کنید، ضدتصمیم‌ها (Anti-decision) را بشناسید و یک درز Publisher/Consumer در کد بگذارید تا انتخاب قابل تغییر بماند.

این صفحهٔ تصمیم در گروه Brokers است و درونیات را دوباره درس نمی‌دهد: RabbitMQ، Kafka و Redis Streams و Pub/Sub سه صفحهٔ عمیق هستند و سایر brokerها NATS JetStream، Pulsar، SQS/SNS و Google Pub/Sub را مرور می‌کند. هر خانهٔ جدول‌ها یک عبارت کوتاه است؛ سازوکارش را از لینک همان موضوع بخوانید.

نقشهٔ صفحه ​

دنبال چه می‌گردیدکجا بروید
«برای بار کاری من کدام broker؟» در یک دقیقههمه‌چیز در یک دقیقه، جدول‌های تصمیم
ماتریس ۴۰ ردیفی کنار‌همماتریس مقایسه
ستون‌های NATS، Pulsar، SQS/SNS، Pub/Sub و driverهای Laravelستون‌های دیگر
چرا مقایسه‌ها گمراه می‌کنندچرا مقایسه‌ها گمراه می‌کنند
رفتن از Redis به RabbitMQ و Kafka یا اجرای دو تامهاجرت و همزیستی
هزینهٔ self-host در برابر managedطرح مدل هزینه
«اصلاً در Laravel broker لازم دارم؟»پرسش Laravel
چه نکنیمضدتصمیم‌ها
یک interface با سه adapter در Go و LaravelGo، Laravel
هر broker چطور «پذیرفته، تحویل، پردازش» را ثابت می‌کندتفاوت‌های اجرا در brokerها
از مونولیت تا چندمنطقه‌ایدر معماری
آزمایشگاه مقایسه (expected, not run)آزمایشگاه

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

جدول ۱: فلسفه. هر broker اول به یک پرسش دیگر جواب می‌دهد.

RabbitMQKafkaRedis Streams
ایدهٔ اصلیbroker باهوش پیام را به queueها مسیر می‌دهد؛ پیام با ack پاک می‌شودlog افزایشی، تکه‌تکه (Partition) و replicate شده؛ position دست consumer استlog افزایشی داخل Redis با consumer group
بهترین درtaskها، commandها، routing، retry، delay، request/replyevent log، replay، خواننده‌های زیاد، stream processing، حجم بالاstreamهای کوچک و سریع در stackی که Redis دارد
ضعیف‌ترین درنگهداری بلند و replay میلیون‌ها event (از streamهایش استفاده کنید)retry تک‌پیام، delay، priority، راه‌اندازی کوچکپایداری پیش‌فرض، دادهٔ بزرگ‌تر از RAM
شما اجرا می‌کنیدیک cluster brokercluster با partition، retention و rebalanceRedis به‌علاوهٔ persistence و failoverی که خودتان تنظیم می‌کنید

جدول ۲: بار کاری به انتخاب اول.

بار کاریانتخاب اولچرا
کارهای پس‌زمینه داخل یک برنامهٔ Laraveldriver database یا redis در Laravelزیرساخت جدید نمی‌خواهد
صف task با retry، priority، delay، DLQ بین سرویس‌هاRabbitMQ (quorum queues)DLX، delivery limit، priority و routing داخلی دارد
event bus که چند تیم مشترکش می‌شوندKafka (یا Pulsar)consumer groupهای مستقل، retention
event log که replay می‌کنیدKafka، RabbitMQ streams، NATS JetStream، Pulsarخواندن بدون حذف (non-destructive)
stream processing (join، window)Kafkaاکوسیستم Kafka Streams / Flink (stream processing)
request/replyRabbitMQ یا NATSreply-to و correlation بومی‌اند (request-reply)
IoT / MQTTRabbitMQ (افزونهٔ MQTT)، NATS یا IoT hub managedپروتکل
fan-out بین منطقه‌ها (cross-region)geo-replication در Pulsar، mirroring در Kafka، SNS/SQS، Pub/Subreplication بین منطقه‌ها قابلیت است، نه اسکریپت
serverlessSQS/SNS (AWS)، Pub/Sub (GCP)managed و trigger آماده

جدول ۳: پنج پرسشی که بیشتر موردها را تعیین می‌کنند.

پرسشاگر بلهاگر نه
consumer جدید باید تاریخچه را بخواند؟Log: Kafka، Pulsar، JetStream، RabbitMQ streamsQueue: RabbitMQ، SQS
یک پیام کند باید تنها و بعداً retry شود؟Queue با ack تک‌پیام و DLQLog کافی است
اوج پایدار بالای حدود ۱۰٬۰۰۰ پیام در ثانیه است؟Log با partitionهرچیزی جواب می‌دهد؛ با ops انتخاب کنید
الان اجرایش می‌کنید و به persistenceاش اعتماد دارید؟اول از همان استفاده کنیدبرای یک قابلیت اضافه‌اش نکنید
سرویس managed قابل‌قبول است؟هزینهٔ managed را مقایسه کنید (مدل هزینه)زمان اپراتور را صادقانه بشمارید

چرا مقایسه‌ها گمراه می‌کنند ​

به زبان ساده: پست‌های «RabbitMQ vs Kafka» اداره‌پست را با کتابخانه مقایسه می‌کنند. اولی هر نامه را به یک نفر می‌دهد و فراموشش می‌کند؛ دومی همهٔ نامه‌ها را روی قفسه نگه می‌دارد و هر کس از هر نقطه می‌خواند.

بدفهمی رایج: «یک broker سریع‌تر وجود دارد.» توان عملیاتی (Throughput) به اندازهٔ پیام، batching، تنظیم ack، replication، fsync و client بستگی دارد. عددی بدون این‌ها تبلیغ است.

مرز هم جابه‌جا می‌شود. مقایسهٔ CloudAMQP که نظر vendor است (خودش RabbitMQ میزبانی می‌فروشد) در ۷ نوامبر ۲۰۲۶ به‌روز شده و می‌گوید: "Both now cover some of what the other does: RabbitMQ has streams for replay, and Kafka has share groups for queue-style work." صفحهٔ design در Kafka 4.2 نیمهٔ Kafka را تأیید می‌کند: share groupها "offer an alternative to consumer groups, particularly when applications require finer-grained sharing of partitions and records". مرور Confluent (آن هم vendor) می‌نویسد "RabbitMQ messages are stored in memory, while Kafka messages are stored on disk"، در حالی که راهنمای خود RabbitMQ می‌گوید پیام persistent در queue durable بعد از "persisting to disk" confirm می‌شود. از صفحه‌های vendor برای فهرست کاربردها استفاده کنید و واقعیت‌ها را با مستندات اصلی بسنجید. قاعده‌های این صفحه:

قاعدهپیامد
واقعیت‌ها (حد، پیش‌فرض، نام پروتکل) از مستندات خود محصول می‌آیند و تاریخ دارندجایی که نسخه مهم است در خانه ذکر شده
Throughput و latency «رده» هستند، نه عددقبل از تصمیم روی payload خودتان benchmark بگیرید (آزمایشگاه)
قابلیتی که افزونه یا پلن پولی می‌خواهد همان‌طور نام برده می‌شوددر خانه‌ها «plugin» و «managed only» می‌بینید
هرچه از منبع اصلی خوانده نشده «check» داردصفحه‌های quota در Pub/Sub به fetch خودکار 403 می‌دهند، پس عدد اندازهٔ پیام علامت خورده است

سازوکار: ماتریس مقایسه ​

سه broker، چهل ردیف. ردیف‌ها گروه‌بندی شده‌اند: مدل (۱ تا ۵)، تضمین‌ها (۶ تا ۱۳)، مصرف و routing (۱۴ تا ۲۱)، نگهداری و اندازه (۲۲ تا ۲۸)، پلتفرم (۲۹ تا ۴۰). یک ردیف را بخوانید و برای سازوکارش لینک را دنبال کنید.

جدول A: RabbitMQ، Kafka، Redis Streams حیاتی ​

#DimensionRabbitMQKafkaRedis Streams
1ModelExchanges route to queues; queue types: classic, quorum, streamTopic of partitions, each an append-only logStream key (a log) with consumer groups
2Storage structurePer-queue message store; streams are a logSegment files per partitionIn-memory radix tree, persisted by AOF/RDB
3Unit of consumptionOne delivery, acked individuallyA record at an offset; commit moves a positionOne entry, acked individually in the group's pending list
4Ordering scopePer queue (single consumer); competing consumers and requeue can reorderPer partitionPer stream
5Ordering key storySingle active consumer or consistent-hash exchangePartition keyOne stream per key, or one stream
6Default delivery guaranteeAt-least-once with publisher confirms and manual ackAt-least-once (idempotent producer removes producer-retry duplicates)At-least-once via group pending list
7Exactly-once storyNone end to end; idempotent consumersTransactions give it inside Kafka; external effects need idempotencyNone; idempotent consumers (Redis 8.6 adds idempotent production, check your version)
8"Accepted" signalPublisher confirm (plus mandatory return)Produce callback with partition and offset (acks=all)XADD reply with entry id
9"Processed" signalbasic.ackCommitted offset (position)XACK
10PersistencePersistent messages in durable queues; quorum and stream queues always replicatedAlways on disk; flush policy is OS-driven by defaultOff by default unless AOF/RDB configured
11Durability knobQuorum queue (majority), confirmsacks=all, min.insync.replicas, replication factorAOF appendfsync, WAIT
12ReplicationRaft-based quorum queues; streams replicatedLeader and follower per partition, ISRAsynchronous primary/replica
13FailoverQuorum leader electionLeader election per partition (KRaft controller)Sentinel or Cluster promote a replica; can lose acked writes
14Consumer modelPush (basic.consume) with prefetch, or pull (basic.get)Pull with fetch batchesPull with blocking XREADGROUP
15Parallelism limitMany consumers per queueConsumers per group up to partition count (share groups lift it)Many consumers per group
16Fan-outBind several queues to an exchangeSeveral consumer groups on one topicSeveral groups on one stream
17RoutingDirect, topic, fanout, headers exchangesTopic and key onlyStream name only
18PrioritiesClassic and quorum queues support themNoneNone
19Delay / schedulingQuorum queues since 4.4 (x-opt-delivery-time); TTL + DLX earlierNone built inNone built in (sorted set pattern)
20RetryRequeue, delivery limit (default 20 on quorum queues since 4.0), DLX loopsClient side: retry topicsClient side: XPENDING + XAUTOCLAIM
21DLQBuilt in (DLX, at-least-once dead-lettering on quorum)Convention: a dead-letter topic you produce toConvention: another stream
22RetentionQueues: until acked or TTL; streams: size/ageTime/size, or compaction by key; tiered storage for old segmentsUntil trimmed (MAXLEN, MINID); bounded by RAM
23ReplayStreams onlyYes, seek to any offsetYes, read from any id
24Key compactionNoYes (cleanup.policy=compact)No
25Message sizemax_message_size default 16 MiB, max 512 MiB (config doc)max.message.bytes default 1048588Entry is a hash of fields; keep small, RAM-bound
26Throughput classMedium (per-message bookkeeping)High (batched sequential I/O)Medium to high, memory-bound
27Latency classLowLow to medium (batching adds latency)Lowest
28BackpressureConsumer prefetch, publisher flow control, memory alarmsConsumer pulls at its pace; broker quotasNone built in; trim policy and XLEN monitoring
29Multi-tenancyVirtual hosts with per-vhost permissionsTopics, ACLs, client quotasKey prefixes, ACLs, logical DBs (not in Cluster)
30ProtocolsAMQP 0-9-1, AMQP 1.0, MQTT 5.0 (plugin), STOMP, streams protocolKafka protocol (plus HTTP REST proxies as add-ons)RESP
31Schema supportNone built in (content-type header)Not in Apache Kafka; Confluent Schema Registry or ApicurioNone
32TransactionsAMQP tx.select on a channel (slow)Producer transactions and read_committed (KIP-98)MULTI/EXEC, Lua scripts
33Ops complexityMedium: cluster, queue types, memory/disk alarmsHigh: partitions, retention, rebalances, controller quorumLow if Redis already runs; failover is yours
34Scaling outMore queues and nodes; a single queue lives on its replicasAdd partitions and brokersCluster shards by key; one stream is on one shard
35Hosting optionsSelf-host, CloudAMQP, Amazon MQ, Kubernetes operatorSelf-host, Confluent Cloud, Amazon MSK, AivenSelf-host, Redis Cloud, ElastiCache, Memorystore
36LicensingApache 2.0 and MPL 2.0 (open source)Apache 2.0Check the license of your Redis version; Valkey is the BSD fork
37Laravel supportPackage vladimir-yuldashev/laravel-queue-rabbitmqPackage mateusjunges/laravel-kafka (needs ext-rdkafka)Redis facade; built-in redis driver uses lists, not streams
38Go client maturityamqp091-go (official RabbitMQ team)franz-go (pure Go, active), kafka-gogo-redis (mature, typed)
39ObservabilityManagement UI, Prometheus plugin, queue depth, unackedConsumer lag per partition, JMX metricsXINFO, XPENDING, INFO
40SecurityTLS, SASL, per-vhost configure/write/read permissionsTLS, SASL (PLAIN, SCRAM, GSSAPI, OAUTHBEARER), ACLsTLS, ACLs, AUTH

ردیف‌های ۶ تا ۱۳ در delivery guarantees و acknowledgment باز شده‌اند؛ ۴ و ۵ در ordering؛ ۱۴ و ۱۵ در competing consumers؛ ۱۷ و ۱۸ در routing؛ ۱۹ تا ۲۱ در retry و delay و DLQ؛ ۲۸ در backpressure؛ ۳۱ در schema evolution؛ ۳۹ در observability؛ ۴۰ در security.

RoutingReplayThroughputLatencyOps easeDelay/DLQRabbitMQKafkaRedis Streams1 = weak, 5 = strongJudgement, not a benchmark

رادار شش محور ماتریس را به یک شکل فشرده می‌کند. این قضاوت از روی جدول بالاست، نه benchmark: RabbitMQ در routing و delay/DLQ پهن است، Kafka در replay و throughput بلند، و Redis Streams در latency و سادگی قوی‌تر.

ستون‌های دیگر مهم ​

عمداً کوتاه است؛ جزئیات در سایر brokerها. «check» یعنی عددی که اینجا از منبع اصلی نخوانده‌ایم.

#DimensionNATS JetStreamPulsarSQS / SNSGoogle Pub/SubLaravel database / sqs drivers
1ModelStreams capture subjects; consumers read themTopics with subscriptions; segment storageSQS queue; SNS topic fans out to queuesTopic and subscriptionsA jobs table; an SQS queue
2OrderingPer streamPer partition (Key_Shared per key)SQS FIFO per message group; Standard best effortPer ordering key when enabledTable: by id, not guaranteed; SQS Standard unordered
3DeliveryAt-least-once with ack; Nats-Msg-Id dedup windowAt-least-once; transactionsStandard at-least-once; FIFO dedupAt-least-once; exactly-once delivery option per subscriptionAt-least-once (lock then delete)
4Persistence and replicationFile or memory storage; replicated in a clusterBookKeeper, replicatedManaged, multi-AZManaged, regionalYour database; SQS managed
5Consumer modelPull and push consumers; AckExplicit, AckAll, AckNoneExclusive, Failover, Shared, Key_Shared subscriptionsPoll with visibility timeout (default 30 s, max 12 h)Pull, push, streaming pull; ack deadlineWorker polls (queue:work)
6RoutingSubject wildcardsTopics, topic patternsSNS filter policies to SQSSubscription filtersNamed queues, priority order
7DelayNot a core feature (check)Delayed delivery on Shared subscriptionsSQS delay up to 15 minNot a core feature (check)Laravel delay(); SQS capped at 15 min
8DLQMaxDeliver and advisoriesRetry letter and dead letter topicsRedrive policyDead-letter topicfailed_jobs table
9Retention and replayLimits, work queue or interest policies; replayRetention plus tiered storage; seekSQS: 4 days default, 60 s to 14 days, no replayDefault 7 days, up to 31 days; seek needs retained acked messagesUntil processed; no replay
10Message sizemax_payload default 1 MB (config up to 64 MB)Default 5 MB1 MiB (larger via S3 extended client, up to 2 GB)Check the quotas pageRow size / 1 MiB
11ThroughputHigh, small messagesHighStandard: very high; FIFO: 300 TPS per partition per API (higher with high-throughput mode)High, autoscalingLow to medium
12Multi-tenancyAccountsTenants and namespaces (first class)AWS accounts and IAMProjects and IAMApplication level
13ProtocolsNATS protocol, MQTT support (check)Pulsar protocolHTTPS APIgRPC and RESTn/a
14Schema supportNone built inBuilt-in schema registryNoneTopic schemas (Avro, Protocol Buffers)None
15TransactionsBatch publish, no multi-stream tx (check)YesFIFO dedup onlyNone across topicsDatabase transaction (afterCommit)
16Ops complexityLow to mediumHigh (brokers plus BookKeeper)None (managed)None (managed)Lowest
17HostingSelf-host, Synadia CloudSelf-host, StreamNativeAWS onlyGCP onlyWherever your DB or AWS runs
18LicensingApache 2.0Apache 2.0Proprietary serviceProprietary serviceMIT (Laravel)
19LaravelNo first-party; use a clientNo first-partyBuilt in (sqs driver)Community packagesBuilt in
20Go clientnats.go (official)pulsar-client-go (official)AWS SDK v2cloud.google.com/go/pubsubn/a
21Observabilitynats CLI, monitoring endpointsAdmin API, PrometheusCloudWatchCloud Monitoringqueue:monitor, Horizon (redis)
22SecurityTLS, accounts, JWT/NKeysTLS, JWT, authorizationIAM, KMSIAM, CMEKDB permissions

واقعیت‌های بالا از صفحه‌های مستندات خود محصولات آمده که برای این فصل ذخیره شده‌اند: NATS JetStream، Pulsar messaging، SQS quotas، تعریف API در Pub/Sub و Laravel queues. سایت مستندات Google به fetch خودکار 403 داد، پس retention و exactly-once در Pub/Sub از تعریف API می‌آید و عدد اندازهٔ پیامش «check» مانده است.

کاتالوگ مفهوم‌ها ​

صف در برابر log حیاتی ​

به زبان ساده: صف (Queue) پیام را بعد از اینکه کسی رسیدگی کرد فراموش می‌کند؛ log (Log) آن را نگه می‌دارد و فقط یادش می‌ماند هر خواننده کجاست.

بدفهمی رایج: «log فقط یک صف است که پیام را بیشتر نگه می‌دارد.» نه: در log «انجام شد» برای هر پیام وجود ندارد. خواننده یک position را جلو می‌برد، پس بدون سازوکار اضافه نمی‌شود یک رکورد خراب را تنها retry کرد.

تعریف: در brokerهای queue (RabbitMQ classic/quorum، SQS) هر delivery ack می‌شود و بعد حذف. در brokerهای log (Kafka، Pulsar، JetStream، RabbitMQ streams، Redis Streams) رکوردها طبق سیاست نگه داشته می‌شوند و consumerها position دارند. Redis Streams وسط است: entry می‌ماند ولی group برای هر entry ack جدا را در pending list ردیابی می‌کند.

Queue (RabbitMQ quorum queue)               Log (Kafka partition)
1 publish m1, m2, m3                        1 produce r0, r1, r2
2 consumer A receives m1                    2 group G reads r0
3 A acks m1  -> m1 deleted                  3 G commits offset 1  -> r0 stays on disk
4 A fails m2 -> m2 requeued, retried alone  4 G fails r1  -> G stops at r1 (no per-record nack)
5 a new consumer sees only m2, m3           5 a new group reads r0, r1, r2 from the start

سناریوی واقعی: ایمیل تأیید سفارش صف است (هر کدام یک بار انجام می‌شود، پیام سمی به DLQ می‌رود). «OrderPlaced» log است (billing، shipping و analytics هر کدام می‌خوانند و سرویس تازهٔ شش ماه دیگر می‌خواهد از روز اول بازسازی کند).

نیازQueueLog
retry و DLQ برای هر پیامبومیخودتان می‌سازید (retry topic)
consumer جدید تاریخچه را بخواندنهبله
خواننده‌های مستقل زیادqueue بیشتر bind کنیدgroup اضافه کنید
حجم ذخیره با چه رشد می‌کندbacklogپنجرهٔ retention

چطور استفاده کنیم: با دو ردیف اول انتخاب کنید. اگر هر دو لازم است، log را برای جریان واقعیت‌ها و queue را برای کاری که از آن‌ها بیرون می‌آید به کار ببرید (EDA).

تضمین تحویل در برابر اثبات حیاتی ​

به زبان ساده: «at-least-once» قولی دربارهٔ retry است؛ دربارهٔ اینکه اثر جانبی شما انجام شد چیزی نمی‌گوید.

بدفهمی رایج: «publisher confirm / offset برگشتی / id در XADD یعنی پیام پردازش شد.» هرکدام فقط یعنی broker پذیرفت.

تعریف: برای هر پیام سه واقعیت هست: پذیرفته‌شده (accepted)، تحویل‌شده (delivered)، پردازش‌شده (processed). سومی را consumer با ack بعد از اثر جانبی ثابت می‌کند. قاعدهٔ RabbitMQ: "A consuming application should not acknowledge messages until it has done whatever it needs to do with them: recorded them in a data store, forwarded them on, or performed any other operation."

1 publisher  -> broker      publish
2 broker     -> publisher   confirm / offset / XADD id    (accepted)
3 broker     -> consumer    delivery                      (delivered)
4 consumer   -> database    INSERT the effect
5 consumer   -> broker      ack / commit / XACK           (processed)
-- crash between 4 and 5 => redelivery => the effect runs twice => needs an idempotent consumer

سناریوی واقعی: consumer پرداخت برای سرعت اول ack می‌زند، بعد crash می‌کند و شارژ بدون هیچ retry گم می‌شود. ترتیب برعکس: شارژ می‌کند، قبل از ack می‌میرد و دوباره شارژ می‌کند، مگر اینکه یک inbox تکراری را رد کند.

Brokerپذیرفته شدپردازش شد
RabbitMQConfirm؛ در quorum queue اکثریت replicaهاbasic.ack
Kafkacallback تولید با offset (acks=all)offset ثبت‌شده = offset بعدی برای خواندن
Redis Streamsid بازگشتی XADD روی primaryXACK ورودی pending را خالی می‌کند

چطور استفاده کنیم: سه adapter در Go و Laravel همین قرارداد را interface می‌کنند: Publish با «پذیرفته شد» برمی‌گردد و handler که nil برگرداند ack است. برنامه‌های راستی‌آزمایی هر broker در تفاوت‌های اجرا است.

واحد ترتیب مهم ​

به زبان ساده: هر broker «چیز کوچکی» را مرتب نگه می‌دارد، هیچ‌وقت «همه‌چیز» را.

بدفهمی رایج: «Kafka ترتیب را تضمین می‌کند.» ترتیب را در هر partition تضمین می‌کند. دو کلید که به partitionهای متفاوت hash شوند ترتیب متقابل ندارند.

تعریف: واحد ترتیب queue (RabbitMQ)، partition (Kafka)، stream (Redis Streams)، message group (SQS FIFO) و ordering key (Pub/Sub) است. چند consumer موازی روی یک واحد، بدون هماهنگی ترتیب را از دست می‌دهند (ordering).

Kafka, key = customer id, 3 partitions
1 order-1 (cust A) -> p0 offset 10
2 order-2 (cust B) -> p2 offset 4
3 order-3 (cust A) -> p0 offset 11    A's events stay ordered
-- B versus A: no relative order

سناریوی واقعی: دفتر کل (Ledger) ترتیب هر حساب را می‌خواهد نه ترتیب سراسری؛ پس شناسهٔ حساب کلید است (partition key در Kafka، MessageGroupId در SQS، ordering key در Pub/Sub).

چطور استفاده کنیم: موجودیتی را که ترتیب رویدادهایش مهم است انتخاب کنید و به واحد broker نگاشت کنید؛ هرگز به consumer قول «ترتیب سراسری» ندهید.

نگهداری و بازپخش مهم ​

به زبان ساده: retention تعیین می‌کند پیام تا کی روی قفسه می‌ماند؛ replay خواندن دوبارهٔ آن است.

بدفهمی رایج: «RabbitMQ می‌تواند replay کند.» queueهای classic و quorum نه؛ replay به RabbitMQ streams نیاز دارد. و XACK در Redis entry را پاک نمی‌کند؛ فقط trim پاک می‌کند.

تعریف: SQS پیام را به‌طور پیش‌فرض ۴ روز نگه می‌دارد (۶۰ ثانیه تا ۱۴ روز) و با DeleteMessage حذف می‌کند. Pub/Sub پیام ack‌نشده را پیش‌فرض ۷ روز نگه می‌دارد (۱۰ دقیقه تا ۳۱ روز) و ackشده‌ها را فقط با retain_acked_messages قابل replay می‌کند. Kafka بر اساس زمان/اندازه نگه می‌دارد یا بر اساس کلید compact می‌کند. JetStream بین limits، work queue و interest انتخاب می‌دهد.

1 Day 0   deploy consumer v1 (bug: drops field "currency")
2 Day 9   bug found
3 log broker: reset offset to day 0, run v2, rebuild the read model
4 queue broker: those messages are gone; restore from the database or the outbox

سناریوی واقعی: بازسازی ایندکس جستجو یا read model بعد از باگ؛ ممیزی اینکه یک سرویس چه eventهایی دیده است.

BrokerReplayمحدود به
RabbitMQ queuesخیرbacklog و TTL
RabbitMQ streamsبلهاندازه/سن
Kafkaبلهزمان/اندازه، دیسک
Redis StreamsبلهMAXLEN/MINID، RAM
SQSخیرحداکثر ۱۴ روز
Pub/Subبا seekحداکثر ۳۱ روز

چطور استفاده کنیم: نیاز replay را قبل از broker تعیین کنید؛ اگر جواب «بله، ماه‌ها» است، log (یا جدول outbox به‌عنوان منبع حقیقت) لازم است.

وزن عملیاتی مهم ​

به زبان ساده: ارزان‌ترین broker آن است که تیمتان ساعت ۳ بامداد بلد است restartش کند.

بدفهمی رایج: «managed یعنی بدون عملیات.» طراحی topic، lag مصرف‌کننده، retry و هزینه هنوز با شماست.

تعریف: وزن مجموع وضعیت cluster (partition، controller quorum، نوع queue)، مسیر upgrade، ظرفیت‌سنجی و runbook شبانه است. metadata در Kafka حالا در KRaft است؛ مستندات می‌گوید مهاجرت از ZooKeeper به KRaft به یک bridge release (۳.۹) نیاز دارد.

سناریوی واقعی: تیم چهار نفره برای ۵۰ پیام در ثانیهٔ ایمیل یک cluster سه‌brokerهٔ Kafka گرفت و وقت بیشتری صرف rebalance کرد تا محصول.

Brokerکارهای اصلی عملیات
RabbitMQalarm حافظه/دیسک، انتخاب نوع queue، عضویت quorum، shovel/federation بین سایت‌ها
Kafkaتعداد partition، retention، under-replicated partition، rebalance، controller quorum
Redis Streamsmaxmemory، persistence، failover، trim
SQS/SNS، Pub/Subquota، هزینه، redrive policy

چطور استفاده کنیم: تعداد افراد on-call را بشمارید؛ اگر یک نفر است، managed یا stackی که الان دارید را ترجیح دهید.

تصمیم در برابر تغییر تکمیلی ​

به زبان ساده: انتخاب اول به‌ندرت آخری است؛ تغییرش را ارزان نگه دارید.

بدفهمی رایج: «یک لایهٔ انتزاع همهٔ تفاوت‌های brokerها را پنهان می‌کند.» نمی‌تواند: واحد ترتیب، retry و replay فرق دارند. درز این صفحه فقط اشتراک را قول می‌دهد.

تعریف: یک Publisher/Consumer باریک (پذیرفته‌شدن در publish، ack با موفقیت handler، handlerهای idempotent) به‌علاوهٔ outbox اجازه می‌دهد consumer group به group جابه‌جا شوید (مهاجرت).

چطور استفاده کنیم: adapterهای پایین را ببینید.

انتخاب ​

بر اساس بار کاری حیاتی ​

بار کاریپیشنهادتکنیک اضافهدلیل
Task queue (ایمیل، thumbnail)database/redis در Laravel؛ RabbitMQ بین سرویس‌ها؛ SQS در AWSjob idempotent، backoff (retry)retry هر پیام از throughput مهم‌تر است
Event busKafka، Pulsar؛ topic exchange در RabbitMQ در مقیاس کوچکoutbox، schema نسخه‌دار (schema)مشترکین مستقل
Event log / replayKafka، Pulsar، JetStream، RabbitMQ streamstopic فشرده برای stateخواندن بدون حذف
Stream processingKafka (Kafka Streams، Flink)exactly-once داخل Kafkaاکوسیستم
Request/replyRabbitMQ (reply-to)، NATScorrelation id، timeoutالگوی بومی
IoT / MQTTافزونهٔ MQTT در RabbitMQ، NATS، IoT managedbridge به Kafka برای analyticsپروتکل
Cross-regiongeo-replication در Pulsar، SNS+SQS، Pub/Sub؛ mirroring در Kafka؛ shovel/federation در RabbitMQمالکیت منطقه‌ای دادهlatency و دامنهٔ خطا
ServerlessSQS/SNS، Pub/Subredrive، payload کوچکtrigger مدیریت‌شده

بر اساس بلوغ تیم و ops مهم ​

وضعیت تیمپیشنهاددلیل
۱ تا ۳ توسعه‌دهنده، یک برنامهصف database یا Redisیک چیز برای اجرا
تیم کوچک، چند سرویس، نیاز به retry/DLQRabbitMQ managedقابلیت‌های اطمینان داخلی
تیم platform دارید، consumer زیادKafka (در صورت امکان managed)اجرایش یک شغل است
cloud-native، استخدام ops برنامه نیستSQS/SNS یا Pub/Subبدون سرور
Redis را خوب اجرا می‌کنیدRedis Streams برای موردهای سبکاستفادهٔ دوبارهٔ مهارت

بر اساس مقیاس مهم ​

نرخ پایدارنیاز retentionتناسب معمول
زیر ۱۰۰ پیام در ثانیهساعتصف database/Redis یا هر broker؛ Kafka اضافه نکنید
۱۰۰ تا ۱۰٬۰۰۰ پیام در ثانیهساعت تا روزRabbitMQ، Redis Streams، SQS
۱۰٬۰۰۰ تا ۱۰۰٬۰۰۰ پیام در ثانیهروز تا هفتهRabbitMQ streams، Kafka، Pulsar، JetStream
بالای ۱۰۰٬۰۰۰ پیام در ثانیههفته، replayKafka یا Pulsar با partition برنامه‌ریزی‌شده

این بازه‌ها قاعدهٔ سرانگشتی از روی ردهٔ ماتریس‌اند، نه اندازه‌گیری؛ با آزمایشگاه تأییدشان کنید.

بر اساس نیاز سازگاری مهم ​

نیازپیشنهاددلیل
هیچ پیامی هرگز گم نشودoutbox به‌علاوهٔ quorum queue یا Kafka با acks=allconfirm بعد از replication پایدار
از دست رفتن قابل‌قبول (اشارهٔ ابطال cache)Redis pub/sub یا لیست Redisارزان‌ترین
ترتیب سخت برای هر موجودیتکلید Kafka، گروه SQS FIFO، queue با single-active-consumerواحد ترتیب
«نوشتن DB و publish» اتمیoutbox + relay یا CDCهیچ brokerی تراکنش اتمی با پایگاه‌دادهٔ شما ندارد
consume-transform-produce اتمیتراکنش‌های Kafkaفقط داخل Kafka

راه‌حل‌ها: مهاجرت و همزیستی ​

Order servicebusiness tables +outbox tableOutbox relaydual publishRabbitMQcommands, tasks, delayKafkaevents, replay, streamsOld Redis queuedraining, then removedWorkersidempotentAnalytics,search, CDCOld workersone group at a timeDashed = migration path being retired. Duplicates during overlap are normal.

Redis، RabbitMQ، Kafka حیاتی ​

به زبان ساده: ترافیک را تدریجی جابه‌جا کنید و بگذارید مدتی هر دو broker همان واقعیت‌ها را حمل کنند.

بدفهمی رایج: «اگر هر دو فراخوانی موفق شوند، dual write امن است.» یکی ممکن است شکست بخورد؛ یک بار در outbox بنویسید و relay به هر دو publish کند.

1 Add outbox table; relay publishes each row to old AND new broker
2 Deploy idempotent consumers (inbox) on the new broker, shadow mode
3 Compare counts and lag, per consumer group
4 Switch one consumer group at a time; the old consumer drains, then stops
5 Stop dual publish; delete the old queue after the retention window
-- during 1-4 duplicates are expected; the inbox makes them harmless
مسیرمحرک معمولچه عوض می‌شودمراقب باشید
Laravel database به Redisبار polling جدولنام driver، QUEUE_CONNECTIONpersistence در Redis
Redis به RabbitMQنیاز به retry، DLQ، routing، پایداریconsumerها و topologyprefetch و معنای ack
RabbitMQ به Kafka (eventها)خواننده‌های زیاد، replayکلیدها partition key می‌شوندretry تک‌پیام از بین می‌رود
Kafka به RabbitMQtopic در واقع work queue بودoffsetها کنار می‌روندreplay را از دست می‌دهید
هر broker به managed هم‌پروتکلهزینهٔ opsendpoint و credentialquota و نسخه

همزیستی (Coexistence) مهم ​

به زبان ساده: بسیاری از شرکت‌ها عمداً دو broker دارند: queue برای commandها، log برای eventها.

بدفهمی رایج: «دو broker یعنی مهاجرت شکست‌خورده.» اغلب همین وضعیت پایدار نهایی است.

جفتتقسیم کار
RabbitMQ + Kafkacommandها و taskها در برابر eventهای دامنه و analytics
Redis + Kafkacache و کار سبک در برابر event log پایدار
SQS + Kafkajobهای بومی AWS در برابر eventهای بین‌تیمی
Laravel database + RabbitMQjobهای درون‌برنامه در برابر یکپارچه‌سازی سرویس‌ها

فقط در لبه با consumer پل‌زننده (RabbitMQ به Kafka) وصل کنید و outbox را تنها producer نگه دارید. معماری رویدادمحور را ببینید.

طرح مدل هزینه (Cost model) ​

به زبان ساده: هزینه ماشین، ذخیره‌سازی، شبکه و آدم است، به ترتیب غافلگیری.

بدفهمی رایج: «managed همیشه گران‌تر است.» یک queue managed با قیمت به‌ازای درخواست زیر یک حجم می‌تواند از cluster به‌علاوهٔ نوبت on-call خیلی ارزان‌تر باشد.

مدل با نماد (قیمت‌ها ورودی‌اند که از صفحهٔ فعلی vendor پر می‌کنید؛ اینجا هیچ قیمتی ذکر نشده):

monthly self-host  = nodes x node_price
                   + retained_bytes x replication_factor x disk_price
                   + cross_AZ_traffic x network_price
                   + ops_hours x hourly_rate
monthly managed    = units x unit_price      (requests, throughput units, partitions)
                   + retained_bytes x storage_price
                   + egress x network_price

اندازه‌گیری نمونه با بار فرضی ۱٬۰۰۰ پیام یک‌کیلوبایتی در ثانیه، نگهداری ۷ روز و replication factor برابر ۳:

کمیتمحاسبهنتیجه
پیام در ماه1,000 x 86,400 x 302.592 billion
ورودی1,000 x 1 KBabout 1 MB/s
دادهٔ نگه‌داشته‌شده1 MB/s x 604,800 sabout 605 GB
با replication ۳ ذخیره‌شده605 GB x 3about 1.8 TB
درخواست SQS (send، receive، delete، بدون batch)2.592 billion x 3about 7.8 billion
عامل هزینهSelf-hostManaged
ظرفیت‌سنجیشما، از قبلvendor، با quota
هزینهٔ بیکاریهمیشه روشناغلب تا صفر scale می‌شود (SQS، Pub/Sub)
ترافیک replication بین AZدر صورت‌حساب شمادر قیمت واحد یا خط جدا
on-callآدم‌های شماvendor برای پلتفرم، شما برای consumerها
نقطهٔ سربه‌سرحجم پایدار بالا، تیم platform داریدحجم کم یا جهشی، تیم کوچک

ضدتصمیم‌ها (Anti-decisions) ​

ضدتصمیمچرا شکست می‌خوردبه‌جایش
Kafka برای task queue با ۱۰۰ پیام در ثانیهیک job کند partition را متوقف می‌کند، retry/delay/DLQ تک‌پیام ندارد؛ cluster بدون حجمصف database/redis در Laravel یا RabbitMQ (share groupهای Kafka این را عوض می‌کنند: نسخه و client را بررسی کنید)
Redis pub/sub برای هر چیز که نباید گم شودpub/sub آتش‌وفراموش است: بدون subscriber پیام رفته؛ ack و replay ندارد (Redis Streams و Pub/Sub)Streams با persistence یا RabbitMQ
queueهای classic در RabbitMQ به‌عنوان event storeپیام با ack می‌رود؛ consumer جدید ماه قبل را نمی‌بیندstreams یا Kafka
Redis Streams به‌عنوان system of recordمحدود به RAM؛ failover می‌تواند نوشتن‌های ackشده را از دست بدهد (durability)پایگاه‌داده به‌علاوهٔ outbox
اشتباه گرفتن driver redis در Laravel با Streamsاز list و sorted set استفاده می‌کند (queue internals)Redis::xadd برای streams
broker برای فرار از تراکنشهیچ brokerی با پایگاه‌دادهٔ شما اتمی commit نمی‌کندoutbox
یک topic/queue غول‌پیکر برای همه‌چیزretention، ترتیب و ACL برای هر کاربرد قابل تنظیم نیستtopic برای هر نوع event یا bounded context

پرسش Laravel ​

به زبان ساده: با صفی شروع کنید که دارید؛ broker را وقتی اضافه کنید که یک محدودیت مشخص پیدا شد، نه مد.

بدفهمی رایج: «سیستم جدی Kafka یا RabbitMQ می‌خواهد.» مستندات Laravel 13 driverهای داخلی را فهرست می‌کند: "the database, Amazon SQS, Redis, and Beanstalkd drivers, as well as a synchronous driver that will execute jobs immediately" (queues). خیلی سیستم‌ها هرگز بیشتر نمی‌خواهند.

driver database jobها را با قفل خواندن برمی‌دارد؛ framework روی MySQL 8.0.1+، MariaDB 10.6+، PostgreSQL 9.5+ و Vitess 19+ عبارت FOR UPDATE SKIP LOCKED را انتخاب می‌کند (سورس DatabaseQueue)، پس چند worker هم را بلاک نمی‌کنند:

sql
-- what the database driver does per pop, simplified (PostgreSQL)
BEGIN;
SELECT * FROM jobs
 WHERE queue = 'default'
   AND (reserved_at IS NULL OR reserved_at <= extract(epoch FROM now()) - 90)
   AND available_at <= extract(epoch FROM now())
 ORDER BY id
 LIMIT 1
 FOR UPDATE SKIP LOCKED;
UPDATE jobs SET reserved_at = extract(epoch FROM now()), attempts = attempts + 1 WHERE id = $1;
COMMIT;

کی broker اضافه کنیم:

نشانهمعناقدم بعد
polling جدول jobs روی CPU پایگاه‌داده غالب استپایگاه‌داده جای اشتباهی استdriver Redis، بعد RabbitMQ
زبان/سرویس دیگری باید مصرف کندپروتکل لازم است نه payload جاب LaravelRabbitMQ یا Kafka با قرارداد پیام مستند
retry تک‌پیام بین سرویس‌ها، DLQ، routingقابلیت‌های queueRabbitMQ
replay یا خواننده‌های مستقل زیادLogKafka
cloud managed بدون سرورعملیاتSQS (driver داخلی)
delay بیش از ۱۵ دقیقه روی SQSسقف SQS ("maximum delay time of 15 minutes")delay در RabbitMQ یا scheduler + database
1 Monolith, jobs in `jobs` table, 20 jobs/s            -> keep
2 Peak 800 jobs/s, DB CPU rising                        -> QUEUE_CONNECTION=redis (+ Horizon)
3 Second service in Go must react to OrderPlaced        -> outbox -> RabbitMQ topic exchange
4 Analytics wants to replay 90 days of events           -> add Kafka for the event stream, keep RabbitMQ for commands

مرتبط: صفحهٔ درونیات queue در Laravel و jobهای پایدار.

Go ​

نمونه ​

یک Publisher و یک Consumer با سه adapter. قرارداد، اشتراک سه broker است: Publish وقتی برمی‌گردد که broker پیام را پذیرفته؛ handler که nil برگرداند ack است؛ خطا یعنی پیام برای تحویل مجدد می‌ماند؛ handlerها idempotent‌اند. فقط compile: main تا BROKER تنظیم نشود خارج می‌شود.

go
// Package main shows one Publisher/Consumer seam with three adapters.
// The contract is deliberately small: it is the intersection of what the three
// brokers can promise, so application code never names a broker feature.
package main

import "context"

// Message is the broker-neutral envelope. Key drives ordering: the Kafka
// partition key, the Redis stream field, the RabbitMQ routing key suffix.
type Message struct {
	Key     string
	Body    []byte
	Headers map[string]string
}

// Handler returns nil to acknowledge. Any error means "do not acknowledge":
// the adapter leaves the message for redelivery. Handlers must be idempotent,
// because every adapter gives at-least-once delivery.
type Handler func(ctx context.Context, m Message) error

// Publisher returns only after the broker has accepted the message
// (publisher confirm, produce callback, XADD reply). It does not mean processed.
type Publisher interface {
	Publish(ctx context.Context, topic string, m Message) error
	Close() error
}

// Consumer blocks until ctx is cancelled. group names the competing-consumer
// set: the queue name, the consumer group id, the stream group.
type Consumer interface {
	Consume(ctx context.Context, topic, group string, h Handler) error
	Close() error
}
go
package main

import (
	"context"
	"errors"
	"fmt"

	amqp "github.com/rabbitmq/amqp091-go"
)

type rabbitPublisher struct {
	conn *amqp.Connection
	ch   *amqp.Channel
}

func newRabbitPublisher(url string) (*rabbitPublisher, error) {
	conn, err := amqp.Dial(url)
	if err != nil {
		return nil, err
	}
	ch, err := conn.Channel()
	if err != nil {
		conn.Close()
		return nil, err
	}
	if err = ch.Confirm(false); err != nil { // publisher confirms on
		conn.Close()
		return nil, err
	}
	return &rabbitPublisher{conn: conn, ch: ch}, nil
}

// Publish uses the default exchange: routing key == queue name == topic.
func (p *rabbitPublisher) Publish(ctx context.Context, topic string, m Message) error {
	headers := amqp.Table{}
	for k, v := range m.Headers {
		headers[k] = v
	}
	conf, err := p.ch.PublishWithDeferredConfirmWithContext(ctx, "", topic, true, false, amqp.Publishing{
		DeliveryMode: amqp.Persistent,
		MessageId:    m.Key,
		Headers:      headers,
		Body:         m.Body,
	})
	if err != nil {
		return err
	}
	acked, err := conf.WaitContext(ctx)
	if err != nil {
		return err
	}
	if !acked {
		return errors.New("rabbitmq: publish nacked")
	}
	return nil
}

func (p *rabbitPublisher) Close() error { return p.conn.Close() }

type rabbitConsumer struct{ conn *amqp.Connection }

func newRabbitConsumer(url string) (*rabbitConsumer, error) {
	conn, err := amqp.Dial(url)
	if err != nil {
		return nil, err
	}
	return &rabbitConsumer{conn: conn}, nil
}

// Consume treats group as the queue name; competing consumers share the queue.
func (c *rabbitConsumer) Consume(ctx context.Context, topic, group string, h Handler) error {
	ch, err := c.conn.Channel()
	if err != nil {
		return err
	}
	defer ch.Close()
	if err = ch.Qos(20, 0, false); err != nil { // prefetch bounds in-flight work
		return err
	}
	q, err := ch.QueueDeclare(group, true, false, false, false, amqp.Table{"x-queue-type": "quorum"})
	if err != nil {
		return err
	}
	// Bind the group queue to the topic through the default exchange only
	// when names match; real topologies would declare an exchange here.
	if q.Name != topic {
		return fmt.Errorf("rabbitmq adapter: group %q must equal topic %q on the default exchange", group, topic)
	}
	msgs, err := ch.ConsumeWithContext(ctx, q.Name, "", false, false, false, false, nil)
	if err != nil {
		return err
	}
	for d := range msgs {
		hdr := map[string]string{}
		for k, v := range d.Headers {
			if s, ok := v.(string); ok {
				hdr[k] = s
			}
		}
		if err = h(ctx, Message{Key: d.MessageId, Body: d.Body, Headers: hdr}); err != nil {
			_ = d.Nack(false, true) // requeue
			continue
		}
		_ = d.Ack(false) // ack after the side effect
	}
	return ctx.Err()
}

func (c *rabbitConsumer) Close() error { return c.conn.Close() }
go
package main

import (
	"context"

	"github.com/twmb/franz-go/pkg/kgo"
)

type kafkaPublisher struct{ cl *kgo.Client }

func newKafkaPublisher(brokers []string) (*kafkaPublisher, error) {
	cl, err := kgo.NewClient(
		kgo.SeedBrokers(brokers...),
		kgo.RequiredAcks(kgo.AllISRAcks()), // acks=all
	)
	if err != nil {
		return nil, err
	}
	return &kafkaPublisher{cl: cl}, nil
}

// Publish waits for the produce result, so a nil error means the leader and
// the in-sync replicas accepted the record.
func (p *kafkaPublisher) Publish(ctx context.Context, topic string, m Message) error {
	rec := &kgo.Record{Topic: topic, Key: []byte(m.Key), Value: m.Body}
	for k, v := range m.Headers {
		rec.Headers = append(rec.Headers, kgo.RecordHeader{Key: k, Value: []byte(v)})
	}
	return p.cl.ProduceSync(ctx, rec).FirstErr()
}

func (p *kafkaPublisher) Close() error { p.cl.Close(); return nil }

type kafkaConsumer struct{ brokers []string }

func newKafkaConsumer(brokers []string) *kafkaConsumer { return &kafkaConsumer{brokers: brokers} }

// Consume stops at the first failing record and does not commit it: Kafka has
// no per-message nack, so "do not acknowledge" means "stop and re-poll".
func (c *kafkaConsumer) Consume(ctx context.Context, topic, group string, h Handler) error {
	cl, err := kgo.NewClient(
		kgo.SeedBrokers(c.brokers...),
		kgo.ConsumerGroup(group),
		kgo.ConsumeTopics(topic),
		kgo.DisableAutoCommit(),
	)
	if err != nil {
		return err
	}
	defer cl.Close()
	for ctx.Err() == nil {
		fetches := cl.PollFetches(ctx)
		if err = fetches.Err0(); err != nil && ctx.Err() == nil {
			return err
		}
		it := fetches.RecordIter()
		for !it.Done() {
			r := it.Next()
			hdr := map[string]string{}
			for _, kh := range r.Headers {
				hdr[kh.Key] = string(kh.Value)
			}
			if err = h(ctx, Message{Key: string(r.Key), Body: r.Value, Headers: hdr}); err != nil {
				break // leave the rest uncommitted; the group redelivers
			}
			if err = cl.CommitRecords(ctx, r); err != nil {
				return err
			}
		}
	}
	return ctx.Err()
}

func (c *kafkaConsumer) Close() error { return nil }
go
package main

import (
	"context"
	"strings"
	"time"

	"github.com/redis/go-redis/v9"
)

type redisPublisher struct{ rdb *redis.Client }

func newRedisPublisher(addr string) *redisPublisher {
	return &redisPublisher{rdb: redis.NewClient(&redis.Options{Addr: addr})}
}

// Publish returns the XADD reply: the entry is on the primary, nothing more.
// Durability still depends on AOF and replication settings.
func (p *redisPublisher) Publish(ctx context.Context, topic string, m Message) error {
	values := map[string]any{"key": m.Key, "body": m.Body}
	for k, v := range m.Headers {
		values["h:"+k] = v
	}
	return p.rdb.XAdd(ctx, &redis.XAddArgs{Stream: topic, Values: values}).Err()
}

func (p *redisPublisher) Close() error { return p.rdb.Close() }

type redisConsumer struct{ rdb *redis.Client }

func newRedisConsumer(addr string) *redisConsumer {
	return &redisConsumer{rdb: redis.NewClient(&redis.Options{Addr: addr})}
}

func (c *redisConsumer) Consume(ctx context.Context, topic, group string, h Handler) error {
	err := c.rdb.XGroupCreateMkStream(ctx, topic, group, "0").Err()
	if err != nil && !strings.HasPrefix(err.Error(), "BUSYGROUP") {
		return err
	}
	for ctx.Err() == nil {
		res, err := c.rdb.XReadGroup(ctx, &redis.XReadGroupArgs{
			Group: group, Consumer: "worker-1",
			Streams: []string{topic, ">"}, Count: 10, Block: 2 * time.Second,
		}).Result()
		if err == redis.Nil {
			continue // block timeout, nothing new
		}
		if err != nil {
			return err
		}
		for _, s := range res {
			for _, x := range s.Messages {
				msg := Message{Headers: map[string]string{}}
				for k, v := range x.Values {
					str, _ := v.(string)
					switch {
					case k == "key":
						msg.Key = str
					case k == "body":
						msg.Body = []byte(str)
					case strings.HasPrefix(k, "h:"):
						msg.Headers[strings.TrimPrefix(k, "h:")] = str
					}
				}
				if h(ctx, msg) != nil {
					continue // stays in the pending entries list (XPENDING)
				}
				if err = c.rdb.XAck(ctx, topic, group, x.ID).Err(); err != nil {
					return err
				}
			}
		}
	}
	return ctx.Err()
}

func (c *redisConsumer) Close() error { return c.rdb.Close() }
go
package main

import (
	"context"
	"fmt"
	"os"
	"strings"
)

// factory is the only place that knows which broker runs. Everything else
// depends on Publisher and Consumer.
func factory(kind string) (Publisher, Consumer, error) {
	switch kind {
	case "rabbitmq":
		url := os.Getenv("AMQP_URL")
		p, err := newRabbitPublisher(url)
		if err != nil {
			return nil, nil, err
		}
		c, err := newRabbitConsumer(url)
		return p, c, err
	case "kafka":
		brokers := strings.Split(os.Getenv("KAFKA_BROKERS"), ",")
		p, err := newKafkaPublisher(brokers)
		return p, newKafkaConsumer(brokers), err
	case "redis":
		addr := os.Getenv("REDIS_ADDR")
		return newRedisPublisher(addr), newRedisConsumer(addr), nil
	}
	return nil, nil, fmt.Errorf("unknown BROKER %q", kind)
}

func main() {
	kind := os.Getenv("BROKER")
	if kind == "" {
		fmt.Println("set BROKER=rabbitmq|kafka|redis (plus its address variable) to run")
		return
	}
	pub, con, err := factory(kind)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	defer pub.Close()
	defer con.Close()

	ctx := context.Background()
	if err = pub.Publish(ctx, "orders", Message{Key: "order-42", Body: []byte(`{"order_id":42}`)}); err != nil {
		fmt.Fprintln(os.Stderr, "publish:", err)
		os.Exit(1)
	}
	fmt.Println("accepted by", kind)
}

نگاه Go ​

کتابخانهٔ استاندارد client برای broker ندارد؛ client هر اکوسیستم مدل broker خودش را بازتاب می‌دهد. amqp091-go کانال‌ها، NotifyReturn و یک confirm معوق (Deferred Confirmation) می‌دهد که منتظرش می‌مانید؛ franz-go callback تولید با Partition و Offset و همچنین DisableAutoCommit و CommitRecords دارد؛ go-redis پوشش تایپ‌دار است که XAdd، XReadGroup و XAck مثل مستندات Redis خوانده می‌شوند. به آنچه adapter نمی‌تواند پنهان کند دقت کنید: RabbitMQ نام group را نام queue می‌گیرد، Kafka چون nack تک‌رکوردی ندارد در اولین رکورد خراب می‌ایستد، و Redis ورودی ناموفق را برای XAUTOCLAIM در pending list می‌گذارد. این هزینهٔ صادقانهٔ درز است. مسیر importها: amqp091-go، franz-go kgo، go-redis.

Laravel ​

نمونه ​

همان درز در PHP: دو interface، سه adapter ناشر (php-amqplib، ext-rdkafka، facade Redis)، یک consumer برای Redis Streams و یک service provider که interface را از config('messaging.broker') bind می‌کند. consumerهای RabbitMQ و Kafka معمولاً داخل worker خود package اجرا می‌شوند؛ آن‌ها را هم به همین شکل بپوشانید.

php
<?php

namespace App\Messaging;

/**
 * Returns after the broker accepted the message (confirm, produce report,
 * XADD reply). It never means "processed".
 */
interface Publisher
{
    /** @param array<string,string> $headers */
    public function publish(string $topic, string $key, string $body, array $headers = []): void;
}
php
<?php

namespace App\Messaging;

use Closure;

interface Consumer
{
    /**
     * Blocks and calls $handler(string $key, string $body, array $headers).
     * Returning normally acknowledges; throwing leaves the message for
     * redelivery. Handlers must be idempotent: delivery is at-least-once.
     */
    public function consume(string $topic, string $group, Closure $handler): void;
}
php
<?php

namespace App\Messaging;

use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
use PhpAmqpLib\Wire\AMQPTable;
use RuntimeException;

/** php-amqplib directly: the Laravel package publishes without waiting for confirms. */
final class RabbitMqPublisher implements Publisher
{
    public function __construct(private readonly AMQPStreamConnection $connection) {}

    public function publish(string $topic, string $key, string $body, array $headers = []): void
    {
        $channel = $this->connection->channel();
        $accepted = false;
        $returned = null;
        $channel->set_ack_handler(function () use (&$accepted) {
            $accepted = true;
        });
        $channel->set_return_listener(function ($code, $text) use (&$returned) {
            $returned = $text;
        });
        $channel->confirm_select();
        $channel->basic_publish(
            new AMQPMessage($body, [
                'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT,
                'message_id' => $key,
                'application_headers' => new AMQPTable($headers),
            ]),
            '',
            $topic,
            true, // mandatory: unroutable messages come back as basic.return
        );
        $channel->wait_for_pending_acks_returns();
        $channel->close();

        if (! $accepted || $returned !== null) {
            throw new RuntimeException('rabbitmq publish failed: '.($returned ?? 'nack'));
        }
    }
}
php
<?php

namespace App\Messaging;

use RdKafka\Conf;
use RdKafka\Producer;
use RuntimeException;

/** ext-rdkafka directly: the flush result is the only "accepted" signal we need here. */
final class KafkaPublisher implements Publisher
{
    private readonly Producer $producer;

    public function __construct(string $brokers)
    {
        $conf = new Conf;
        $conf->set('bootstrap.servers', $brokers);
        $conf->set('acks', 'all');
        $conf->set('enable.idempotence', 'true');
        $this->producer = new Producer($conf);
    }

    public function publish(string $topic, string $key, string $body, array $headers = []): void
    {
        $this->producer->newTopic($topic)->producev(RD_KAFKA_PARTITION_UA, 0, $body, $key, $headers);
        $this->producer->poll(0);
        if ($this->producer->flush(10000) !== RD_KAFKA_RESP_ERR_NO_ERROR) {
            throw new RuntimeException('kafka flush failed or timed out');
        }
    }
}
php
<?php

namespace App\Messaging;

use Illuminate\Support\Facades\Redis;

/** The Redis facade, because Laravel's redis queue driver uses lists, not streams. */
final class RedisStreamPublisher implements Publisher
{
    public function publish(string $topic, string $key, string $body, array $headers = []): void
    {
        $fields = ['key' => $key, 'body' => $body];
        foreach ($headers as $name => $value) {
            $fields['h:'.$name] = $value;
        }
        Redis::xadd($topic, '*', $fields); // an id means "on the primary", not "durable"
    }
}
php
<?php

namespace App\Messaging;

use Closure;
use Illuminate\Support\Facades\Redis;
use Throwable;

final class RedisStreamConsumer implements Consumer
{
    public function consume(string $topic, string $group, Closure $handler): void
    {
        try {
            Redis::xgroup('CREATE', $topic, $group, '0', true); // MKSTREAM
        } catch (Throwable) {
            // BUSYGROUP: the group already exists
        }

        while (true) {
            $read = Redis::xreadgroup($group, 'worker-1', [$topic => '>'], 10, 2000);
            foreach ($read[$topic] ?? [] as $id => $fields) {
                $headers = [];
                foreach ($fields as $name => $value) {
                    if (str_starts_with($name, 'h:')) {
                        $headers[substr($name, 2)] = $value;
                    }
                }
                try {
                    $handler($fields['key'] ?? '', $fields['body'] ?? '', $headers);
                } catch (Throwable) {
                    continue; // stays in the pending entries list for XAUTOCLAIM
                }
                Redis::xack($topic, $group, [$id]);
            }
        }
    }
}
php
<?php

namespace App\Providers;

use App\Messaging\KafkaPublisher;
use App\Messaging\Publisher;
use App\Messaging\RabbitMqPublisher;
use App\Messaging\RedisStreamPublisher;
use Illuminate\Support\ServiceProvider;
use InvalidArgumentException;
use PhpAmqpLib\Connection\AMQPStreamConnection;

/** The only class that knows which broker runs: change MESSAGING_BROKER, not callers. */
final class BrokerServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->singleton(Publisher::class, function () {
            return match (config('messaging.broker')) {
                'rabbitmq' => new RabbitMqPublisher(new AMQPStreamConnection(
                    config('messaging.rabbitmq.host'), 5672,
                    config('messaging.rabbitmq.user'), config('messaging.rabbitmq.password'),
                )),
                'kafka' => new KafkaPublisher(config('messaging.kafka.brokers')),
                'redis' => new RedisStreamPublisher,
                default => throw new InvalidArgumentException('unknown messaging.broker'),
            };
        });
    }
}

نگاه Laravel ​

driverهای داخلی Laravel 13 عبارت‌اند از database، sqs، redis، beanstalkd، sync و null؛ RabbitMQ و Kafka داخلی نیستند. برای jobها نام connection خودش درز است: QUEUE_CONNECTION و ورودی config/queue.php را عوض کنید و jobها بدون تغییر اجرا می‌شوند، اما فقط برای task queueها. eventها روی Kafka یا Streams consumer خودشان را می‌خواهند و interface بالا برای همین است. واقعیت‌های package که اینجا استفاده شد: vladimir-yuldashev/laravel-queue-rabbitmq در composer.json اجازهٔ illuminate/queue تا ^13.0 را می‌دهد (جدول پشتیبانی README کهنه است) و منتظر publisher confirm نمی‌ماند، برای همین adapter مستقیم از php-amqplib استفاده می‌کند. mateusjunges/laravel-kafka به PHP 8.2+، Laravel 12+ و ext-rdkafka نیاز دارد؛ send() اش نتیجهٔ flush برمی‌گرداند نه offset، برای همین adapter از RdKafka\Producer استفاده می‌کند. Redis Streams با facade Redis است و فرض بر phpredis است (امضای xadd، xreadgroup، xack در Predis فرق دارد). jobهای delayed روی SQS تا ۱۵ دقیقه سقف دارند.

تفاوت‌های اجرا در brokerها ​

اینجا خود مقایسه موضوع است، پس هر زیربخش فلسفهٔ broker را خلاصه می‌کند و نشان می‌دهد روی آن چطور «پذیرفته، تحویل، پردازش» را ثابت می‌کنند. هر سه برنامه اگر متغیر محیطی‌شان نباشد بی‌صدا خارج می‌شوند.

RabbitMQ ​

فلسفه: broker باهوش، consumerهای به‌اندازهٔ کافی ساده. routing، retry، TTL، DLX و ack تک‌پیام در خود broker است. زنجیرهٔ شواهد: confirm (پذیرفته) سپس عمق queue (ready) سپس ack (پردازش‌شده). confirm برای پیام routable یعنی "has been accepted by all the queues"؛ در quorum queue یعنی اکثریت replicaها. دو تله: پیام unroutable هم confirm می‌شود، پس mandatory publish کنید و به basic.return گوش بدهید؛ و عمق queue فقط پیام‌های ready را می‌شمارد، پس پیام تحویل‌شدهٔ ack‌نشده هم‌اکنون «رفته» به نظر می‌رسد. برنامه‌ها پیش از بررسی نهایی channel مصرف‌کننده را می‌بندند چون deliveryهای ack‌نشده "automatically requeued when the channel (or connection) on which the delivery happened is closed".

go
// Command rabbitmq proves one message was delivered and processed end to end:
// publisher confirm -> queue depth -> consume -> ack -> depth after the channel
// that held the delivery is closed.
package main

import (
	"context"
	"fmt"
	"os"
	"time"

	amqp "github.com/rabbitmq/amqp091-go"
)

const queue = "verify.orders"

func main() {
	url := os.Getenv("AMQP_URL") // e.g. amqp://guest:guest@localhost:5672/
	if url == "" {
		fmt.Println("set AMQP_URL to run this check")
		return
	}
	if err := run(url); err != nil {
		fmt.Fprintln(os.Stderr, "FAIL:", err)
		os.Exit(1)
	}
}

func run(url string) error {
	ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
	defer cancel()

	conn, err := amqp.Dial(url)
	if err != nil {
		return err
	}
	defer conn.Close()

	pub, err := conn.Channel()
	if err != nil {
		return err
	}
	if _, err = pub.QueueDeclare(queue, true, false, false, false, amqp.Table{"x-queue-type": "quorum"}); err != nil {
		return err
	}

	// 1. Publisher confirm: the broker accepted the message (for a quorum queue,
	// a majority of replicas hold it). This says nothing about any consumer.
	if err = pub.Confirm(false); err != nil {
		return err
	}
	// A confirm also arrives for a message that matched no queue, so ask for
	// mandatory publishing and listen for the basic.return that precedes it.
	returns := pub.NotifyReturn(make(chan amqp.Return, 1))
	conf, err := pub.PublishWithDeferredConfirmWithContext(ctx, "", queue, true, false, amqp.Publishing{
		DeliveryMode: amqp.Persistent,
		MessageId:    "order-42",
		Body:         []byte(`{"order_id":42}`),
	})
	if err != nil {
		return err
	}
	acked, err := conf.WaitContext(ctx)
	if err != nil || !acked {
		return fmt.Errorf("publisher confirm failed (acked=%v, err=%v)", acked, err)
	}
	select {
	case r := <-returns:
		return fmt.Errorf("confirmed but unroutable: %s", r.ReplyText)
	default:
	}
	fmt.Println("confirm: broker acked the publish")

	// 2. Depth through a passive declare: no management plugin, no HTTP API.
	// Messages counts READY messages only, not delivered-but-unacked ones.
	ready, err := depth(conn)
	if err != nil {
		return err
	}
	fmt.Println("depth before consume:", ready)

	// 3. Consume with manual ack; ack only after the side effect succeeded.
	cons, err := conn.Channel()
	if err != nil {
		return err
	}
	deliveries, err := cons.ConsumeWithContext(ctx, queue, "", false, false, false, false, nil)
	if err != nil {
		return err
	}
	select {
	case d := <-deliveries:
		fmt.Printf("consumed %s redelivered=%v\n", d.MessageId, d.Redelivered)
		// ...write to the database here...
		if err = d.Ack(false); err != nil {
			return err
		}
	case <-ctx.Done():
		return ctx.Err()
	}

	// 4. Closing the consuming channel requeues anything still unacked, so a
	// depth of 0 afterwards proves the ack was applied, not merely that the
	// message left the "ready" state.
	if err = cons.Close(); err != nil {
		return err
	}
	ready, err = depth(conn)
	if err != nil {
		return err
	}
	if ready != 0 {
		return fmt.Errorf("message was requeued, depth=%d", ready)
	}
	fmt.Println("depth after ack and channel close: 0 -> processed")
	return nil
}

// depth uses a throwaway channel because a failed passive declare closes it.
func depth(conn *amqp.Connection) (int, error) {
	ch, err := conn.Channel()
	if err != nil {
		return 0, err
	}
	defer ch.Close()
	q, err := ch.QueueDeclarePassive(queue, true, false, false, false, amqp.Table{"x-queue-type": "quorum"})
	if err != nil {
		return 0, err
	}
	return q.Messages, nil
}
php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Queue;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
use PhpAmqpLib\Wire\AMQPTable;

/**
 * php artisan verify:rabbitmq
 *
 * Uses vladimir-yuldashev/laravel-queue-rabbitmq for the queue side and its
 * dependency php-amqplib directly for publisher confirms, because the package
 * publishes without waiting for them.
 */
class VerifyRabbitMq extends Command
{
    protected $signature = 'verify:rabbitmq';

    protected $description = 'Publish with a confirm, consume, ack, then prove the queue is empty';

    private const QUEUE = 'verify.orders';

    public function handle(): int
    {
        $queue = Queue::connection('rabbitmq');
        $queue->declareQueue(self::QUEUE, true, false, ['x-queue-type' => 'quorum']);

        // 1. Publisher confirm on a channel of our own.
        $cfg = config('queue.connections.rabbitmq.hosts.0');
        $conn = new AMQPStreamConnection($cfg['host'], $cfg['port'], $cfg['user'], $cfg['password'], $cfg['vhost']);
        $channel = $conn->channel();

        $outcome = null;
        $channel->set_ack_handler(function (AMQPMessage $m) use (&$outcome) {
            $outcome = 'ack';
        });
        $channel->set_nack_handler(function (AMQPMessage $m) use (&$outcome) {
            $outcome = 'nack';
        });
        // A confirm also arrives for a message that matched no queue, so publish
        // as mandatory and listen for the basic.return that precedes the ack.
        $unroutable = null;
        $channel->set_return_listener(function ($code, $text) use (&$unroutable) {
            $unroutable = $text;
        });
        $channel->confirm_select();
        $channel->basic_publish(
            new AMQPMessage('{"order_id":42}', ['delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT]),
            '',
            self::QUEUE,
            true,
        );
        $channel->wait_for_pending_acks_returns();
        $conn->close();

        if ($outcome !== 'ack' || $unroutable !== null) {
            $this->error('publish failed: '.($unroutable ?? $outcome));

            return self::FAILURE;
        }
        $this->info('confirm: broker acked the publish');

        // 2. size() is a passive queue.declare: ready messages only.
        $this->line('depth before consume: '.$queue->size(self::QUEUE));

        // 3. pop() is basic.get; delete() sends basic.ack (see RabbitMQJob::delete).
        $job = $queue->pop(self::QUEUE);
        if ($job === null) {
            $this->error('nothing to consume');

            return self::FAILURE;
        }
        $this->line('consumed '.$job->getRawBody());
        // ...write to the database here...
        $job->delete();

        // 4. Close the package's connection (the broker requeues anything
        // unacked), then look at the queue from a brand-new connection.
        $queue->close();
        $verify = new AMQPStreamConnection($cfg['host'], $cfg['port'], $cfg['user'], $cfg['password'], $cfg['vhost']);
        [, $ready] = $verify->channel()->queue_declare(self::QUEUE, true, true, false, false, false, new AMQPTable(['x-queue-type' => 'quorum']));
        $verify->close();

        if ($ready !== 0) {
            $this->error("message was requeued, depth={$ready}");

            return self::FAILURE;
        }
        $this->info('depth after ack and reconnect: 0 -> processed');

        return self::SUCCESS;
    }
}

Kafka ​

فلسفه: broker ساده، log باهوش. broker ذخیره و replicate می‌کند؛ consumerها position را نگه می‌دارند. زنجیرهٔ شواهد: callback تولید (partition و offset) سپس offset ثبت‌شده (position). با acks=all رهبر منتظر "the full set of in-sync replicas" می‌ماند و offset واقعی است (با acks=0 همیشه -1). offset ثبت‌شده offset بعدی برای خواندن است، پس بعد از پردازش رکورد n گروه n+1 را نشان می‌دهد. position است نه رسید: ثبت یک رکورد بعدی بی‌صدا رکورد خراب قبلی را می‌پوشاند. برنامه از group coordinator می‌پرسد (kadm.FetchOffsets، getCommittedOffsets) به‌جای اینکه به دفتر خودش اعتماد کند. تولید idempotent تکراری‌های ناشی از retry تولیدکننده را حذف می‌کند؛ consumer شما را idempotent نمی‌کند (delivery guarantees).

go
// Command kafka proves one record was delivered and processed end to end:
// produce callback (partition+offset) -> consume -> commit -> committed offset.
package main

import (
	"context"
	"fmt"
	"os"
	"strings"
	"time"

	"github.com/twmb/franz-go/pkg/kadm"
	"github.com/twmb/franz-go/pkg/kgo"
)

const (
	topic = "verify.orders"
	group = "verify-workers"
)

func main() {
	brokers := os.Getenv("KAFKA_BROKERS") // e.g. localhost:9092
	if brokers == "" {
		fmt.Println("set KAFKA_BROKERS to run this check")
		return
	}
	if err := run(strings.Split(brokers, ",")); err != nil {
		fmt.Fprintln(os.Stderr, "FAIL:", err)
		os.Exit(1)
	}
}

func run(brokers []string) error {
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	cl, err := kgo.NewClient(
		kgo.SeedBrokers(brokers...),
		kgo.RequiredAcks(kgo.AllISRAcks()), // acks=all: wait for the in-sync replicas
		kgo.ConsumerGroup(group),
		kgo.ConsumeTopics(topic),
		kgo.ConsumeResetOffset(kgo.NewOffset().AtStart()),
		kgo.DisableAutoCommit(), // we commit after the side effect, not on a timer
	)
	if err != nil {
		return err
	}
	defer cl.Close()

	// 1. Produce with a callback. The callback fires once the broker has
	// answered (or retries are exhausted); r.Partition and r.Offset are the
	// coordinates of the committed record.
	type where struct {
		partition int32
		offset    int64
		err       error
	}
	done := make(chan where, 1)
	rec := &kgo.Record{Topic: topic, Key: []byte("order-42"), Value: []byte(`{"order_id":42}`)}
	cl.Produce(ctx, rec, func(r *kgo.Record, err error) {
		done <- where{r.Partition, r.Offset, err}
	})
	w := <-done
	if w.err != nil {
		return fmt.Errorf("produce failed: %w", w.err)
	}
	fmt.Printf("produced to %s[%d] at offset %d\n", topic, w.partition, w.offset)

	// 2. Consume until we see that exact record.
	var got *kgo.Record
	for got == nil {
		fetches := cl.PollFetches(ctx)
		if err = fetches.Err(); err != nil {
			return err
		}
		fetches.EachRecord(func(r *kgo.Record) {
			if r.Partition == w.partition && r.Offset == w.offset {
				got = r
			}
		})
	}

	// ...write to the database here, then commit. The committed offset is the
	// NEXT offset to read, so it is record offset + 1.
	if err = cl.CommitRecords(ctx, got); err != nil {
		return fmt.Errorf("commit failed: %w", err)
	}

	// 3. Ask the group coordinator what it has stored, independently of the
	// client's own bookkeeping.
	offs, err := kadm.NewClient(cl).FetchOffsets(ctx, group)
	if err != nil {
		return err
	}
	committed, ok := offs.Lookup(topic, w.partition)
	if !ok || committed.Err != nil {
		return fmt.Errorf("no committed offset for %s[%d]", topic, w.partition)
	}
	if committed.At < w.offset+1 {
		return fmt.Errorf("committed %d is behind produced %d", committed.At, w.offset)
	}
	fmt.Printf("group %s committed offset %d -> processed offset %d\n", group, committed.At, w.offset)
	return nil
}
php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Junges\Kafka\Contracts\ConsumerMessage;
use Junges\Kafka\Contracts\MessageConsumer;
use Junges\Kafka\Facades\Kafka;
use RdKafka\Conf;
use RdKafka\KafkaConsumer;
use RdKafka\Message;
use RdKafka\Producer;
use RdKafka\TopicPartition;

/**
 * php artisan verify:kafka
 *
 * mateusjunges/laravel-kafka sits on ext-rdkafka. The package's send() returns
 * only a flush result, so the produce side uses RdKafka\Producer directly to
 * read the delivery report (partition + offset); the consume side uses the
 * package with manual commit.
 */
class VerifyKafka extends Command
{
    protected $signature = 'verify:kafka';

    protected $description = 'Produce with a delivery report, consume, commit, then read the committed offset';

    private const TOPIC = 'verify.orders';

    private const GROUP = 'verify-workers';

    public function handle(): int
    {
        $brokers = config('kafka.brokers');

        // 1. Delivery report callback: fires when the broker has answered.
        $report = null;
        $conf = new Conf;
        $conf->set('metadata.broker.list', $brokers);
        $conf->set('acks', 'all');
        $conf->set('enable.idempotence', 'true');
        $conf->setDrMsgCb(function ($producer, Message $m) use (&$report) {
            $report = $m->err === RD_KAFKA_RESP_ERR_NO_ERROR
                ? ['partition' => $m->partition, 'offset' => $m->offset]
                : ['error' => $m->errstr()];
        });

        $producer = new Producer($conf);
        $producer->newTopic(self::TOPIC)->produce(RD_KAFKA_PARTITION_UA, 0, '{"order_id":42}', 'order-42');
        if ($producer->flush(10000) !== RD_KAFKA_RESP_ERR_NO_ERROR || ! isset($report['offset'])) {
            $this->error('produce failed: '.json_encode($report));

            return self::FAILURE;
        }
        ['partition' => $partition, 'offset' => $offset] = $report;
        $this->info("produced to ".self::TOPIC."[{$partition}] at offset {$offset}");

        // 2. Consume with manual commit; commit only after the side effect.
        Kafka::consumer([self::TOPIC], self::GROUP, $brokers)
            ->withManualCommit()
            ->withOption('auto.offset.reset', 'earliest')
            ->withHandler(function (ConsumerMessage $message, MessageConsumer $consumer) use ($partition, $offset) {
                if ($message->getPartition() !== $partition || $message->getOffset() !== $offset) {
                    return;
                }
                // ...write to the database here...
                $consumer->commit($message);
                $consumer->stopConsuming();
            })
            ->build()
            ->consume();

        // 3. Ask the group coordinator what it has stored. The committed
        // offset is the NEXT offset to read, so it is the record offset + 1.
        $conf = new Conf;
        $conf->set('metadata.broker.list', $brokers);
        $conf->set('group.id', self::GROUP);
        $committed = (new KafkaConsumer($conf))
            ->getCommittedOffsets([new TopicPartition(self::TOPIC, $partition)], 10000)[0]
            ->getOffset();

        if ($committed < $offset + 1) {
            $this->error("committed {$committed} is behind produced {$offset}");

            return self::FAILURE;
        }
        $this->info("group committed offset {$committed} -> processed offset {$offset}");

        return self::SUCCESS;
    }
}

Redis Streams ​

فلسفه: log به‌صورت ساختار داده داخل پایگاه‌دادهای که از قبل اجرا می‌کنید. زنجیرهٔ شواهد: id در XADD سپس شمارش XPENDING سپس XACK سپس شمارش XPENDING. برگشتن id از XADD فقط ثابت می‌کند entry همین الان روی primary هست: Redis می‌گوید "by default the asynchronous replication will not guarantee that XADD commands or consumer groups state changes are replicated"، "AOF must be used with a strong fsync policy if persistence of messages is important" و WAIT از دست رفتن را "very unlikely" می‌کند، نه ناممکن (streams، WAIT). بعد از XACK entry در stream می‌ماند؛ فقط pending list کوچک می‌شود.

go
// Command redis proves one entry was delivered and processed end to end:
// XADD id -> XREADGROUP -> XPENDING count -> XACK -> XPENDING count.
package main

import (
	"context"
	"fmt"
	"os"
	"strings"
	"time"

	"github.com/redis/go-redis/v9"
)

const group = "workers"

// A fresh stream per run keeps old pending entries out of the counts.
var stream = fmt.Sprintf("verify:orders:%d", time.Now().UnixNano())

func main() {
	addr := os.Getenv("REDIS_ADDR") // e.g. localhost:6379
	if addr == "" {
		fmt.Println("set REDIS_ADDR to run this check")
		return
	}
	if err := run(addr); err != nil {
		fmt.Fprintln(os.Stderr, "FAIL:", err)
		os.Exit(1)
	}
}

func run(addr string) error {
	ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
	defer cancel()

	rdb := redis.NewClient(&redis.Options{Addr: addr})
	defer rdb.Close()
	defer rdb.Del(context.Background(), stream)

	// Create the group (and the stream) once; BUSYGROUP means it already exists.
	err := rdb.XGroupCreateMkStream(ctx, stream, group, "0").Err()
	if err != nil && !strings.HasPrefix(err.Error(), "BUSYGROUP") {
		return err
	}

	// 1. XADD returns the entry id the server assigned. A non-error reply means
	// the entry is in the stream in the primary's memory; whether it survives a
	// crash depends on AOF/replication settings, not on this reply.
	id, err := rdb.XAdd(ctx, &redis.XAddArgs{
		Stream: stream,
		Values: map[string]any{"order_id": 42},
	}).Result()
	if err != nil {
		return err
	}
	fmt.Println("XADD id:", id)

	// 2. Deliver to a consumer of the group; ">" means "never delivered before".
	res, err := rdb.XReadGroup(ctx, &redis.XReadGroupArgs{
		Group:    group,
		Consumer: "worker-1",
		Streams:  []string{stream, ">"},
		Count:    1,
		Block:    2 * time.Second,
	}).Result()
	if err != nil {
		return err
	}
	var got string
	for _, s := range res {
		for _, m := range s.Messages {
			got = m.ID
		}
	}
	if got == "" {
		return fmt.Errorf("nothing delivered")
	}

	// 3. Delivered but not acknowledged: the entry sits in the group's PEL.
	p, err := rdb.XPending(ctx, stream, group).Result()
	if err != nil {
		return err
	}
	fmt.Println("XPENDING before XACK:", p.Count)

	// ...write to the database here, then acknowledge...
	if err = rdb.XAck(ctx, stream, group, got).Err(); err != nil {
		return err
	}

	p, err = rdb.XPending(ctx, stream, group).Result()
	if err != nil {
		return err
	}
	if p.Count != 0 {
		return fmt.Errorf("still pending: %d", p.Count)
	}
	fmt.Println("XPENDING after XACK: 0 -> processed", got)
	return nil
}
php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;

/**
 * php artisan verify:redis-stream
 *
 * Laravel's redis queue driver uses lists and sorted sets, not streams, so this
 * goes through the Redis facade. Method signatures below are phpredis's
 * (REDIS_CLIENT=phpredis); Predis orders its arguments differently.
 */
class VerifyRedisStream extends Command
{
    protected $signature = 'verify:redis-stream';

    protected $description = 'XADD, XREADGROUP, check XPENDING, XACK, check XPENDING again';

    private const GROUP = 'workers';

    public function handle(): int
    {
        // A fresh stream per run keeps old pending entries out of the counts.
        $stream = 'verify:orders:'.bin2hex(random_bytes(4));

        Redis::xgroup('CREATE', $stream, self::GROUP, '0', true); // MKSTREAM

        // 1. XADD returns the id the server assigned. It proves the entry is in
        // the stream on the primary, not that it is durable or consumed.
        $id = Redis::xadd($stream, '*', ['order_id' => 42]);
        $this->info("XADD id: {$id}");

        // 2. Deliver to one consumer of the group.
        $read = Redis::xreadgroup(self::GROUP, 'worker-1', [$stream => '>'], 1, 2000);
        $got = array_key_first($read[$stream] ?? []);
        if ($got === null) {
            $this->error('nothing delivered');

            return self::FAILURE;
        }

        // 3. Delivered but unacknowledged: the entry is in the group's PEL.
        $this->line('XPENDING before XACK: '.Redis::xpending($stream, self::GROUP)[0]);

        // ...write to the database here, then acknowledge...
        Redis::xack($stream, self::GROUP, [$got]);

        $pending = (int) Redis::xpending($stream, self::GROUP)[0];
        Redis::del($stream);

        if ($pending !== 0) {
            $this->error("still pending: {$pending}");

            return self::FAILURE;
        }
        $this->info("XPENDING after XACK: 0 -> processed {$got}");

        return self::SUCCESS;
    }
}

در سیستم‌های واقعی ​

  • quorum queueهای RabbitMQ. confirm وقتی فرستاده می‌شود که اکثریت پیام را دارد؛ dead-lettering از نوع at-least-once با "publisher confirms turned on internally" دوباره publish می‌کند؛ از نسخهٔ ۴.۰ delivery limit پیش‌فرض ۲۰ است (confirms، DLX، quorum queues).
  • delay در RabbitMQ 4.4. ناشر x-opt-delivery-time را می‌گذارد؛ مخزن افزونهٔ delayed-message-exchange می‌گوید "This Project is No Longer Maintained".
  • share groupهای Kafka. رکوردها زیر قفلی گرفته می‌شوند که پیش‌فرضش ۳۰ ثانیه است (share.record.lock.duration.ms) و تعداد تلاش‌های تحویل شمرده می‌شود (design).
  • Redis. وضعیت stream و group در AOF و RDB می‌رود و ناهمگام replicate می‌شود، پس failover می‌تواند نوشتن‌های ackشده را از دست بدهد مگر WAIT و fsync قوی داشته باشید (persistence).
  • SQS. retention پیش‌فرض ۴ روز (۶۰ ثانیه تا ۱۴ روز)، visibility timeout پیش‌فرض ۳۰ ثانیه تا ۱۲ ساعت، FIFO بدون حالت high-throughput ۳۰۰ تراکنش در ثانیه برای هر partition و هر API (quotas).
  • Pub/Sub. retention تا ۳۱ روز روی topic؛ پیش‌فرض subscription ۷ روز؛ exactly-once یک flag برای هر subscription است که "not resent before the acknowledgment deadline" و "an acknowledged message will not be resent" را تضمین می‌کند، در حالی که retry ناشر هنوز می‌تواند پیام‌های متمایز بسازد (تعریف API).
  • Laravel. driver database روی engineهای پشتیبانی‌شده ردیف‌ها را با FOR UPDATE SKIP LOCKED قفل می‌کند (Illuminate\Queue\DatabaseQueue).

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

Under ~100 jobs/s, one app,jobs only from your own code?yesLaravel databaseor redis drivernoMust consumers re-read historyor many teams read the same data?yesnoOver ~10k msg/s, partitions and an opsteam available, or managed Kafka?yesnoKafka (or Pulsar)partitioned logRabbitMQ streams orNATS JetStreamNeed routing, per-message retry,priorities, delay or a DLQ?yesnoRabbitMQ (quorum)or SQS on AWSRedis Streams if youtrust its persistenceTie-breakers: what the team can operate at 3 a.m.; whether a managed service exists;whether the cloud already has SQS/SNS or Pub/Sub; MQTT devices point to RabbitMQ or NATS.

مونولیت (Monolith) ​

یک برنامهٔ Laravel، یک پایگاه‌داده. jobها به driver database می‌روند (یا وقتی polling اذیت کرد redis). jobهای delayed و failed را delay() و failed_jobs پوشش می‌دهند. اضافه کردن broker اینجا هزینه بدون سود است؛ interface Publisher را فقط اگر به‌زودی consumer با زبان دیگری می‌آید نگه دارید. مثال: ایمیل تأیید سفارش با ۵ job در ثانیه.

مونولیت ماژولار ​

ماژول‌ها integration eventها را درون‌فرایندی یا از همان queue منتشر می‌کنند، با outbox داخل تراکنش خود ماژول. هر ماژول مالک نوع eventهای خودش است؛ انتخاب broker همچنان database یا Redis است. مثال: Billing به OrderPlaced از Sales گوش می‌دهد و کلاس event همان قرارداد است (domain events در برابر integration events).

میکروسرویس‌ها (Microservices) ​

سرویس‌ها پروتکل و deploy مستقل می‌خواهند، پس broker واقعی می‌آید. تقسیم رایج: topic exchange در RabbitMQ برای commandها و eventهای سرویس، با quorum queue، DLX و delivery limit؛ Kafka فقط اگر چند تیم replay می‌خواهند. هر handler idempotent است (inbox)؛ جریان‌های بلند saga می‌شوند؛ سبک ارتباط سرویس‌ها در service communication و اطمینان در designing for failure انتخاب می‌شود.

1 Order service   -> outbox row in the same DB transaction as the order
2 Relay           -> RabbitMQ exchange "orders", key "order.placed"
3 Billing queue   -> charge, ack after INSERT into billing + inbox
4 Failure x20     -> DLX -> orders.dead, alert, manual or scheduled replay

داده توزیع‌شده (Distributed data) ​

replicaها، cacheها و منطقه‌ها تضمین‌ها را عوض می‌کنند. replicaهای Redis ناهمگام‌اند، پس failover روی stream می‌تواند entry از دست بدهد؛ min.insync.replicas به‌علاوهٔ acks=all در Kafka دسترس‌پذیری را با پایداری معاوضه می‌کند؛ SQS/SNS و Pub/Sub منطقه‌ای‌اند و cross-region با fan-out یا geo-replication در Pulsar انجام می‌شود؛ RabbitMQ پیام را با shovel یا federation بین سایت‌ها می‌برد، نه با کشیدن یک cluster. consumerهایی که از cache یا replica می‌خوانند lag می‌بینند: replication و Redis.

مسیر مقیاس (Scaling path) ​

مقیاسچیدمانچه عوض می‌شود
1x (حدود ۱۰ پیام/ثانیه)صف database در Laravelهیچ
10x (حدود ۱۰۰ پیام/ثانیه)driver redis + Horizon، یا RabbitMQ اگر سرویس‌ها آمدندpersistence و retry
100x (حدود ۱۰٬۰۰۰ پیام/ثانیه)RabbitMQ quorum queues با competing consumers، یا Kafka برای eventهاتعداد partition/consumer (scaling consumers)
1000xKafka/Pulsar با partition برنامه‌ریزی‌شده و mirroring چند clusterبرنامه‌ریزی ظرفیت و retention، quota، حاکمیت schema

آزمایشگاه (Lab) ​

همان بار کاری را روی سه adapter اجرا و latency و lag را مقایسه کنید. expected, not run: برای این صفحه هیچ brokerی بالا نیامد؛ عددها شکلِ نتیجه‌اند نه نتیجه.

راه‌اندازی (دستورها؛ هر بار یک broker، یک ماشین، یک payload):

docker compose up -d rabbitmq            # or kafka, or redis (own compose files)
export BROKER=rabbitmq AMQP_URL=amqp://guest:guest@localhost:5672/
go run ./adapters          # publishes one message and prints "accepted by rabbitmq"
#ExperimentCommand (sketch)Expected, not run
1Publish accepted latency, 1 KB, 10,000 messages, sequentialloop Publish, record p50/p99Redis lowest; RabbitMQ (confirm) low; Kafka (acks=all) higher p50 unless batched
2Batched throughputpublish concurrently, batch 100Kafka highest; RabbitMQ and Redis medium
3Consumer lag under a slow handler (50 ms)1 consumer, publish 1,000/s for 60 sBacklog grows ~950/s on all; lag visible as queue depth, group lag, XLEN - acked
4Scale consumers to 4start 3 moreRabbitMQ and Redis drain faster; Kafka only if partitions are at least 4
5Kill the consumer mid-messagekill -9 the handlerRedelivery on all three (unacked requeue, uncommitted offset, pending entry)
6Kill the broker (replicated setup)stop the leaderRabbitMQ quorum and Kafka continue after election; Redis may lose acked entries

برای هر broker ثبت کنید: p50/p99 تأخیر publish، تأخیر سرتاسر (timestamp انتشار در header و تفریق در handler)، اوج lag و تکراری‌های دیده‌شده بعد از آزمایش ۵. با ردیف‌های ۲۶، ۲۷ و ۲۸ ماتریس مقایسه کنید.

# expected, not run: shape of the result table
broker    pub_p50  pub_p99  e2e_p99  peak_lag  duplicates
redis     <1 ms    few ms   low      grows     0..few
rabbitmq  low ms   ~10 ms   low      grows     0..few
kafka     ms       ~10s ms  ms-tens  grows     0..few

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

باورواقعیت
«Kafka یک RabbitMQ سریع‌تر است»مدل‌ها فرق دارند؛ Kafka در throughput log برتر است و RabbitMQ در routing و قابلیت‌های تک‌پیام
«RabbitMQ روی دیسک نگه می‌دارد، Kafka در حافظه» (یا برعکس)هر دو persist می‌کنند؛ RabbitMQ پیام persistent در queue durable را، Kafka همیشه در log می‌نویسد
«Redis Streams پایدار است چون XADD برگشت»روی primary است؛ پایداری تنظیم AOF و replication است
«pub/sub و Streams در Redis یکی‌اند»pub/sub ذخیره و ack ندارد
«exactly-once بین سیستم‌ها وجود دارد»فقط داخل یک سیستم (تراکنش Kafka)؛ جای دیگر at-least-once به‌علاوهٔ idempotency
«confirm یعنی پردازش شد»یعنی پذیرفته شد
«offset ثبت‌شده یعنی رکوردهای قبل موفق بودند»یعنی position جلو رفت
«brokerهای managed ops نمی‌خواهند»طراحی topic، lag و هزینه با شماست
«SQS FIFO بی‌نهایت است»بدون حالت high-throughput، ۳۰۰ TPS برای هر partition و هر API
«لایهٔ انتزاع brokerها را قابل‌تعویض می‌کند»فقط اشتراک را می‌پوشاند؛ ترتیب، retry و replay هنوز فرق دارند

چکیدهٔ فشرده (Cheat sheet) ​

موضوعچه چیز یادتان بماند
انتخاب اولصفی که الان دارید (Laravel database/redis)
Task queue با retry/DLQ/delayRabbitMQ quorum queues
Event bus و replayKafka (یا Pulsar، JetStream، RabbitMQ streams)
سبک، سریع، داخل stackRedis Streams، با فهم AOF و WAIT
AWS / GCP managedSQS+SNS / Pub/Sub
ترتیبدر هر queue، partition، stream، message group، ordering key
پذیرفته در برابر پردازش‌شدهconfirm/offset/XADD در برابر ack/commit/XACK
Dual writeهرگز؛ outbox
مهاجرتdual publish از outbox، consumer idempotent، یک group در هر بار
همزیستیcommand روی broker نوع queue، event روی broker نوع log
هزینهماشین، ذخیره × replication، شبکه، آدم
ضدتصمیم‌هاKafka با ۱۰۰ پیام/ثانیه؛ Redis pub/sub برای چیزی که نباید گم شود
Laravelداخلی: database، sqs، redis، beanstalkd، sync، null؛ بقیه با package یا client خام
درزPublisher/Consumer، handlerهای idempotent

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

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

۱ — همکارتان Kafka را برای ۸۰ job در ثانیهٔ resize تصویر پیشنهاد می‌دهد. چه می‌گویید و چه پیشنهاد می‌کنید؟ حیاتی ​

پاسخ

پاسخ: Kafka retry و delay و DLQ تک‌پیام ندارد و یک job کند partition را متوقف می‌کند؛ صف database/redis در Laravel یا RabbitMQ.

۲ — چرا «RabbitMQ می‌تواند replay کند» می‌تواند غلط باشد؟ حیاتی ​

پاسخ

پاسخ: queueهای classic و quorum با ack حذف می‌کنند؛ replay به RabbitMQ streams نیاز دارد.

۳ — offset برگشتی Kafka چه چیزی را ثابت می‌کند و چه چیزی را نه؟ مهم ​

پاسخ

پاسخ: broker رکورد را پذیرفته (با acks=all یعنی in-sync replicaها). دربارهٔ پردازش توسط consumer چیزی نمی‌گوید.

۴ — واحد ترتیب را برای Kafka، SQS FIFO، Pub/Sub و RabbitMQ بگویید. حیاتی ​

پاسخ

پاسخ: partition، message group، ordering key، queue.

۵ — چرا pub/sub برای رویداد پرداخت مناسب نیست؟ حیاتی ​

پاسخ

پاسخ: بدون subscriber پیام رفته است؛ ack و replay ندارد.

۶ — چطور یک consumer group را امن از RabbitMQ به Kafka ببرید؟ مهم ​

پاسخ

پاسخ: dual publish از outbox، consumer idempotent روی Kafka در حالت shadow، مقایسه، جابه‌جایی group، تخلیهٔ queue قدیم.

۷ — retention پیش‌فرض SQS و حداکثرش چقدر است؟ تکمیلی ​

پاسخ

پاسخ: ۴ روز پیش‌فرض، ۶۰ ثانیه تا ۱۴ روز.

۸ — چرا adapter کافکا در Go در رکورد خراب می‌ایستد؟ مهم ​

پاسخ

پاسخ: Kafka position را commit می‌کند نه ack تک‌پیام؛ commit رکورد بعدی بی‌صدا رکورد خراب را می‌پوشاند.

۹ — کی به برنامهٔ Laravel broker اضافه می‌کنید؟ حیاتی ​

پاسخ

پاسخ: وقتی صف database/redis به محدودیت مشخصی خورد: consumer با زبان دیگر، retry تک‌پیام بین سرویس‌ها، replay، بار روی پایگاه‌داده یا نیاز managed در cloud.

۱۰ — حجم ذخیره برای ۱٬۰۰۰ پیام یک‌کیلوبایتی در ثانیه با retention هفت‌روزه و replication factor برابر ۳ چقدر است؟ مهم ​

پاسخ

پاسخ: حدود 1 MB/s × 604,800 s ≈ 605 GB، ضرب در ۳ ≈ 1.8 TB.

واژه‌نامه ​

اصطلاحمعنی
Brokerسروری که پیام را ذخیره و مسیریابی می‌کند
Queue (صف)مقصدی که پیام بعد از ack از آن حذف می‌شود
Log (لاگ)دنبالهٔ افزایشی و نگه‌داشته‌شده که با position خوانده می‌شود
Topicکانال نام‌دار (Kafka، Pulsar، SNS، Pub/Sub)
Partitionیک تکهٔ مرتب از topic در Kafka یا Pulsar
Consumer groupconsumerهایی که کار topic و positionها را تقسیم می‌کنند
Offsetجایگاه رکورد در partition
Ackconsumer به broker می‌گوید پیام پردازش شد
Publisher confirmسیگنال RabbitMQ که broker publish را پذیرفت
acks=allتنظیم تولید در Kafka: منتظر in-sync replicaها
ISRin-sync replicaهای یک partition در Kafka
DLX / DLQexchange / queue پیام‌های مرده در RabbitMQ
Delivery limitحداکثر تحویل مجدد قبل از dead-letter (quorum queues)
Quorum queueنوع queue replicate‌شدهٔ RabbitMQ با Raft
Stream (RabbitMQ)نوع queue غیرمخرب و افزایشی
Pending entries listفهرست entryهای تحویل‌شدهٔ ack‌نشدهٔ group در Redis
XAUTOCLAIMفرمان Redis برای گرفتن entryهای pending بیکار
JetStreamلایهٔ persistence در NATS
Share groupمصرف queue‌مانند partitionها در Kafka
Visibility timeoutمدتی که پیام دریافت‌شده در SQS پنهان می‌ماند
Redrive policyقاعدهٔ SQS برای انتقال به DLQ بعد از دریافت‌های مکرر
Outboxجدولی که همراه دادهٔ کسب‌وکار نوشته و به broker relay می‌شود
Idempotent consumerhandler که اجرای دوباره برای یک پیام بی‌خطر است
Anti-decisionانتخابی که زیر بار کاری گفته‌شده شکست می‌خورد
KRaftquorum metadata داخلی Kafka که جای ZooKeeper را گرفت
Geo-replicationreplicate کردن topicها بین cluster/منطقه‌ها

منابع ​

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