A queue in classic programming is a data structure (DS) used for storing and managing data in a specific order. In the real-world simulation, you can imagine a queue of people waiting for their order, and people who ordered it first will receive it first and vice-versa.
, a dynamic, functional programming language that has absorbed the best programming patterns, and I like it a lot.
Elixir has a great module called
In this screenshot, you can see the client-side implementation of GenServer module, which is responsible for the public interface of our queue which we mentioned before. Let’s go through the code line-by-line:
Line 2 — We use the GenServer behavior which allows us to create an independent process in the Elixir and store the state. init_arg in this case will be passed from the GenServer.start_link/3 function, and it will be an array from the client side or an empty array by default.
Line 8— This function is responsible for starting a separate process, which will hold our queue with a process identifier.
Line 14— Here you can see the presence of all the necessary methods that a public queue interface should have (queue, dequeue, peek, is_empty). These functions will call methods on the server and return the updated result from them.
On the server side, we have all the dirty work, namely how the queue works:
Line 43 — Here you can see how the client call of the enqueue method calls this callback, which in turn operates by adding the necessary element (the usual push to the end of the array).
Line 48 — The dequeue callback checks if the queue is empty, because if it is, the requested item cannot be pulled. If the queue is empty, we return the tuple with an error and a message about the empty queue {:error, :empty}.
Line 58 and 67 — The same as with dequeue, we pull an element by index and make an additional check for array emptiness, so that there would be no runtime error when pulling elements.
Line 72 — Server callback which is responsible for checking the queue for emptiness, the callback calls a private method is_empty that is not available in the public interface.
Result
We’ve implemented our queue using Elixir, which follows the FIFO principle. Let’s take a look at how it works:
Conclusion
Today we learned what a queue is as a data structure in programming, where it is most often used, and how to implement its basic array-based version using Elixir GenServer. In the next article, we will create a library that can enqueue tasks into queues, persist them in the database with Redis, and process those tasks with workers. Thanks for reading and see you soon!

SOCIAL SHARE CARD GENERATOR