manju16832003

manju16832003

What is GenServer and whats its use cases?

Have been using Elixir / Phoenix for a while but still I get confused with the role of GenServer and its use cases. Would love to know about it and its use cases in both web apps and as in general GenServer implementation

Most Liked

AstonJ

AstonJ

I highly recommend @sasajuric’s book Elixir In Action if you want to learn more about GenServers.

He starts by creating generic servers from scratch before going on to GenServers and that really helps you get your head around it. (He does the same for Supervisors as well.) Definitely a must-get book :023:

10
Post #6
mbuhot

mbuhot

Some common use cases for GenServer along with Agent and Task which are built on top are:

Concurrency

Spawn processes to handle independent workloads. Task.async makes it easy to run a function in a separate process and later await the result.

Stateful computations

The GenServer init callback produces an initial state, and it can be transformed by each of the handle_* callbacks. Agent makes it easy to wrap up a state value in a process.

Synchronization

Instead of guarding a resource with a lock, let a GenServer hold it as state, and use GenServer.call to access it.

Failure isolation

A crash in a GenServer will be handled by its supervisor, which can restart it to hopefully get it back into a valid state.

To spawn, or not to spawn has some great advice on best use of processes.

kokolegorille

kokolegorille

TL;DR Use them when You want concurrency.

Under the hood, Elixir and Phoenix uses a lot of GenServers. You can see them running with the observer.

GenServer is just a part of OTP (Open Telecom Platform), so it would be better to understand what is OTP. Mostly, it is a set of specialized processes, You can see them as design pattern for processes…

There are

  • Application
  • GenServer
  • Supervisor
  • state machine (gen_statem, or older gen_fsm)
  • GenEvent (kinda obsolete in the Elixir world)

And even more specialized GenServer, Agent and Task …

You might even not notice them while using them.

For example, in Phoenix, each socket connection is powered by a GenServer process.

When You code modules, it’s like librairies of functions. But when You code processes, it’s like managing thousand (million) of Lemmings. Each process acts as primitive for concurrent programming.

JoeZMar

JoeZMar

I heard about Phoenix’s GenServers and it was what ultimately got me hooked on Phoenix/Elixir. I was previously a Rails developer and couldn’t figure out how to solve a concurrency problem.

My application was for a bot that had about 1000 or so users that would, at the same, log into a JS heavy site and perform about 10-15 minutes worth of timed actions. This was where GenServers came in handy.

I ended up making a GenServer module that would represent a user and hold a Hound() session as state. So when it was time for every user to bot the site concurrently, 1000 processes would spawn, each representing a user that was running a browser on a Selenium server. This way I was able to hold the state, and establish supervisors to monitor each process in case one crashed.

kokolegorille

kokolegorille

If You implement a package, for example a caching micro service, You would want the cache server to bootup with your main application.

Building a package can include modules and functions, but can also include full working microservice. Also, when You build umbrella projects, You can consider each application as an independant package, started from one main entry point.

One good exercice is to implement a web scrapper because it implies to think concurently.

Where Next?

Popular in Questions Top

shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
Werner
Hi, I’m using Ubuntu 18.04 and after updating to OTP-24.0 yesterday i have this warning when I run “mix local.hex”: 14:57:30.512 [warn] ...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
New
beno
I will often find my self writing things similar to: case some_value do nil -> something() "" -> something() _ -> someth...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New

Other popular topics Top

Qqwy
Update: How to use the Blogs & Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3268 119930 1237
New
yawaramin
In the Dialyzer docs ( http://erlang.org/doc/man/dialyzer.html#requesting-or-suppressing-warnings-in-source-files ), there is a way to tu...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 45766 226
New
quazar
How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New

We're in Beta

About us Mission Statement