Skip to main content

Messaging and streaming

In synchronous microservice architectures, when service A calls service B directly over HTTP or gRPC, the calling thread blocks until the downstream service finishes processing. If service B experiences latency or goes offline, service A quickly exhausts its thread pool, triggering cascading outages across the entire application stack.

Introducing an asynchronous messaging layer decouples services in both time and space. The producer writes an event or task payload to a managed message broker and immediately resumes processing user traffic. Downstream consumers pull or receive messages at their own pace. If a consumer crashes or is taken down for deployment, messages accumulate safely within the broker until the service recovers.

Cloud providers offer three primary messaging abstractions: queues, pub/sub topics, and event streams.

Queues

A provides point-to-point task buffering where each message is delivered to and processed by exactly one worker. For example, when a user requests an export, the web API enqueues a task and returns an immediate confirmation. A background worker picks up the message, compiles the report, and acknowledges the job by deleting the message.

When a worker retrieves a message, the queue hides it from other consumers for a configurable duration known as a visibility timeout. If the worker completes its processing and deletes the message, the task is finished. If the worker crashes, runs out of memory, or encounters a fatal error, the visibility timeout expires and the message becomes visible again for another worker to process.

This mechanism guarantees . The broker ensures that no message is lost, but intermittent network partitions or worker crashes can result in duplicate deliveries. Consequently, queue consumers must be engineered to be idempotent: processing the same message payload multiple times must produce the identical system state as processing it once.

Queues also deliver essential load-leveling capabilities. A sudden surge of ten thousand requests is absorbed instantly by the queue, allowing downstream database workers to process tasks at a steady, sustainable rate without exhausting database connection pools.

Topics

While queues deliver messages to a single worker, a broadcasts each published event to multiple independent subscribers simultaneously. This architecture—known as (pub/sub)—allows systems to emit business state notifications without coupling the producer to downstream consumers.

When an order_placed event is published to a topic, it can be fanned out simultaneously to inventory, invoicing, email notification, and fraud detection services. Introducing a new consumer requires subscribing to the topic without modifying upstream code. In production systems, topics typically deliver into dedicated subscriber queues, providing each downstream service with its own isolated buffer and retry policies.

Streams

A organizes data into an append-only, distributed commit log. Unlike message queues that delete items upon consumption, event streams retain all published events across a configurable time window (ranging from days to weeks).

Multiple consumer groups maintain independent cursor positions (offsets) within the log, reading events sequentially at their own pace. Because data is immutable and persistent, consumers can replay historical event streams from any previous timestamp or offset. This makes event streaming the standard foundation for event-sourcing architectures, real-time analytics pipelines, and audit trails.

Streams guarantee total message ordering within individual partitions. Using a consistent partition key (such as an account ID or device UUID) ensures that all events for a given entity land on the same partition, preserving strict chronological ordering while scaling cluster throughput across multiple partitions in parallel.

MechanismPoint-to-Point QueuePub/Sub TopicDistributed Event Stream
Delivery topologyOne-to-one: exactly one consumer processes each messageOne-to-many: fan-out delivers each message to all active subscribersMany-to-many: independent consumer groups read from shared partitions
Message orderingBest-effort standard delivery; strict order in FIFO queuesBest-effort delivery orderStrict sequential ordering guaranteed within each partition
Storage & retentionEphemeral: deleted immediately upon successful processingEphemeral: dropped after delivery to subscriber endpoints or queuesPersistent: retained across configurable time windows (days or weeks)
Historical replayUnsupported; once consumed or expired, messages are goneUnsupported; messages deliver to current active subscribers onlySupported; consumers can rewind offset cursors to replay historical events
Primary architectural roleBackground task execution, rate leveling, service decouplingEvent broadcasting, asynchronous notifications, domain event fan-outEvent sourcing, continuous stream analytics, audit logging, data sync

Failure and dead-letter queues

When a message payload is corrupt, contains unexpected data, or triggers an unhandled application exception, automated retries will fail repeatedly. Without intervention, a failing message (a "poison pill") will loop indefinitely, consuming worker resources and blocking valid messages behind it.

To resolve this, queues and subscriptions route unprocessable messages to a (DLQ). When a message exceeds a configured maximum receive count, the broker automatically transfers it to the DLQ and continues normal processing. Operations teams configure automated alarms on DLQ depth to investigate underlying application bugs, release fixes, and redrive messages back into the primary queue.

Writing a queue consumer

Guarantee idempotency by validating unique message identifiers before executing side effects.

  1. Retrieve the message payload and extract its unique message identifier or idempotency key.
  2. Query the persistent store or cache to check whether this identifier has already been processed.
  3. If the identifier exists, delete the message from the queue and exit immediately.
  4. Execute the business logic, persisting the identifier and the result within the same transactional boundary if possible.
  5. Acknowledge and delete the message from the queue upon successful completion.

When to use asynchronous messaging

Use direct synchronous calls when the caller requires immediate data to proceed (such as authenticating a user password or confirming live inventory during checkout).

