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

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
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
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
mathew4509
I have a list say x = ["23gh", "56kh", "97mh"] I would like to pass each element to Val in each iteration. Say, in iteration 1 -------...
New
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New

Other popular topics Top

Tee
can someone please explain to me how Enum.reduce works with maps
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
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
New
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set? Thanks.
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

We're in Beta

About us Mission Statement