Skip to content

Instantly share code, notes, and snippets.

@speric
Last active December 10, 2016 06:54
Show Gist options
  • Save speric/b900c099199efbe837d5 to your computer and use it in GitHub Desktop.
Save speric/b900c099199efbe837d5 to your computer and use it in GitHub Desktop.
Introducing Phoenix: Concurrent

An excerpt from Programming Phoenix by Chris McCord, Bruce Tate, and José Valim


You won’t find a "PhoenixDelayedJob" or "ElixirResque", those complex packages that exist only to spin off reliable processes as a separate web task.

You don’t need one. Don’t get us wrong. In Ruby, those packages are well-conceived and a critical part of any well-crafted solution. In Elixir, those frameworks turn into primitives. The Elixir programming model makes reasoning about concurrent systems almost as easy as reasoning about single threaded ones. When you have two database fetches, you won’t have to artificially batch them together with a stored procedure or a complex query. You can just let them work at the same time, like this:

company_task  = Task.async(fn -> find_company(cid) end)
user_task     = Task.async(fn -> find_user(uid) end)
cart_task     = Task.async(fn -> find_cart(cart_id) end)

company = Task.await(company_task)
user = Task.await(user_task)
cart = Task.await(cart_task)

You don’t have to wait for the combined time for three database requests. Your code will take as long as the single longest database request. You’ll be able to use more of your database’s available power, and other types of work, like web requests or long exports, will complete much more quickly.

In aggregate, your code will spend less time waiting and more time working.

Here’s the kicker. This code is more reliable. Elixir is based on the libraries that form the backbone of the most reliable systems in the world. You can start concurrent tasks and services that are fully supervised. When one crashes, Elixir can restart it in the last known good state, along with any tainted related service.

Reliability and performance don’t need to be mutually exclusive.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment