📎 Webclip
An intro to OTP in Elixir
The post introduces OTP as the set of Erlang libraries and tools used for concurrent programming, then shows how an Elixir FizzBuzz server can be turned into an OTP app. It focuses on application behaviours, where Elixir supplies default callback implementations and the developer overrides only what is needed.
Reading notes #
- OTP is described as the Open Telecom Platform and as a complete development environment for concurrent programming, with the libraries as the part people usually mean by OTP.
- Erlang/OTP behaviours define generic implementations for common tasks, such as a generic server module.
- Elixir provides default implementations for these callback functions, so only needed ones must be overridden.
- The example starts a new Mix project with a CamelCase module name by passing
--module FizzBuzz. - The server implements the
GenServerbehaviour and usesLoggerfor debugging. FizzBuzz.start_link/0wrapsGenServer.start_link/3and starts the server as a linked process, often in a supervision tree.- The module name is used as the server name so other functions do not need to address it by PID.
FizzBuzz.get/1andFizzBuzz.print/1form the client API, withgetusing a synchronous call andprintusing an asynchronous cast.- Wrapping the GenServer interface in client APIs is presented as a common pattern.
- The callbacks
handle_call/2andhandle_cast/2pattern match on{:print, n}and delegate tofetch_or_calculate/2. fetch_or_calculate/2checks whether the FizzBuzz value was already computed, fetches it from the dictionary if present, or calculates it and stores it in the state.- The state is a simple Elixir map.
- The complete example is run in
iex -S mix, and the output shows asynchronous requests interleaving logs, function return values, andIO.putsoutput. - The post notes that
IO.putsoutput appears in theiexsession because it uses the current group leader. - Fetching an already computed value returns it from the cache.
- The summary says OTP makes it easy to implement server applications and that the FizzBuzz server can be deployed in a larger Elixir application with supervision and hot code swapping.