Other Brokers: NATS, Pulsar, SQS/SNS & Pub/Sub
"JetStream provides ... the ability to replay messages on demand (i.e. 'streaming')." — NATS documentation, JetStream
Summary: Beyond RabbitMQ, Kafka and Redis Streams there are ten more systems you will meet in real projects, and queue and log are useful starting models, with retention policies and subscription state deciding the actual behavior. Focus: NATS JetStream, Apache Pulsar, Amazon SQS and SNS, Google Pub/Sub, Azure Service Bus and Event Hubs, MQTT brokers (Mosquitto, EMQX), ActiveMQ Artemis, ZeroMQ (a library, not a broker) and Laravel's built-in sqs and database drivers: model, guarantees, ordering, retention, consumers, delay and DLQ, scaling, protocol, hosting, Go and Laravel support, gotchas. Learning goal: Place any broker you are offered on the queue-versus-log map, predict its ack, ordering and retry behaviour from its model, choose between cloud-managed and self-hosted on purpose, and write the same publish/consume program against SQS and NATS.
This page is a survey, one section per system, and a reference for the knobs that bite in production (visibility timeout, ack deadline, AckWait, maxReceiveCount, session locks). It does not re-teach the three core brokers: RabbitMQ, Kafka and Redis Streams & Pub/Sub have their own pages, and broker comparison sets the three side by side. Every other broker here is explained by mapping it to the closest of those three, in Broker differences.
Page map
| If you are looking for | Go to |
|---|---|
| One table per concern you can memorise | Everything in one minute |
| Why so many brokers exist | Why there are more brokers |
| Where each came from | Where it comes from |
| NATS JetStream streams and consumers | NATS JetStream |
| Pulsar segments, BookKeeper, tiered storage, geo-replication | Apache Pulsar |
| Visibility timeout, FIFO limits, standard vs FIFO | Amazon SQS |
| Fan-out to queues, filter policies | Amazon SNS |
| Ack deadlines, ordering keys, exactly-once | Google Pub/Sub |
| Sessions, peek-lock, Event Hubs partitions | Azure Service Bus and Event Hubs |
| QoS levels, retained messages, last will | MQTT brokers |
| JMS and multi-protocol on the JVM | ActiveMQ Artemis |
| Sockets, no broker | ZeroMQ |
sqs and database drivers | Laravel's built-in drivers |
| Every broker in one table | The master comparison |
| Mapping to RabbitMQ, Kafka, Redis Streams | Broker differences |
| Cloud-managed vs self-hosted | Choosing |
| Go and Laravel code | Go, Laravel |
| Reproduce it locally | Lab |
Everything in one minute
Start with queue versus log, then check retention and subscriptions. A product may support both; the table is a map rather than an exhaustive guarantee.
| Model | Message after a successful ack | Consumer state lives in | Replay | Products on this page |
|---|---|---|---|---|
| Queue | Deleted | The broker (per message) | No (unless you keep a copy elsewhere) | SQS, Service Bus, Artemis, Laravel database driver, MQTT QoS 1 sessions |
| Log / stream | Kept until retention removes it | A cursor per consumer or subscription | Yes, within retention | Pulsar, NATS JetStream, Event Hubs, Kafka |
| Pub/sub with queue-like subscriptions | Deleted per subscription (optionally retained) | The subscription | Optional (Seek, retained acked messages) | Google Pub/Sub, SNS to SQS |
| Library, no broker | Not stored | Nowhere | No | ZeroMQ |
The one setting that decides redelivery on each product. Learn the name of this knob first; it is where most production incidents start.
| Product | The "I will give it back if you are too slow" knob | Default | Maximum |
|---|---|---|---|
| Amazon SQS | Visibility timeout | 30 seconds | 12 hours from first receive |
| Google Pub/Sub | Ack deadline (ackDeadlineSeconds) | 10 seconds | 600 seconds |
| NATS JetStream | AckWait (or BackOff) | Set per consumer | Any duration |
| Azure Service Bus | Lock duration (peek-lock) | Set per entity | Minutes, renewable |
| Pulsar | ackTimeout or negative-ack delay | Off (ackTimeout 0) | Any duration |
Laravel database / redis driver | retry_after | 90 seconds | Any; must exceed job timeout |
| MQTT QoS 1 | Unacked packet state; MQTT 5 retransmits on reconnect | No generic lease timer | Session expiry |
Where each one wins.
| If you need | Pick | Why |
|---|---|---|
| Zero servers, AWS already there | SQS (+ SNS) | Nothing to run; Laravel supports it out of the box |
| Zero servers, GCP already there | Pub/Sub | Global service, ordering keys, push and pull |
| Ordered, session-based work in Azure | Service Bus | Sessions give FIFO per key plus DLQ |
| Tiny messages from millions of devices | MQTT (EMQX or Mosquitto) | Lightweight protocol, QoS levels, last will |
| One system for queues, streams and multi-tenancy | Pulsar | Storage split from serving, tenants and namespaces |
| Very low latency plus durable streams in one small binary | NATS JetStream | Subjects, streams, consumers; easy to run |
| Existing JVM and JMS code | Artemis | JMS 2.0 and Jakarta Messaging, plus AMQP, MQTT, STOMP |
| Fast in-process or between processes without a server | ZeroMQ | A socket library, you design the topology |
| A queue with no new infrastructure | Laravel database driver | The table is already there |
Why there are more brokers
The three core brokers are general purpose, yet each cloud and each niche made its own because the trade-off differs: operating a broker costs people, a managed queue costs per request, a device protocol must fit a 2 KB microcontroller, and a streaming platform wants separate storage and compute. The table is the same two-column trade-off as everywhere in this section.
| You optimise | You give up |
|---|---|
| No servers to operate (SQS, Pub/Sub, Service Bus) | Fine control, portability, often per-message latency and some features (no replay on SQS) |
| One system for everything (Pulsar) | Operational weight: brokers, bookies, a metadata store |
| Small and fast (NATS) | A smaller ecosystem of connectors than Kafka |
| Device-friendly protocol (MQTT) | Rich routing and large-scale replay |
| No broker at all (ZeroMQ) | Durability, discovery, monitoring: you build them |
An everyday picture used through the page. A postal system. SQS is a post-office box the state runs: you rent a box, letters wait, you take one and must sign for it before a timer runs out. A log broker (Pulsar, JetStream, Event Hubs) is the newspaper archive: every issue stays on the shelf and each reader keeps their own bookmark. MQTT is a village noticeboard with a note saying "last will": if the person who posted goes silent, the board pins their farewell note. ZeroMQ is two neighbours running a string between their windows: fast, free, and nobody keeps the letters.
Three common misunderstandings, up front.
- "A managed queue is just RabbitMQ somebody else runs." No. SQS has no exchanges and no replay; Pub/Sub subscriptions are the routing; Service Bus is closer to RabbitMQ than SQS is, but it has sessions, which RabbitMQ does not.
- "NATS is a Redis Pub/Sub replacement." Core NATS is at-most-once like Redis Pub/Sub, but JetStream adds durable streams and consumers; they are two layers.
- "Exactly-once is a setting I can turn on." SQS FIFO, Pub/Sub exactly-once delivery and JetStream double-ack each cover one hop, under conditions. End-to-end still needs an idempotent consumer.
Where it comes from
| Origin / design lineage | What it explains | Primary source |
|---|---|---|
| NATS adds JetStream persistence to Core NATS | Transient subjects and stored streams are separate contracts | NATS docs |
| Pulsar separates brokers from BookKeeper storage | Serving and storage scale independently | Pulsar docs |
| AWS separates SQS queues from SNS topics | Work distribution and fan-out compose | SNS-to-SQS guide |
| Pub/Sub defines topics plus subscriptions | Every subscription owns a backlog | API definition |
| Azure offers Service Bus and Event Hubs | Work queues and partitioned streams solve different needs | Service Bus, Event Hubs |
| MQTT is a standard protocol, not one server | QoS is portable; storage and clustering remain product choices | OASIS MQTT 5 |
| Artemis unifies protocols through addresses and queues | JMS, AMQP and MQTT map onto broker resources | Artemis manual |
| ZeroMQ builds messaging patterns into sockets | Applications own persistence and recovery | ZeroMQ guide |
The concept catalogue: one section per system
NATS JetStream Must-know
In plain words: NATS is a small server that moves messages by subject name. JetStream is a layer inside it that saves messages into streams, so consumers can read them later and ack them.
Common misunderstanding: "NATS is fire-and-forget, so it is not reliable." Core NATS is at-most-once; JetStream is a separate persistence engine you turn on and which is, in the documentation's words, "at least once" for publishing and consuming, with an "exactly once" option built on a dedup header.
Definition: a stream is a message store that captures one or more subjects, with a retention policy (LimitsPolicy by default, WorkQueuePolicy, InterestPolicy) and limits (MaxMsgs, MaxBytes, MaxAge). A consumer is a stateful view of a stream: it remembers what it delivered and what was acked. Consumers are pull or push, durable or ephemeral. Publishing to a stream returns a PubAck with the sequence number.
Publisher Stream ORDERS Consumer "billing"
1 js.Publish(ORDERS.placed, id=order-42-placed)
2 append at seq 17
3 <-- PubAck{Sequence:17}
4 js.Publish(same Nats-Msg-Id) within the dedup window
5 <-- PubAck{Duplicate:true} (not stored again)
6 Fetch(10) -> seq 17
7 process, then Ack()
8 AckWait expires if no ack -> redeliver seq 17
9 MaxDeliver reached -> stays in the streamReal scenarios: an order service publishes ORDERS.placed; billing and shipping each own a durable consumer; a new analytics service starts a consumer at the first message and replays the whole history; a work-queue stream feeds image-resize workers with ack-based removal and possible redelivery.
| Property | JetStream |
|---|---|
| Model | Log (limits retention), queue (WorkQueuePolicy), or interest-based |
| Delivery | At-least-once; ack policies AckExplicit (default), AckAll, AckNone (AckFlowControl documented for 2.14; sourcing/mirroring use) |
| Ordering | Per stream in sequence; a pull consumer can deliver redelivered messages out of order |
| Retention / replay | Limits by count, bytes, age; ReplayPolicy instant or original; DeliverPolicy all, last, by time or sequence |
| Consumers | Pull (recommended for new projects, per the docs) or push; durable or ephemeral; ordered consumers for simple replays |
| Delay / DLQ | BackOff list for redelivery, nakWithDelay; MaxDeliver leaves the message in the stream (no automatic DLQ stream: you watch advisories and republish) |
| Flow control | MaxAckPending; pull MaxWaiting, MaxRequestBatch |
| Scaling | Streams replicate with Raft (up to 5 replicas); sources and mirrors copy between streams and clusters; leaf nodes and superclusters |
| Multi-tenancy | Accounts with isolated subject spaces and JetStream limits per account |
| Protocol | NATS text protocol over TCP; WebSocket and MQTT listeners exist |
| Licence / hosting | Apache 2.0; self-hosted, or Synadia Cloud |
Gotchas: with LimitsPolicy deleting a consumer never deletes messages, but with InterestPolicy a stream with zero consumers drops everything immediately. MaxDeliver exhaustion does not delete the message: it stays in the stream and you must find it through the advisory subjects. Backoff applies to ack timeouts, not to nak: a plain nak redelivers at once unless you use a delayed nak. Deduplication needs a Nats-Msg-Id header and works only inside the stream's DuplicateWindow.
Fix / how to use it: Go in the Go example, Laravel through the basis-company/nats package in the Laravel section.
Apache Pulsar Must-know
In plain words: Pulsar splits a broker into two layers: stateless brokers that serve clients and BookKeeper bookies that store the data in segments. That split is why it can grow storage and serving independently.
Common misunderstanding: "Pulsar is Kafka with extra pieces." The model differs: a subscription is a named cursor on a topic with a type (Exclusive, Failover, Shared, Key_Shared), so one topic serves both queue-style and stream-style consumers with no partition-count cap on Shared consumers.
Definition: a topic belongs to persistent://tenant/namespace/topic. Messages are written to BookKeeper ledgers (immutable segments once closed) through a managed ledger. A message is deleted only after every subscription has acknowledged it, unless a retention policy keeps acked messages. Old sealed segments can be offloaded to object storage by tiered storage. Geo-replication copies topic data between clusters.
Producer Broker (stateless) BookKeeper bookies Subscription "billing"
1 send(key=c7) ->
2 write to managed ledger -> 3 copies on 3 bookies
3 <- MessageId (ledger:entry) once bookies ack
4 Shared consumer A receive
5 consumer B receive (next msg)
6 A ack -> cursor moves
7 B nack -> redeliver after NackRedeliveryDelay
8 ledger sealed -> eligible for tiered storage offload (default local delete lag 4 hours)Real scenarios: a multi-tenant SaaS platform giving each customer a namespace with quotas; a billing pipeline on a Shared subscription that fans work over many workers; per-key ordered processing on Key_Shared; a long retention audit stream with old segments on S3.
| Property | Pulsar |
|---|---|
| Model | Both: topic with subscriptions; log by retention, queue by Shared subscription |
| Delivery | At-least-once; ack, cumulative ack (not on Shared/Key_Shared), negative ack, ack timeout; transactions and deduplication optional |
| Ordering | Per partition; Key_Shared keeps per-key order; negative acks can reorder on ordered types |
| Retention / replay | Acked data deleted unless retention; backlog quota and TTL; Seek and reader API for replay |
| Consumer model | Exclusive (default), Failover, Shared, Key_Shared; a unique subscription name per consumer gives fan-out |
| Delay / DLQ | Delayed delivery (deliverAt, deliverAfter) on Shared and Key_Shared; retry/dead-letter support depends on client and subscription type |
| Scaling | Add brokers (stateless) or bookies (storage) separately; partitioned topics |
| Multi-tenancy | First class: tenants, namespaces, quotas, isolation policies |
| Protocol | Pulsar binary protocol; Kafka-on-Pulsar and AMQP/MQTT proxies exist as add-ons |
| Licence / hosting | Apache 2.0; self-hosted, StreamNative, DataStax Astra Streaming |
Gotchas: the dead-letter policy maxRedeliverCount may never be reached on negative acks unless retry is enabled: the docs warn that without enableRetry(true) "the redelivery counter ... is not persisted and can be reset unexpectedly". Cumulative ack is forbidden on Shared subscriptions. Without batch-index acknowledgment, acknowledged entries of a partly processed batch can be redelivered; enable batch-index support on broker and client when needed. Geo-replication copies messages, not subscriptions: a consumer reconnecting to another cluster starts a new, unrelated subscription unless you enable replicated subscriptions, and even those are for failover, not active-active consumption. Tiered storage reads are slower on first access. The metadata store (Oxia or ZooKeeper) is one more thing to run.
Amazon SQS Must-know
In plain words: SQS is a queue you rent. You send, you receive, you delete; if you do not delete in time, the message comes back.
Common misunderstanding: "Receiving a message removes it." Receiving only hides it for the visibility timeout. The delete call is the ack. Forget it, or run longer than the timeout, and another worker gets the same message.
Definition: two queue types. Standard: nearly unlimited throughput, at-least-once delivery, best-effort ordering. FIFO (name ends in .fifo): ordering inside a MessageGroupId, deduplication on MessageDeduplicationId within a 5-minute window, and a throughput cap per partition. The visibility timeout "starts as soon as a message is delivered to you"; its default is 30 seconds and the maximum is 12 hours from first receive; ChangeMessageVisibility extends it and does not reset the 12-hour limit.
Producer SQS queue Worker A Worker B
1 SendMessage(m1) -> stored
2 ReceiveMessage(Wait=20s) -> m1 (invisible 30s)
3 processing... takes 45s
4 t=30s: visibility expires, m1 visible again
5 ReceiveMessage -> m1 (ReceiveCount=2)
6 DeleteMessage(old receipt) -> ok or error, m1 already processed twice
7 ReceiveCount > maxReceiveCount -> move to DLQ (redrive policy)Real scenarios: image processing jobs on a standard queue; per-customer ordered payment events on FIFO with MessageGroupId=customer-id; a nightly batch queue with 15-minute delay for retries; a Laravel app using QUEUE_CONNECTION=sqs.
| Property | SQS standard | SQS FIFO |
|---|---|---|
| Delivery | At-least-once | Publish deduplication for 5 minutes; processing can repeat after visibility expiry |
| Ordering | Best effort | Strict within a message group |
| Throughput | "Nearly unlimited" API calls | 300 API calls per second per partition per action (3,000 messages per second with batches of 10); high-throughput mode raises it (for example up to 70,000 TPS in some regions) |
| Retention | 4 days default, 60 seconds to 14 days | Same |
| Message size | Up to 1 MiB (1,048,576 bytes) | Same |
| Delay | Per queue or per message, up to 15 minutes | Per queue only (per-message delay not supported) |
| DLQ | Redrive policy with maxReceiveCount, and redrive back | Same, FIFO to FIFO |
| Consumer model | Competing consumers, long polling up to 20 seconds, batches of up to 10 | Same; a group is blocked while one of its messages is in flight |
| Fair queues | Setting a message group on a standard queue enables fair queueing across tenants | n/a |
| Protocol / hosting | HTTPS API; managed AWS only (LocalStack and ElasticMQ emulate it) | Same |
Gotchas: a visibility timeout shorter than the job time causes duplicates; a longer one delays retries after a crash. In FIFO, one slow or failing message holds back its whole message group; spread load over many group IDs, because one group is processed sequentially. DelaySeconds cannot be used with FIFO per-message. Standard queues can deliver twice and out of order, so the consumer must be idempotent. SQS has no replay: a deleted message is gone, so keep an event store or archive when you need history. Laravel relies on SQS visibility; configure that timeout in SQS and keep Laravel's job timeout below it.
Amazon SNS Important
In plain words: SNS is the broadcast half. You publish once to a topic and SNS pushes a copy to every subscriber: SQS queues, Lambda functions, HTTP endpoints, email, SMS.
Common misunderstanding: "Every SNS topic is a replayable queue." Standard topics push and retry; FIFO topics optionally support archive/replay. Put an SQS queue behind each worker that needs an independent processing backlog.
Definition: a topic with subscriptions; each subscription may have a filter policy on message attributes (or payload), a redrive policy to an SQS DLQ for failed deliveries, and raw message delivery so the SQS message body is your payload instead of the SNS JSON envelope. FIFO topics deliver to both SQS FIFO and SQS standard queues. FIFO destinations preserve group ordering; standard destinations retain best-effort ordering and possible duplicates.
Publisher SNS topic order-events SQS billing SQS shipping SQS analytics
1 Publish(type=OrderPlaced) ->
2 filter policies evaluated
3 copy -> ----------------------> stored
4 copy -> ------------------------------------> stored
5 copy -> filter type=OrderPlaced -------------------------------> stored
6 Publish(type=OrderCancelled): analytics filter does not match -> no copy| Property | SNS (with SQS) |
|---|---|
| Model | Pub/sub topic; SQS provides subscriber backlog; FIFO optionally archives for replay |
| Ordering | Standard: none; FIFO topic: per message group |
| Fan-out | Many subscriptions per topic; each SQS queue is independent (own DLQ, own pace) |
| Filtering | Subscription filter policy on attributes or JSON payload (FilterPolicyScope) |
| Permissions | The queue's access policy must allow sns.amazonaws.com to SendMessage from the topic ARN |
| Go / Laravel | aws-sdk-go-v2/service/sns; Laravel has no SNS queue driver (use aws/aws-sdk-php directly or the notification channel packages) |
Gotchas: without raw message delivery a consumer sees {"Type":"Notification","Message":"..."} and must unwrap it. A missing queue policy makes the subscription silently receive nothing. The envelope also carries a signature and UnsubscribeURL, which matter for HTTP endpoints. See the picture below.
Google Cloud Pub/Sub Must-know
In plain words: you publish to a topic and each subscription gets its own copy and its own backlog. A subscription behaves like a queue for the workers attached to it.
Common misunderstanding: "A message is deleted once it is delivered." It is held until acked, and the ack deadline is the lease: miss it and the message becomes eligible for redelivery.
Definition: a subscription has an ack_deadline_seconds (10 to 600; 0 means the default of 10). The client library extends the lease automatically up to MaxExtension (60 minutes by default in the Go client). The subscription retention setting message_retention_duration defaults to seven days and accepts ten minutes through 31 days. With retain_acked_messages you can Seek to a timestamp and replay. With enable_message_ordering, messages with the same non-empty ordering_key are delivered in the order received. With enable_exactly_once_delivery, successful acknowledgments prevent later redelivery and valid leases suppress early redelivery; duplicate publishes still produce distinct message_ids.
Publisher Topic orders Subscription orders-billing Subscriber
1 Publish(key=customer-7, m1) -> stored
2 Publish(key=customer-7, m2) -> stored
3 deliver m1 (ack deadline 10s) -> handler
4 library extends deadline while running (MaxExtension)
5 callbacks run in order per key; ack in order
6 publish failure for key customer-7 -> topic.ResumePublish("customer-7") before sending more
7 around max_delivery_attempts -> dead_letter_topic (best effort)| Property | Pub/Sub |
|---|---|
| Model | Topic plus subscriptions; each subscription is a queue; optional retention gives replay |
| Delivery | At-least-once; exactly-once delivery per subscription as an option (pull, regional) |
| Ordering | Per ordering key, only when the subscription enables ordering; publishers use a regional endpoint |
| Retention / replay | 10 minutes to 31 days per subscription; Seek to time or snapshot |
| Consumer model | StreamingPull, pull, push to HTTPS endpoints; flow control via MaxOutstandingMessages |
| Delay / DLQ | Retry policy (backoff) and DeadLetterPolicy with max_delivery_attempts; no per-message delay |
| Scaling | Fully managed, scales with load; no partitions to size |
| Multi-tenancy | Projects, IAM per topic and subscription |
| Protocol / hosting | gRPC and REST; Google Cloud only (emulator for local tests) |
Gotchas: ordering is per key, and one failed publish pauses that key until you call ResumePublish. Nack or a missed deadline on an ordered subscription redelivers that message and all later messages of the key, so ordered consumers must be idempotent. An ack deadline shorter than your processing causes duplicates; the client library hides this by extending, but only while the process lives. Ordering plus high fan-out can concentrate load on one key; spread keys.
Azure Service Bus and Event Hubs Important
In plain words: Azure ships two products with different jobs. Service Bus is the enterprise queue and topic broker. Event Hubs is the log: partitions, offsets and consumer groups, with a Kafka-compatible endpoint.
Common misunderstanding: "They are the same service in two sizes." Service Bus settles individual messages (complete, abandon, dead-letter, defer) and supports sessions; Event Hubs only lets you checkpoint a position.
Definition: Service Bus has queues and topics with subscriptions. Receive mode PeekLock gives a lock you settle; ReceiveAndDelete is at-most-once. A session is a group of messages sharing a session ID; one receiver holds the session lock and gets those messages in order (FIFO), and session state holds your progress. The default maximum delivery count is 10; then the message goes to the dead-letter sub-queue, with reasons such as MaxDeliveryCountExceeded and TTLExpiredException. Sessions are not available on the Basic tier. Message size is 256 KB on Standard and up to 100 MB on Premium. Event Hubs has partitions (ordered within a partition), consumer groups (an independent view; $Default exists), offsets and checkpointing.
Sender Service Bus queue (sessions on) Receiver 1 Receiver 2
1 Send(sessionId=cust-7, m1) ->
2 Send(sessionId=cust-9, m2) ->
3 AcceptNextSession -> locks cust-7, gets m1
4 AcceptNextSession -> locks cust-9, gets m2
5 Receiver 1 receives m1; processing not yet settled
6 lock expires before Complete -> m1 eligible for redelivery
7 deliveryCount > 10 -> dead-letter queue, reason MaxDeliveryCountExceeded| Property | Service Bus | Event Hubs |
|---|---|---|
| Model | Queue and topic broker | Partitioned log |
| Delivery | At-least-once with peek-lock; at-most-once with receive-and-delete; duplicate detection available | At-least-once; consumer checkpoints offsets |
| Ordering | FIFO per session | Per partition (partition key) |
| Retention | Until consumed or TTL | Time-based retention; Capture to storage |
| Delay / DLQ | Scheduled enqueue time, deferral, built-in dead-letter sub-queue per entity | No DLQ; the consumer handles bad events |
| Scaling | Premium dedicated units; partitions | Throughput units / partitions; Kafka protocol endpoint |
| Protocol | AMQP 1.0 (and a REST/HTTPS API) | AMQP 1.0, Kafka protocol, HTTPS |
| Go client | github.com/Azure/azure-sdk-for-go/sdk/messaging/azservicebus and azeventhubs | same family |
| Laravel | No built-in; community packages or the REST API | Kafka protocol with mateusjunges/laravel-kafka |
Gotchas: settle each message before closing the receiver or connection: a lost lock redelivers the message and burns a delivery attempt; the service also closes an idle connection after 10 minutes. A sessions-enabled entity dead-letters a message with no session ID (Session ID is null). Session state remains even after all messages are consumed, until the application clears it; explicitly clear completed workflow state. Auto-forwarding chains are limited to four hops.
MQTT brokers: Mosquitto and EMQX Important
In plain words: MQTT is a tiny publish/subscribe protocol for devices and phones. Clients connect to a broker, subscribe to topic filters like sensors/+/temp, and publish small messages.
Common misunderstanding: "QoS 2 means the broker never loses anything." QoS is a per-hop delivery contract between a client and the broker, not durability: persistence and session settings decide what survives a restart.
Definition: three QoS levels from the specification: QoS 0 "At most once delivery" (no response, no retry), QoS 1 "At least once delivery" (PUBACK), QoS 2 "Exactly once delivery" (a four-part handshake). The effective QoS is the lower of the publisher's and the subscriber's. Retained messages give a new subscriber the last state. Last will and testament is a message the broker publishes when a client disappears. Persistent sessions queue QoS 1 and 2 messages for an offline client. In MQTT 3.1.1 use CleanSession=false; in MQTT 5 use a nonzero Session Expiry Interval and CleanStart=false when resuming. A missing expiry is zero, so clean start alone does not preserve the session. MQTT 5 adds shared subscriptions ($share/group/topic), the load-balancing form, user properties, and reason codes. For ordered topics, MQTT preserves messages from a given publisher at the same QoS; duplicate redelivery and multiple publishers still require application-level ordering decisions.
Publisher Broker (Mosquitto / EMQX) Subscriber (QoS 1, persistent session)
1 CONNECT(clientId=publisher-1, cleanStart=false, sessionExpiry=3600) ->
2 CONNECT(clientId=billing-1, expiry=3600), SUBSCRIBE -> offline
3 PUBLISH QoS1 orders/42/placed ->
4 <- PUBACK
5 queue message for the offline session
6 CONNECT again -> broker sends PUBLISH
7 PUBACK -> broker discards it| Property | Mosquitto | EMQX |
|---|---|---|
| Model | Broker; topic-based pub/sub; per-client queues | Clustered broker; rule engine and data bridges |
| Delivery | QoS 0, 1, 2 | QoS 0, 1, 2 |
| Retention | Retained message per topic; persistence file; max_queued_messages per client | Retained, session persistence, message storage options |
| Consumer model | Subscriptions with filters; shared subscriptions (v5) | Same, with cluster-wide shared subscriptions |
| DLQ / delay | None built in; delayed publish is an EMQX feature | Dead-letter via rules; delayed publish |
| Scaling | Single node (bridges for federation) | Horizontally clustered, millions of connections |
| Licence | EPL-2.0 or EDL-1.0 | Business Source License 1.1 from 5.9.0 (read the licence before commercial use) |
| Go client | github.com/eclipse/paho.mqtt.golang | same |
Gotchas: MQTT has no per-message ack back to the application: a publisher-side PUBACK confirms only its hop to the broker, so a QoS 1 subscriber that crashes after PUBACK but before processing loses it. Use a persistent session and ack after the work if your client library supports manual acks. Topic wildcards are for subscriptions only. A retained message with a payload larger than expected will be replayed to every new subscriber.
ActiveMQ Artemis Good to know
In plain words: Artemis is the successor of ActiveMQ for the JVM world: a multi-protocol broker that speaks JMS and Jakarta Messaging, AMQP, STOMP, MQTT and OpenWire against one core.
Common misunderstanding: "It is just old RabbitMQ." Its core is the address model: messages go to an address, which has a routing type (anycast to one queue or multicast to all) and zero or more queues. That model is the shared translation layer for every protocol.
Definition: Artemis maps the destination concepts of JMS, STOMP, MQTT and AMQP onto three broker concepts: address, queue and routing type. A persistent journal stores messages; clustering, HA with live and backup pairs, and message redistribution are built in.
| Property | Artemis |
|---|---|
| Model | Queue broker with address model (anycast = queue, multicast = topic) |
| Delivery | At-least-once; JMS transactions and acknowledge modes; duplicate detection |
| Ordering | Per queue |
| Retention / replay | Delete on ack; paging to disk; a journal; no replay |
| Delay / DLQ | Scheduled delivery, dead letter address, redelivery delay |
| Hosting / licence | Apache 2.0; self-hosted, also embedded in Red Hat AMQ |
| Go / Laravel | Go via AMQP (github.com/Azure/go-amqp for AMQP 1.0) or STOMP; Laravel via STOMP or AMQP packages (unverified here) |
Gotchas: choose it when JVM and JMS code already exists or when one broker must accept JMS, AMQP and MQTT; otherwise RabbitMQ is simpler outside the JVM.
ZeroMQ: a library, not a broker Good to know
In plain words: ZeroMQ gives you smart sockets with patterns: PUB/SUB, PUSH/PULL, REQ/REP, DEALER/ROUTER. There is no server in the middle unless you write one.
Common misunderstanding: "ZeroMQ is a fast RabbitMQ." The guide's own words: "It's sockets on steroids. It's like mailboxes with routing." There is no persistence, no ack to the sender in PUB/SUB, and a message to a slow or dead peer may be dropped or block, depending on the socket's high-water mark.
| Property | ZeroMQ |
|---|---|
| Model | Brokerless socket patterns (PUB/SUB, PUSH/PULL, REQ/REP, ROUTER/DEALER) |
| Delivery | In-memory buffers; at-most-once unless you add acks and retries |
| Ordering | Per connection |
| Retention | None |
| DLQ / delay | You build them |
| Hosting / licence | A library (LGPL with a static-linking exception); used inside services, or to build a broker |
| Go client | github.com/pebbe/zmq4 (cgo) or the pure-Go github.com/go-zeromq/zmq4 |
Use it for in-datacentre fan-out where loss is tolerable, for building your own broker, or for low-latency intra-process style pipelines. Do not use it where you need the guarantees on delivery guarantees.
Laravel's built-in sqs and database drivers Must-know
In plain words: Laravel ships queue drivers for SQS, the database, Redis and Beanstalkd. The database driver is the zero-infrastructure start; the sqs driver is the zero-servers start.
Common misunderstanding: "Laravel's retry_after is a timeout that kills the job." It is only the time after which the queue considers the job lost and hands it to another worker; the job's own $timeout is what stops it. Keep timeout several seconds below retry_after (and below the SQS visibility timeout).
Definition: the database driver stores jobs in a jobs table (create it with php artisan make:queue-table). Reading a job reserves it by setting reserved_at, and the framework source takes the row with FOR UPDATE SKIP LOCKED where the database supports it, so several workers do not collide. The sqs driver needs aws/aws-sdk-php, supports FIFO queues through onGroup() and a deduplicationId() method, fair queueing on standard queues through a message group, and overflow storage that keeps large payloads in a cache store. Laravel's docs state that if you dispatch to FIFO without a group, "Laravel will use the queue name as the message group ID".
-- What the database driver's table looks like (the shape make:queue-table creates).
CREATE TABLE jobs (
id BIGSERIAL PRIMARY KEY,
queue VARCHAR(255) NOT NULL,
payload TEXT NOT NULL,
attempts SMALLINT NOT NULL,
reserved_at INTEGER NULL,
available_at INTEGER NOT NULL,
created_at INTEGER NOT NULL
);
CREATE INDEX jobs_queue_index ON jobs (queue);
-- The pop is essentially this, inside a transaction; SKIP LOCKED lets workers pass over locked rows.
SELECT * FROM jobs
WHERE queue = 'default'
AND ((reserved_at IS NULL AND available_at <= extract(epoch FROM now()))
OR reserved_at <= extract(epoch FROM now()) - 90)
ORDER BY id LIMIT 1
FOR UPDATE SKIP LOCKED;| Property | database driver | sqs driver |
|---|---|---|
| Model | Queue in a table | Queue in SQS |
| Delivery | At-least-once (retry_after re-reserves a stale job) | At-least-once (visibility timeout) |
| Delay | delay() sets available_at | delay() up to 15 minutes (not on FIFO) |
| Ordering | Roughly id order; not guaranteed under concurrency | FIFO queue plus onGroup() |
| Transactions | Atomic only on the same DB connection/transaction with dispatch before commit; after_commit leaves a post-commit crash window | after_commit config; the dispatch is a network call, not part of your transaction |
| Scaling | Limited by database load; polling | Practically unbounded; long polling |
| When | Small apps, background jobs next to the data, tests | Production on AWS, bursty load |
Gotchas: the database driver polls and adds write load on your primary; with MySQL older than 8 or no SKIP LOCKED support, workers contend on locks. A job insertion can share the business transaction only when it uses the same DB connection and dispatch happens before commit (beforeCommit() or after_commit=false). The config below instead uses after_commit=true to avoid a worker seeing uncommitted data; that callback still has a crash gap after commit. Use an outbox for durable cross-broker publication. Laravel's own internals are in Laravel queue internals.
The master comparison
| NATS JetStream | Pulsar | SQS | SNS | Pub/Sub | Service Bus | Event Hubs | MQTT (Mosquitto, EMQX) | Artemis | ZeroMQ | |
|---|---|---|---|---|---|---|---|---|---|---|
| Model | Log + queue | Log + queue | Queue | Topic fan-out | Topic + queue-like subs | Queue + topic | Log | Topic | Queue + topic | Sockets |
| Delivery | At-least-once, dedup option | At-least-once | At-least-once; FIFO publish dedup window | At-least-once | At-least-once; exactly-once option | At-least-once | At-least-once | QoS 0/1/2 | At-least-once | At-most-once |
| Ordering | Per stream | Per partition / key | FIFO per group | FIFO topic per group | Per ordering key | Per session | Per partition | Per topic | Per queue | Per connection |
| Retention / replay | Limits; replay | Retention, tiered storage; Seek | 4 days default, max 14; no replay | Optional FIFO archive/replay | 7 days default, max 31; Seek | TTL; no replay | Time-based; replay | Retained message only | No replay | None |
| Consumer model | Pull / push durable | Subscription types | Competing, long poll | Push to subscribers | Pull, StreamingPull, push | Peek-lock, sessions | Consumer groups | Subscribe, shared (v5) | JMS consumers | Socket peers |
| Delay | nakWithDelay, BackOff | deliverAt | up to 15 min | via SQS | Retry policy | Scheduled enqueue | No | EMQX delayed publish | Scheduled | You build it |
| DLQ | Advisory, you republish | Dead letter topic | Redrive policy | Subscription DLQ | Dead letter topic | Built-in sub-queue | None | Rules (EMQX) | Dead letter address | None |
| Scaling | Raft replicas, superclusters | Stateless brokers + bookies | Managed | Managed | Managed | Premium units | Partitions / TUs | Clustering (EMQX) | HA pairs, clusters | n/a |
| Multi-tenancy | Accounts | Tenants, namespaces | Per queue, IAM | Per topic, IAM | Projects, IAM | Namespaces | Namespaces | ACLs, listeners | Security domains | n/a |
| Protocol | NATS | Pulsar binary | HTTPS | HTTPS | gRPC, REST | AMQP 1.0 | AMQP, Kafka | MQTT | Many | ZMTP |
| Hosting / licence | Self-hosted; Apache 2.0 | Self-hosted or managed; Apache 2.0 | AWS only | AWS only | GCP only | Azure only | Azure only | Self-hosted; EPL / BSL 1.1 | Self-hosted; Apache 2.0 | Library; LGPL |
| Go client | nats.go | pulsar-client-go | aws-sdk-go-v2 | aws-sdk-go-v2 | cloud.google.com/go/pubsub | azservicebus | azeventhubs | paho.mqtt.golang | AMQP or STOMP libs | zmq4 |
| Laravel | Package or SDK | SDK | Built-in driver | SDK / packages | Package or SDK | SDK | Kafka package | Package | STOMP / AMQP | Extension |
Mechanics: the knobs that decide redelivery, order and loss
Visibility timeout, ack deadline, AckWait and lock duration
All five products use the same idea, a lease: the broker hands you a message, starts a timer, and re-offers it if you do not settle in time. The difference is who renews the lease.
| Product | Lease name | Who extends it | Extension call | Hard cap |
|---|---|---|---|---|
| SQS | Visibility timeout | You | ChangeMessageVisibility | 12 hours from first receive |
| Pub/Sub | Ack deadline | The client library, automatically | modifyAckDeadline | MaxExtension in the library (60 minutes default in Go); server custom deadline 10 to 600 seconds |
| JetStream | AckWait | You | Progress ack (InProgress) resets the timer | None |
| Service Bus | Lock duration | You or the SDK's auto lock renewal | Renew lock | Settled before receiver closes |
| Laravel | retry_after / visibility | Not extended | None | Must exceed job timeout |
Rule: set the lease longer than your p99 processing time, shorter than the time you can afford to wait after a crash, and make the handler idempotent anyway.
Error codes and reasons you will read
| Where | Symbol | Meaning | Retry? |
|---|---|---|---|
| SQS | Stale or invalid receipt handle (ReceiptHandleIsInvalid) on delete or change-visibility | The handle belongs to an earlier receive; after a re-receive only the newest handle is reliable | No: the new holder owns the message |
| SQS | AWS.SimpleQueueService.NonExistentQueue | Wrong queue URL or region | No |
| SQS FIFO | InvalidParameterValue for a missing MessageGroupId | FIFO requires a group on every message | Fix the code |
| Pub/Sub | FAILED_PRECONDITION on pull of a detached subscription | The subscription is detached from its topic | No |
| Pub/Sub | Publish error on an ordering key | The key is paused | Call ResumePublish, then retry |
| JetStream | MaxDeliver exhausted | The message stays in the stream, advisory published | Republish or inspect |
| Service Bus | MaxDeliveryCountExceeded | Delivery count above 10 (default) | Dead-letter queue |
| Service Bus | TTLExpiredException | Message expired | DLQ if dead-lettering on expiry is enabled |
| Service Bus | Session ID is null | Session entity got a message without a session ID | Fix the sender |
| MQTT | Connection refused with a reason code (v5) | Not authorised or protocol error | Per code |
Ordering knobs
| Product | The key | Parallelism limit | What breaks ordering |
|---|---|---|---|
| SQS FIFO | MessageGroupId | One received batch per group; process same-group batch entries sequentially | Visibility timeout expiry mid-processing |
| Pub/Sub | ordering_key (subscription must enable it) | Ordered callbacks per key; multiple messages can be outstanding | Nack of an earlier message redelivers later ones |
| Service Bus | Session ID | One receiver per session | Lock loss |
| JetStream | Stream sequence, filter subjects | Many pull consumers share a consumer | Redelivery of a nacked message |
| Pulsar | Partition, or Key_Shared key | Consumers per key range | Negative ack on ordered subscriptions |
| Event Hubs | Partition key | One reader per partition per group | Re-partitioning |
| MQTT | Topic (non-shared) | One subscriber | Shared subscriptions, QoS mixing |
See ordering and partitioning for the theory.
Solving the classic problems on these brokers
| Problem | Solution | How | Advantage | Cost / limit |
|---|---|---|---|---|
| One event, many independent consumers | SNS topic with SQS queue per consumer; Pub/Sub subscription per consumer; Pulsar subscription per consumer; JetStream consumer per consumer | Each consumer gets its own backlog | Independent pace and DLQ | One queue or subscription per consumer to manage |
| Per-customer ordering with parallelism | SQS FIFO group, Pub/Sub ordering key, Service Bus session, Pulsar Key_Shared | Key = customer id | Order where it matters | A hot key serialises that customer |
| Poison message | maxReceiveCount + DLQ (SQS), max_delivery_attempts (Pub/Sub), MaxDeliver (JetStream), dead letter topic (Pulsar), delivery count 10 (Service Bus) | Cap attempts | Stops the loop | Needs a DLQ process |
| Delayed retry | SQS DelaySeconds (not FIFO), ChangeMessageVisibility; JetStream BackOff; Pulsar deliverAfter; Service Bus scheduled enqueue | Re-offer later | Backoff without a scheduler | Per-product limits; see retry and backoff |
| Large payload | Store the body in object storage and send a pointer; Laravel's SQS overflow storage does this with a cache store | Claim check | Stays under the size limit | Extra read |
| Replay a month of history | JetStream, Pulsar, Event Hubs, Pub/Sub Seek; not SQS | Retained log | Rebuild a read model | Storage cost |
| Reliable publish from a database | Write an outbox row and publish after commit | Outbox | No dual-write | A relay to run |
| Duplicates | Idempotency key in a table; SQS FIFO dedup id; JetStream Nats-Msg-Id | Inbox | Safe redelivery | Storage for keys |
Go
Example
One program per system, each constructing a real client and exiting quietly when its environment variable is missing, so it compiles and passes go vet without a broker. Imports: github.com/nats-io/nats.go (with the jetstream package), github.com/aws/aws-sdk-go-v2/service/sqs and .../sns, github.com/eclipse/paho.mqtt.golang. The Pub/Sub and Pulsar programs live in their own modules because their dependency trees are large.
SQS publish and consume with long polling, an explicit visibility timeout and delete-after-work:
// Publish and consume with Amazon SQS (aws-sdk-go-v2). Works against LocalStack
// when SQS_ENDPOINT is set. Exits quietly when no queue URL is configured.
package main
import (
"context"
"fmt"
"log"
"os"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/sqs"
"github.com/aws/aws-sdk-go-v2/service/sqs/types"
)
func main() {
queueURL := os.Getenv("SQS_QUEUE_URL")
if queueURL == "" {
fmt.Println("SQS_QUEUE_URL not set; nothing to do")
return
}
ctx := context.Background()
cfg, err := config.LoadDefaultConfig(ctx)
if err != nil {
log.Fatal(err)
}
client := sqs.NewFromConfig(cfg, func(o *sqs.Options) {
if ep := os.Getenv("SQS_ENDPOINT"); ep != "" {
o.BaseEndpoint = aws.String(ep) // LocalStack, for example http://localhost:4566
}
})
// Publish. For a FIFO queue also set MessageGroupId and MessageDeduplicationId.
_, err = client.SendMessage(ctx, &sqs.SendMessageInput{
QueueUrl: aws.String(queueURL),
MessageBody: aws.String(`{"order_id":42}`),
DelaySeconds: 0,
MessageAttributes: map[string]types.MessageAttributeValue{
"type": {DataType: aws.String("String"), StringValue: aws.String("OrderPlaced")},
},
})
if err != nil {
log.Fatal(err)
}
// Consume: long polling (WaitTimeSeconds) and an explicit visibility timeout.
out, err := client.ReceiveMessage(ctx, &sqs.ReceiveMessageInput{
QueueUrl: aws.String(queueURL),
MaxNumberOfMessages: 10,
WaitTimeSeconds: 20,
VisibilityTimeout: 60,
MessageAttributeNames: []string{"All"},
})
if err != nil {
log.Fatal(err)
}
for _, m := range out.Messages {
fmt.Println("got", aws.ToString(m.Body))
// Do the side effect first; delete only afterwards (that is the ack).
time.Sleep(10 * time.Millisecond)
if _, err := client.DeleteMessage(ctx, &sqs.DeleteMessageInput{
QueueUrl: aws.String(queueURL),
ReceiptHandle: m.ReceiptHandle,
}); err != nil {
log.Fatal(err)
}
}
}SNS publish with a message attribute for filter policies:
// Publish to an SNS topic that fans out to SQS queues. Exits quietly without a topic ARN.
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/sns"
"github.com/aws/aws-sdk-go-v2/service/sns/types"
)
func main() {
arn := os.Getenv("SNS_TOPIC_ARN")
if arn == "" {
fmt.Println("SNS_TOPIC_ARN not set; nothing to do")
return
}
ctx := context.Background()
cfg, err := config.LoadDefaultConfig(ctx)
if err != nil {
log.Fatal(err)
}
client := sns.NewFromConfig(cfg)
// The attribute is what subscription filter policies match on.
_, err = client.Publish(ctx, &sns.PublishInput{
TopicArn: aws.String(arn),
Message: aws.String(`{"order_id":42}`),
MessageAttributes: map[string]types.MessageAttributeValue{
"type": {DataType: aws.String("String"), StringValue: aws.String("OrderPlaced")},
},
})
if err != nil {
log.Fatal(err)
}
fmt.Println("published")
}NATS JetStream: stream, dedup publish, durable pull consumer with explicit ack:
// NATS JetStream: a stream, a durable pull consumer with explicit acks, publish with a dedup id.
// Exits quietly when NATS_URL is not set.
package main
import (
"context"
"fmt"
"log"
"os"
"time"
"github.com/nats-io/nats.go"
"github.com/nats-io/nats.go/jetstream"
)
func main() {
url := os.Getenv("NATS_URL")
if url == "" {
fmt.Println("NATS_URL not set; nothing to do")
return
}
nc, err := nats.Connect(url)
if err != nil {
log.Fatal(err)
}
defer nc.Drain()
js, err := jetstream.New(nc)
if err != nil {
log.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
// A stream stores every message published to ORDERS.*; limits retention is the default.
_, err = js.CreateOrUpdateStream(ctx, jetstream.StreamConfig{
Name: "ORDERS",
Subjects: []string{"ORDERS.*"},
Storage: jetstream.FileStorage,
Replicas: 1,
MaxAge: 24 * time.Hour,
})
if err != nil {
log.Fatal(err)
}
// Publish and wait for the stream's PubAck; Nats-Msg-Id enables deduplication.
ack, err := js.Publish(ctx, "ORDERS.placed", []byte(`{"order_id":42}`), jetstream.WithMsgID("order-42-placed"))
if err != nil {
log.Fatal(err)
}
fmt.Println("stored at sequence", ack.Sequence, "duplicate:", ack.Duplicate)
// A durable pull consumer: explicit ack, bounded redelivery.
cons, err := js.CreateOrUpdateConsumer(ctx, "ORDERS", jetstream.ConsumerConfig{
Durable: "billing",
AckPolicy: jetstream.AckExplicitPolicy,
AckWait: 30 * time.Second,
MaxDeliver: 5,
BackOff: []time.Duration{time.Second, 5 * time.Second, 30 * time.Second},
})
if err != nil {
log.Fatal(err)
}
batch, err := cons.Fetch(10, jetstream.FetchMaxWait(2*time.Second))
if err != nil {
log.Fatal(err)
}
for msg := range batch.Messages() {
fmt.Println("got", string(msg.Data()))
if err := msg.Ack(); err != nil { // ack after the side effect
log.Println("ack failed:", err)
}
}
if err := batch.Error(); err != nil {
log.Println(err)
}
}MQTT with Paho, QoS 1 and a persistent session:
// MQTT with Eclipse Paho: QoS 1 publish and subscribe against Mosquitto or EMQX.
// Exits quietly when MQTT_URL is not set.
package main
import (
"fmt"
"log"
"os"
"time"
mqtt "github.com/eclipse/paho.mqtt.golang"
)
func main() {
url := os.Getenv("MQTT_URL") // for example tcp://localhost:1883
if url == "" {
fmt.Println("MQTT_URL not set; nothing to do")
return
}
opts := mqtt.NewClientOptions().
AddBroker(url).
SetClientID("billing-1").
SetCleanSession(false). // keep the session so QoS 1 messages queue while offline
SetAutoReconnect(true).
SetAutoAckDisabled(true) // settle only after processing, not after the callback returns
c := mqtt.NewClient(opts)
if t := c.Connect(); t.Wait() && t.Error() != nil {
log.Fatal(t.Error())
}
defer c.Disconnect(250)
got := make(chan mqtt.Message, 1)
if t := c.Subscribe("orders/+/placed", 1, func(_ mqtt.Client, m mqtt.Message) {
select {
case got <- m:
default:
// Keep the callback bounded. Leave overflow unacked for session recovery.
}
}); t.Wait() && t.Error() != nil {
log.Fatal(t.Error())
}
if t := c.Publish("orders/42/placed", 1, false, `{"order_id":42}`); t.Wait() && t.Error() != nil {
log.Fatal(t.Error())
}
select {
case p := <-got:
fmt.Println("got", string(p.Payload()))
p.Ack() // replace printing with the durable side effect before acknowledging
case <-time.After(3 * time.Second):
fmt.Println("timeout")
}
}Google Pub/Sub with an ordering key and flow control (module academy/other-brokers-pubsub):
// Google Cloud Pub/Sub: publish with an ordering key, receive with flow control. Exits quietly
// without PUBSUB_PROJECT; set PUBSUB_EMULATOR_HOST to talk to the emulator.
package main
import (
"context"
"fmt"
"log"
"os"
"time"
"cloud.google.com/go/pubsub"
)
func main() {
project := os.Getenv("PUBSUB_PROJECT")
if project == "" {
fmt.Println("PUBSUB_PROJECT not set; nothing to do")
return
}
ctx := context.Background()
client, err := pubsub.NewClient(ctx, project)
if err != nil {
log.Fatal(err)
}
defer client.Close()
topic := client.Topic("orders")
topic.EnableMessageOrdering = true // required before publishing with an ordering key
defer topic.Stop()
res := topic.Publish(ctx, &pubsub.Message{
Data: []byte(`{"order_id":42}`),
OrderingKey: "customer-7",
})
id, err := res.Get(ctx) // blocks until the server acknowledges the publish
if err != nil {
topic.ResumePublish("customer-7") // an ordering key is paused after a failure
log.Fatal(err)
}
fmt.Println("published", id)
sub := client.Subscription("orders-billing")
sub.ReceiveSettings.MaxOutstandingMessages = 100
sub.ReceiveSettings.MaxExtension = 10 * time.Minute // the library extends the ack deadline up to this
cctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
err = sub.Receive(cctx, func(_ context.Context, m *pubsub.Message) {
fmt.Println("got", string(m.Data), "attempt", m.DeliveryAttempt)
m.Ack() // or m.Nack() to redeliver
})
if err != nil {
log.Fatal(err)
}
}Pulsar with a Shared subscription, negative ack and a dead letter policy (module academy/other-brokers-pulsar):
// Apache Pulsar: produce with a key, consume on a Shared subscription with ack and negative ack.
// Exits quietly when PULSAR_URL is not set.
package main
import (
"context"
"fmt"
"log"
"os"
"time"
"github.com/apache/pulsar-client-go/pulsar"
)
func main() {
url := os.Getenv("PULSAR_URL")
if url == "" {
fmt.Println("PULSAR_URL not set; nothing to do")
return
}
client, err := pulsar.NewClient(pulsar.ClientOptions{URL: url, OperationTimeout: 30 * time.Second})
if err != nil {
log.Fatal(err)
}
defer client.Close()
ctx := context.Background()
topic := "persistent://shop/orders/placed" // tenant/namespace/topic
producer, err := client.CreateProducer(pulsar.ProducerOptions{Topic: topic})
if err != nil {
log.Fatal(err)
}
defer producer.Close()
consumer, err := client.Subscribe(pulsar.ConsumerOptions{
Topic: topic,
SubscriptionName: "billing",
Type: pulsar.Shared, // Exclusive, Failover, Shared or Key_Shared
NackRedeliveryDelay: 10 * time.Second,
SubscriptionInitialPosition: pulsar.SubscriptionPositionEarliest,
DLQ: &pulsar.DLQPolicy{
MaxDeliveries: 5,
DeadLetterTopic: "persistent://shop/orders/placed-billing-DLQ",
},
RetryEnable: true,
})
if err != nil {
log.Fatal(err)
}
defer consumer.Close()
// Create the subscription before publishing: an empty topic may retain no backlog.
id, err := producer.Send(ctx, &pulsar.ProducerMessage{Key: "customer-7", Payload: []byte(`{"order_id":42}`)})
if err != nil {
log.Fatal(err)
}
fmt.Println("stored at", id)
rctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
msg, err := consumer.Receive(rctx)
if err != nil {
log.Fatal(err)
}
fmt.Println("got", string(msg.Payload()))
if err := consumer.Ack(msg); err != nil {
log.Fatal(err)
} // consumer.Nack(msg) requests redelivery; it is not a durable retry counter.
}The Go angle
Go's standard library has no broker client, and each ecosystem client mirrors its broker. The NATS client's jetstream package gives you Stream and Consumer handles, so the model in your code is the model in the server. The AWS SDK is plain request and response: you write the polling loop, the visibility extension and the delete. The Pub/Sub client inverts that: Receive runs your callback concurrently and extends deadlines for you, and m.Ack() / m.Nack() are the settle calls. Paho gives tokens you Wait() on. Always close or drain clients, pass a context.Context, and settle only after the side effect. Concurrency limits belong in the client options (MaxOutstandingMessages, MaxAckPending), not in an unbounded go func.
Laravel
Example
Laravel 13's queue docs list the built-in backends (SQS, Redis, database) and the SQS-specific features. Everything else on this page is not a Laravel queue driver: for NATS, Pub/Sub and MQTT you call the product's PHP client from a job or a console command.
SQS connection with after_commit, overflow storage and the SDK requirement:
<?php
// config/queue.php (excerpt): the built-in sqs driver, with FIFO and overflow storage.
// Install the SDK first: composer require aws/aws-sdk-php
return [
'default' => env('QUEUE_CONNECTION', 'sqs'),
'connections' => [
'sqs' => [
'driver' => 'sqs',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'),
'queue' => env('SQS_QUEUE', 'orders'), // a FIFO queue name must end in ".fifo"
'suffix' => env('SQS_SUFFIX'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'after_commit' => true, // dispatch only after the database transaction commits
'overflow' => [
'enabled' => env('SQS_OVERFLOW_ENABLED', false),
'store' => env('SQS_OVERFLOW_STORE'),
],
],
],
];A job that works on SQS FIFO (group and dedup id) and on standard queues (fair queueing):
<?php
namespace App\Jobs;
use App\Models\Order;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
// Works on an SQS FIFO queue (group + deduplication) and on a standard queue (fair queueing by group).
class ProcessOrder implements ShouldQueue
{
use Queueable;
// The SQS visibility timeout must be longer than this, or the message reappears mid-run.
public int $timeout = 60;
public int $tries = 5;
public function __construct(public Order $order)
{
$this->onConnection('sqs');
}
/** FIFO: jobs in the same group run in order. Standard queues use the group for fairness only. */
public function messageGroup(): string
{
return "customer-{$this->order->customer_id}";
}
/** SQS FIFO drops a second message with this id for five minutes. */
public function deduplicationId(): string
{
return "order-{$this->order->id}-placed";
}
public function handle(): void
{
// Side effect here; the worker releases failures using its backoff (possibly zero), or eventually marks them failed.
}
}<?php
namespace App\Orders;
use App\Jobs\ProcessOrder;
use App\Models\Order;
class DispatchOrder
{
public function __invoke(Order $order): void
{
// onGroup overrides messageGroup() for this dispatch only.
ProcessOrder::dispatch($order)->onGroup("customer-{$order->customer_id}");
}
}The database driver connection:
<?php
// config/queue.php (excerpt): the built-in database driver. No extra service, one jobs table.
// Create the table with: php artisan make:queue-table && php artisan migrate
return [
'connections' => [
'database' => [
'driver' => 'database',
'connection' => env('DB_QUEUE_CONNECTION'),
'table' => env('DB_QUEUE_TABLE', 'jobs'),
'queue' => env('DB_QUEUE', 'default'),
'retry_after' => (int) env('DB_QUEUE_RETRY_AFTER', 90), // the "visibility timeout" of this driver
'after_commit' => true, // avoids early reads; not atomic with the business commit
// For one DB transaction, use the same connection and dispatch with beforeCommit().
],
],
];NATS JetStream through basis-company/nats (calls taken from its README):
<?php
namespace App\Messaging;
use Basis\Nats\Client;
use Basis\Nats\Configuration;
use Basis\Nats\Stream\RetentionPolicy;
use Basis\Nats\Stream\StorageBackend;
// Uses basis-company/nats (composer require basis-company/nats). Calls follow its README.
class NatsJetStream
{
public function run(): void
{
$client = new Client(new Configuration(host: env('NATS_HOST', '127.0.0.1')));
$stream = $client->getApi()->getStream('orders');
$stream->getConfiguration()
->setRetentionPolicy(RetentionPolicy::WORK_QUEUE)
->setStorageBackend(StorageBackend::FILE)
->setSubjects(['orders.placed']);
$stream->create();
// WorkQueue retention serves one logical worker group; use LIMITS for independent fan-out.
// Publish into the stream.
$stream->put('orders.placed', json_encode(['order_id' => 42]));
// A consumer reads through the queue interface and acks after the side effect.
$billing = $stream->getConsumer('billing');
$billing->getConfiguration()->setSubjectFilter('orders.placed');
$queue = $billing->setBatching(10)->create()->getQueue();
while ($message = $queue->next()) {
try {
// Side effect here.
$message->ack();
} catch (\Throwable) {
$message->nack(5); // redeliver after five seconds
}
}
}
}MQTT through php-mqtt/laravel-client (README calls):
<?php
namespace App\Messaging;
use PhpMqtt\Client\Facades\MQTT;
// Uses php-mqtt/laravel-client (composer require php-mqtt/laravel-client). Calls follow its README.
class MqttPublish
{
public function __invoke(): void
{
// QoS 0 one-liner: fire and forget.
MQTT::publish('orders/42/placed', json_encode(['order_id' => 42]));
// QoS 1 needs an event loop so the client can resend until the broker acknowledges.
$mqtt = MQTT::connection();
$mqtt->publish('orders/42/placed', json_encode(['order_id' => 42]), 1);
$mqtt->loop(true, true); // exit the loop as soon as every resend queue is empty
}
}Pub/Sub through the official google/cloud-pubsub client (raw SDK; there is a community queue driver, kainxspirits/laravel-pubsub-queue, whose API I did not verify):
<?php
namespace App\Messaging;
use Google\Cloud\PubSub\PubSubClient;
// Uses the official google/cloud-pubsub package (composer require google/cloud-pubsub).
// Laravel has no built-in Pub/Sub queue driver; this is the raw SDK from a job or listener.
class PubSubPublish
{
public function __invoke(): void
{
$pubsub = new PubSubClient(['projectId' => env('GOOGLE_CLOUD_PROJECT')]);
$topic = $pubsub->topic('orders');
$topic->publish([
'data' => json_encode(['order_id' => 42]),
'attributes' => ['type' => 'OrderPlaced'],
'orderingKey' => 'customer-7', // only honoured when the subscription enables ordering
]);
}
}The Laravel angle
Use the built-in driver when it exists: sqs and database give you retries, backoff, failed_jobs, Horizon-less workers and after_commit, all described in Laravel queue internals. For everything else decide whether you want a queue driver (jobs as Laravel serialises them, so only Laravel can read them) or a message (a contract other languages read): events for other services should be plain JSON on a topic you publish with the SDK, not a serialised Job. Keep the job timeout below the visibility timeout or retry_after, and use after_commit or an outbox for jobs that depend on a row you just wrote.
Broker differences
Each surveyed broker maps to the closest core broker. The mapping tells you which of the three deep-dive pages explains the mechanism and what to expect.
RabbitMQ
Closest: SQS, Service Bus, Artemis, and Pub/Sub when used with a subscription per consumer. They are queue brokers: competing consumers, delete on ack, a dead letter path, delay. What RabbitMQ has and they lack: exchanges and routing keys (SNS filter policies, Pub/Sub filters and Artemis address routing are the partial equivalents), and SQS has no per-message TTL-and-DLX chains. What they have that RabbitMQ lacks: no servers (SQS, Pub/Sub, Service Bus), sessions (Service Bus), fair queues (SQS).
| RabbitMQ mechanism | SQS | Service Bus | Artemis |
|---|---|---|---|
| Ack / nack | Delete / let visibility expire | Complete / abandon | JMS acknowledge / rollback |
| Prefetch | MaxNumberOfMessages up to 10, in-flight limit | Prefetch count | Consumer window size |
| DLX / DLQ | Redrive policy, maxReceiveCount | Dead-letter sub-queue, max delivery count 10 | Dead letter address |
| Delay | DelaySeconds up to 15 minutes | Scheduled enqueue time | Scheduled delivery |
| Priority | None (use two queues) | None | Message priority |
// Publish and consume with Amazon SQS (aws-sdk-go-v2). Works against LocalStack
// when SQS_ENDPOINT is set. Exits quietly when no queue URL is configured.
package main
import (
"context"
"fmt"
"log"
"os"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/sqs"
"github.com/aws/aws-sdk-go-v2/service/sqs/types"
)
func main() {
queueURL := os.Getenv("SQS_QUEUE_URL")
if queueURL == "" {
fmt.Println("SQS_QUEUE_URL not set; nothing to do")
return
}
ctx := context.Background()
cfg, err := config.LoadDefaultConfig(ctx)
if err != nil {
log.Fatal(err)
}
client := sqs.NewFromConfig(cfg, func(o *sqs.Options) {
if ep := os.Getenv("SQS_ENDPOINT"); ep != "" {
o.BaseEndpoint = aws.String(ep) // LocalStack, for example http://localhost:4566
}
})
// Publish. For a FIFO queue also set MessageGroupId and MessageDeduplicationId.
_, err = client.SendMessage(ctx, &sqs.SendMessageInput{
QueueUrl: aws.String(queueURL),
MessageBody: aws.String(`{"order_id":42}`),
DelaySeconds: 0,
MessageAttributes: map[string]types.MessageAttributeValue{
"type": {DataType: aws.String("String"), StringValue: aws.String("OrderPlaced")},
},
})
if err != nil {
log.Fatal(err)
}
// Consume: long polling (WaitTimeSeconds) and an explicit visibility timeout.
out, err := client.ReceiveMessage(ctx, &sqs.ReceiveMessageInput{
QueueUrl: aws.String(queueURL),
MaxNumberOfMessages: 10,
WaitTimeSeconds: 20,
VisibilityTimeout: 60,
MessageAttributeNames: []string{"All"},
})
if err != nil {
log.Fatal(err)
}
for _, m := range out.Messages {
fmt.Println("got", aws.ToString(m.Body))
// Do the side effect first; delete only afterwards (that is the ack).
time.Sleep(10 * time.Millisecond)
if _, err := client.DeleteMessage(ctx, &sqs.DeleteMessageInput{
QueueUrl: aws.String(queueURL),
ReceiptHandle: m.ReceiptHandle,
}); err != nil {
log.Fatal(err)
}
}
}Kafka
Closest: Pulsar, Event Hubs, NATS JetStream (limits retention). They keep messages and let a consumer reposition. Pulsar partitions plus a subscription are Kafka's partitions plus a consumer group, with Shared and Key_Shared lifting the consumer cap. Event Hubs even exposes the Kafka wire protocol. JetStream's stream is a log without partitions: ordering is per stream and scaling is by consumers and filter subjects, with partitioned subjects as an add-on.
| Kafka mechanism | Pulsar | Event Hubs | JetStream |
|---|---|---|---|
| Topic / partition | Topic, optionally partitioned | Event hub, partitions | Stream, subjects |
| Consumer group | Subscription (type decides sharing) | Consumer group | Durable consumer |
| Offset commit | Cumulative ack, or per-message ack | Checkpoint | Ack floor, per-message ack |
| Retention | Time, size, backlog quota, tiered storage | Time-based; Capture | Limits: age, count, bytes |
| Key ordering | Partition or Key_Shared | Partition key | Subject plus consumer filter |
| Transactions / EOS | Pulsar transactions | None | Dedup id plus double ack |
// Apache Pulsar: produce with a key, consume on a Shared subscription with ack and negative ack.
// Exits quietly when PULSAR_URL is not set.
package main
import (
"context"
"fmt"
"log"
"os"
"time"
"github.com/apache/pulsar-client-go/pulsar"
)
func main() {
url := os.Getenv("PULSAR_URL")
if url == "" {
fmt.Println("PULSAR_URL not set; nothing to do")
return
}
client, err := pulsar.NewClient(pulsar.ClientOptions{URL: url, OperationTimeout: 30 * time.Second})
if err != nil {
log.Fatal(err)
}
defer client.Close()
ctx := context.Background()
topic := "persistent://shop/orders/placed" // tenant/namespace/topic
producer, err := client.CreateProducer(pulsar.ProducerOptions{Topic: topic})
if err != nil {
log.Fatal(err)
}
defer producer.Close()
consumer, err := client.Subscribe(pulsar.ConsumerOptions{
Topic: topic,
SubscriptionName: "billing",
Type: pulsar.Shared, // Exclusive, Failover, Shared or Key_Shared
NackRedeliveryDelay: 10 * time.Second,
SubscriptionInitialPosition: pulsar.SubscriptionPositionEarliest,
DLQ: &pulsar.DLQPolicy{
MaxDeliveries: 5,
DeadLetterTopic: "persistent://shop/orders/placed-billing-DLQ",
},
RetryEnable: true,
})
if err != nil {
log.Fatal(err)
}
defer consumer.Close()
// Create the subscription before publishing: an empty topic may retain no backlog.
id, err := producer.Send(ctx, &pulsar.ProducerMessage{Key: "customer-7", Payload: []byte(`{"order_id":42}`)})
if err != nil {
log.Fatal(err)
}
fmt.Println("stored at", id)
rctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
msg, err := consumer.Receive(rctx)
if err != nil {
log.Fatal(err)
}
fmt.Println("got", string(msg.Payload()))
if err := consumer.Ack(msg); err != nil {
log.Fatal(err)
} // consumer.Nack(msg) requests redelivery; it is not a durable retry counter.
}Redis Streams
Closest: NATS JetStream, then MQTT and ZeroMQ versus Redis Pub/Sub. A Redis stream with consumer groups, XACK, a pending list and XAUTOCLAIM corresponds to a JetStream stream with a durable consumer, Ack and AckWait. Both are small, fast and easy to run. Core NATS and ZeroMQ PUB/SUB resemble transient Redis Pub/Sub. MQTT QoS and persistent sessions add delivery state, and retained messages replay only the latest state rather than a log.
| Redis Streams mechanism | JetStream | MQTT | ZeroMQ |
|---|---|---|---|
XADD | js.Publish returns a sequence | PUBLISH QoS 1 returns PUBACK | send returns when buffered |
| Consumer group | Durable consumer | Shared subscription (v5) | PUSH/PULL peers |
XACK | msg.Ack() | PUBACK settles one protocol hop; it is not an application transaction | None |
Pending list, XAUTOCLAIM | Consumer pending + redelivery after AckWait | Session queue | None |
| Trim | Limits (MaxAge, MaxMsgs) | Retained message replaced | None |
| Pub/Sub | Core NATS subjects | Topics | PUB/SUB |
// NATS JetStream: a stream, a durable pull consumer with explicit acks, publish with a dedup id.
// Exits quietly when NATS_URL is not set.
package main
import (
"context"
"fmt"
"log"
"os"
"time"
"github.com/nats-io/nats.go"
"github.com/nats-io/nats.go/jetstream"
)
func main() {
url := os.Getenv("NATS_URL")
if url == "" {
fmt.Println("NATS_URL not set; nothing to do")
return
}
nc, err := nats.Connect(url)
if err != nil {
log.Fatal(err)
}
defer nc.Drain()
js, err := jetstream.New(nc)
if err != nil {
log.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
// A stream stores every message published to ORDERS.*; limits retention is the default.
_, err = js.CreateOrUpdateStream(ctx, jetstream.StreamConfig{
Name: "ORDERS",
Subjects: []string{"ORDERS.*"},
Storage: jetstream.FileStorage,
Replicas: 1,
MaxAge: 24 * time.Hour,
})
if err != nil {
log.Fatal(err)
}
// Publish and wait for the stream's PubAck; Nats-Msg-Id enables deduplication.
ack, err := js.Publish(ctx, "ORDERS.placed", []byte(`{"order_id":42}`), jetstream.WithMsgID("order-42-placed"))
if err != nil {
log.Fatal(err)
}
fmt.Println("stored at sequence", ack.Sequence, "duplicate:", ack.Duplicate)
// A durable pull consumer: explicit ack, bounded redelivery.
cons, err := js.CreateOrUpdateConsumer(ctx, "ORDERS", jetstream.ConsumerConfig{
Durable: "billing",
AckPolicy: jetstream.AckExplicitPolicy,
AckWait: 30 * time.Second,
MaxDeliver: 5,
BackOff: []time.Duration{time.Second, 5 * time.Second, 30 * time.Second},
})
if err != nil {
log.Fatal(err)
}
batch, err := cons.Fetch(10, jetstream.FetchMaxWait(2*time.Second))
if err != nil {
log.Fatal(err)
}
for msg := range batch.Messages() {
fmt.Println("got", string(msg.Data()))
if err := msg.Ack(); err != nil { // ack after the side effect
log.Println("ack failed:", err)
}
}
if err := batch.Error(); err != nil {
log.Println(err)
}
}Choosing
Cloud-managed versus self-hosted
| Factor | Cloud-managed (SQS/SNS, Pub/Sub, Service Bus, Event Hubs) | Self-hosted (NATS, Pulsar, Artemis, EMQX/Mosquitto, RabbitMQ, Kafka) |
|---|---|---|
| Operations | Vendor runs servers; you manage quotas, backlog, retries, IAM and capacity/cost | You run, monitor, upgrade, back up |
| Cost shape | Per request or per unit; cheap when idle, can grow with volume | Fixed infrastructure plus people; cheap at sustained high volume |
| Portability | Locked to the cloud's API (Event Hubs offers Kafka protocol) | Runs anywhere, including on-premises and edge |
| Latency | Network round trips to a regional endpoint | Local network, tunable |
| Features | What the vendor ships | What you configure, plus plugins |
| Compliance and data residency | Region and tenancy of the vendor | Your control |
| Failure modes | Vendor outage, throttling quotas | Your outage, your upgrade mistakes |
| Best for | Teams without a platform group; spiky load | Platform teams; hybrid, edge or very high steady volume |
Workload to recommendation
| Workload | Recommended | Extra technique | Reason |
|---|---|---|---|
| Laravel app on AWS, jobs and mail | SQS (built-in driver) | DLQ, visibility above job timeout, after_commit | Zero servers, supported out of the box |
| Laravel app, first version, one server | database driver | Move to Redis or SQS when load grows | No new infrastructure |
| Domain events to many services on AWS | SNS to SQS | Filter policies, raw delivery, DLQ per queue | Each consumer isolated |
| Event replay, analytics feeds | Kafka, Pulsar, Event Hubs, JetStream | Retention sized to the replay window | Log with cursors |
| Ordered work per entity on Azure | Service Bus sessions | Session state, settle before close | FIFO per key and DLQ |
| IoT telemetry | MQTT (EMQX at scale, Mosquitto for small) | QoS 1, persistent sessions, last will | Device-friendly |
| Multi-tenant platform with quotas | Pulsar | Namespaces, Key_Shared | Tenancy is first class |
| Edge, microservices, low latency, small ops budget | NATS JetStream | Pull consumers, dedup id | One binary |
| JVM monolith migrating from JMS | Artemis | Keep JMS, add AMQP clients | No code change |
| Need a task queue with complex routing | RabbitMQ | Topic exchange | Richest routing |
Compare with the side-by-side on broker comparison.
In architecture: from a single process to a distributed system
Monolith (one process, one database)
Start with no broker: Laravel's database driver or a Go in-process channel. A jobs insertion can join the business transaction when it shares the DB connection and is dispatched before commit; after_commit=true does not make that atomic. Example: a Laravel monolith sends order confirmation mails through QUEUE_CONNECTION=database and a queue:work process under Supervisor. Cost: polling load on the primary, and no fan-out to other languages.
Modular monolith / multiple databases
Modules publish integration events in process, then through the same queue. Move to SQS (Laravel sqs driver) when you have more than one worker host. Example: the Billing module listens to OrderPlaced published by Orders; both run in the same codebase but on separate SQS queues so billing backlog does not delay emails. Keep the event shape in a shared contract, see domain events and integration events.
Microservices
Between services, publish JSON events to a topic and give each consumer its own queue or subscription. Example on AWS: the orders service publishes to the SNS topic order-events; billing, shipping and analytics each have an SQS queue with a DLQ and a filter policy; billing and shipping are Laravel, analytics is a Go worker using aws-sdk-go-v2. Add an outbox so the intent to publish is atomic with the order insert; the relay publishes later, and an inbox in each consumer. Cross-service calls and their trade-offs are in service communication, and the failure design in designing for failure and reliable messaging.
Distributed data (replicas, caches, multi-region)
Multi-region changes the options: Pulsar geo-replication copies topic data but not subscriptions; JetStream uses mirrors and sources between clusters (a stream and its replicas live in one cluster); Pub/Sub is global but ordering needs regional endpoints; SQS and SNS are regional (cross-region means publishing twice or SNS subscriptions in another region); MQTT uses bridges. A consumer that reads its own writes through a cache or replica must tolerate the delay of the event path; see replication and failover and durability and crash recovery.
Scaling path
| Load | Design | Change |
|---|---|---|
| 1x: hundreds of jobs per minute | Laravel database driver | Nothing to run |
| 10x: thousands per minute, several workers | SQS or Redis queue | Move connection, set DLQ and visibility timeout |
| 100x: events consumed by many teams, replay needed | SNS to SQS fan-out, or a log (Kafka, Pulsar, JetStream, Event Hubs) | Contracts, schema registry, per-consumer subscriptions |
| Device fleet | MQTT with EMQX cluster | Shared subscriptions into a stream |
| Platform of many tenants | Pulsar or managed cloud services | Namespaces, quotas |
See competing consumers and scaling and backpressure for how consumers scale.
Lab
Expected, not run. Use an existing disposable SQS standard queue and a native NATS development endpoint with JetStream already enabled. These are broker experiments, not reported measurements. No container setup is required. The SQS SDK uses your normal AWS credential chain; keep the queue separate from application traffic. NATS subjects/consumer names below belong to this exercise.
cd docs/snippets/messaging/other-brokers/go
export AWS_REGION=us-east-1
export SQS_QUEUE_URL='https://sqs.us-east-1.amazonaws.com/ACCOUNT/academy-orders'
export NATS_URL='nats://127.0.0.1:4222'1. Publish and settle on SQS. On an empty standard queue, go run ./sqs is expected to print got {"order_id":42} and delete that received message. A successful send plus an empty receive is not loss: short delays and retries are possible, so poll again if needed.
2. Observe the visibility lease from a second terminal.
aws sqs send-message --queue-url "$SQS_QUEUE_URL" --message-body hi
aws sqs receive-message --queue-url "$SQS_QUEUE_URL" --visibility-timeout 5 --wait-time-seconds 1 --message-system-attribute-names ApproximateReceiveCount
# Expected: body hi, a receipt handle and ApproximateReceiveCount=1 on a fresh queue.
aws sqs receive-message --queue-url "$SQS_QUEUE_URL" --wait-time-seconds 1
# Expected before expiry: normally no message; standard queues can still duplicate.
sleep 6
aws sqs receive-message --queue-url "$SQS_QUEUE_URL" --wait-time-seconds 1 --message-system-attribute-names ApproximateReceiveCount
# Expected eventually: hi again, a NEW receipt handle, ApproximateReceiveCount increased.
# Delete only with that latest receipt handle after inspecting it:
# aws sqs delete-message --queue-url "$SQS_QUEUE_URL" --receipt-handle 'LATEST_HANDLE'3. Compare publish deduplication and consumer state on NATS.
go run ./nats
# Expected on a fresh ORDERS stream: sequence 1, duplicate false, then got order_id 42.
go run ./nats
# Expected inside the dedup window: same sequence, duplicate true.
# The durable billing consumer has already acknowledged it: no second work item is expected.4. Test redelivery without mixing it with deduplication. In a disposable copy of the NATS example, choose a new event ID and skip msg.Ack(). Run it, wait longer than the first BackOff entry (one second), then run again within the stream dedup window. The unacked message is expected again. BackOff overrides AckWait in this example. After MaxDeliver the consumer stops delivery; the message remains subject to stream retention and needs an operator policy.
5. Explain the difference. SQS deletes after settlement. This JetStream example uses limits retention, so another consumer starting at the beginning can replay the retained event. The PHP NATS example instead uses WORK_QUEUE: it is one logical work queue, not independent fan-out to billing and shipping. These are retention choices, not contradictions between languages.
Common misconceptions
| Belief | Reality |
|---|---|
| SQS deletes a message when I receive it | It only hides it for the visibility timeout; DeleteMessage is the ack |
| SQS FIFO is slow and cannot scale | One message group is sequential, but many groups run in parallel; high-throughput mode raises the per-partition limits |
| Every SNS topic is a replayable worker queue | Standard topics push/retry; FIFO optionally archives/replays; SQS gives each worker a backlog |
| Pub/Sub ordering is global | Ordering is per ordering key, and only when the subscription enables it |
| Pub/Sub exactly-once means my handler runs once | It covers redelivery from Pub/Sub within the ack deadline; a message published twice is two messages |
| NATS cannot persist | Core NATS cannot; JetStream is a persistence layer inside the same server |
JetStream moves a message to a DLQ after MaxDeliver | It stays in the stream; you read the max-deliveries advisory and republish |
| Pulsar subscriptions are partitions | A subscription is a cursor with a type; Shared lets many consumers read one partition |
| MQTT QoS 2 gives end-to-end exactly-once | It is a client-to-broker contract per hop; processing still needs idempotency |
| ZeroMQ is a broker | It is a library; durability, discovery and monitoring are yours |
Laravel retry_after kills slow jobs | It re-offers the job; the job timeout kills it; set timeout below retry_after |
| The database queue driver is only for toys | It is fine for modest load and gives transactional dispatch; at scale polling load and lock contention push you to SQS or Redis |
Cheat sheet
| Topic | Remember |
|---|---|
| Two models | Queue settles per message; log replays within configured retention |
| SQS timer | Visibility timeout 30 seconds default, 12 hours max, extend with ChangeMessageVisibility |
| SQS FIFO | MessageGroupId required; 5-minute dedup window; group blocked while a message is in flight |
| SQS limits | 1 MiB message, 4 days default retention (max 14), 15-minute delay, long poll 20 seconds |
| SNS | Fan-out to SQS; filter policy; raw message delivery; queue policy must allow the topic |
| Pub/Sub timer | Ack deadline 10 to 600 seconds, library extends it, retention 7 days default (max 31) |
| Pub/Sub order | ordering_key plus subscription ordering; ResumePublish after a failure |
| JetStream | Stream stores, consumer remembers; AckExplicit, AckWait, MaxDeliver, BackOff, Nats-Msg-Id |
| Pulsar | Stateless brokers, BookKeeper segments, tiered storage, subscription types, tenants and namespaces |
| Service Bus | Peek-lock, sessions for FIFO, delivery count 10, DLQ sub-queue |
| Event Hubs | Partitions, consumer groups, checkpoints, Kafka endpoint |
| MQTT | QoS 0/1/2, retained, last will, persistent session, shared subscription (v5) |
| Artemis | Address plus routing type; JMS, AMQP, MQTT, STOMP |
| ZeroMQ | Library with socket patterns; no persistence |
| Laravel | sqs and database built in; onGroup, deduplicationId, after_commit, retry_after above job timeout |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Why does an SQS message come back even though a worker received it? Must-know
Answer
Answer: Receiving starts the visibility timeout. If the worker does not call DeleteMessage before it expires, the message is visible again and another worker can receive it.
2 — What does MessageGroupId do on a FIFO queue, and what does it do on a standard queue? Important
Answer
Answer: On FIFO it defines the ordering and serial processing unit. On a standard queue it enables fair queueing across tenants; there is no ordering guarantee.
3 — Why put an SQS queue behind each SNS subscriber? Must-know
Answer
Answer: SNS pushes and retries but is not a durable backlog; each queue gives the consumer its own storage, pace, DLQ and visibility timeout.
4 — In Pub/Sub, what happens to ordered delivery if a publish for an ordering key fails? Good to know
Answer
Answer: Publishing for that key is paused until the publisher calls ResumePublish for it, so later messages cannot overtake the failed one.
5 — What is the difference between a JetStream stream and a consumer? Must-know
Answer
Answer: The stream stores messages under a retention policy. A consumer is a stateful view of the stream that tracks delivery and acknowledgement for one application.
6 — What happens to a JetStream message when MaxDeliver is reached? Important
Answer
Answer: It stays in the stream; the consumer stops delivering it and publishes an advisory. You must handle it yourself, for example by republishing it to a dead-letter subject.
7 — Which Pulsar subscription type lets many consumers share one topic as a queue, and which preserves per-key order? Important
Answer
Answer: Shared for queue-style sharing; Key_Shared keeps per-key ordering across consumers.
8 — Why is Pulsar geo-replication not an active-active consumer setup? Good to know
Answer
Answer: It replicates topic data, not subscriptions; each cluster has its own local subscriptions, and replicated subscriptions only help failover.
9 — When would you pick Service Bus sessions over SQS FIFO? Good to know
Answer
Answer: When you are on Azure and need FIFO per key with per-session state and a built-in dead-letter sub-queue; SQS FIFO is the AWS equivalent for ordering by group.
10 — What does MQTT QoS 1 actually guarantee, and what does it not? Must-know
Answer
Answer: QoS 1 tracks acknowledgment on each protocol hop and allows duplicates. MQTT 5 resends outstanding packets on reconnect; PUBACK does not commit an application transaction.
11 — Why is ZeroMQ not a replacement for RabbitMQ? Must-know
Answer
Answer: It is a socket library with no broker, persistence or acks; you build those pieces yourself.
12 — How should Laravel's timeout relate to retry_after and the SQS visibility timeout? Important
Answer
Answer: The job timeout must be shorter than both, otherwise a still-running job is handed to a second worker.
Glossary
| Term | Meaning |
|---|---|
| Visibility timeout | SQS lease after receive during which other consumers cannot see the message |
| Receipt handle | SQS token, valid for one receive, needed to delete or change visibility |
maxReceiveCount | SQS redrive-policy attempt limit before a message moves to the DLQ |
MessageGroupId | SQS FIFO ordering key; fair-queue key on standard queues |
MessageDeduplicationId | SQS FIFO id that suppresses duplicates for 5 minutes |
| Long polling | SQS receive that waits up to 20 seconds for a message |
| Redrive | Moving messages from a DLQ back to a source queue |
| SNS filter policy | Rule on a subscription that selects which messages it receives |
| Raw message delivery | SNS option that delivers your payload without the JSON envelope |
| Ack deadline | Pub/Sub lease for a delivered message |
| Ordering key | Pub/Sub key whose messages are delivered in order |
Seek | Pub/Sub replay to a timestamp or snapshot |
| Stream (JetStream) | Persistent message store capturing subjects |
| Consumer (JetStream) | Stateful view of a stream with ack tracking |
AckWait | JetStream time to wait for an ack before redelivery |
MaxDeliver | JetStream limit on delivery attempts |
Nats-Msg-Id | Header JetStream uses for publish deduplication |
| BookKeeper | Replicated log storage Pulsar writes to |
| Ledger / segment | Immutable unit of Pulsar storage |
| Tiered storage | Offloading sealed Pulsar segments to object storage |
| Subscription type | Pulsar sharing mode: Exclusive, Failover, Shared, Key_Shared |
| Peek-lock | Service Bus receive mode that holds a lock until you settle |
| Session | Service Bus group of ordered related messages handled by one receiver |
| Dead-letter sub-queue | Service Bus built-in DLQ per queue or subscription |
| QoS | MQTT delivery level 0, 1 or 2 |
| Retained message | MQTT last message kept per topic for new subscribers |
| Last will | MQTT message published when a client vanishes |
| Shared subscription | MQTT 5 load-balanced subscription ($share/group/topic) |
| Routing type | Artemis anycast (queue) or multicast (topic) |
| Overflow storage | Laravel SQS feature storing oversized payloads in a cache store |
retry_after | Laravel queue time after which a reserved job is given to another worker |
References
- NATS JetStream.
- NATS consumer policies.
- Pulsar architecture and messaging.
- Pulsar client for Go.
- SQS FIFO ordering and receives.
- SQS visibility timeout.
- SQS quotas.
- SNS to SQS.
- SNS FIFO destinations.
- SNS FIFO archive and replay.
- Pub/Sub API definition.
- Pub/Sub Go client documentation.
- Pub/Sub PHP client.
- Service Bus sessions and state lifetime.
- Service Bus documentation.
- Event Hubs documentation.
- MQTT 5 OASIS standard.
- Mosquitto configuration.
- EMQX license.
- Artemis manual.
- ZeroMQ guide.
- Laravel 13 queues.
- Laravel DatabaseQueue implementation.
- Laravel SqsQueue implementation.
- NATS PHP client.
- MQTT Laravel client.
- NATS Go client.
- AWS SDK Go v2.
- Eclipse Paho Go client.