🎓 A1Learner
🔍
0 of 46 lessons completed

Elixir RPC Patterns

A remote procedure call runs a function on a named node and returns its result. This lesson proves the pattern on the current node, since a real cluster needs named nodes.

A remote call runs a function on a node

:rpc.call() runs a named function on a named node and returns its result. Here the node is the current node, so the call runs locally.

IO.inspect(:rpc.call(Node.self(), Kernel, :+, [40, 2]))

A remote call can use a string function

:rpc.call() works with any module and function. This call uppercases a word on the current node.

IO.inspect(:rpc.call(Node.self(), String, :upcase, ["hello"]))

A remote call can use your own module

A module defined in the script is callable too. This call doubles 21 on the current node.

defmodule Doubler do
  def double(n), do: n * 2
end

IO.inspect(:rpc.call(Node.self(), Doubler, :double, [21]))

Example

defmodule Calculator do
  def add(a, b), do: a + b
  def multiply(a, b), do: a * b
end

IO.inspect(:rpc.call(Node.self(), Calculator, :add, [19, 23]))
IO.inspect(:rpc.call(Node.self(), Calculator, :multiply, [6, 8]))

Key points

  • :rpc.call(): runs a function on a named node and returns its result.
  • Target: the call names a module, a function, and a list of arguments.
  • Local proof: calling the current node proves the call shape, not a real network hop.
  • Return: the result comes back as a plain value, like 42.
  • Own modules: a module defined in the script can be called the same way.

In this example, the script defines a calculator module, then makes two remote calls on the current node. The first call adds 19 and 23, and the second call multiplies 6 by 8.

Note

a real cluster needs named nodes, and this lesson proves only the single-node mechanics.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does :rpc.call(Node.self(), Kernel, :+, [40, 2]) return?