smedegaard
I’ve got an app that connects to a number of TCP sockets using Ranch.
The supervision tree looks like this:
|-------|
| APP |
|-------|
|
▼
|---------------------|
| Manager(Supervisor) |
|---------------------|
| | |
▼ ▼ ▼
|-------||-------||----------------|
| Sup 1 || Sup 2 || Sup N |
|-------||-------||----------------|
| |
▼ ▼
|------------| |-------------|
| TCP Reader | | Other Child |
|------------| |-------------|
For each connection I start a GenServer in a supervisor.. The GenServer init\1 calls connect\1.
def connect(config) do
case :ranch_tcp.connect(config.ip, config.port, []) do
{:ok, socket} ->
{:ok, socket}
error = {:error, :econnrefused} ->
Logger.error("Connection refused to #{inspect(config)}. Shutting down Reader")
error
error = {:error, _error} ->
Logger.error(
"CTC Socket failed to connect to #{inspect(config)}. Shutting down Reader"
)
error
end
end
What I want to do is let the Supervisor and its children die gracefully if :ranch_tcp.connect\2 returns {:error, :econnrefused}
The GenServer init looks like this
@impl true
def init(config) do
case connect(config) do
{:ok, socket} ->
#nice, start reading
{:ok, %{:config => config, socket: socket}}
{:error, :econnrefused} ->
#too bad. Close self and Supervisor gracefully
exit(:normal)
{:error, error} ->
#What the what! Try again X times
{:stop, error}
end
end
Observed behaviour
If the Genserver init\1 does not return {:ok, state} the error is propagated all the way to the Application, and it quits.
Starting ctc socket app
12:25:25.694 [error] Connection refused to %Server{ctc_name: :down_tcp_server, ip: {127, 0, 0, 1}, port: 5555, recv_buffer: 0}. Shutting down CtcReader
12:25:25.697 [info] Application ctc_socket exited: CtcSocket.Application.start(:normal, []) returned an error: shutdown: failed to start child: Supervision.Manager
** (EXIT) shutdown: failed to start child: :down_tcp_server_supervisor
** (EXIT) shutdown: failed to start child: :down_tcp_server_reader
** (EXIT) normal
** (Mix) Could not start application ctc_socket: CtcSocket.Application.start(:normal, []) returned an error: shutdown: failed to start child: Supervision.Manager
** (EXIT) shutdown: failed to start child: :down_tcp_server_supervisor
** (EXIT) shutdown: failed to start child: :down_tcp_server_reader
** (EXIT) normal
Trending in Questions
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
Hi everyone,
I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding.
I sta...
New
Hello,
I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
Documentation
While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
So my question is quite simple and i have found no conclusive answer on forum, google or AI.
Should we use :erlang.float for Integer to ...
New
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
I’m new to elixir and just tried to install the elixirLS extension for VScode(ium) and it is throwing some errors that I would like help ...
New
Other Trending Topics
Edit: 2026 May 15 - This post is archived.
Mob is alive!!
Main docs: mob v0.7.11 — Documentation
A bit of explanation for the slightly c...
New
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
I am happy to introduce the very α version of the new programming language compiled to BEAM.
Welcome Cure.
It has literally three kille...
New
Hi there! We created Gust: A task orchestrator inspired by Airflow.
For those who have never heard about Aiflow, it’s a Python-based wor...
New
Hi everyone!
The first release candidate for the Expert language server project is now available!
We’ve published a press release detai...
New
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #library
- #deployment
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #elixirconf
- #channels
- #exunit
- #discussion
- #code-sync
- #podcasts
- #javascript
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #ai
- #elixirconf-us
- #blog-post
- #elixir-ls
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #elixirconf-eu
- #metaprogramming
- #hex











Showing Posts 1 to 10- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
amnu3387
You’ll want to return either
{:stop, :normal}or:ignorefrom the init so that the Supervisor ignores the child otherwise it considers it to be crashing. I think in this case:ignoredescribes better its functionality. I think if you do{:stop, :normal}you’ll also have to change the GenServer restart strategy to be:transient(meaning it will only be restarted by the Supervisor in case it exits with something else than:normalor through:shutdown, or shutdown tuple, by usinguse GenServer, restart: :transient).lud
You can return
{:ok, state}from yourinit/1function and then spawn a function that would callSupervisor.stopto stop the parent supervisor.But that is hacky. I would have it done by the process that starts each Sup1, Sup2, SupN for each connection.
smedegaard
Thanks for the answer.
:ignorewill keep a referance to thepidso you have the possibility to doSupervisor.restart_child(). That’s not quite what I’m looking for.What I can’t seem to understand is how I handle the children stopping, In the Supervisor.
Shuold I rather trap exits in the GenServer and then send a message to the Supervisor that it should stop itself and all children? That seems to defeat the Purpose of the strategy that I sat to
:rest_for_one.I’ve got the
{:error, :econnrefused}case working so that it does not crash its supervisor by usinghandle_infoinstead of trying to connect directly ininit()smedegaard
I read that having a GenServer monitor the shutdown of other GenServers is a common pattern.
But it seemed strange to me to have a GenServer to help my Supervisor supervising…
I ended up passing the Supervisor’s pid as a init arg to the Genservers and if I got
{:error, :econnrefused}when trying to connect to the TCP socket, I close the Supervisor withSupervisor.stop\1On all other errors I let it crash
Feel free to suggest better patterns to this
lud
Isn’t
Supervisor.stopis a synchronous call ? You call will await supervisor termination, but the supervisor will not be able to terminate the child gracefully, since the child is blocking on areceive, awaiting termination.The supervisor will wait like 5 seconds and then kill the child.
That is why is suggested to do it from a process that is not the child.
Another solution, if
ranch_tcp:connectdoes not link anything to the caller, would be to call it from the supervisor and then pass the socket to the child if successful, or cancel the supervisor initialization otherwise.smedegaard
I checked with
:observer.start()and it seems to work as expected. The blocking:ranch_tcp.recv()is not called if I get a connection refused.But I’m willing to try from a monitoring GenServer to learn
How would that be done?
Start the the monitoring GenServer from the supervisor and then call
spawn_monitor(GenServerToBeMonitored, :some_function, [])from the Supervisor ?I’m a bit hesitant to do spawn_monitor since the docs says:
lud
It is
Supervisor.stopthat should be blocking. But as your GenServer is not trapping exits and you are calling fromhandle_infoit is fine. I thought you were still oninit.What I was saying after is that you could call
ranch_tcp.connectin the supervisorinitfunction, and depending on the result callSupervisor.initor return:ignore: Supervisor — Elixir v1.20.2smedegaard
Ok, thanks.
Starting the
ranch_tcp.connectin the Supervisor is an option. I would gain not having to pass the Supervisor pid, but would have to passe the tcp socket. So I guess I don’t win too much by making that change.Also, I avoid starting the Genserver and (1) sibling process, just to shut them down. But It’s less than 20 TCP connections. So the performance impact is negligible.
Again, thanks a lot for the feedback.
lud
Well you gain that if you have
:econnrefusedyour supervisorinit/1callback just returns:ignoreso:Also, if the connect returns an error that is NOT
:econnrefused, you canexit(...)from the supervisor and try again, just like you do now. But again, the child does not have to deal with it, it only receives connected sockets.ityonemo
is your manager supervisor a dynamic supervisor? It seems like you probably would want your TCP reader supervisor to be dynamic, and your TCP Reader and “other child” to be statically supervised. If that’s the case then the repeated deaths of your one level-3 supervisor won’t bring down your level-2 supervisor, and then your app.
also consider using Connection Connection — connection v1.1.0