Agent, Task, GenServer, GenEvent: what do you use it for?

First, a nit pick. There are only Elixir apps. Some Elixir apps use phoenix, some do not, but there are only Elixir apps.

Let’s start with the simplest case, tasks. We have an async job worker system, and every job is run inside a task. This makes it easy for the worker process to monitor what happens to the job. It also makes for less work for the garbage collector because any memory the job uses can be all easily reclaimed when the process quits.

GenServers: These get used for a variety of things. I have a slack bot process that aggregates some info and periodically shoves it in slack. I have processes that represent sensors out in warehouses monitoring temperature, and these genservers give us notifications if they haven’t heard from a sensor in X amount of time (amongst other things).

Agent: Basically just a simplified genserver. Never used one.

GenEvent: Used it a long time ago, but there were pain points. Technically I still use it cause I have a customer Logger backend and IIRC it uses GenEvent.

Not mentioned: :gen_statem I used recently in some sensor management software. Each connected sensor gets its own state machine process that ensures it walks through the right states / transitions as it gets configured / upgraded / etc.

6 Likes