Skip to content

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 forGo to
One table per concern you can memoriseEverything in one minute
Why so many brokers existWhy there are more brokers
Where each came fromWhere it comes from
NATS JetStream streams and consumersNATS JetStream
Pulsar segments, BookKeeper, tiered storage, geo-replicationApache Pulsar
Visibility timeout, FIFO limits, standard vs FIFOAmazon SQS
Fan-out to queues, filter policiesAmazon SNS
Ack deadlines, ordering keys, exactly-onceGoogle Pub/Sub
Sessions, peek-lock, Event Hubs partitionsAzure Service Bus and Event Hubs
QoS levels, retained messages, last willMQTT brokers
JMS and multi-protocol on the JVMActiveMQ Artemis
Sockets, no brokerZeroMQ
sqs and database driversLaravel's built-in drivers
Every broker in one tableThe master comparison
Mapping to RabbitMQ, Kafka, Redis StreamsBroker differences
Cloud-managed vs self-hostedChoosing
Go and Laravel codeGo, Laravel
Reproduce it locallyLab

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.

ModelMessage after a successful ackConsumer state lives inReplayProducts on this page
QueueDeletedThe broker (per message)No (unless you keep a copy elsewhere)SQS, Service Bus, Artemis, Laravel database driver, MQTT QoS 1 sessions
Log / streamKept until retention removes itA cursor per consumer or subscriptionYes, within retentionPulsar, NATS JetStream, Event Hubs, Kafka
Pub/sub with queue-like subscriptionsDeleted per subscription (optionally retained)The subscriptionOptional (Seek, retained acked messages)Google Pub/Sub, SNS to SQS
Library, no brokerNot storedNowhereNoZeroMQ

The one setting that decides redelivery on each product. Learn the name of this knob first; it is where most production incidents start.

ProductThe "I will give it back if you are too slow" knobDefaultMaximum
Amazon SQSVisibility timeout30 seconds12 hours from first receive
Google Pub/SubAck deadline (ackDeadlineSeconds)10 seconds600 seconds
NATS JetStreamAckWait (or BackOff)Set per consumerAny duration
Azure Service BusLock duration (peek-lock)Set per entityMinutes, renewable
PulsarackTimeout or negative-ack delayOff (ackTimeout 0)Any duration
Laravel database / redis driverretry_after90 secondsAny; must exceed job timeout
MQTT QoS 1Unacked packet state; MQTT 5 retransmits on reconnectNo generic lease timerSession expiry

Where each one wins.

If you needPickWhy
Zero servers, AWS already thereSQS (+ SNS)Nothing to run; Laravel supports it out of the box
Zero servers, GCP already therePub/SubGlobal service, ordering keys, push and pull
Ordered, session-based work in AzureService BusSessions give FIFO per key plus DLQ
Tiny messages from millions of devicesMQTT (EMQX or Mosquitto)Lightweight protocol, QoS levels, last will
One system for queues, streams and multi-tenancyPulsarStorage split from serving, tenants and namespaces
Very low latency plus durable streams in one small binaryNATS JetStreamSubjects, streams, consumers; easy to run
Existing JVM and JMS codeArtemisJMS 2.0 and Jakarta Messaging, plus AMQP, MQTT, STOMP
Fast in-process or between processes without a serverZeroMQA socket library, you design the topology
A queue with no new infrastructureLaravel database driverThe 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 optimiseYou 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.

  1. "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.
  2. "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.
  3. "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 lineageWhat it explainsPrimary source
NATS adds JetStream persistence to Core NATSTransient subjects and stored streams are separate contractsNATS docs
Pulsar separates brokers from BookKeeper storageServing and storage scale independentlyPulsar docs
AWS separates SQS queues from SNS topicsWork distribution and fan-out composeSNS-to-SQS guide
Pub/Sub defines topics plus subscriptionsEvery subscription owns a backlogAPI definition
Azure offers Service Bus and Event HubsWork queues and partitioned streams solve different needsService Bus, Event Hubs
MQTT is a standard protocol, not one serverQoS is portable; storage and clustering remain product choicesOASIS MQTT 5
Artemis unifies protocols through addresses and queuesJMS, AMQP and MQTT map onto broker resourcesArtemis manual
ZeroMQ builds messaging patterns into socketsApplications own persistence and recoveryZeroMQ 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 stream

