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.
See it run
Send and continue, a line that grows, a message that arrives twice, and one that never succeeds.
Operations
Send and continue
The producer stores three messages and goes on. The consumer works at its own pace.
Step 1 of 5
Send the first
Waiting
M1
Processed
The producer sends M1 and gets a confirmation from the queue.
Step 1: Send the first
def sign_up(user): save(user) queue.send({"type": "welcome", "user": user.id}) # stored, then go on return "welcome"def worker(): msg = queue.receive() send_email(msg) queue.ack(msg) # only after the work- Sender waits for
- Broker only
- Result
- Later
- Synchronous call
- waits for the work
Say both waits: the short one for the broker, and the long one nobody has to do.
In the real world
The same asynchronous communication doing real jobs. Pick one and step through it.
How the user gets the result of asynchronous work.
Step 1 of 3
Accept
The user asks for a report. The API stores a job and answers 202 with a status link.
Step 1: Accept
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Acknowledging before the work
criticalA crash during the work loses the message.
Wrongqueue.ack(msg)charge(msg)Rightcharge_once(msg)queue.ack(msg)Check, work, then remember
criticalTwo workers can both pass the check, and a crash after the work forgets it.
Wrongif not seen(msg.id): charge(msg) remember(msg.id)Rightwith db.transaction() as tx: if tx.insert_once("processed", msg.id): charge(tx, msg)No dead letter queue
majorA poison message fails forever and uses up the workers.
Wrongretry_forever(msg)Rightif msg.tries > 3: dead_letters.send(msg) alert()Save, then publish
majorA crash between the two loses the event.
Wrongdb.save(order)broker.publish(event)Rightwith db.transaction() as tx: tx.save(order) tx.save_outbox(event) # a sender publishes it
Interview tips
How to explain it
- Store a message, go on, work happens later.
- Queue: one consumer. Topic: a copy for each.
- Decoupled in time, eventually consistent.
Memory trick: ASYNC
- Acknowledge after the work, Send and continue.
- Yield to the broker, Non-blocking.
- Consumer takes it when ready.
Use it for
- Email, images, reports, analytics.
- Bursts.
- Events with several readers.
Always add
- Idempotent consumers.
- Dead letter queue with an alert.
- Age of the oldest message on a dashboard.