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.

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

senddeliverProducersendingMessage queuedepth 1Consumerwaiting

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

Our systemUser appReport API202, job 12Job queuejob 12Worker

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

    critical

    A crash during the work loses the message.

    Wrong
    queue.ack(msg)charge(msg)
    Right
    charge_once(msg)queue.ack(msg)
  • Check, work, then remember

    critical

    Two workers can both pass the check, and a crash after the work forgets it.

    Wrong
    if not seen(msg.id):    charge(msg)    remember(msg.id)
    Right
    with db.transaction() as tx:    if tx.insert_once("processed", msg.id):        charge(tx, msg)
  • No dead letter queue

    major

    A poison message fails forever and uses up the workers.

    Wrong
    retry_forever(msg)
    Right
    if msg.tries > 3:    dead_letters.send(msg)    alert()
  • Save, then publish

    major

    A crash between the two loses the event.

    Wrong
    db.save(order)broker.publish(event)
    Right
    with 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.