Embedded mode

Embedded mode allows you to insert Ranch listeners directly in your supervision tree. This allows for greater fault tolerance control by permitting the shutdown of a listener due to the failure of another part of the application and vice versa.

However, just as for non-embedded listeners that were started via ranch:start_listener/5, it is required that the ranch application is running before you can start embedded listeners. Furthermore, this also means that embedded listeners will restart when ranch_sup fails.

WARNING: By using embedded mode, it is possible to start a listener with the same name as an already existing listener. This will corrupt the information Ranch keeps for that listener, so you should take care to ensure unique listener names yourself. A good way to achieve this is by combining the embedded listener's name with ?MODULE, or the name of the application it is used in.


To embed Ranch in your application you can simply add the child specs to your supervision tree. This can all be done in the init/1 function of one of your application supervisors.

Ranch has a convenience function for getting the listeners child specs called ranch:child_spec/5, that works like ranch:start_listener/5, except that it doesn't start anything, it only returns child specs.

The following example adds one listener to another application's supervision tree.

Embed Ranch directly in your supervision tree
init([]) ->
	ListenerSpec = ranch:child_spec({?MODULE, echo},
		ranch_tcp, #{socket_opts => [{port, 5555}]},
		echo_protocol, []
	{ok, {#{}, [ListenerSpec]}}.

Embedded listeners cannot be stopped via ranch:stop_listener/1. Instead, are to be stopped as part of the shutdown of your application's supervison tree.

Ranch 2.1 User Guide


Version select

Like my work? Donate!

Donate to Loïc Hoguin because his work on Cowboy, Ranch, Gun and Erlang.mk is fantastic:

Recurring payment options are also available via GitHub Sponsors. These funds are used to cover the recurring expenses like food, dedicated servers or domain names.