AlgoViz

Queues & streams

medium 30 min

A message queue stores work between the program that asks for it and the program that does it.

See it run

Follow one message, crash a worker, share the work, copy an event, and set a bad message aside.

Operations

The life of a message

M1, M2 and M3 wait. M4 is sent, and M1 is handled.

Step 1 of 7

The producer sends

senddeliverProducercreating M4Message queue3 waitingConsumerfree

Visible

M1 · M2 · M3

Hidden

The producer creates M4 with a payload and metadata.

Step 1: The producer sends

message_id = queue.send(payload)       # stored, then confirmedreceipt, body = queue.receive()        # hidden, not removedhandle(body)queue.acknowledge(receipt)             # now it is removed
Producer waits for
Storing only
Result
Removed after the ack

Two confirmations: the queue to the producer, and the consumer to the queue.

In the real world

The same queues & streams doing real jobs. Pick one and step through it.

864,000 jobs a day, 0.5 seconds for each.

Step 1 of 4

Average

Average10 a second
Peak, 3x
Busy workers
At 80% use

864,000 / 86,400 = 10 a second.

Step 1: Average

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.acknowledge(receipt)handle(body)
    Right
    handle(body)queue.acknowledge(receipt)
  • Acknowledging by message id

    major

    A slow worker can remove a message that another worker now holds.

    Wrong
    queue.acknowledge(message.id)
    Right
    queue.acknowledge(receipt)   # this delivery only
  • Counting only reported failures

    major

    A crash reports nothing, so poison returns forever.

    Wrong
    except Exception:    message.retries += 1
    Right
    # on receivemessage.receives += 1
  • A file inside the message

    minor

    Queues have size limits, and large messages slow everyone.

    Wrong
    queue.send(video_bytes)
    Right
    url = store.put(video_bytes)queue.send({"url": url})

Interview tips

  • How to explain it

    • Store, receive, work, acknowledge, remove.
    • Receive hides. Silence brings it back.
    • Each message goes to one worker.
  • Memory trick: QUEUE

    • Quality of delivery, Uncouple.
    • Enable async work, Use buffering.
    • Ensure order within a scope.
  • Best practices

    • Idempotent consumers.
    • A dead letter queue with an alert.
    • Batches, and a link instead of a file.
  • Watch these

    • Age of the oldest message.
    • Receives for each message.
    • Use of the system behind the workers.