Real 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.

PropertyJetStream
ModelLog (limits retention), queue (WorkQueuePolicy), or interest-based
DeliveryAt-least-once; ack policies AckExplicit (default), AckAll, AckNone (AckFlowControl documented for 2.14; sourcing/mirroring use)
OrderingPer stream in sequence; a pull consumer can deliver redelivered messages out of order
Retention / replayLimits by count, bytes, age; ReplayPolicy instant or original; DeliverPolicy all, last, by time or sequence
ConsumersPull (recommended for new projects, per the docs) or push; durable or ephemeral; ordered consumers for simple replays
Delay / DLQBackOff list for redelivery, nakWithDelay; MaxDeliver leaves the message in the stream (no automatic DLQ stream: you watch advisories and republish)
Flow controlMaxAckPending; pull MaxWaiting, MaxRequestBatch
ScalingStreams replicate with Raft (up to 5 replicas); sources and mirrors copy between streams and clusters; leaf nodes and superclusters
Multi-tenancyAccounts with isolated subject spaces and JetStream limits per account
ProtocolNATS text protocol over TCP; WebSocket and MQTT listeners exist
Licence / hostingApache 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.

ORDERS.placedORDERS.shippedStream ORDERSsubjects ORDERS.* storage file replicas 312345retention limits: MaxAge, MaxMsgs, MaxBytesPubAck returns the sequence numberConsumer billingdurable, pull, AckExplicitAckWait, MaxDeliver, BackOffConsumer shippingfilter ORDERS.shippedown cursor, own pendingA consumer is a stateful view of the streamthe stream stores; the consumer remembers delivered and acked; with limits retention, deleting a consumer never deletes messages

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.

PropertyPulsar
ModelBoth: topic with subscriptions; log by retention, queue by Shared subscription
DeliveryAt-least-once; ack, cumulative ack (not on Shared/Key_Shared), negative ack, ack timeout; transactions and deduplication optional
OrderingPer partition; Key_Shared keeps per-key order; negative acks can reorder on ordered types
Retention / replayAcked data deleted unless retention; backlog quota and TTL; Seek and reader API for replay
Consumer modelExclusive (default), Failover, Shared, Key_Shared; a unique subscription name per consumer gives fan-out
Delay / DLQDelayed delivery (deliverAt, deliverAfter) on Shared and Key_Shared; retry/dead-letter support depends on client and subscription type
ScalingAdd brokers (stateless) or bookies (storage) separately; partitioned topics
Multi-tenancyFirst class: tenants, namespaces, quotas, isolation policies
ProtocolPulsar binary protocol; Kafka-on-Pulsar and AMQP/MQTT proxies exist as add-ons
Licence / hostingApache 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.

PropertySQS standardSQS FIFO
DeliveryAt-least-oncePublish deduplication for 5 minutes; processing can repeat after visibility expiry
OrderingBest effortStrict within a message group
Throughput"Nearly unlimited" API calls300 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)
Retention4 days default, 60 seconds to 14 daysSame
Message sizeUp to 1 MiB (1,048,576 bytes)Same
DelayPer queue or per message, up to 15 minutesPer queue only (per-message delay not supported)
DLQRedrive policy with maxReceiveCount, and redrive backSame, FIFO to FIFO
Consumer modelCompeting consumers, long polling up to 20 seconds, batches of up to 10Same; a group is blocked while one of its messages is in flight
Fair queuesSetting a message group on a standard queue enables fair queueing across tenantsn/a
Protocol / hostingHTTPS 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
PropertySNS (with SQS)
ModelPub/sub topic; SQS provides subscriber backlog; FIFO optionally archives for replay
OrderingStandard: none; FIFO topic: per message group
Fan-outMany subscriptions per topic; each SQS queue is independent (own DLQ, own pace)
FilteringSubscription filter policy on attributes or JSON payload (FilterPolicyScope)
PermissionsThe queue's access policy must allow sns.amazonaws.com to SendMessage from the topic ARN
Go / Laravelaws-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.

