Sub topic 1
Why Asynchronous Messaging: Decoupling Producers and Consumers
Prerequisites
This chapter assumes you already know the following:
- Basic AWS concepts: accounts, regions, and IAM users and roles.
- How to read JSON.
- Basic Python. The examples use boto3, the AWS SDK for Python.
- A general idea of what a distributed or event-driven application is.
You don't need to have used SQS or SNS yet. This chapter explains why they exist. Later chapters cover how to use them.
The problem with synchronous calls
In a synchronous design, one component calls another and waits for the answer. Suppose a web service handles a checkout. It might call a payment service, then an inventory service, then an email service, one after another, and only then respond to the customer.
This design has three weaknesses:
- Latency adds up. The customer waits for every step, including steps such as sending a receipt that don't affect whether the order succeeded.
- Failures spread. If the email service is down, the checkout fails, even though the payment worked.
- Load spreads. If a sale triples traffic, every downstream service must handle triple the request rate at the same moment, or requests fail.
The services are tightly coupled. The caller must know who the callee is, where it is, and that it is healthy right now.
What asynchronous messaging changes
In asynchronous messaging, the component that produces work does not call the component that does the work. It writes a message to an intermediary and moves on. A message is a small piece of data, usually JSON, that describes something to do or something that happened.
- A producer is the component that sends messages.
- A consumer is the component that receives and processes them.
- A broker is the managed service that sits between them and stores messages until they are handled.
On AWS, Amazon SQS (Simple Queue Service) and Amazon SNS (Simple Notification Service) are brokers with different delivery models:
| Service | Model | Who receives a message |
|---|---|---|
| SQS | Queue, pull-based | One consumer per message. Consumers poll for messages. |
| SNS | Topic, push-based | Every subscriber gets a copy. SNS delivers to them. |
The next chapters cover each in detail, and a later chapter shows how to combine them.
Three kinds of decoupling
Decoupling means a change or failure on one side does not force a change or failure on the other. A broker gives you three separate forms of it.
- Time decoupling. The producer and consumer don't need to run at the same moment. If a consumer is down for a deployment, messages wait in the broker and are processed when it returns.
- Load decoupling. The broker absorbs bursts. A producer can send 10,000 messages in a minute while consumers work at a steady 100 per second. This is called load leveling. The queue gets longer during the spike and shorter afterwards.
- Failure decoupling. A failing consumer does not break the producer. The checkout service succeeds once the message is stored, even if email is broken. The failed work can be retried later.
There is also a fourth, softer benefit. The producer does not need to know how many consumers exist. With SNS, you can add a new subscriber, such as an analytics service, without changing the producer.
A first look at the producer side
The sketch below shows the checkout service from earlier, rewritten to send a message instead of calling the other services. It assumes your AWS credentials and region are configured. create_queue returns the existing queue's URL if a queue with that name and the same attributes already exists, so this script is safe to run more than once. The next chapter explains queue creation properly.
import json
import boto3
sqs = boto3.client("sqs")
queue_url = sqs.create_queue(QueueName="orders")["QueueUrl"]
def checkout(order_id, amount):
# Payment is the one step the customer must wait for.
print("charged", order_id, amount)
# Everything else is handed off as a message.
sqs.send_message(
QueueUrl=queue_url,
MessageBody=json.dumps({"orderId": order_id, "amount": amount}),
)
return {"status": "accepted", "orderId": order_id}
print(checkout("1001", 25))The function returns as soon as SQS has stored the message. The customer's wait no longer includes inventory or email work. Those happen later, in consumers you will build in the following chapters.
What you give up
Asynchronous messaging is a trade-off, not a free upgrade. Plan for these costs from the start.
- No immediate result. The producer cannot return the outcome of the downstream work. If the customer needs to know whether the shipment succeeded, you need another way to report it, such as a status page or a follow-up notification.
- Eventual consistency. For a short time, the payment exists but the inventory has not yet changed. Your design and your users must tolerate that gap.
- Duplicates and ordering. Brokers commonly deliver a message more than once or out of order, so consumers must be written defensively. Later chapters cover idempotent consumers and FIFO queues.
- More moving parts. You now monitor queue depth, retries, and failed messages. Debugging a request means following it across several components.
- Extra cost. Each send, receive, and delete is billed as a request.
Deciding where to put the boundary
A practical test for each downstream step: does the caller need its result before it can respond?
- If yes, call it synchronously.
- If no, and the work is slow, bursty, or allowed to fail and retry, send a message.
- If several independent systems care about the same event, publish it to a topic so each gets its own copy.
Applying this test to checkout gives a clear split. Payment stays synchronous. Inventory update, receipt email, and analytics become messages. Because analytics and email are independent reactions to the same event, they are good candidates for the fan-out pattern you will build later.
Exercise
A checkout service calls a recommendations service to refresh a "customers also bought" list after each order. The recommendations service is slow and sometimes down. Should the checkout service call it synchronously or send a message, and which kind of decoupling does your choice provide?
Show answer
Send a message. The checkout response does not depend on the recommendation refresh, so the work can happen later. This gives time decoupling (the consumer can be down and catch up), load decoupling (spikes are absorbed by the queue), and failure decoupling (a recommendations outage no longer fails checkouts).