GenServer Lifecycle and Termination
In the previous lesson, you focused on asynchronous operations with GenServer and saw how call waits for a reply while cast does not. Today, you will learn how GenServers start, expose state safely, and shut down cleanly. This is essential for managing resources, such as database connections or file handles, over a process’s lifetime.
Start and Initialize the Server
Explanation:
use GenServerbrings in the GenServer behavior and default implementations.start_link/1starts the server and passesresource_nameinto the callback module.init/1runs first on the server process. It prints an initialization message and returns the initial state as a map. The{:ok, state}tuple tellsOTPthe server is ready.
Query Status and Request a Graceful Stop
Explanation:
stop/1asksOTPto terminate the server with the reason:normal. This is a graceful shutdown.handle_call/3handles a synchronous request for:status. It replies with the current state and keeps the state unchanged. Usingcallhere ensures the caller gets a consistent snapshot.
Clean Up with Terminate/2
Explanation:
terminate/2runs just before the process exits (except for brutal kills). It is the right place to release resources and log why the server stopped. Thereasonwill be:normalwhen triggered byGenServer.stop/2.
Run the Lifecycle
Explanation:
- Start the server with a label (
"DatabaseConnection") and keep thepid. - Sleep briefly to observe the initialization output.
- Request a graceful stop, which triggers
terminate/2with:normal. - Sleep again to let the termination messages print before the script ends.
Summary and Next Steps
You started a GenServer, initialized state, exposed a safe :status query, and shut it down gracefully while cleaning up in terminate/2. These lifecycle steps help you manage real resources reliably. When you are ready, head to the practice section and put these ideas to work.

Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal