AlgoViz

Asynchronous communication

medium 26 min

In 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

0:00 / 3:49

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

  1. August 1982

    RFC 821 specifies SMTP. Email is stored and forwarded: sender and reader need not be present together.

  2. December 1993

    IBM launches MQSeries, later called IBM MQ, a family of message queueing products.

  3. 2003

    AMQP, an open protocol for messaging, is started at JPMorgan Chase.

  4. July 2006

    Amazon Simple Queue Service enters production.

  5. 2007

    RabbitMQ appears as an open source broker for AMQP.

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

Step 1 of 3

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.

Leave the shoe, take a ticket
567Ticket 7

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

A user signs up with the signup service. The service puts a welcome email job in a message queue. Email workers 1 and 2 each take jobs. A job that failed too often moves to a dead letter queue.
The user gets an answer before any email is sent. Dashed arrows are messages.

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

Compare with synchronous communication, where the caller waits until the end.

Common technologies

TechnologyBest forOrderingKeeps messages?
Apache KafkaEvent streams, logs, replayWithin a partitionYes, for a set time or size
RabbitMQTask queues, flexible routingWithin a queue; several consumers can finish out of orderYes, with durable queues and persistent messages
Amazon SQS, with SNS for fan-outSimple managed queues, serverlessBest effort, or per group in FIFO queuesYes, up to 14 days
Google Cloud Pub/SubManaged topicsOptional, by ordering keyYes
Redis Pub/SubShort-lived live updatesAs sent on one connectionNo: at most once. Redis Streams keep them
All of these can be fast. Throughput depends on message size, copies and hardware, so measure yours. How brokers work inside is in queues and streams.

Patterns

Four messaging patterns

  1. 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. 2

    Publish and subscribe (topic)

    Every subscription gets its own copy. Example: event notifications and live updates.

  3. 3

    Event driven

    Services publish facts such as OrderCreated. Inventory, email and analytics react to what concerns them.

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

The order service publishes OrderCreated to a topic named orders. Inventory, email and analytics each receive their own copy.
Adding a fourth reader does not change the order service.

A saga, with a step that undoes

Arrows are events that travel through a broker. There is no big rollback: each step needs a compensating step.

Inside

Anatomy of a queue

FeatureWhat it does
PersistenceMessages survive a restart of the broker
AcknowledgementThe consumer confirms that it is done
Visibility timeoutHides a message while it is being processed. In SQS the default is 30 seconds
Dead letter queueHolds messages that failed too often
Retry policyTries 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

GuaranteeMeaningTrade-offUse
At most onceMay be lost, not repeatedFastest, unreliableMetrics, some logs
At least onceNot lost, may be repeatedNeeds idempotent consumersMost business events
Exactly-once processingEach message has its effect onceHighest overhead, and only inside a boundary such as one database or one streaming platformCounts and balances, when the boundary covers them
Networks cannot promise exactly-once delivery. Systems get the same effect from at-least-once delivery plus remembering what was done. Money systems do it that way too.

Why a message arrives twice

Acknowledge after the work. Doing it before turns a crash into a lost message.

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.

Python
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 commit
If the work is outside your database, such as a payment provider, pass the message id as an idempotency key. See idempotency.

Order

Message ordering

KindHowCost
GlobalOne line and one consumer at a timeLimited throughput
Per keyMessages with the same key go to the same partitionParallel across keys. A very busy key is still one line
NoneAny consumer takes any messageFastest. Consumers must cope
Use the order id as the key to keep each order's events in order. Use the user id if events of one user must stay in order across orders.

Same key, same partition

Arithmetic

How long is the line?

A burst and its drain

backlog=(300−200)×600 s=60,000drain=60,000200−100=600 s\text{backlog} = (300 - 200) \times 600\text{ s} = 60{,}000 \qquad \text{drain} = \frac{60{,}000}{200 - 100} = 600\text{ s}
Assumed: average 100 messages a second, peak 3 times that for 10 minutes, consumers handle 200 a second. The last ones wait, and 10 minutes after the peak the line is empty.

How many consumers?

n≥λ×ttarget use=200×0.050.7≈14.3;→;15n \ge \frac{\lambda \times t}{\text{target use}} = \frac{200 \times 0.05}{0.7} \approx 14.3 ;\to; 15
200 messages a second, 50 ms each, at most 70% busy. In a partitioned stream you also need at least that many partitions.

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

The sender may publish a row twice after a crash, so consumers must still be idempotent.

When to use it

Use cases

Use casePathWhy
Email and SMSUserCreated, email queue, mail providerSign-up does not wait for mail
Images and videoUpload, processing queue, transcoding workersThe upload finishes quickly
Analytics and loggingUser action, Kafka, data warehouseThe app is not blocked
Order processingOrderCreated starts payment, then stock, then shippingSteps are separate. The confirmation is sent after payment
ReportsReport request, job queue, file in S3 and a notificationIt takes minutes
Data syncCRM update, event bus, ERP and analyticsMany readers, one change

When not to use it

TaskWhy not
User authenticationThe user must know at once
Reserving stock at checkoutThe answer decides the next screen
Payment authorisationUsually needed before the order is confirmed. Some methods do answer later, so allow a pending state
Simple CRUD with a screenPeople expect to see their change

Decide

Build it well

Implementation rules

  1. 1

    Make consumers idempotent

    Messages may be delivered more than once.

  2. 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. 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. 4

    Acknowledge after processing

    Not before, or a crash loses the message.

  5. 5

    Retry with backoff

    Growing delays with jitter and a limit. See retries.

Python
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)
Celery. With late acknowledgement a task can run twice, so it must be idempotent.

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.

Sources