Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 36 ยท Processes and Message Passing

Sending and receiving messages

Learn Erlang message passing: the ! operator, mailboxes, receive with pattern matching, replying with the sender's pid, and request-response patterns.

Processes share nothing, so the only way to cooperate is to send messages. A message can be any Erlang term: an atom, a tuple, a list, a map, even a fun. Sending is asynchronous: the sender never waits for the receiver, it just drops a copy of the term into the receiver's mailbox and moves on.

This lesson covers the two operations that everything else in concurrent Erlang is built from: ! (send) and receive.

Sending with !

ERLANG
Pid ! {greet, "Ada"}.

The left side is a pid (or a registered name, see registered processes); the right side is any term. The expression returns the message itself, so A ! B ! hello sends hello to both. Sending to a pid that no longer exists is not an error: the message is silently discarded. Sending never blocks and never fails because the receiver is slow.

Messages between a given pair of processes arrive in the order they were sent. Between different senders there is no ordering guarantee.

Receiving with receive

receive looks through the mailbox of the current process, tries each message against the patterns, and runs the first clause that matches. If nothing matches, the process blocks until a matching message arrives.

ERLANG
loop() ->
    receive
        {greet, Name} ->
            io:format("Hello, ~s!~n", [Name]);
        stop ->
            io:format("bye~n")
    end.

Patterns work exactly like in function heads (see the pattern matching chapter): variables bind, atoms and constants must be equal, guards with when are allowed.

ERLANG
receive
    {add, A, B} when is_number(A), is_number(B) ->
        A + B
end

The value of the receive expression is the value of the clause that ran.

A first complete example

A process that waits for one message, greets, and ends:

ERLANG
-module(hello).
-export([start/0, run/0]).

start() ->
    Pid = spawn(?MODULE, run, []),
    Pid ! {greet, "Ada"},
    Pid.

run() ->
    receive
        {greet, Name} -> io:format("Hello, ~s!~n", [Name])
    end.

Calling hello:start() prints Hello, Ada! from the child process. The parent did not wait; it sent and returned.

Replying: include your own pid

The receiver has no idea who sent a message unless the sender says so. Put self() inside the message and the receiver can answer:

ERLANG
double_server() ->
    receive
        {From, N} ->
            From ! {self(), N * 2},
            double_server()
    end.

client() ->
    S = spawn(fun double_server/0),
    S ! {self(), 21},
    receive
        {S, Answer} -> Answer        % matches only a reply from S
    end.

Note that the pattern {S, Answer} uses the already bound variable S. Because S is bound, only a message whose first element equals that pid matches. This is a very common trick for ignoring messages from strangers. Production code uses a unique reference instead of the pid, so that replies to different requests cannot be mixed up (see the next lessons).

Request and reply

Client sends Server ! {self(), Request}
Server receives Matches the pattern
Server replies From ! {self(), Reply}
Client receives Matches on the server pid

Both sides are asynchronous; the waiting is done by receive.

1 / 2

Messages are copied

Sending copies the term from the sender's heap to the receiver's heap (large binaries over 64 bytes are reference counted and not copied). That is why one process can never corrupt another's data. It also means you should not send enormous structures needlessly; send an id, a pid or a reference instead.

Run it: a mailbox stand-in in JavaScript

This is not Erlang: it is a small model of a mailbox so you can watch the request-reply flow. receive here is an async function that waits for the next message matching a predicate.

JS Stand-in: double server

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

No output.

Fire and forget versus call

Two patterns appear everywhere:

  • Cast: send and do not wait. Use it for notifications such as logging an event.
  • Call: send a request with a unique reference, then receive the matching reply, usually with a timeout. Selective receive and timeouts are the next lesson.

The OTP behaviour gen_server packages both patterns so you rarely write them by hand: gen_server:cast/2 and gen_server:call/2.

Ordering and mailbox growth

If a process receives messages faster than it handles them, its mailbox grows without limit. Erlang has no built-in backpressure, so a mailbox can eat all memory. Watch it with process_info(Pid, message_queue_len). Typical cures: slow the producer, use call instead of cast so senders wait, or drop work.

Messages that no clause matches stay in the mailbox forever. A receive that only handles {add, _, _} will skip a {unknown, x} message and leave it there, slowing later receives because they must scan past it. Always include a catch-all clause in long-running loops.

ERLANG
loop() ->
    receive
        {add, A, B} -> io:format("~p~n", [A + B]);
        Other       -> io:format("ignoring ~p~n", [Other])
    end,
    loop().

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does Pid ! Message do when the receiver is slow?

    Sending is asynchronous. The message is queued in the mailbox of the receiver.
  2. 2. How does a server know where to send its reply?

    A message carries no sender information by itself, so clients include self() or a reference.
  3. 3. What happens to a message that no receive clause matches?

    Unmatched messages remain queued, which can slow later receives and grow memory; add a catch-all clause.
  4. 4. In the pattern {S, Answer} where S is already bound, what happens?

    A bound variable in a pattern acts as a constant, so it filters by equality.

Summary

  • Pid ! Msg sends a copy of any term asynchronously and never blocks.
  • receive pattern-matches the mailbox and blocks until a message matches.
  • Include self() (or better a reference) in requests so the receiver can reply.
  • Messages from one sender to one receiver keep their order.
  • Unmatched messages pile up; handle unknown messages in long-running loops.

Next: Selective receive and timeouts