100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Programming

gen_server Behaviour

Master the gen_server OTP behaviour — the standard pattern for building stateful, message-handling server processes with synchronous and asynchronous calls.

Concurrency & OTPIntermediate10 min readJul 10, 2026
Analogies

Why gen_server?

Writing a raw process that loops on receive, matches messages, tracks state, and replies to callers correctly is easy to get subtly wrong — missing a catch-all clause, forgetting to loop with the new state, or mishandling replies are common bugs. gen_server is an OTP behaviour that provides this receive loop, state threading, and reply mechanism as a well-tested, standardized library, so a developer only has to implement a handful of callback functions describing what should happen for each kind of request.

🏏

Cricket analogy: Just as a standardized net-bowling machine setup at every franchise nets session removes the need for each team to reinvent how to feed balls at a batter, gen_server abstracts away the repetitive receive-loop boilerplate so every OTP server process follows the same reliable pattern.

The Callback Contract: init, handle_call, handle_cast, handle_info

A gen_server module implements init/1, which runs once at startup and returns the initial state as {ok, State}; handle_call/3, invoked for synchronous requests sent via gen_server:call/2,3, which must return something like {reply, Reply, NewState}; handle_cast/2, invoked for asynchronous requests sent via gen_server:cast/2, returning {noreply, NewState}; and handle_info/2, invoked for any other message that arrives in the mailbox outside the call/cast protocol, such as a monitor's 'DOWN' message.

🏏

Cricket analogy: init/1 is like a team's pre-match warm-up setting the starting XI (initial state); handle_call is answering a direct question from the umpire that needs an immediate ruling reply; handle_cast is signaling a substitution to the dugout without waiting for acknowledgment; handle_info is reacting to an unplanned rain interruption announcement.

erlang
-module(counter_server).
-behaviour(gen_server).
-export([start_link/0, increment/0, get_count/0]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2]).

start_link() ->
    gen_server:start_link({local, ?MODULE}, ?MODULE, 0, []).

increment() ->
    gen_server:cast(?MODULE, increment).

get_count() ->
    gen_server:call(?MODULE, get_count).

init(InitialCount) ->
    {ok, InitialCount}.

handle_call(get_count, _From, State) ->
    {reply, State, State}.

handle_cast(increment, State) ->
    {noreply, State + 1}.

handle_info(_Msg, State) ->
    {noreply, State}.

call vs cast: Synchronous vs Asynchronous Requests

gen_server:call/2,3 sends a request and blocks the calling process until a reply arrives or a timeout expires — 5000 milliseconds by default, configurable via a third argument or set to infinity. gen_server:cast/2, by contrast, sends a request and returns immediately without waiting for it to be handled at all, making it appropriate for notifications where the caller doesn't need confirmation. A subtle danger is calling gen_server:call from inside a handle_call callback on a process that, directly or indirectly, calls back into the original caller — this creates a circular wait that hangs both processes until the call times out.

🏏

Cricket analogy: Asking the third umpire for a review and waiting on the big screen for the decision before play resumes mirrors gen_server:call's blocking wait for a reply; a captain waving to signal a field change without waiting for confirmation mirrors cast; but if the third umpire tried reviewing their own decision it would freeze the game, like a process calling itself.

Never let handle_call for process A make a gen_server:call to process B if there's any chance B's own handling path calls back into A synchronously — this circular wait will hang both processes until the call timeout fires (default 5000ms), surfacing as a confusing timeout exception far from the real cause.

State Management and Hot Code Upgrades

Every gen_server callback threads the process's state explicitly through its return value — {reply, Reply, NewState}, {noreply, NewState}, and so on — rather than mutating a shared variable, keeping state changes explicit and traceable. Beyond ordinary state updates, gen_server also supports the optional code_change/3 callback, which is invoked during a hot code upgrade to transform a running process's existing state into the shape the new code version expects, allowing the server to keep running — and keep its accumulated state — without ever stopping.

🏏

