6 Generic server processes

 

This chapter covers

  • Building a generic server process
  • Using GenServer

In chapter 5, you became familiar with basic concurrency techniques: you learned how to create processes and communicate with them. I also explained the idea behind stateful server processes — long-running processes that maintain state and can react to messages, do some processing, optionally send a response, and maybe change the internal process state.

Server processes play an important role and are used frequently when building highly concurrent systems in Elixir and Erlang, so we’ll spend some time exploring them in detail. In this chapter, you’ll learn how to reduce some of the boilerplate associated with server processes, such as infinite recursion, state management, and message passing.

Erlang provides a helper for implementing server processes — it’s part of the framework called Open Telecom Platform (OTP). Despite its misleading name, the framework has nothing to do with telecoms; rather, it provides patterns and abstractions for tasks such as creating components, building releases, developing server processes, handling and recovering from runtime errors, logging, event handling, and upgrading code.

6.1 Building a generic server process

6.1.1 Plugging in with modules

6.1.2 Implementing the generic code

6.1.3 Using the generic abstraction

6.1.4 Supporting asynchronous requests

6.1.5 Exercise: refactoring the to-do server

6.2 Using GenServer

6.2.1 OTP behaviours

6.2.2 Plugging into GenServer

6.2.3 Handling requests

6.2.4 Handling plain messages

6.2.5 Other GenServer features

6.2.6 Process lifecycle

6.2.7 OTP-compliant processes

6.2.8 Exercise: GenServer-powered to-do server

Summary