Skip to content
Erlang

Selective Receive with References

Match a specific reply out of many messages using a unique reference.

By EZ4Code Team
receivereferencesrpc

Code

-module(rpc).
-export([call/2]).

call(Server, Request) ->
    Ref = make_ref(),                          % unique reference
    Server ! {call, Ref, self(), Request},
    receive
        {Ref, Reply} -> Reply                  % only matches our reply
    after 5000 ->
        exit(timeout)
    end.

% Server side (typically in a gen_server handle_call):
%   handle_call(Request, {FromPid, Ref}, State) ->
%       Reply = ...,
%       FromPid ! {Ref, Reply},
%       {noreply, State}.

% The Ref makes the receive selective — even if the mailbox contains
% dozens of unrelated messages, receive skips them and matches only
% the one tagged with our Ref. Stale messages stay in the mailbox
% until a later receive handles them.

Explanation

make_ref/0 returns a globally-unique reference. Tagging a request with it lets the caller's receive match only the corresponding reply, even when the mailbox holds other traffic. This is the building block of every synchronous RPC in Erlang, including gen_server:call. The downside of selective receive is that non-matching messages accumulate and slow future scans — gen_server avoids this by handling every message in order.

More Erlang Snippets