TIL: GenServer’s init/1 in Elixir

Viral Patel
PathFactory
Published in
1 min readAug 22, 2019

--

Today I’ve learned, that you can return timeout as part of init call response to let theGenServer know how long to wait for a reply. If no reply is received within the specified time, the function call fails and the caller exits.

GenServer is a process like any other Elixir process and it can be used to keep state, execute code asynchronously and so on. The advantage of using a generic server process (GenServer) implemented using this module is that it will have a standard set of interface functions and include functionality for tracing and error reporting.

defmodule ServerModule do
use GenServer
@timeout 5000 # 5 Seconds def init(args) do
{:ok, args, @timeout}
end

...
end

When starting the GenServer usingGenServer.start_link/3 or GenServer.start/3, it invokes theinit call. Returning {:ok, args, :timeout} like in the code above will cause start_link/3 to return {:ok, pid} and sets the timeout to block the process from entering in a loop until the server response is received within the timeout limit.

If the caller catches the failure and continues running, and the server is just late with the reply, it may arrive at a later time into the caller’s message queue. The caller must, in this case, be prepared for this and discard any such messages that are two-element tuples with a reference as the first element.

--

--