Use asynchronous messaging when work can execute in the background, when operations take longer than several hundred milliseconds, or when multiple independent systems need to react to domain state changes. Relying on direct HTTP calls for multi-step workflows creates tight coupling that inevitably leads to cascading outages when any downstream dependency degrades.

Terms introduced

  • Queue: a buffer that delivers each message to one consumer and redelivers it if the consumer fails.
  • At-least-once delivery: the promise that no message is lost, at the cost that some arrive twice.
  • Topic: a channel that delivers each message to every subscriber.
  • Publish-subscribe: the pattern where producers send to a topic and never know who receives.
  • Stream: an ordered, replayable log of events with a retention period, read by consumers at their own pace.
  • Dead-letter queue: where a message goes after it has failed every retry, so it stops blocking the others.

How providers do it

Asynchronous messaging primitives—point-to-point queues, publish-subscribe topics, and distributed event streams—are supported across AWS, Azure, and Google Cloud. However, each provider structures its product portfolio differently, with Google Cloud unifying queuing and pub/sub into a single integrated architecture.

ConceptAWSAzureGoogle Cloud
Point-to-point queueAmazon SQSAzure Service Bus queues; Azure Queue StorageCloud Pub/Sub subscription
Pub/Sub topicAmazon SNSAzure Service Bus topics (with subscriptions)Cloud Pub/Sub topic
Distributed event streamAmazon Kinesis Data Streams, Amazon MSKAzure Event Hubs (with Kafka endpoint)Google Cloud Managed Service for Apache Kafka
Dead-letter queue (DLQ)Secondary SQS queue configured via redrive policyBuilt-in dead-letter sub-queueCloud Pub/Sub dead-letter topic
Processing lock timeoutVisibility TimeoutMessage Lock DurationAcknowledgment Deadline (ack deadline)
Message ordering guaranteesSQS FIFO queues (ordered by Message Group ID)Service Bus SessionsCloud Pub/Sub ordering keys
Historical message replayNot supported on SQS/SNS; Kinesis replays within retentionNot supported on Service Bus; Event Hubs replays within retentionCloud Pub/Sub Seek (rewind subscription to timestamp/snapshot)
Managed event busAmazon EventBridgeAzure Event GridGoogle Cloud Eventarc

Every product name and technical mapping above is confirmed against provider documentation. Specific maximum payload limits and service tier lifecycles are marked unconfirmed in the provider tabs below.

A distinctive architectural model exists in Google Cloud Pub/Sub:

  • In AWS, SQS (queuing) and SNS (pub/sub topics) are separate services; implementing a fan-out pattern requires explicitly provisioning an SNS topic and subscribing individual SQS queues to it.
  • In Google Cloud Pub/Sub, the topic and subscription model is natively integrated: publishers always write to a topic, and consumers read from individual subscriptions. A single subscription behaves exactly like a point-to-point worker queue, while attaching multiple subscriptions provides fan-out broadcasting without managing separate queuing services.

What this maps to: Amazon SQS for queues and Amazon SNS for topics. Streams are Amazon Kinesis Data Streams or Amazon MSK (Managed Streaming for Apache Kafka). Amazon EventBridge is an event bus that routes between all of them.

ConceptOn AWSStatus
QueueSQS. Standard queues are at-least-once with best-effort order. FIFO queues are exactly-once within a deduplication window and ordered within a message group, at lower throughputconfirmed
RedeliveryA message read but not deleted reappears after the visibility timeoutconfirmed
Dead-letter queueAnother SQS queue, named in the source queue's redrive policy with a maximum receive countconfirmed
TopicSNS. Subscribers are SQS queues, Lambda functions, HTTP endpoints, email, or SMS. SNS to SQS is the usual fan-outconfirmed
StreamKinesis Data Streams, partitioned into shards, retained for a period you set. MSK for Kafka with its own vocabularyconfirmed
Event busEventBridge, with rules matching on event content and routing to targets. Also the source for scheduled eventsconfirmed
Function triggerLambda polls SQS and Kinesis through an event source mapping; SNS and EventBridge pushconfirmed
Message sizeA hard limit per message, with an extended client library that stores larger payloads in S3unconfirmed; check current quotas

Their vocabulary

Standard termTheir term
Redelivery timeoutVisibility timeout
Move to the dead-letter queue after N failuresRedrive policy, maxReceiveCount
PartitionShard (Kinesis), partition (MSK)

Where to look

The SQS console shows how many messages are available, in flight, and sitting in the dead-letter queue. For alarms, the CloudWatch metric you want is ApproximateAgeOfOldestMessage.

Last verified: never.


Check your understanding

0 of 4 answered

  1. A worker reads a message, charges a card, and crashes before deleting the message. What happens next?
  2. A new analytics consumer needs to see every event from the past week. Which shape allows that?
  3. An order-placed event must reach the warehouse, the email service, and analytics. Which shape carries it?
  4. What does a dead-letter queue prevent?