Cricket analogy: A scorer who updates the scoreboard after every single ball, carrying forward the exact same running total into the next delivery, mirrors how gen_server threads state immutably through each callback's return tuple; switching to a new digital scoreboard system mid-match without stopping the game mirrors code_change/3's hot upgrade.

gen_server:call/2 defaults to a 5000ms timeout; pass gen_server:call(Server, Request, Timeout) with an explicit value, or infinity, when an operation is known to take longer — but avoid infinity for calls to servers you don't fully trust, since it removes your ability to fail fast.

  • gen_server is an OTP behaviour that abstracts the standard receive-loop pattern for stateful server processes.
  • init/1 initializes state; handle_call/3 handles synchronous requests; handle_cast/2 handles asynchronous requests; handle_info/2 handles out-of-band messages.
  • gen_server:call/2,3 blocks the caller until a reply arrives or a timeout (default 5000ms) expires.
  • gen_server:cast/2 is fire-and-forget and returns immediately without waiting for the server to process it.
  • Calling gen_server:call on a process that then calls back into the original caller synchronously can deadlock.
  • State is threaded immutably through the return tuples of each callback ({reply, Reply, NewState}, {noreply, NewState}, etc.).
  • code_change/3 allows a running gen_server's state to be transformed during a hot code upgrade without stopping the process.

Practice what you learned

Was this page helpful?

Topics covered

#Programming#ErlangStudyNotes#GenServerBehaviour#Gen#Server#Behaviour#Callback#StudyNotes#SkillVeris#ExamPrep

Frequently Asked Questions

21 categories · pick one to explore

