Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 36 ยท Processes and Message Passing

Selective receive and timeouts

Learn how Erlang receive picks messages out of order, how the after clause adds timeouts, how make_ref prevents mixups, and how to avoid mailbox scans.

receive does not simply take the first message in the mailbox. It scans the mailbox from oldest to newest and removes the first message that matches any clause. Messages that do not match are left in place, in their original order. This is called selective receive, and it lets a process deal with the messages it cares about right now while others wait.

How the scan works

Imagine the mailbox holds [a, b, c] and the process runs:

ERLANG
receive
    c -> got_c;
    b -> got_b
end

Erlang takes a and checks it against all clauses: no match. Then b: it matches the second clause, so b is removed and got_b is returned. The mailbox is now [a, c]. Note that clause order only matters per message: the scan goes message by message, and for each message tries the clauses top to bottom.

If the whole mailbox is scanned without a match, the process blocks. When a new message arrives, only the new message is checked against the clauses (the process is not rescanned from the start).

Priority messages

Because unmatched messages wait, you can build priorities with nested receives:

ERLANG
next_job() ->
    receive
        {urgent, Job} -> Job
    after 0 ->
        receive
            {normal, Job} -> Job
        end
    end.

after 0 means "do not wait": if no urgent message is already in the mailbox, fall through to the normal one.

Timeouts with after

after Milliseconds adds a final clause that runs when nothing matched in time:

ERLANG
receive
    {reply, R} -> {ok, R}
after 2000 ->
    {error, timeout}
end.

Without after, a process waiting for a reply that never comes would sleep forever. Rule of thumb: every receive that waits for another process's answer should have a timeout. The special value infinity means no timeout (the default).

A neat use of after is a sleep without extra modules:

ERLANG
receive after 500 -> ok end.     % same as timer:sleep(500)

References: matching the right reply

If a client sends two requests to the same server, a plain {reply, R} could belong to either. Use a unique reference from make_ref/0:

ERLANG
call(Server, Request) ->
    Ref = make_ref(),
    Server ! {self(), Ref, Request},
    receive
        {Ref, Reply} -> {ok, Reply}
    after 5000 ->
        {error, timeout}
    end.

server_loop() ->
    receive
        {From, Ref, {add, A, B}} ->
            From ! {Ref, A + B},
            server_loop()
    end.

Ref is bound when the receive starts, so only the reply with exactly that reference matches. A late reply to an earlier request that timed out has a different reference and will never be confused with a new answer. (It will, however, sit in the mailbox; gen_server:call and the modern alias mechanism deal with that.)

Since OTP 24 the compiler optimises the pattern "create a reference, send, then receive matching that reference" so the receive does not scan the whole mailbox. Keep that exact shape: make the ref, send, receive in the same function.

The danger of a long mailbox

Selective receive is powerful, but if the mailbox holds thousands of messages that never match, every new receive scans all of them. The process slows to a crawl while using more CPU, a classic production problem. Prevent it:

  • Always add a catch-all clause in a main loop, or use a generic server that does.
  • Never leave replies unconsumed after a timeout without a plan.
  • Watch process_info(Pid, message_queue_len) in monitoring.

Flushing

To empty a mailbox of everything (for example in a test), loop with after 0:

ERLANG
flush() ->
    receive
        _ -> flush()
    after 0 ->
        ok
    end.

The shell has a helper flush(). that prints and drops all messages.

receive scans the mailbox

Take oldest message Try every clause
No match? Leave it, try the next
Match found Remove it, run the clause
Nothing matches Block, or run after

Skipped messages keep their order for later receives.

1 / 2

Run it: timeouts and selective receive (stand-in)

This JavaScript model is not Erlang. It supports a predicate and an optional timeout, like receive ... after. Watch how the b message is taken first because the predicate only accepts it, leaving a behind, and how a timeout produces an error tuple.

JS Stand-in: selective receive

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Using a reference (stand-in)

A reference is a unique token. In JavaScript a Symbol() plays that role. The late reply for the first request is ignored by the second request.

JS Stand-in: references

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A mailbox holds [a, b, c] and a receive has only clauses for c and b. Which message is removed?

    The scan goes through messages oldest first; a does not match, b matches the second clause.
  2. 2. What does receive ... after 0 -> ... end do?

    A zero timeout means: do not block; run the after body at once if no message matches.
  3. 3. Why use make_ref() in a request?

    Each reference is unique, so replies cannot be mixed up between requests.
  4. 4. What is the risk of many unmatched messages in a mailbox?

    A receive scans the mailbox from the start, so a long tail of unmatched messages is costly.

Summary

  • receive removes the oldest message that matches any clause and leaves the rest.
  • after Ms adds a timeout; use it whenever you wait for another process.
  • after 0 polls without blocking and enables priority messages.
  • make_ref() gives unique tags so replies match their requests.
  • Unmatched messages accumulate; keep mailboxes short with catch-all clauses.

Next: Process loops and state