Leveraging Workers in Dependencies

Let's learn how to leverage code from dependencies in Elixir.

We are using Elixir partially because it provides an excellent foundation for concurrency. The worker layer is a concurrency management layer, and in this section, we’ll look at the different tools at our disposal to manage concurrency. We’ll start with some of the most basic ones:

  • Dependencies will allow us to include the work of others.

  • Processes are Elixir concurrency primitives we can lean on in a pinch, but typically we’ll be working at a higher level of abstraction.

  • Tasks will allow us to do one-off jobs and still rely on the rich OTP library.

  • Connection-pooling libraries let us share long-running connections across processes.

Finally, we can integrate existing frameworks that provide OTP abstractions that serve as containers for our code.

Let’s look at the simplest example possible for starting a worker, the dependency.

Using dependencies

The easiest way to use concurrency in Elixir is to leverage code someone else has already written. When we think about it, that’s not such a strange concept. Most of us don’t use much recursion in our day-to-day code because we can lean on Enum’s implementations to do that work for us. Many of Elixir’s most popular dependencies are full OTP implementations, and most of them take the job of dealing with concurrency off of our plate. For example, when we use Phoenix Channels, we’re using OTP and Phoenix deals with the complex parts so we don’t have to. The same is true of hundreds of other dependencies. Let’s see how that works.

Each mix project potentially has its application file, thus its own lifecycle. Unless a dependency specifies app: false, mix will use the policies in the app file to determine how to:

  • Start the application.

  • Restart the application.

  • Shutdown the application.

We can see the running dependencies. Let’s build an empty app to see what happens. We’ll create a new project named workers and then build the project. The commands for both of them are specified below:

mix new workers
iex -S mix

Now, let’s use the Application module to find out what’s running, like this:

Executable

Get hands-on with 1200+ tech skills courses.