liveBook · Manning

Message passing

As explained in Elixir in Action, Third Edition

Message passing is interprocess communication in which processes exchange data through runtime messages rather than shared memory.

Message passing lets isolated processes exchange data without shared memory. A sender uses send/2, continues asynchronously, and places a term in the receiver’s mailbox; the receiver uses receive to select matching messages. section 5.2.1 section 5.2.2

Use the mechanism according to the communication pattern:

  • Use fire-and-forget messaging when the caller needs no result or completion notification. section 5.2.1
  • Build a response protocol by including the caller’s PID, then having the worker send a tagged response such as {:query_result, result}. section 5.2.2
  • Pattern-match message shapes in receive and add an after clause when waiting indefinitely would be unsafe. section 5.2.2
  • Scale the same primitive across nodes: services such as :rpc send requests to registered remote processes and receive their responses. section 12.1.5

Collecting concurrent query results

Store the caller before spawning so self() refers to the original process, not the worker: caller = self(); spawn(fn -> result = run_query.(query); send(caller, {:query_result, result}) end). The caller can then repeatedly receive {:query_result, result} messages and assemble results in completion order. section 5.2.2

Figure 5.2 Inter-process communication via messages
CH05_F02_Juric3

Use the inter-process communication figure to visualize messages moving between independent processes. section 5.2.2

How Elixir in Action, Third Edition covers it

How deep it goes
Explains send/2, receive, tagged responses, caller PIDs, mailbox matching, timeouts, and remote implementation boundaries.
Examples
Demonstrates spawned queries, tagged result messages, receive timeouts, remote :rpc calls, and distributed locks.
What it assumes
Assumes familiarity with Elixir processes, PIDs, functions, pattern matching, and basic concurrency; clarifies self() behavior.
What you can do after
Apply it via Elixir's send/2 and receive to coordinate workers, collect asynchronous results, and invoke remote services.
How it connects
Connects processes, concurrency, mailboxes, distributed systems, remote procedure calls, and cluster-wide locks.

Also explained in

Compare how 9 books explain message passing →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Elixir in Action, Third Edition. The section links point to the parts of the book it draws on.