Publisherorders serviceSNS topicorder-eventsSQS billingvisibility timeoutSQS shippingstandard queueSQS analyticsfilter: type = OrderPlacedworkersworkersworkersDLQ (maxReceiveCount)DLQ (maxReceiveCount)One publish, N independent queues: a slow or failing consumer never affects the others

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)
PropertyPub/Sub
ModelTopic plus subscriptions; each subscription is a queue; optional retention gives replay
DeliveryAt-least-once; exactly-once delivery per subscription as an option (pull, regional)
OrderingPer ordering key, only when the subscription enables ordering; publishers use a regional endpoint
Retention / replay10 minutes to 31 days per subscription; Seek to time or snapshot
Consumer modelStreamingPull, pull, push to HTTPS endpoints; flow control via MaxOutstandingMessages
Delay / DLQRetry policy (backoff) and DeadLetterPolicy with max_delivery_attempts; no per-message delay
ScalingFully managed, scales with load; no partitions to size
Multi-tenancyProjects, IAM per topic and subscription
Protocol / hostinggRPC 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
PropertyService BusEvent Hubs
ModelQueue and topic brokerPartitioned log
DeliveryAt-least-once with peek-lock; at-most-once with receive-and-delete; duplicate detection availableAt-least-once; consumer checkpoints offsets
OrderingFIFO per sessionPer partition (partition key)
RetentionUntil consumed or TTLTime-based retention; Capture to storage
Delay / DLQScheduled enqueue time, deferral, built-in dead-letter sub-queue per entityNo DLQ; the consumer handles bad events
ScalingPremium dedicated units; partitionsThroughput units / partitions; Kafka protocol endpoint
ProtocolAMQP 1.0 (and a REST/HTTPS API)AMQP 1.0, Kafka protocol, HTTPS
Go clientgithub.com/Azure/azure-sdk-for-go/sdk/messaging/azservicebus and azeventhubssame family
LaravelNo built-in; community packages or the REST APIKafka 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
PropertyMosquittoEMQX
ModelBroker; topic-based pub/sub; per-client queuesClustered broker; rule engine and data bridges
DeliveryQoS 0, 1, 2QoS 0, 1, 2
RetentionRetained message per topic; persistence file; max_queued_messages per clientRetained, session persistence, message storage options
Consumer modelSubscriptions with filters; shared subscriptions (v5)Same, with cluster-wide shared subscriptions
DLQ / delayNone built in; delayed publish is an EMQX featureDead-letter via rules; delayed publish
ScalingSingle node (bridges for federation)Horizontally clustered, millions of connections
LicenceEPL-2.0 or EDL-1.0Business Source License 1.1 from 5.9.0 (read the licence before commercial use)
Go clientgithub.com/eclipse/paho.mqtt.golangsame

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.

PropertyArtemis
ModelQueue broker with address model (anycast = queue, multicast = topic)
DeliveryAt-least-once; JMS transactions and acknowledge modes; duplicate detection
OrderingPer queue
Retention / replayDelete on ack; paging to disk; a journal; no replay
Delay / DLQScheduled delivery, dead letter address, redelivery delay
Hosting / licenceApache 2.0; self-hosted, also embedded in Red Hat AMQ
Go / LaravelGo 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.

PropertyZeroMQ
ModelBrokerless socket patterns (PUB/SUB, PUSH/PULL, REQ/REP, ROUTER/DEALER)
DeliveryIn-memory buffers; at-most-once unless you add acks and retries
OrderingPer connection
RetentionNone
DLQ / delayYou build them
Hosting / licenceA library (LGPL with a static-linking exception); used inside services, or to build a broker
Go clientgithub.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".

