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 GenServer brings in the GenServer behavior and default implementations.
  • start_link/1 starts the server and passes resource_name into the callback module.
  • init/1 runs first on the server process. It prints an initialization message and returns the initial state as a map. The {:ok, state} tuple tells OTP the server is ready.
Query Status and Request a Graceful Stop

Explanation:

  • stop/1 asks OTP to terminate the server with the reason :normal. This is a graceful shutdown.
  • handle_call/3 handles a synchronous request for :status. It replies with the current state and keeps the state unchanged. Using call here ensures the caller gets a consistent snapshot.
Clean Up with Terminate/2

Explanation:

  • terminate/2 runs just before the process exits (except for brutal kills). It is the right place to release resources and log why the server stopped. The reason will be :normal when triggered by GenServer.stop/2.
Run the Lifecycle

Explanation:

  • Start the server with a label ("DatabaseConnection") and keep the pid.
  • Sleep briefly to observe the initialization output.
  • Request a graceful stop, which triggers terminate/2 with :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.

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