Asynchronous communication
medium 26 minIn asynchronous communication the sender hands a message to a broker and goes on without waiting for the work to be done.
Video lesson · Chapter 1 of 5
Ask for a report and take a numbered ticket
Messages instead of calls, in 80 seconds
1:20Reel coming soon
Theory
Read or listen first. About 2 min.
What it is
Asynchronous communication means leaving a message and moving on. A producer sends a message to a broker, which stores it. A consumer takes it when it is ready. The producer does not wait for the work, and often does not know who does it.
The producer does usually wait for one small thing: the broker's confirmation that the message is safely stored. That takes milliseconds. It is very different from waiting for an email to be sent or a video to be converted.
Why it exists
A direct call ties two programs together: both must be up, and the slower one sets the pace. With a message between them, a consumer can be slow, restarted or offline for a while, and the producer carries on. A burst of work becomes a longer line instead of an outage.
The same message can also reach several independent readers, so new features can react to an event without changing the sender. The cost is that results come later, messages can be repeated or arrive out of order, and somebody has to watch the line.
A short history
August 1982
RFC 821 specifies SMTP. Email is stored and forwarded: sender and reader need not be present together.
December 1993
IBM launches MQSeries, later called IBM MQ, a family of message queueing products.
2003
AMQP, an open protocol for messaging, is started at JPMorgan Chase.
July 2006
Amazon Simple Queue Service enters production.
2007
RabbitMQ appears as an open source broker for AMQP.
January 2011
LinkedIn announces that it is open-sourcing Kafka, its distributed message queue.
Words to know
- Producer
- The program that sends messages. Also publisher.
- Consumer
- The program that receives and processes them. Also subscriber or worker.
- Broker
- The system between them that stores and delivers messages.
- Acknowledgement
- The consumer's signal that a message is done and can be removed.
- Visibility timeout
- How long a message is hidden from others while one consumer works on it.
- Dead letter queue
- Where messages go after failing too many times.
- Consumer lag
- How far a consumer is behind the newest message.
- Eventual consistency
- Parts of the system agree after all messages are processed, not before.
How it works
Step through the idea, or press Play.
Send. Store the message in a broker, get a confirmation, move on
Understand it
Start here
The shoe repair story
Imagine a shoe repair shop. You could stand at the counter until your shoe is ready. Or you leave the shoe, take a ticket and go.
The shelf is the queue, the ticket is the message id, and the cobblers are the consumers.
The idea
What it looks like
A work queue
Characteristics
The sender goes on
It does not wait for the work.
Decoupled
Producer and consumer are deployed, scaled and restarted separately.
Eventually consistent
There is a gap between sending and processing.
Tolerates failure
If the broker stores messages, a consumer can be down for a while.
Scales out
Add consumers, up to the limits of ordering and of what they write to.
Send and continue
Common technologies
| Technology | Best for | Ordering | Keeps messages? |
|---|---|---|---|
| Apache Kafka | Event streams, logs, replay | Within a partition | Yes, for a set time or size |
| RabbitMQ | Task queues, flexible routing | Within a queue; several consumers can finish out of order | Yes, with durable queues and persistent messages |
| Amazon SQS, with SNS for fan-out | Simple managed queues, serverless | Best effort, or per group in FIFO queues | Yes, up to 14 days |
| Google Cloud Pub/Sub | Managed topics | Optional, by ordering key | Yes |
| Redis Pub/Sub | Short-lived live updates | As sent on one connection | No: at most once. Redis Streams keep them |
Patterns
Four messaging patterns
- 1
Point to point (queue)
Each message is processed by one of the consumers. Several may compete for the messages. Example: jobs and tasks.
- 2
Publish and subscribe (topic)
Every subscription gets its own copy. Example: event notifications and live updates.
- 3
Event driven
Services publish facts such as OrderCreated. Inventory, email and analytics react to what concerns them.
- 4
Saga by choreography
A long transaction made of local steps. Each service does its part and publishes an event that triggers the next.
One event, three readers
A saga, with a step that undoes
Inside
Anatomy of a queue
| Feature | What it does |
|---|---|
| Persistence | Messages survive a restart of the broker |
| Acknowledgement | The consumer confirms that it is done |
| Visibility timeout | Hides a message while it is being processed. In SQS the default is 30 seconds |
| Dead letter queue | Holds messages that failed too often |
| Retry policy | Tries again, with a growing delay |
Decide
- Which ordering you need
- At-least-once or at-most-once
- How long a message stays useful (TTL)
- Who repairs dead letters
Watch
- Queue depth: how many wait
- Age of the oldest message
- Consumer lag
- Dead letter count
Promises
Delivery guarantees
| Guarantee | Meaning | Trade-off | Use |
|---|---|---|---|
| At most once | May be lost, not repeated | Fastest, unreliable | Metrics, some logs |
| At least once | Not lost, may be repeated | Needs idempotent consumers | Most business events |
| Exactly-once processing | Each message has its effect once | Highest overhead, and only inside a boundary such as one database or one streaming platform | Counts and balances, when the boundary covers them |
Why a message arrives twice
Duplicates
Make consumers idempotent
A common first attempt is: look up the message id, do the work, then store the id. It has two holes. Two workers can both look before either stores, and a crash between work and store causes a repeat. Put the id and the change into one database transaction.
def handle(message): with db.transaction() as tx: # A unique key on message_id: the second insert changes nothing. new = tx.execute( "INSERT INTO processed (message_id) VALUES (%s) ON CONFLICT DO NOTHING", [message.id]).rowcount == 1 if new: apply_change(tx, message) # same transaction message.ack() # only after the commitOrder
Message ordering
| Kind | How | Cost |
|---|---|---|
| Global | One line and one consumer at a time | Limited throughput |
| Per key | Messages with the same key go to the same partition | Parallel across keys. A very busy key is still one line |
| None | Any consumer takes any message | Fastest. Consumers must cope |
Same key, same partition
Arithmetic
How long is the line?
A burst and its drain
How many consumers?
Safely out
Save and send together
Saving to a database and then sending a message are two steps. A crash between them loses the message. The outbox pattern writes the message to a table in the same transaction, and a separate sender publishes it later.
Transactional outbox
When to use it
Use cases
| Use case | Path | Why |
|---|---|---|
| Email and SMS | UserCreated, email queue, mail provider | Sign-up does not wait for mail |
| Images and video | Upload, processing queue, transcoding workers | The upload finishes quickly |
| Analytics and logging | User action, Kafka, data warehouse | The app is not blocked |
| Order processing | OrderCreated starts payment, then stock, then shipping | Steps are separate. The confirmation is sent after payment |
| Reports | Report request, job queue, file in S3 and a notification | It takes minutes |
| Data sync | CRM update, event bus, ERP and analytics | Many readers, one change |
When not to use it
| Task | Why not |
|---|---|
| User authentication | The user must know at once |
| Reserving stock at checkout | The answer decides the next screen |
| Payment authorisation | Usually needed before the order is confirmed. Some methods do answer later, so allow a pending state |
| Simple CRUD with a screen | People expect to see their change |
Decide
Build it well
Implementation rules
- 1
Make consumers idempotent
Messages may be delivered more than once.
- 2
Configure a dead letter queue
After the last retry, move the message aside so it does not block the rest. Alert on it and have a way to replay.
- 3
Monitor the line
Alert on the age of the oldest message as well as on depth. Growth means the consumers cannot keep up.
- 4
Acknowledge after processing
Not before, or a crash loses the message.
- 5
Retry with backoff
Growing delays with jitter and a limit. See retries.
from celery import Celery, chainapp = Celery("tasks", broker="redis://localhost:6379/0")app.conf.update( task_acks_late=True, # acknowledge after the work task_reject_on_worker_lost=True, # a killed worker does not lose the task task_serializer="json", result_serializer="json", accept_content=["json"],)@app.task(autoretry_for=(ConnectionError,), max_retries=3, retry_backoff=True, retry_jitter=True)def send_welcome_email(user_id): send_email_once(user_id, key=f"welcome:{user_id}") # idempotentdef process_order(order_id): # Each step starts after the one before it succeeded. chain(reserve_stock.si(order_id), charge_payment.si(order_id), send_confirmation.si(order_id)).delay()def handle_signup(user_id): send_welcome_email.delay(user_id) # or with options: start in 60 s, drop it if it has not started after an hour # send_welcome_email.apply_async(args=[user_id], countdown=60, expires=3600)Summary
The whole topic in one minute.
The producer stores a message and goes on. The consumer works when it can. A queue gives each message to one worker, and a topic gives every subscriber its own copy.
Assume at-least-once delivery: acknowledge after the work, make consumers idempotent, send repeated failures to a dead letter queue, and watch the age and length of the line. Use it for work nobody waits for, and keep synchronous calls where the next step needs the answer.
- Store the message, get a short confirmation, go on.
- Queue: one worker per message. Topic: a copy for each subscription.
- Expect duplicates: idempotent consumers, acknowledge after the work.
- Order is kept per key, not everywhere.
- Queues smooth bursts. They do not add capacity.