Messages and the mailbox

Every process in Elixir owns a mailbox, and receive is the only way to take a message out of it. The block is not a queue read: it scans the mailbox for the first message that matches its patterns, leaves the others where they are, and waits when nothing matches. That single rule explains both the power and the danger of a mailbox, and this page is about the two.

Selective receive

Three messages are sent to the process itself, and the first receive asks only for the one in the middle. It gets it, and the two others stay in the mailbox for the next blocks, in the order they were sent:

selective.exs

send(self(), :first) send(self(), {:important, 42}) send(self(), :last) receive do {:important, n} -> IO.puts("got #{n}") end receive do msg -> IO.puts("then #{msg}") end receive do msg -> IO.puts("then #{msg}") end

elixir selective.exs

got 42
then first
then last

The match is what decides the order, not the arrival: the :first message is older, and the block that wants {:important, n} walked past it. A protocol that sends several kinds of message relies on this; a program that matches everything with a bare variable gets the oldest message first, which is the plain queue a reader expects.

The queue and its length

The mailbox is visible through Process.info/2. The length is what a monitoring tool shows and what a program checks when a producer may be faster than its consumer:

queue.exs

send(self(), :a) send(self(), :b) IO.inspect(Process.info(self(), :message_queue_len)) IO.inspect(Process.info(self(), :messages))

elixir queue.exs

{:message_queue_len, 2}
{:messages, [:a, :b]}

Process.info/2 answers a one-item tuple or nil for a dead process, which is why the inspector shows the key with the value. The full message list is a debugging tool: it copies the mailbox, and a program that calls it in a loop is slower than the work it measures.

A mailbox that grows

A sender never waits for the receiver, so the mailbox grows when the reader is slower than the writers. A hundred messages arrive at once, the block takes one, and ninety-nine are left:

grow.exs

for n <- 1..100, do: send(self(), {:job, n}) IO.inspect(Process.info(self(), :message_queue_len)) receive do {:job, n} -> IO.puts("first job #{n}") end IO.inspect(Process.info(self(), :message_queue_len))

elixir grow.exs

{:message_queue_len, 100}
first job 1
{:message_queue_len, 99}

The mailbox has no limit: a process that never reads grows until the VM runs out of memory, and the crash names the process rather than the sender. The design that prevents it is the one OTP uses, a bounded queue with back pressure, or a producer that waits for an acknowledgement; the number from Process.info/2 is what a test asserts when it checks that the back pressure works.

The mistake: a pattern that never matches

A receive waits for a shape, and a message of another shape is invisible to it. The program sends {:ok, 1}, waits for {:done, n}, and the timeout is the only thing that ends the wait:

mistake.exs

send(self(), {:ok, 1}) receive do {:done, n} -> IO.puts("done #{n}") after 50 -> IO.puts("nothing matched") end IO.inspect(Process.info(self(), :message_queue_len))

elixir mistake.exs

nothing matched
{:message_queue_len, 1}

The last line is the diagnosis: the message is still there, so the sender worked and the receiver asked for the wrong shape. A protocol between two processes has to agree on the tuples, which is why the reply of a call is written next to the call and not guessed. The timeout turns the bug into a report instead of a hang, and the processes lesson showed the same limit on a call.

The programs on this page were run with Elixir 1.19.7 on Erlang/OTP 27 (erts 15.2.7.14), on Linux x86_64 in a Docker container.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. How does receive choose the message it takes?

    Answer

    the first message from the front that matches one of its patterns

    The block scans the mailbox in order and takes the first match, leaving the rest.

  2. What happens to a message that no pattern of a receive matches?

    Answer

    it stays in the mailbox

    Unmatched messages stay for a later receive, which is what makes the receive selective.

  3. Why can a mailbox grow without limit?

    Answer

    because a send never waits for the receiver

    The sender keeps sending, and a reader that is slower leaves the messages where they are.

  4. Which call answers the number of messages waiting in a process?

    Answer

    Process.info(pid, :message_queue_len)

    Process.info/2 reads one piece of information, and the queue length is one of them.

  5. What does this program print? send(self(), :first) send(self(), :second) receive do msg -> IO.puts(msg) end

    Answer

    first

    A bare pattern matches everything, so the older message is taken first.

  6. What does this program print? send(self(), :a) send(self(), :b) IO.inspect(Process.info(self(), :message_queue_len))

    Answer

    {:message_queue_len, 2}

    Process.info/2 answers a tuple of the key and the value.

  7. What does this program print? send(self(), :done) receive do {:done, n} -> IO.puts("number #{n}") after 50 -> IO.puts("nothing matched") end

    Answer

    nothing matched

    The message is a bare atom and the pattern wants a tuple, so the wait times out.

  8. What does this program print? send(self(), {:ok, 1}) send(self(), :stop) receive do :stop -> IO.puts("stopped") end

    Answer

    stopped

    The receive walks past the first message to the atom it matches.

  9. What does this program print? send(self(), :one) receive do :one -> IO.puts("taken") end IO.inspect(Process.info(self(), :message_queue_len))

    Answer

    {:message_queue_len, 0}

    The one message was taken, so the mailbox is empty.

  10. What does a receive do when its timeout passes with no match?

    Answer

    runs the after block

    The after clause is the timeout branch, and its value is the value of the receive.

Автор статьи: Arthur Isaev

Изображение баннера