Decoupling with Queues, Topics and Events

Topics Covered

Why Decouple and Amazon SQS Basics

Tight coupling and its failure modes

Amazon SQS fundamentals

Standard queues

Short polling and long polling

Consumers and scaling

Security and encryption

What SQS is not

Message attributes and metadata

Cost model

Request patterns built on queues

When not to use a queue

The design resilient architectures domain is the second largest on the exam, and decoupling is at its heart. Many scenarios describe a system that loses requests during traffic spikes, fails entirely when one component is slow, or is hard to change because every service calls every other service directly. The answer is almost always to put a queue, a topic, an event bus or a workflow service between the components. This lesson covers each of these and how to choose between them. The practical details of each service are covered in SQS, SNS and EventBridge in the AWS in Practice course.

Tight coupling and its failure modes

In a tightly coupled design, a web tier calls an order processing service synchronously and waits for it to finish. If the order service is slow, the web tier's threads pile up waiting and it slows down too. If the order service fails, the web tier returns errors and the orders are lost. If traffic doubles, both tiers must scale at exactly the same time and rate. And adding a new consumer, such as an analytics service that also needs every order, means changing the web tier to call it.

Decoupling breaks these dependencies. The web tier puts the order on a queue and returns immediately. The order service reads from the queue when it can. A slow or failed consumer delays processing but loses nothing, because messages wait in the queue. The two tiers scale independently: the web tier with request rate, the workers with queue depth. This is the main reason questions with words such as spikes, lost requests, independent scaling and resilience to component failure point towards a queue.

Amazon SQS fundamentals

Amazon Simple Queue Service is a fully managed message queue. Producers send messages with SendMessage; consumers poll with ReceiveMessage, process each message and then delete it with DeleteMessage. SQS stores messages redundantly across multiple Availability Zones, scales to nearly unlimited throughput for standard queues and needs no servers or capacity planning.

A queue absorbs bursts so producers and consumers can run at different speeds.

Key limits and settings appear repeatedly in questions. A message can be up to 256 KB; larger payloads are stored in S3 and the message carries a pointer, a pattern supported by the extended client library. Messages are retained for four days by default, configurable from one minute to fourteen days. A delivery delay of up to 15 minutes can be set per queue or per message to postpone delivery. Consumers can receive up to ten messages per call, which reduces cost because SQS charges per request.

Standard queues

Standard queues offer nearly unlimited throughput, at-least-once delivery and best effort ordering. At-least-once means a message is occasionally delivered more than once, for example when a consumer is slow to delete it or a rare internal event occurs. Best effort ordering means messages usually arrive in the order sent but are not guaranteed to. Applications using standard queues must therefore be idempotent: processing the same message twice must have the same effect as processing it once, for example by recording processed message identifiers or by making each operation an upsert keyed on an order ID.

For most decoupling scenarios, standard queues are the right default. They are cheaper per message, scale without any thought and tolerate any traffic pattern. Choose FIFO only when the requirement explicitly needs strict ordering or no duplicates.

Short polling and long polling

By default, ReceiveMessage uses short polling: it queries a subset of SQS servers and returns immediately, even if no messages are found. With many empty responses, this wastes requests and money. Long polling, enabled by setting the receive wait time to up to 20 seconds on the queue or the request, waits until a message arrives or the wait time ends and queries all servers. Long polling reduces empty receives, lowers cost and reduces the latency between a message arriving and a consumer seeing it. When a question mentions high SQS costs from consumers polling an often empty queue, the answer is long polling.

Consumers and scaling

SQS consumers can be EC2 instances in an Auto Scaling group, containers in ECS or EKS, or Lambda functions. For EC2 and containers, the standard scaling metric is the backlog per instance: the number of visible messages divided by the number of workers, compared with how many messages one worker can process within the acceptable latency. Target tracking on that custom metric, or step scaling on the ApproximateNumberOfMessagesVisible metric, adds workers as the backlog grows and removes them as it shrinks. Questions that ask how to scale a worker fleet with demand when work arrives through SQS expect scaling on queue depth, not on CPU.

With Lambda, the event source mapping polls the queue for you, scales the number of concurrent function invocations with the backlog and deletes messages when the function returns successfully. Lambda is often the lowest operational effort answer for processing SQS messages, provided each message can be processed within the function's 15 minute limit.

Security and encryption

Access to queues is controlled with IAM policies and with SQS queue policies, which are resource policies used to allow other accounts or services, such as SNS topics and S3 event notifications, to send messages. Messages can be encrypted at rest with SSE-SQS, which uses keys managed by SQS, or SSE-KMS with a KMS key. Producers in private subnets can reach SQS through an interface VPC endpoint without a NAT gateway. When an S3 bucket in one account sends events to a queue, the queue policy must allow the S3 service principal with a condition on the source bucket ARN.

What SQS is not

SQS does not deliver one message to many consumers: once a consumer deletes a message, it is gone for everyone. That makes it the right tool for distributing work among identical workers, and the wrong tool when several different services each need every message; that is the role of SNS or EventBridge, covered later. SQS also does not let consumers replay old messages after they are deleted; for replay and multiple independent readers of the same ordered log, Kinesis Data Streams is the usual answer.

Message attributes and metadata

Besides the body, a message can carry up to ten message attributes, typed name and value pairs such as an order type or a trace identifier, which consumers read without parsing the body. System attributes include the number of times the message has been received and when it was first sent. The approximate receive count is useful in consumer logic, for example logging a warning when a message has been tried several times, and it is what the dead-letter queue mechanism uses, covered in the next section.

Cost model

SQS charges per million requests, where each request can carry up to ten messages and up to 256 KB in total, measured in 64 KB chunks. Batching sends and receives, long polling and deleting messages in batches therefore cut costs substantially for high volume queues. There is no charge for storing messages, and the first million requests each month are free. FIFO requests cost a little more than standard ones. Questions about lowering SQS cost almost always resolve to batching and long polling.

Request patterns built on queues

Queues support more than one shape of interaction. The simplest is fire and forget: the producer does not need any answer. For request and response over queues, the producer includes a reply queue and a correlation ID in the message, and the consumer sends the result to that queue; a temporary queue client library helps create short lived reply queues cheaply. For priority, use two queues, one for urgent work and one for normal work, and have consumers check the urgent queue first, since SQS has no message priority within one queue.

When not to use a queue

A queue adds latency, typically milliseconds to seconds, and makes the result of the work asynchronous. When a user must see the result immediately, such as a price quote or an authorisation decision, a synchronous call with timeouts, retries and enough capacity behind a load balancer may be the better answer, with a queue used only for the parts that can wait.

Words that point to a queue

Lost requests during spikes, a slow or failing downstream component, scaling tiers independently and processing work asynchronously all point to SQS between the components.