How to cache API response using Cachex — Elixir?

Sahil Paudel
Codantastic
Published in
2 min readMay 10, 2020

In this article, I am going to tell you, how I used cachex to cache the API response in Elixir application.

Let’s get started.

Step 1. Add cachex in the mix.exs file.

{:cachex, “~> 3.1”}

Step 2. Declare a worker that initializes the application cache key.

children = [# Start the Ecto repository
...
worker(Cachex, [:myapplication_cache, []])]

Step 3. Create an application cache module & write the logic on what to perform on cache hit & miss

defmodule MyApplication.Cache do
def fetch(key, func, ttl \\ 1_000_000_000) do
case Cachex.get(:diamond_cache, key) do {:ok, nil} -> Cachex.put(:diamond_cache, key, value = func.(), ttl: :timer.seconds(ttl)) value {:ok, value} -> value _ -> func.() end
end

In this module, we have defined a function fetch that takes the key of the cache we want to set, a function that needs to be executed in case of miss and the TTL time after how long the cache will be invalidated.

Let us look into each line.

Cachex.get(:myapplication_cache, key)

In this line, we are asking cachex to give the application-level cache, remember the key myapplication_cache we initialized the cache with.

{:ok, nil}

here the function returns success but their cache is empty as it doesn’t contain any cache keys. So we will populate the cache with key received in the function parameter & value returned by the function passed in the parameter. Also, note that value is returned here, it is for the function that is calling this fetch method to get the data it is expecting from the cache.

{:ok, value} -> value

This is the cache hit case where we are getting the data in the case no need to execute the func.().

_ -> func.()

If nothing matches just execute the function and return the data to the calling function.

Now let us define a function that would make this request.

alias MyApplication.Cachedef cached_all_cities() do    Cache.fetch(       "all_cities_from_location",       fn -> fetch_all_cities_from_location() end    )end

Here inside the cached_all_cities function, we are calling the Cache fetch function that we declared above. For the first time, myapplication_cache cache will not have the key all_cities_from_location, it will be a cache missed hence below function will be executed.

fn -> fetch_all_cities_from_location() end

The response will be stored with key all_cities_from_location. Now on the data will be served from the cache for this key.

fetch_all_cities_from_location()

This function queries the DB or external API call to fetch the latest data.

How to delete a cache

Cachex.del(:myapplication_cache, key) # -> key you want to delete

Note: If the application is restarted the cache will be cleared. This is my first article sorry for any typos & suggestions are most welcome.

--

--

Sahil Paudel
Codantastic

Backend Engineer in love with Full-Stack. Develops in Java | Spring Boot | Elixir | NodeJS | ExpressJS | React | Go https://portfolio.sahilpaudel.in