sql
-- 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;
Propertydatabase driversqs driver
ModelQueue in a tableQueue in SQS
DeliveryAt-least-once (retry_after re-reserves a stale job)At-least-once (visibility timeout)
Delaydelay() sets available_atdelay() up to 15 minutes (not on FIFO)
OrderingRoughly id order; not guaranteed under concurrencyFIFO queue plus onGroup()
TransactionsAtomic only on the same DB connection/transaction with dispatch before commit; after_commit leaves a post-commit crash windowafter_commit config; the dispatch is a network call, not part of your transaction
ScalingLimited by database load; pollingPractically unbounded; long polling
WhenSmall apps, background jobs next to the data, testsProduction 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 JetStreamPulsarSQSSNSPub/SubService BusEvent HubsMQTT (Mosquitto, EMQX)ArtemisZeroMQ
ModelLog + queueLog + queueQueueTopic fan-outTopic + queue-like subsQueue + topicLogTopicQueue + topicSockets
DeliveryAt-least-once, dedup optionAt-least-onceAt-least-once; FIFO publish dedup windowAt-least-onceAt-least-once; exactly-once optionAt-least-onceAt-least-onceQoS 0/1/2At-least-onceAt-most-once
OrderingPer streamPer partition / keyFIFO per groupFIFO topic per groupPer ordering keyPer sessionPer partitionPer topicPer queuePer connection
Retention / replayLimits; replayRetention, tiered storage; Seek4 days default, max 14; no replayOptional FIFO archive/replay7 days default, max 31; SeekTTL; no replayTime-based; replayRetained message onlyNo replayNone
Consumer modelPull / push durableSubscription typesCompeting, long pollPush to subscribersPull, StreamingPull, pushPeek-lock, sessionsConsumer groupsSubscribe, shared (v5)JMS consumersSocket peers
DelaynakWithDelay, BackOffdeliverAtup to 15 minvia SQSRetry policyScheduled enqueueNoEMQX delayed publishScheduledYou build it
DLQAdvisory, you republishDead letter topicRedrive policySubscription DLQDead letter topicBuilt-in sub-queueNoneRules (EMQX)Dead letter addressNone
ScalingRaft replicas, superclustersStateless brokers + bookiesManagedManagedManagedPremium unitsPartitions / TUsClustering (EMQX)HA pairs, clustersn/a
Multi-tenancyAccountsTenants, namespacesPer queue, IAMPer topic, IAMProjects, IAMNamespacesNamespacesACLs, listenersSecurity domainsn/a
ProtocolNATSPulsar binaryHTTPSHTTPSgRPC, RESTAMQP 1.0AMQP, KafkaMQTTManyZMTP
Hosting / licenceSelf-hosted; Apache 2.0Self-hosted or managed; Apache 2.0AWS onlyAWS onlyGCP onlyAzure onlyAzure onlySelf-hosted; EPL / BSL 1.1Self-hosted; Apache 2.0Library; LGPL
Go clientnats.gopulsar-client-goaws-sdk-go-v2aws-sdk-go-v2cloud.google.com/go/pubsubazservicebusazeventhubspaho.mqtt.golangAMQP or STOMP libszmq4
LaravelPackage or SDKSDKBuilt-in driverSDK / packagesPackage or SDKSDKKafka packagePackageSTOMP / AMQPExtension
Queue brokers (delete on ack)RabbitMQ (closest core broker)Amazon SQS standard / FIFOAzure Service Bus queues, topics, sessionsActiveMQ Artemis JMS, AMQP, MQTTcompeting consumers, DLQ, per-message ackLog / stream brokers (keep and replay)Kafka (closest core broker)Apache Pulsar segments on BookKeeperNATS JetStream streams + consumersAzure Event Hubs partitions, Kafka protocoloffset or cursor, retention, replayPub/sub that behaves like queuesGoogle Pub/Sub topic + subscriptionsAmazon SNS topic, fans out to SQSfan-out first, each subscription is a queueLightweight telemetry brokersMQTT: Mosquitto, EMQXQoS 0/1/2, retained messages, last willmillions of small devices, topic filtersLibrary, not a brokerZeroMQ: sockets with patterns (PUB/SUB, PUSH/PULL, REQ/REP); you build the broker, if any

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.

ProductLease nameWho extends itExtension callHard cap
SQSVisibility timeoutYouChangeMessageVisibility12 hours from first receive
Pub/SubAck deadlineThe client library, automaticallymodifyAckDeadlineMaxExtension in the library (60 minutes default in Go); server custom deadline 10 to 600 seconds
JetStreamAckWaitYouProgress ack (InProgress) resets the timerNone
Service BusLock durationYou or the SDK's auto lock renewalRenew lockSettled before receiver closes
Laravelretry_after / visibilityNot extendedNoneMust 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 ​

