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

I’m trying to understand more about Elixir OTP concepts, particularly the ones mentioned in the title. The tutorials gave examples with KV buckets, but I think I need more realistic examples.

Can anyone give examples on how you use them in your apps/libraries? (I’m particularly interested in their usage on a Phoenix app, but if you do use it on Elixir app it’s okay too.)

2 Likes

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

True! I wonder why I wrote that, especially when I just reread this “Phoenix is not your application” thread. Sorry about that :sweat_smile: I meant when you are mainly using Phoenix for your app.

1 Like