smpallen99

smpallen99

Beginner Hint: Using GenServers

Some advice for Elixir programmers.

I was reviewing someone’s Elixir Code yesterday and found a deadlock condition bug in a GenServer implementation. That’s not a big deal, since I’ve created one or two in the past (while not paying attention). However, I was surprised how long it took me to explain the issue to someone that has been coding in Elixir for a number of years now. I had go back to first principles and explain how servers work in Elixir.

So, here’s my Tip:

Learn how to write your own servers with both synchronous (GenServer.call/2) and asynchronous (GenServer.cast/2) APIs before using GenServers. GenServers provide a convenient API with lots of functionality behind the scene. However, to avoid potential concurrency issues, you should have an understanding of how they work internally. It will help you reason with the message serialization and know when to use GenServer.call/2 vs GenServer.cast/2. Especially, when not to use GenServer.call/2.

If you are still reading this, and have not figured out how deadlock may happen, then I’ll elaborate. Elixir and Erlang message passing is asynchronous, Full stop. When you send a message, the sender does not wait for the destination process to receive and/or process the message. To do something, the caller sends an async message to another process and includes their own pid in the payload of the message and then calls receive, blocking on a response from the target process.

If you send a sync message using this model (same as a GenServer.call/2) to yourself (send and receive processes are the same pid), then you will deadlock.

This has some implications on how to design and use API functions and helpers in your GenServers. Here are my rules:

  • Never call your public APIs (in the same module) from any call back or helper code
  • Only ever use GenServer.call/2 (to same process) in your public APIs.
  • If you want to share code between an API and a helper, factor out the common code into a separate function and call it from each.
  • Think hard every time you do a sync call from one GenServer to another First, It could lead to a deadlock, if it results into a sync call back into the original caller. But equally important you may be creating a sterilizing bottleneck that may have negative throughout implications.

Most Liked

rvirding

rvirding

Creator of Erlang

I think one reason for this problem is where you come from when you get to a GenServer. What do I mean?

If you are coming bottom-up so to speak from the basic concurrency with processes, messages, receive etc, then you know that a GenServer is just a process and the call and cast are just sending messages. Then know that doing a call just sends a message to yourself and so waiting for a reply is just ridiculous.

If however you come top-down then you see the GenServer through its function interface and the concurrent nature is hidden. I am just calling the GenServer should why shouldn’t I be able to call myself. Coming from an OO background and then “seeing” a GenServer as an object strengthens this view.

That the GenServer, and other behaviours, put effort into hiding the concurrency does not help in this respect. Unfortunately you can not avoid the concurrent nature of the erlang/elixir systems.

Though I must add I have seen people who do realise GenServers are concurrent processes still get into a lot of problems when they try to do calls between servers and find that they block. This I think is more based on not being used to thinking concurrently.

10
Post #7
peerreynders

peerreynders

i.e. when talking to yourself use GenServer.cast/2.

smpallen99

smpallen99

I’m not sure that I’ve found a good reference for this, but its been 4 years since I went through that learning process. There are two basic approaches for starting GenServers. First, you can start them from a supervisor that runs at startup. In this care they will be named (which is not your question).

The second approach is to start them from another stateful process (Another GenServer, GenFSM, or GenStatem. In this case you will need to store the pid as part of that server’s state. When I need to have multiple processes access a common GenServer, I will create a “Manager” that uses a Map to map an id to the PID.

The other I have done is to propagate the pid to all processes that need the pid. But then you need to handle updating that pid if the server restarts.

This isn’t too difficult, you just need to trap exits on the process so you will receive a :DOWN message.

Also, when starting dynamic servers, I don’t usually run start_link directly, but create an API on a supervisor to start the process.

One thing that you have to watch out for is providing a pid in the start up arguments of a supervised GenServer. When a supervised process restarts, it receives the original arguments provide on its initial startup. So, if you provide the pid of some process and that process has restarted, then the pid will be stale. I remember struggling with this for a while when I was starting out with elixir.

Where Next?

Popular in Guides/Tuts Top

tfwright
I thought I’d share a small project I’m working on to gain some familiarty with LiveView in a Phoenix app. Github Repo Deployment It’s...
New
thetechnologyvault
One of our team members just published this getting started guide for Elixir/Phoenix devs to use the Nanobox platform: https://content.n...
New
jswny
Hello everyone, I recently redesigned my entire deployment process for Phoenix apps based on Docker. I really like the strategy that I ca...
New
voltone
The EEF’s Security WG has released the first public draft of the Secure Coding and Deployment Hardening Guidelines for BEAM languages. “...
New
egze
I was preparing to deploy a production application to AWS Fargate, and to practice I wanted to play with DNS polling and node discovery o...
New
New
nelsonic
Complete beginners Todo List Tutorial in Phoenix 1.5.3 (latest and greatest): https://github.com/dwyl/phoenix-todo-list-tutorial It’s a...
New
9mm
So I’m really loving elixir. BY FAR the most excruciating piece of learning a functional language for me is having to “transform” all my ...
New
danschultzer
I wrote this blog post based on our experiences setting up continuous delivery for our first production umbrella Phoenix app. Coming from...
New
anuragg
We just published a guide to automatic clustering in Elixir 1.9, with Mix releases and libcluster. The cluster automatically discovers n...
New

Other popular topics Top

danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 29377 241
New
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
Nvim
Anybody knows a comprehensive comparison of Django and Phoenix, thanks for the help. Where are they similar? Where do they differ the m...
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
chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 30877 112
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
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
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New

We're in Beta

About us Mission Statement