Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 48 ยท Concurrency and OTP

Processes and Message Passing

Learn how Elixir processes work: spawn, send, receive, mailboxes and self(). Includes a JavaScript actor stand-in you can run in the browser.

Elixir's best-known strength is concurrency, and it all rests on one idea: the process. An Elixir process is not an operating-system process or thread. It is a tiny, isolated unit of work managed by the BEAM virtual machine. Each one has its own memory, its own mailbox, and communicates with others only by sending messages. A running system commonly has tens or hundreds of thousands of them.

This lesson covers spawn, send, receive, mailboxes and self(). Elixir cannot run on this site, so the Elixir code is read-only. The editors use JavaScript async functions to build a small imitation of the actor model, and we say clearly where it differs from the real thing. You will need what you learned about immutability, because it is what makes message passing safe.

What a process is

Lightweight A few kilobytes at start.
Isolated Own heap, nothing shared.
Mailbox Messages queue up in order.
Pid Every process has an address.

Processes talk only by messages.

1 / 2

Starting a process with spawn

spawn/1 takes a function, starts a new process that runs it, and immediately returns the new process's identifier, called a pid. The caller does not wait.

ELIXIR
pid =
  spawn(fn ->
    IO.puts("Hello from another process")
  end)

IO.inspect(pid)   # something like #PID<0.110.0>
IO.inspect(Process.alive?(pid))

When the function returns, the process ends. Process.alive?/1 often says false a moment later, because the work was tiny. The exact pid numbers and the order of printed output between processes can change from run to run: concurrent processes are scheduled independently.

self/0 returns the pid of the process that calls it. The shell you type in is a process too, and so is every function you call: code always runs inside some process.

ELIXIR
IO.inspect(self())   # the pid of the current process

Sending and receiving

send(pid, message) puts a copy of any value into the mailbox of that process and returns the message right away. Sending never blocks and does not fail even if the target has died. receive looks through the mailbox for a message matching one of its patterns and runs the matching clause.

ELIXIR
parent = self()

child =
  spawn(fn ->
    receive do
      {:greet, name} -> send(parent, {:reply, "Hello, #{name}!"})
    end
  end)

send(child, {:greet, "Ana"})

receive do
  {:reply, text} -> IO.puts(text)
end

Follow the flow: the parent gives the child its own pid (processes only know what you tell them), sends {:greet, "Ana"}, then waits in its own receive. The child answers and finishes. The request and reply are plain tuples, which fits nicely with pattern matching.

sequenceDiagram
    participant P as Parent
    participant C as Child
    P->>C: spawn(fn)
    P->>C: send {:greet, "Ana"}
    C->>P: send {:reply, "Hello, Ana!"}
    Note over P: receive matches {:reply, text}

A request and a reply between two processes.

Because data is immutable and each message is copied between heaps, the two processes can never fight over the same value. (Large binaries are a small exception that the runtime handles safely behind the scenes.)

The mailbox and selective receive

Each process has exactly one mailbox, a queue ordered by arrival. Messages from one sender to one receiver always arrive in the order they were sent. Nothing else about ordering is guaranteed: if two different processes send to the same target, either may arrive first.

receive is selective. It scans the mailbox from the oldest message and takes the first one matching any clause, leaving the others queued for later receive calls:

ELIXIR
send(self(), {:low, 1})
send(self(), {:urgent, 2})
send(self(), {:low, 3})

receive do
  {:urgent, n} -> IO.puts("urgent #{n}")
end

receive do
  {:low, n} -> IO.puts("low #{n}")
end

This prints urgent 2 and then low 1; {:low, 3} is still waiting in the mailbox. A message that matches no clause stays there forever, which is why the performance lesson warns about unbounded mailboxes.

You can give receive an after clause to stop waiting:

ELIXIR
receive do
  {:done, result} -> result
after
  1_000 -> :timeout
end

after 0 checks the mailbox without waiting at all.

A JavaScript actor stand-in

JavaScript has no processes, but an async function plus a queue gives a convincing model. Our spawn creates an object with a mailbox, send queues a message (and wakes a waiting receiver), and receive returns a promise that resolves when a message is available. Everything below is a stand-in written to show the idea: the real BEAM runs processes in parallel on many CPU cores and preempts them, while JavaScript runs one at a time and only switches at await.

JS Spawn, send and receive (JavaScript stand-in)

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

No output.

Notice that main.receive(...) pauses main without blocking anything else, much like receive pauses only the calling Elixir process.

The next editor shows selective receive. Three messages arrive in one order, but the receiver takes them in the order of its own patterns.

JS Selective receive (JavaScript stand-in)

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

No output.

The last part imitates receive ... after. One difference: in Elixir the after clause stops waiting for good, while here the abandoned receiver is still listening in the background.

Why processes are cheap

A new BEAM process starts with a few hundred machine words of memory and grows as needed. Creating one takes microseconds, so Elixir programs spawn one per connection, per job or per game player instead of pooling threads. Each process has its own heap and its own garbage collector, so collecting garbage in one never pauses the others. Isolation also means that a crashing process takes down only itself, which is the subject of the next lesson.

Raw spawn, send and receive are the foundation, but you will rarely write them directly in applications. Tasks, Agents, GenServers and supervisors wrap the common patterns safely.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does spawn(fn -> ... end) return?

    spawn starts the process and returns its pid immediately. The caller does not wait for the function to finish.
  2. 2. Messages A then B are sent by the same process to the same receiver. In what order do they arrive?

    Between one sender and one receiver, order is preserved. There is no ordering guarantee between different senders.
  3. 3. What happens to a message that matches none of the patterns in a receive?

    receive is selective: unmatched messages stay queued and can be taken by a later receive, or pile up if nothing ever matches them.
  4. 4. Why can two processes safely share data by sending messages?

    Nothing can modify a value, and each process has its own heap, so there is no shared mutable state to protect.

Summary

  • A process is a lightweight, isolated unit with its own heap and mailbox, scheduled by the BEAM.
  • spawn/1 starts a process and returns its pid; self/0 gives your own.
  • send/2 never blocks; receive pattern-matches the mailbox and may wait.
  • Order is preserved between one sender and one receiver; unmatched messages stay queued.
  • after gives receive a timeout.
  • The JavaScript editors are an actor stand-in, not real BEAM scheduling.

Next up: Links, Monitors and Let It Crash.