Legitimate reasons to use unlinked processes in production

Not starting some short jobs (which are not server processes) directly under a supervisor is fine. However, plain spawn is IMO plain wrong, as is not linking the process to its parent. By doing that, you’re breaking the parent-child relationship, which can lead to dangling processes or silent crashes. It’s going to make it harder to reason about some subtle bugs.

Here’s what you could do in your case. First, use Task.start_link instead of a spawn. This ensures that the task is a proper OTP child of the GenServer, and that its termination doesn’t go unnoticed. This also ensures that if the parent terminates, all the children will be taken down as well (which is presumably what you want).

Another important change is to not use crashes for the normal flow (a packet is not of the specified type). Instead, use pattern matching. For example:

def assimilate(raw_packet) do
  with {:packet, _link_type, time, _pkt_len, frame} <- raw_packet,
       {:ok, ...} <- :pkt.decode(frame),
       :ets.member(Sniffer.HostList, remote_ip)
  do
    ...
  end
end

This way if your process crashes for some other reasons (perhaps of a bug), that crash will be logged, and you’ll be able to understand what happened. Can this process crash somewhere else? One possible place is GenEvent.notify. If the event manager is down for some reasons, then this function will fail. In your code, you’re treating it implicitly. In the new version, you have to decide whether you want to do something about this case, or you’ll just let it fail.

Even if there’s no possible bug today, it could be introduced tomorrow, because the code is usually changed from time to time. The proper parent-child relationship will ensure that such bugs don’t go unnoticed.

So the summary is, it’s not necessarily bad to start one worker directly under another (see also this thread). However, spawn or start without link is IMO always a bad practice, because it can lead to some implicit problems which will be hard to track down.

3 Likes