Where can I get free study notes for programming and tech subjects?
SkillVeris offers completely free study notes covering programming and tech subjects, with no signup fees or paywalls. The notes are structured by course and topic, written for quick understanding, and enriched with the Learn Through Hobbies analogy method, so you can revise concepts through cricket, music, gaming, cooking and more.
Are SkillVeris study notes good for exam revision?
Yes, the study notes are designed for efficient revision: each topic answers its heading immediately, keeps explanations concise, and links to related glossary terms and cheat sheets. Students preparing for university exams or certification tests use them as quick revision notes because they distil concepts without the padding of full textbooks.
What subjects do the free study notes cover?
The study notes span the platform's main domains, including AI and machine learning, Python and programming, web development, DevOps, cloud, security and databases. Coverage mirrors the 37 live courses, so notes exist for the topics you are actually studying, and new note sets are added as courses launch.
How are SkillVeris study notes different from regular textbooks?
The notes are answer-first, concise and free, whereas textbooks are long and often expensive. Each section explains one concept directly, then reinforces it through selectable hobby analogies like cricket or cooking. Notes also cross-link to the glossary, blog and cheat sheets, letting you jump to related material instantly instead of flipping pages.
Can I use the developer study material without creating an account?
The study notes are free to access, and SkillVeris does not charge anything for its developer study material at any point. Browsing notes is straightforward from the Study Notes section, and if you want progress tracking, certificates and AI Mentor conversations tied to your learning, a free account unlocks those extras.
Do the study notes explain concepts with analogies?
Yes, this is a signature SkillVeris feature. Study notes use the Learn Through Hobbies method, explaining technical concepts through analogies from twelve domains including cricket, music, gaming, photography, travel, movies, fitness, chess, cooking, finance, business and sports. You can switch the analogy domain instantly to whichever hobby makes the concept click.
Are the revision notes suitable for last-minute exam preparation?
Yes, revision notes on SkillVeris work well for last-minute preparation because every section states the answer in its first sentences, so skimming is genuinely effective. Pair them with the relevant cheat sheet for formulas and syntax, and use the glossary for any unfamiliar term you meet while cramming.
Is there free study material for AI and machine learning?
Yes, SkillVeris provides free study notes across its AI and ML catalogue, covering Python for AI, deep learning frameworks like PyTorch and TensorFlow, Hugging Face Transformers, Large Language Models, RAG, AI agents and MLOps. All of it is free, making it a strong resource for Indian students and global learners alike.
Can beginners understand the study notes, or are they for experts?
Beginners can absolutely use them. The notes are written in plain language, define terms as they appear, and lean on hobby analogies to make abstract ideas concrete. Difficulty scales with the underlying course level, so beginner-course notes stay gentle while advanced-course notes go deeper, and the glossary supports you throughout.
How do study notes connect with SkillVeris courses?
Study notes are organised by course and topic, so they map directly to the structured courses and their 24–40-lesson curriculum. Many learners study a lesson first, then use the matching notes for revision before module assessments and the final exam, where 80 percent is required to pass and earn the certificate.
Are there study notes for Python specifically?
Yes, Python is well covered through notes tied to the Python-focused courses, including Python for AI and ML. Topics span fundamentals through applied machine learning usage. You can reinforce the notes with Python practice in Code Lab, which runs code in your browser with no installation required.
Do the study notes include code examples?
Yes, study notes include code examples wherever a concept is best shown in code, alongside explanations, key points and analogies. Reading a snippet in the notes and then reproducing it yourself in Code Lab is an effective loop, since Code Lab lets you run code in the browser across six languages.
How often is new study material added to SkillVeris?
Study material grows alongside the course catalogue. Whenever new courses join the platform's 37 live courses, matching study notes, glossary entries and cheat sheets are added so the resources stay in sync. Existing notes are also refined over time, so it is worth revisiting topics you studied earlier.
Can I use SkillVeris notes to prepare for technical interviews?
Yes, the notes make excellent interview revision because they compress each concept into direct, answer-first explanations, which mirrors how you should answer interview questions. Combine them with the SkillVeris interview questions feature, which includes readiness scoring, to test whether your revision has actually made you interview-ready.
Are the study notes mobile-friendly for studying on the go?
Yes, the study notes are built to load fast and read comfortably on mobile devices, so you can revise during a commute or between classes. Sections are short and answer-first, which suits small screens, and analogy switching works on mobile too, letting you study anywhere without carrying books.
What is the difference between study notes and cheat sheets?
Study notes explain concepts in depth with context, examples and analogies, making them ideal for learning and revision. Cheat sheets are compact quick-reference summaries of syntax, commands and key facts, ideal once you already understand a topic. Most learners study the notes first, then keep the cheat sheet handy while coding.
Do study notes help if I am stuck on a course lesson?
Yes, reading the matching study notes often clarifies a lesson because the same concept is explained from a different angle, frequently with a different analogy. If you are still stuck, ask the AI Mentor, which answers 24/7 at Quick, Detailed or Deep-dive depth until the idea genuinely makes sense.
Is there free study material for DevOps and cloud topics?
Yes, SkillVeris carries free study notes for DevOps and cloud topics as part of its coverage across 37 live courses. The material suits learners following the DevOps Engineer or Cloud Engineer paths, and it links to related glossary terms and cheat sheets so you can revise the whole toolchain in one place.
Can school or college students in India use these notes for projects?
Yes, students across India and worldwide use SkillVeris notes for coursework, projects and exam preparation, and everything is free, which matters for student budgets. The notes explain concepts clearly enough to cite in project reports, and Code Lab lets you prototype the project code directly in your browser.
How should I combine study notes with other SkillVeris resources?
A proven loop: learn from a course lesson, revise with the matching study notes, look up unfamiliar terms in the glossary, keep the cheat sheet open while practising in Code Lab, and quiz yourself with interview questions. The AI Mentor fills any remaining gaps 24/7, at whatever depth you need.

What Learners Say

Real journeys from the SkillVeris community — swipe for more.

SkillVeris taught me Python through Cricket. Now I’m building real projects and feeling confident!
Arjun S. · B.Tech Student
The best platform for hobby-based learning. Concepts finally stick.
Priya R. · Data Analyst
I went from zero coding to a portfolio of projects — all by learning through my love for gaming. Landed my first internship!
Kabir M. · CS Undergraduate
Trending Topics50 popular tags — tap to explore
Trending CoursesAll 37 free courses — tap to browse