WhereSymbolMeaningRetry?
SQSStale or invalid receipt handle (ReceiptHandleIsInvalid) on delete or change-visibilityThe handle belongs to an earlier receive; after a re-receive only the newest handle is reliableNo: the new holder owns the message
SQSAWS.SimpleQueueService.NonExistentQueueWrong queue URL or regionNo
SQS FIFOInvalidParameterValue for a missing MessageGroupIdFIFO requires a group on every messageFix the code
Pub/SubFAILED_PRECONDITION on pull of a detached subscriptionThe subscription is detached from its topicNo
Pub/SubPublish error on an ordering keyThe key is pausedCall ResumePublish, then retry
JetStreamMaxDeliver exhaustedThe message stays in the stream, advisory publishedRepublish or inspect
Service BusMaxDeliveryCountExceededDelivery count above 10 (default)Dead-letter queue
Service BusTTLExpiredExceptionMessage expiredDLQ if dead-lettering on expiry is enabled
Service BusSession ID is nullSession entity got a message without a session IDFix the sender
MQTTConnection refused with a reason code (v5)Not authorised or protocol errorPer code

Ordering knobs ​

ProductThe keyParallelism limitWhat breaks ordering
SQS FIFOMessageGroupIdOne received batch per group; process same-group batch entries sequentiallyVisibility timeout expiry mid-processing
Pub/Subordering_key (subscription must enable it)Ordered callbacks per key; multiple messages can be outstandingNack of an earlier message redelivers later ones
Service BusSession IDOne receiver per sessionLock loss
JetStreamStream sequence, filter subjectsMany pull consumers share a consumerRedelivery of a nacked message
PulsarPartition, or Key_Shared keyConsumers per key rangeNegative ack on ordered subscriptions
Event HubsPartition keyOne reader per partition per groupRe-partitioning
MQTTTopic (non-shared)One subscriberShared subscriptions, QoS mixing

See ordering and partitioning for the theory.

Solving the classic problems on these brokers ​

ProblemSolutionHowAdvantageCost / limit
One event, many independent consumersSNS topic with SQS queue per consumer; Pub/Sub subscription per consumer; Pulsar subscription per consumer; JetStream consumer per consumerEach consumer gets its own backlogIndependent pace and DLQOne queue or subscription per consumer to manage
Per-customer ordering with parallelismSQS FIFO group, Pub/Sub ordering key, Service Bus session, Pulsar Key_SharedKey = customer idOrder where it mattersA hot key serialises that customer
Poison messagemaxReceiveCount + DLQ (SQS), max_delivery_attempts (Pub/Sub), MaxDeliver (JetStream), dead letter topic (Pulsar), delivery count 10 (Service Bus)Cap attemptsStops the loopNeeds a DLQ process
Delayed retrySQS DelaySeconds (not FIFO), ChangeMessageVisibility; JetStream BackOff; Pulsar deliverAfter; Service Bus scheduled enqueueRe-offer laterBackoff without a schedulerPer-product limits; see retry and backoff
Large payloadStore the body in object storage and send a pointer; Laravel's SQS overflow storage does this with a cache storeClaim checkStays under the size limitExtra read
Replay a month of historyJetStream, Pulsar, Event Hubs, Pub/Sub Seek; not SQSRetained logRebuild a read modelStorage cost
Reliable publish from a databaseWrite an outbox row and publish after commitOutboxNo dual-writeA relay to run
DuplicatesIdempotency key in a table; SQS FIFO dedup id; JetStream Nats-Msg-IdInboxSafe redeliveryStorage 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:

go
// 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:

go
// 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:

go
// 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:

go
// 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):

go
// 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):

