A GenServer is one process
The GenServer of Elixir is one process, and one process runs one message at a time. That is the source of its safety, because the state cannot change under a callback, and the source of its limit, because two slow calls wait for each other. This lesson measures the limit and shows the three ways out: a cast, an offload with GenServer.reply/2, and a separate pool of workers.
One call at a time
The server below sleeps 20 milliseconds in every call. One call costs that sleep; ten calls cost ten sleeps, because the mailbox delivers one message at a time. The program prints the answers; the time it took is the reason the answers arrive one after another:
serial.exs
defmodule Slow do use GenServer def start_link(_opts), do: GenServer.start_link(__MODULE__, 0, name: __MODULE__) def work, do: GenServer.call(__MODULE__, :work, 5_000) @impl true def init(n), do: {:ok, n} @impl true def handle_call(:work, _from, n) do Process.sleep(20) {:reply, n + 1, n + 1} end end {:ok, _} = Slow.start_link([]) results = for _ <- 1..10, do: Slow.work() IO.inspect(results)
elixir serial.exs
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Ten sleeps of 20 milliseconds make the call take at least 200 milliseconds, and the program does not print a duration that changes with the machine. The calls are serialised by the process, not by the mailbox size: the second call waits until the first callback returns.
A cast is not faster
A cast returns at once, so a caller that only needs to hand over work waits for nothing. The work itself still runs one message at a time, and the server is just as busy:
cast.exs
defmodule Slow do use GenServer def start_link(_opts), do: GenServer.start_link(__MODULE__, 0, name: __MODULE__) def queue, do: GenServer.cast(__MODULE__, :work) @impl true def init(n), do: {:ok, n} @impl true def handle_cast(:work, n) do Process.sleep(20) {:noreply, n + 1} end end {:ok, _} = Slow.start_link([]) for _ <- 1..10, do: Slow.queue() IO.puts("the calls returned")
elixir cast.exs
the calls returned
The caller returned at once, and the server spends 200 milliseconds on the same work afterwards. A cast moves the wait from the caller to the mailbox; it does not add a second process, and a program that needs the answer still has to call.
Offload and reply
The middle path keeps the call synchronous for the caller and lets the server do other things meanwhile. handle_call/3 starts a task, returns {:noreply, state}, and the task answers the caller with GenServer.reply(from, answer) when it is done:
offload.exs
defmodule Offload do use GenServer def start_link(_opts), do: GenServer.start_link(__MODULE__, :ok, name: __MODULE__) def work, do: GenServer.call(__MODULE__, :work, 5_000) @impl true def init(state), do: {:ok, state} @impl true def handle_call(:work, from, state) do Task.start(fn -> Process.sleep(20) GenServer.reply(from, :done) end) {:noreply, state} end end {:ok, _} = Offload.start_link([]) results = 1..10 |> Task.async_stream(fn _ -> Offload.work() end, max_concurrency: 10) |> Enum.map(fn {:ok, reply} -> reply end) |> Enum.uniq() IO.inspect(results)
elixir offload.exs
[:done]
Ten callers now wait about 20 milliseconds, not 200, because ten tasks do the sleeping in parallel. The program prints the one answer the ten callers share. The server itself did almost nothing: its callbacks only started tasks and returned. The same shape works for a database query or a file read, and the state stays in the server.
The mistake: tasks around one process
Wrapping the calls in Task.async_stream is not enough. The tasks run in parallel, and every one of them asks the same server, which still handles one message at a time:
parallel.exs
defmodule Slow do use GenServer def start_link(_opts), do: GenServer.start_link(__MODULE__, 0, name: __MODULE__) def work, do: GenServer.call(__MODULE__, :work, 5_000) @impl true def init(n), do: {:ok, n} @impl true def handle_call(:work, _from, n) do Process.sleep(20) {:reply, n + 1, n + 1} end end {:ok, _} = Slow.start_link([]) results = 1..10 |> Task.async_stream(fn _ -> Slow.work() end, max_concurrency: 10) |> Enum.map(fn {:ok, n} -> n end) |> Enum.sort() IO.inspect(results)
elixir parallel.exs
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
The ten tasks were ready at the same time and the total is still 200 milliseconds, which is why the answers arrive one after another. The fix is to move the slow part out of the callback, as the offload example does, or to keep several servers and choose one per call. Many small servers beat one big server when the work is the reason for the call, and the DynamicSupervisor lesson shows how a program starts a pool of them.
The programs on this page were run with Elixir 1.19.7 on Erlang/OTP 27 (erts 15.2.7.14), on Linux x86_64 in a Docker container.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Why does a GenServer handle one call at a time?
Answer
Because one process runs one message before the next
A process runs one callback at a time; the state cannot change under it.
-
What does a cast change about a slow callback?
Answer
It returns at once but the work is still serialised
A cast moves the wait to the mailbox; the server still runs the callbacks one by one.
-
How does an offload keep a call synchronous for the caller?
Answer
It returns {:noreply, state} and replies later with GenServer.reply/2
The from reference is kept and the task answers it when the work is done.
-
Why does wrapping calls in
Task.async_streamnot speed up one server?Answer
Because every task asks the same process, which is still serial
Parallel callers still queue at one process; the bottleneck is the server, not the caller.
-
What does this program print?
defmodule S do use GenServer def start_link(_), do: GenServer.start_link(__MODULE__, 0, name: __MODULE__) def work, do: GenServer.call(__MODULE__, :work) @impl true def init(n), do: {:ok, n} @impl true def handle_call(:work, _from, n) do Process.sleep(20) {:reply, n + 1, n + 1} end end {:ok, _} = S.start_link([]) results = for _ <- 1..3, do: S.work() IO.inspect(results)Answer
[1, 2, 3]
Each call increments the state and returns the new value, and the calls are serialised.
-
What does this program print?
defmodule S do use GenServer def start_link(_), do: GenServer.start_link(__MODULE__, 0, name: __MODULE__) def queue, do: GenServer.cast(__MODULE__, :work) @impl true def init(n), do: {:ok, n} @impl true def handle_cast(:work, n), do: {:noreply, n + 1} end {:ok, _} = S.start_link([]) IO.inspect(S.queue())Answer
:ok
A cast returns :ok as soon as the message is queued.
-
What does this program print?
defmodule O do use GenServer def start_link(_), do: GenServer.start_link(__MODULE__, :ok, name: __MODULE__) def work, do: GenServer.call(__MODULE__, :work) @impl true def init(s), do: {:ok, s} @impl true def handle_call(:work, from, s) do Task.start(fn -> GenServer.reply(from, :done) end) {:noreply, s} end end {:ok, _} = O.start_link([]) IO.inspect(O.work())Answer
:done
The task replies to the from reference, so the caller receives :done.
-
Which change removes a GenServer bottleneck for slow work?
Answer
Offload the work or split it across several servers
The work must leave the one process, or the number of servers must grow.
-
What does
GenServer.reply/2need to answer a caller?Answer
The from reference the callback received
The from argument of handle_call/3 is the reference reply/2 sends the answer to.
-
A server spends 50 ms in every handle_call. Ten clients call it at once. How long do they wait in total?
Answer
About 500 ms, because the calls are serialised
One process runs one callback at a time, so ten 50 ms calls take about 500 ms.
Автор статьи: Arthur Isaev