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 و Laravel | Go، Laravel |
| هر broker چطور «پذیرفته، تحویل، پردازش» را ثابت میکند | تفاوتهای اجرا در brokerها |
| از مونولیت تا چندمنطقهای | در معماری |
| آزمایشگاه مقایسه (expected, not run) | آزمایشگاه |
همهچیز در یک دقیقه
جدول ۱: فلسفه. هر broker اول به یک پرسش دیگر جواب میدهد.
| RabbitMQ | Kafka | Redis Streams | |
|---|---|---|---|
| ایدهٔ اصلی | broker باهوش پیام را به queueها مسیر میدهد؛ پیام با ack پاک میشود | log افزایشی، تکهتکه (Partition) و replicate شده؛ position دست consumer است | log افزایشی داخل Redis با consumer group |
| بهترین در | taskها، commandها، routing، retry، delay، request/reply | event log، replay، خوانندههای زیاد، stream processing، حجم بالا | streamهای کوچک و سریع در stackی که Redis دارد |
| ضعیفترین در | نگهداری بلند و replay میلیونها event (از streamهایش استفاده کنید) | retry تکپیام، delay، priority، راهاندازی کوچک | پایداری پیشفرض، دادهٔ بزرگتر از RAM |
| شما اجرا میکنید | یک cluster broker | cluster با partition، retention و rebalance | Redis بهعلاوهٔ persistence و failoverی که خودتان تنظیم میکنید |
جدول ۲: بار کاری به انتخاب اول.
| بار کاری | انتخاب اول | چرا |
|---|---|---|
| کارهای پسزمینه داخل یک برنامهٔ Laravel | driver 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/reply | RabbitMQ یا NATS | reply-to و correlation بومیاند (request-reply) |
| IoT / MQTT | RabbitMQ (افزونهٔ MQTT)، NATS یا IoT hub managed | پروتکل |
| fan-out بین منطقهها (cross-region) | geo-replication در Pulsar، mirroring در Kafka، SNS/SQS، Pub/Sub | replication بین منطقهها قابلیت است، نه اسکریپت |
| serverless | SQS/SNS (AWS)، Pub/Sub (GCP) | managed و trigger آماده |
جدول ۳: پنج پرسشی که بیشتر موردها را تعیین میکنند.
| پرسش | اگر بله | اگر نه |
|---|---|---|
| consumer جدید باید تاریخچه را بخواند؟ | Log: Kafka، Pulsar، JetStream، RabbitMQ streams | Queue: RabbitMQ، SQS |
| یک پیام کند باید تنها و بعداً retry شود؟ | Queue با ack تکپیام و DLQ | Log کافی است |
| اوج پایدار بالای حدود ۱۰٬۰۰۰ پیام در ثانیه است؟ | 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 حیاتی
| # | Dimension | RabbitMQ | Kafka | Redis Streams |
|---|---|---|---|---|
| 1 | Model | Exchanges route to queues; queue types: classic, quorum, stream | Topic of partitions, each an append-only log | Stream key (a log) with consumer groups |
| 2 | Storage structure | Per-queue message store; streams are a log | Segment files per partition | In-memory radix tree, persisted by AOF/RDB |
| 3 | Unit of consumption | One delivery, acked individually | A record at an offset; commit moves a position | One entry, acked individually in the group's pending list |
| 4 | Ordering scope | Per queue (single consumer); competing consumers and requeue can reorder | Per partition | Per stream |
| 5 | Ordering key story | Single active consumer or consistent-hash exchange | Partition key | One stream per key, or one stream |
| 6 | Default delivery guarantee | At-least-once with publisher confirms and manual ack | At-least-once (idempotent producer removes producer-retry duplicates) | At-least-once via group pending list |
| 7 | Exactly-once story | None end to end; idempotent consumers | Transactions give it inside Kafka; external effects need idempotency | None; idempotent consumers (Redis 8.6 adds idempotent production, check your version) |
| 8 | "Accepted" signal | Publisher confirm (plus mandatory return) | Produce callback with partition and offset (acks=all) | XADD reply with entry id |
| 9 | "Processed" signal | basic.ack | Committed offset (position) | XACK |
| 10 | Persistence | Persistent messages in durable queues; quorum and stream queues always replicated | Always on disk; flush policy is OS-driven by default | Off by default unless AOF/RDB configured |
| 11 | Durability knob | Quorum queue (majority), confirms | acks=all, min.insync.replicas, replication factor | AOF appendfsync, WAIT |
| 12 | Replication | Raft-based quorum queues; streams replicated | Leader and follower per partition, ISR | Asynchronous primary/replica |
| 13 | Failover | Quorum leader election | Leader election per partition (KRaft controller) | Sentinel or Cluster promote a replica; can lose acked writes |
| 14 | Consumer model | Push (basic.consume) with prefetch, or pull (basic.get) | Pull with fetch batches | Pull with blocking XREADGROUP |
| 15 | Parallelism limit | Many consumers per queue | Consumers per group up to partition count (share groups lift it) | Many consumers per group |
| 16 | Fan-out | Bind several queues to an exchange | Several consumer groups on one topic | Several groups on one stream |
| 17 | Routing | Direct, topic, fanout, headers exchanges | Topic and key only | Stream name only |
| 18 | Priorities | Classic and quorum queues support them | None | None |
| 19 | Delay / scheduling | Quorum queues since 4.4 (x-opt-delivery-time); TTL + DLX earlier | None built in | None built in (sorted set pattern) |
| 20 | Retry | Requeue, delivery limit (default 20 on quorum queues since 4.0), DLX loops | Client side: retry topics | Client side: XPENDING + XAUTOCLAIM |
| 21 | DLQ | Built in (DLX, at-least-once dead-lettering on quorum) | Convention: a dead-letter topic you produce to | Convention: another stream |
| 22 | Retention | Queues: until acked or TTL; streams: size/age | Time/size, or compaction by key; tiered storage for old segments | Until trimmed (MAXLEN, MINID); bounded by RAM |
| 23 | Replay | Streams only | Yes, seek to any offset | Yes, read from any id |
| 24 | Key compaction | No | Yes (cleanup.policy=compact) | No |
| 25 | Message size | max_message_size default 16 MiB, max 512 MiB (config doc) | max.message.bytes default 1048588 | Entry is a hash of fields; keep small, RAM-bound |
| 26 | Throughput class | Medium (per-message bookkeeping) | High (batched sequential I/O) | Medium to high, memory-bound |
| 27 | Latency class | Low | Low to medium (batching adds latency) | Lowest |
| 28 | Backpressure | Consumer prefetch, publisher flow control, memory alarms | Consumer pulls at its pace; broker quotas | None built in; trim policy and XLEN monitoring |
| 29 | Multi-tenancy | Virtual hosts with per-vhost permissions | Topics, ACLs, client quotas | Key prefixes, ACLs, logical DBs (not in Cluster) |
| 30 | Protocols | AMQP 0-9-1, AMQP 1.0, MQTT 5.0 (plugin), STOMP, streams protocol | Kafka protocol (plus HTTP REST proxies as add-ons) | RESP |
| 31 | Schema support | None built in (content-type header) | Not in Apache Kafka; Confluent Schema Registry or Apicurio | None |
| 32 | Transactions | AMQP tx.select on a channel (slow) | Producer transactions and read_committed (KIP-98) | MULTI/EXEC, Lua scripts |
| 33 | Ops complexity | Medium: cluster, queue types, memory/disk alarms | High: partitions, retention, rebalances, controller quorum | Low if Redis already runs; failover is yours |
| 34 | Scaling out | More queues and nodes; a single queue lives on its replicas | Add partitions and brokers | Cluster shards by key; one stream is on one shard |
| 35 | Hosting options | Self-host, CloudAMQP, Amazon MQ, Kubernetes operator | Self-host, Confluent Cloud, Amazon MSK, Aiven | Self-host, Redis Cloud, ElastiCache, Memorystore |
| 36 | Licensing | Apache 2.0 and MPL 2.0 (open source) | Apache 2.0 | Check the license of your Redis version; Valkey is the BSD fork |
| 37 | Laravel support | Package vladimir-yuldashev/laravel-queue-rabbitmq | Package mateusjunges/laravel-kafka (needs ext-rdkafka) | Redis facade; built-in redis driver uses lists, not streams |
| 38 | Go client maturity | amqp091-go (official RabbitMQ team) | franz-go (pure Go, active), kafka-go | go-redis (mature, typed) |
| 39 | Observability | Management UI, Prometheus plugin, queue depth, unacked | Consumer lag per partition, JMX metrics | XINFO, XPENDING, INFO |
| 40 | Security | TLS, SASL, per-vhost configure/write/read permissions | TLS, SASL (PLAIN, SCRAM, GSSAPI, OAUTHBEARER), ACLs | TLS, ACLs, AUTH |
ردیفهای ۶ تا ۱۳ در delivery guarantees و acknowledgment باز شدهاند؛ ۴ و ۵ در ordering؛ ۱۴ و ۱۵ در competing consumers؛ ۱۷ و ۱۸ در routing؛ ۱۹ تا ۲۱ در retry و delay و DLQ؛ ۲۸ در backpressure؛ ۳۱ در schema evolution؛ ۳۹ در observability؛ ۴۰ در security.
رادار شش محور ماتریس را به یک شکل فشرده میکند. این قضاوت از روی جدول بالاست، نه benchmark: RabbitMQ در routing و delay/DLQ پهن است، Kafka در replay و throughput بلند، و Redis Streams در latency و سادگی قویتر.
ستونهای دیگر مهم
عمداً کوتاه است؛ جزئیات در سایر brokerها. «check» یعنی عددی که اینجا از منبع اصلی نخواندهایم.
| # | Dimension | NATS JetStream | Pulsar | SQS / SNS | Google Pub/Sub | Laravel database / sqs drivers |
|---|---|---|---|---|---|---|
| 1 | Model | Streams capture subjects; consumers read them | Topics with subscriptions; segment storage | SQS queue; SNS topic fans out to queues | Topic and subscriptions | A jobs table; an SQS queue |
| 2 | Ordering | Per stream | Per partition (Key_Shared per key) | SQS FIFO per message group; Standard best effort | Per ordering key when enabled | Table: by id, not guaranteed; SQS Standard unordered |
| 3 | Delivery | At-least-once with ack; Nats-Msg-Id dedup window | At-least-once; transactions | Standard at-least-once; FIFO dedup | At-least-once; exactly-once delivery option per subscription | At-least-once (lock then delete) |
| 4 | Persistence and replication | File or memory storage; replicated in a cluster | BookKeeper, replicated | Managed, multi-AZ | Managed, regional | Your database; SQS managed |
| 5 | Consumer model | Pull and push consumers; AckExplicit, AckAll, AckNone | Exclusive, Failover, Shared, Key_Shared subscriptions | Poll with visibility timeout (default 30 s, max 12 h) | Pull, push, streaming pull; ack deadline | Worker polls (queue:work) |
| 6 | Routing | Subject wildcards | Topics, topic patterns | SNS filter policies to SQS | Subscription filters | Named queues, priority order |
| 7 | Delay | Not a core feature (check) | Delayed delivery on Shared subscriptions | SQS delay up to 15 min | Not a core feature (check) | Laravel delay(); SQS capped at 15 min |
| 8 | DLQ | MaxDeliver and advisories | Retry letter and dead letter topics | Redrive policy | Dead-letter topic | failed_jobs table |
| 9 | Retention and replay | Limits, work queue or interest policies; replay | Retention plus tiered storage; seek | SQS: 4 days default, 60 s to 14 days, no replay | Default 7 days, up to 31 days; seek needs retained acked messages | Until processed; no replay |
| 10 | Message size | max_payload default 1 MB (config up to 64 MB) | Default 5 MB | 1 MiB (larger via S3 extended client, up to 2 GB) | Check the quotas page | Row size / 1 MiB |
| 11 | Throughput | High, small messages | High | Standard: very high; FIFO: 300 TPS per partition per API (higher with high-throughput mode) | High, autoscaling | Low to medium |
| 12 | Multi-tenancy | Accounts | Tenants and namespaces (first class) | AWS accounts and IAM | Projects and IAM | Application level |
| 13 | Protocols | NATS protocol, MQTT support (check) | Pulsar protocol | HTTPS API | gRPC and REST | n/a |
| 14 | Schema support | None built in | Built-in schema registry | None | Topic schemas (Avro, Protocol Buffers) | None |
| 15 | Transactions | Batch publish, no multi-stream tx (check) | Yes | FIFO dedup only | None across topics | Database transaction (afterCommit) |
| 16 | Ops complexity | Low to medium | High (brokers plus BookKeeper) | None (managed) | None (managed) | Lowest |
| 17 | Hosting | Self-host, Synadia Cloud | Self-host, StreamNative | AWS only | GCP only | Wherever your DB or AWS runs |
| 18 | Licensing | Apache 2.0 | Apache 2.0 | Proprietary service | Proprietary service | MIT (Laravel) |
| 19 | Laravel | No first-party; use a client | No first-party | Built in (sqs driver) | Community packages | Built in |
| 20 | Go client | nats.go (official) | pulsar-client-go (official) | AWS SDK v2 | cloud.google.com/go/pubsub | n/a |
| 21 | Observability | nats CLI, monitoring endpoints | Admin API, Prometheus | CloudWatch | Cloud Monitoring | queue:monitor, Horizon (redis) |
| 22 | Security | TLS, accounts, JWT/NKeys | TLS, JWT, authorization | IAM, KMS | IAM, CMEK | DB 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 هر کدام میخوانند و سرویس تازهٔ شش ماه دیگر میخواهد از روز اول بازسازی کند).
| نیاز | Queue | Log |
|---|---|---|
| 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 | پذیرفته شد | پردازش شد |
|---|---|---|
| RabbitMQ | Confirm؛ در quorum queue اکثریت replicaها | basic.ack |
| Kafka | callback تولید با offset (acks=all) | offset ثبتشده = offset بعدی برای خواندن |
| Redis Streams | id بازگشتی XADD روی primary | XACK ورودی 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هایی دیده است.
| Broker | Replay | محدود به |
|---|---|---|
| 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 | کارهای اصلی عملیات |
|---|---|
| RabbitMQ | alarm حافظه/دیسک، انتخاب نوع queue، عضویت quorum، shovel/federation بین سایتها |
| Kafka | تعداد partition، retention، under-replicated partition، rebalance، controller quorum |
| Redis Streams | maxmemory، persistence، failover، trim |
| SQS/SNS، Pub/Sub | quota، هزینه، 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 در AWS | job idempotent، backoff (retry) | retry هر پیام از throughput مهمتر است |
| Event bus | Kafka، Pulsar؛ topic exchange در RabbitMQ در مقیاس کوچک | outbox، schema نسخهدار (schema) | مشترکین مستقل |
| Event log / replay | Kafka، Pulsar، JetStream، RabbitMQ streams | topic فشرده برای state | خواندن بدون حذف |
| Stream processing | Kafka (Kafka Streams، Flink) | exactly-once داخل Kafka | اکوسیستم |
| Request/reply | RabbitMQ (reply-to)، NATS | correlation id، timeout | الگوی بومی |
| IoT / MQTT | افزونهٔ MQTT در RabbitMQ، NATS، IoT managed | bridge به Kafka برای analytics | پروتکل |
| Cross-region | geo-replication در Pulsar، SNS+SQS، Pub/Sub؛ mirroring در Kafka؛ shovel/federation در RabbitMQ | مالکیت منطقهای داده | latency و دامنهٔ خطا |
| Serverless | SQS/SNS، Pub/Sub | redrive، payload کوچک | trigger مدیریتشده |
بر اساس بلوغ تیم و ops مهم
| وضعیت تیم | پیشنهاد | دلیل |
|---|---|---|
| ۱ تا ۳ توسعهدهنده، یک برنامه | صف database یا Redis | یک چیز برای اجرا |
| تیم کوچک، چند سرویس، نیاز به retry/DLQ | RabbitMQ 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 |
| بالای ۱۰۰٬۰۰۰ پیام در ثانیه | هفته، replay | Kafka یا Pulsar با partition برنامهریزیشده |
این بازهها قاعدهٔ سرانگشتی از روی ردهٔ ماتریساند، نه اندازهگیری؛ با آزمایشگاه تأییدشان کنید.
بر اساس نیاز سازگاری مهم
| نیاز | پیشنهاد | دلیل |
|---|---|---|
| هیچ پیامی هرگز گم نشود | outbox بهعلاوهٔ quorum queue یا Kafka با acks=all | confirm بعد از replication پایدار |
| از دست رفتن قابلقبول (اشارهٔ ابطال cache) | Redis pub/sub یا لیست Redis | ارزانترین |
| ترتیب سخت برای هر موجودیت | کلید Kafka، گروه SQS FIFO، queue با single-active-consumer | واحد ترتیب |
| «نوشتن DB و publish» اتمی | outbox + relay یا CDC | هیچ brokerی تراکنش اتمی با پایگاهدادهٔ شما ندارد |
| consume-transform-produce اتمی | تراکنشهای Kafka | فقط داخل Kafka |
راهحلها: مهاجرت و همزیستی
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_CONNECTION | persistence در Redis |
| Redis به RabbitMQ | نیاز به retry، DLQ، routing، پایداری | consumerها و topology | prefetch و معنای ack |
| RabbitMQ به Kafka (eventها) | خوانندههای زیاد، replay | کلیدها partition key میشوند | retry تکپیام از بین میرود |
| Kafka به RabbitMQ | topic در واقع work queue بود | offsetها کنار میروند | replay را از دست میدهید |
| هر broker به managed همپروتکل | هزینهٔ ops | endpoint و credential | quota و نسخه |
همزیستی (Coexistence) مهم
به زبان ساده: بسیاری از شرکتها عمداً دو broker دارند: queue برای commandها، log برای eventها.
بدفهمی رایج: «دو broker یعنی مهاجرت شکستخورده.» اغلب همین وضعیت پایدار نهایی است.
| جفت | تقسیم کار |
|---|---|
| RabbitMQ + Kafka | commandها و taskها در برابر eventهای دامنه و analytics |
| Redis + Kafka | cache و کار سبک در برابر event log پایدار |
| SQS + Kafka | jobهای بومی AWS در برابر eventهای بینتیمی |
| Laravel database + RabbitMQ | jobهای درونبرنامه در برابر یکپارچهسازی سرویسها |
فقط در لبه با 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 30 | 2.592 billion |
| ورودی | 1,000 x 1 KB | about 1 MB/s |
| دادهٔ نگهداشتهشده | 1 MB/s x 604,800 s | about 605 GB |
| با replication ۳ ذخیرهشده | 605 GB x 3 | about 1.8 TB |
| درخواست SQS (send، receive، delete، بدون batch) | 2.592 billion x 3 | about 7.8 billion |
| عامل هزینه | Self-host | Managed |
|---|---|---|
| ظرفیتسنجی | شما، از قبل | 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 هم را بلاک نمیکنند:
-- 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 جاب Laravel | RabbitMQ یا Kafka با قرارداد پیام مستند |
| retry تکپیام بین سرویسها، DLQ، routing | قابلیتهای queue | RabbitMQ |
| replay یا خوانندههای مستقل زیاد | Log | Kafka |
| 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 تنظیم نشود خارج میشود.
// 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
}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() }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 }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() }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
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
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
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
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
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
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
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".
// 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
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).
// 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
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 کوچک میشود.
// 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
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).
در معماری: از یک فرایند تا سیستم توزیعشده
مونولیت (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) |
| 1000x | Kafka/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"| # | Experiment | Command (sketch) | Expected, not run |
|---|---|---|---|
| 1 | Publish accepted latency, 1 KB, 10,000 messages, sequential | loop Publish, record p50/p99 | Redis lowest; RabbitMQ (confirm) low; Kafka (acks=all) higher p50 unless batched |
| 2 | Batched throughput | publish concurrently, batch 100 | Kafka highest; RabbitMQ and Redis medium |
| 3 | Consumer lag under a slow handler (50 ms) | 1 consumer, publish 1,000/s for 60 s | Backlog grows ~950/s on all; lag visible as queue depth, group lag, XLEN - acked |
| 4 | Scale consumers to 4 | start 3 more | RabbitMQ and Redis drain faster; Kafka only if partitions are at least 4 |
| 5 | Kill the consumer mid-message | kill -9 the handler | Redelivery on all three (unacked requeue, uncommitted offset, pending entry) |
| 6 | Kill the broker (replicated setup) | stop the leader | RabbitMQ 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/delay | RabbitMQ quorum queues |
| Event bus و replay | Kafka (یا Pulsar، JetStream، RabbitMQ streams) |
| سبک، سریع، داخل stack | Redis Streams، با فهم AOF و WAIT |
| AWS / GCP managed | SQS+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 group | consumerهایی که کار topic و positionها را تقسیم میکنند |
| Offset | جایگاه رکورد در partition |
| Ack | consumer به broker میگوید پیام پردازش شد |
| Publisher confirm | سیگنال RabbitMQ که broker publish را پذیرفت |
acks=all | تنظیم تولید در Kafka: منتظر in-sync replicaها |
| ISR | in-sync replicaهای یک partition در Kafka |
| DLX / DLQ | exchange / 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 consumer | handler که اجرای دوباره برای یک پیام بیخطر است |
| Anti-decision | انتخابی که زیر بار کاری گفتهشده شکست میخورد |
| KRaft | quorum metadata داخلی Kafka که جای ZooKeeper را گرفت |
| Geo-replication | replicate کردن topicها بین cluster/منطقهها |
منابع
- Apache Kafka documentation, Design, Producer configs, Topic configs, KRaft
- RabbitMQ, Confirms, Reliability, Dead Letter Exchanges, Quorum Queues, Streams, Priority queues, MQTT, Configuration
- Redis, Streams, XACK, WAIT, Persistence
- NATS, JetStream, Streams, Consumers
- Apache Pulsar, Messaging concepts, Overview
- AWS, SQS quotas, SNS FIFO topics
- Google, Pub/Sub API definition
- Laravel 13, Queues, Redis; DatabaseQueue source
- vladimir-yuldashev/laravel-queue-rabbitmq، php-amqplib، mateusjunges/laravel-kafka، phpredis
- Go clients: amqp091-go, franz-go, go-redis
- نظر vendor: CloudAMQP، RabbitMQ vs Kafka؛ Confluent، RabbitMQ vs. Apache Kafka