go
// 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
<?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
<?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
<?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
<?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
<?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
<?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
<?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 mechanismSQSService BusArtemis
Ack / nackDelete / let visibility expireComplete / abandonJMS acknowledge / rollback
PrefetchMaxNumberOfMessages up to 10, in-flight limitPrefetch countConsumer window size
DLX / DLQRedrive policy, maxReceiveCountDead-letter sub-queue, max delivery count 10Dead letter address
DelayDelaySeconds up to 15 minutesScheduled enqueue timeScheduled delivery
PriorityNone (use two queues)NoneMessage priority
go
// 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 mechanismPulsarEvent HubsJetStream
Topic / partitionTopic, optionally partitionedEvent hub, partitionsStream, subjects
Consumer groupSubscription (type decides sharing)Consumer groupDurable consumer
Offset commitCumulative ack, or per-message ackCheckpointAck floor, per-message ack
RetentionTime, size, backlog quota, tiered storageTime-based; CaptureLimits: age, count, bytes
Key orderingPartition or Key_SharedPartition keySubject plus consumer filter
Transactions / EOSPulsar transactionsNoneDedup id plus double ack
go
// 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 mechanismJetStreamMQTTZeroMQ
XADDjs.Publish returns a sequencePUBLISH QoS 1 returns PUBACKsend returns when buffered
Consumer groupDurable consumerShared subscription (v5)PUSH/PULL peers
XACKmsg.Ack()PUBACK settles one protocol hop; it is not an application transactionNone
Pending list, XAUTOCLAIMConsumer pending + redelivery after AckWaitSession queueNone
TrimLimits (MaxAge, MaxMsgs)Retained message replacedNone
Pub/SubCore NATS subjectsTopicsPUB/SUB
go
// 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 ​

FactorCloud-managed (SQS/SNS, Pub/Sub, Service Bus, Event Hubs)Self-hosted (NATS, Pulsar, Artemis, EMQX/Mosquitto, RabbitMQ, Kafka)
OperationsVendor runs servers; you manage quotas, backlog, retries, IAM and capacity/costYou run, monitor, upgrade, back up
Cost shapePer request or per unit; cheap when idle, can grow with volumeFixed infrastructure plus people; cheap at sustained high volume
PortabilityLocked to the cloud's API (Event Hubs offers Kafka protocol)Runs anywhere, including on-premises and edge
LatencyNetwork round trips to a regional endpointLocal network, tunable
FeaturesWhat the vendor shipsWhat you configure, plus plugins
Compliance and data residencyRegion and tenancy of the vendorYour control
Failure modesVendor outage, throttling quotasYour outage, your upgrade mistakes
Best forTeams without a platform group; spiky loadPlatform teams; hybrid, edge or very high steady volume

Workload to recommendation ​

WorkloadRecommendedExtra techniqueReason
Laravel app on AWS, jobs and mailSQS (built-in driver)DLQ, visibility above job timeout, after_commitZero servers, supported out of the box
Laravel app, first version, one serverdatabase driverMove to Redis or SQS when load growsNo new infrastructure
Domain events to many services on AWSSNS to SQSFilter policies, raw delivery, DLQ per queueEach consumer isolated
Event replay, analytics feedsKafka, Pulsar, Event Hubs, JetStreamRetention sized to the replay windowLog with cursors
Ordered work per entity on AzureService Bus sessionsSession state, settle before closeFIFO per key and DLQ
IoT telemetryMQTT (EMQX at scale, Mosquitto for small)QoS 1, persistent sessions, last willDevice-friendly
Multi-tenant platform with quotasPulsarNamespaces, Key_SharedTenancy is first class
Edge, microservices, low latency, small ops budgetNATS JetStreamPull consumers, dedup idOne binary
JVM monolith migrating from JMSArtemisKeep JMS, add AMQP clientsNo code change
Need a task queue with complex routingRabbitMQTopic exchangeRichest 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 ​

LoadDesignChange
1x: hundreds of jobs per minuteLaravel database driverNothing to run
10x: thousands per minute, several workersSQS or Redis queueMove connection, set DLQ and visibility timeout
100x: events consumed by many teams, replay neededSNS to SQS fan-out, or a log (Kafka, Pulsar, JetStream, Event Hubs)Contracts, schema registry, per-consumer subscriptions
Device fleetMQTT with EMQX clusterShared subscriptions into a stream
Platform of many tenantsPulsar or managed cloud servicesNamespaces, 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.

sh
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.

sh
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.

sh
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 ​

BeliefReality
SQS deletes a message when I receive itIt only hides it for the visibility timeout; DeleteMessage is the ack
SQS FIFO is slow and cannot scaleOne 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 queueStandard topics push/retry; FIFO optionally archives/replays; SQS gives each worker a backlog
Pub/Sub ordering is globalOrdering is per ordering key, and only when the subscription enables it
Pub/Sub exactly-once means my handler runs onceIt covers redelivery from Pub/Sub within the ack deadline; a message published twice is two messages
NATS cannot persistCore NATS cannot; JetStream is a persistence layer inside the same server
JetStream moves a message to a DLQ after MaxDeliverIt stays in the stream; you read the max-deliveries advisory and republish
Pulsar subscriptions are partitionsA subscription is a cursor with a type; Shared lets many consumers read one partition
MQTT QoS 2 gives end-to-end exactly-onceIt is a client-to-broker contract per hop; processing still needs idempotency
ZeroMQ is a brokerIt is a library; durability, discovery and monitoring are yours
Laravel retry_after kills slow jobsIt re-offers the job; the job timeout kills it; set timeout below retry_after
The database queue driver is only for toysIt is fine for modest load and gives transactional dispatch; at scale polling load and lock contention push you to SQS or Redis

Cheat sheet ​

TopicRemember
Two modelsQueue settles per message; log replays within configured retention
SQS timerVisibility timeout 30 seconds default, 12 hours max, extend with ChangeMessageVisibility
SQS FIFOMessageGroupId required; 5-minute dedup window; group blocked while a message is in flight
SQS limits1 MiB message, 4 days default retention (max 14), 15-minute delay, long poll 20 seconds
SNSFan-out to SQS; filter policy; raw message delivery; queue policy must allow the topic
Pub/Sub timerAck deadline 10 to 600 seconds, library extends it, retention 7 days default (max 31)
Pub/Sub orderordering_key plus subscription ordering; ResumePublish after a failure
JetStreamStream stores, consumer remembers; AckExplicit, AckWait, MaxDeliver, BackOff, Nats-Msg-Id
PulsarStateless brokers, BookKeeper segments, tiered storage, subscription types, tenants and namespaces
Service BusPeek-lock, sessions for FIFO, delivery count 10, DLQ sub-queue
Event HubsPartitions, consumer groups, checkpoints, Kafka endpoint
MQTTQoS 0/1/2, retained, last will, persistent session, shared subscription (v5)
ArtemisAddress plus routing type; JMS, AMQP, MQTT, STOMP
ZeroMQLibrary with socket patterns; no persistence
Laravelsqs and database built in; onGroup, deduplicationId, after_commit, retry_after above job timeout

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
Visibility timeoutSQS lease after receive during which other consumers cannot see the message
Receipt handleSQS token, valid for one receive, needed to delete or change visibility
maxReceiveCountSQS redrive-policy attempt limit before a message moves to the DLQ
MessageGroupIdSQS FIFO ordering key; fair-queue key on standard queues
MessageDeduplicationIdSQS FIFO id that suppresses duplicates for 5 minutes
Long pollingSQS receive that waits up to 20 seconds for a message
RedriveMoving messages from a DLQ back to a source queue
SNS filter policyRule on a subscription that selects which messages it receives
Raw message deliverySNS option that delivers your payload without the JSON envelope
Ack deadlinePub/Sub lease for a delivered message
Ordering keyPub/Sub key whose messages are delivered in order
SeekPub/Sub replay to a timestamp or snapshot
Stream (JetStream)Persistent message store capturing subjects
Consumer (JetStream)Stateful view of a stream with ack tracking
AckWaitJetStream time to wait for an ack before redelivery
MaxDeliverJetStream limit on delivery attempts
Nats-Msg-IdHeader JetStream uses for publish deduplication
BookKeeperReplicated log storage Pulsar writes to
Ledger / segmentImmutable unit of Pulsar storage
Tiered storageOffloading sealed Pulsar segments to object storage
Subscription typePulsar sharing mode: Exclusive, Failover, Shared, Key_Shared
Peek-lockService Bus receive mode that holds a lock until you settle
SessionService Bus group of ordered related messages handled by one receiver
Dead-letter sub-queueService Bus built-in DLQ per queue or subscription
QoSMQTT delivery level 0, 1 or 2
Retained messageMQTT last message kept per topic for new subscribers
Last willMQTT message published when a client vanishes
Shared subscriptionMQTT 5 load-balanced subscription ($share/group/topic)
Routing typeArtemis anycast (queue) or multicast (topic)
Overflow storageLaravel SQS feature storing oversized payloads in a cache store
retry_afterLaravel queue time after which a reserved job is given to another worker

References ​

Built by Morteza Negahi