Building an intelligent cache (memoization) in 2 steps

Iván Corrales Solera
2 min readDec 4, 2019

In this article we’ll learn to build a functions memoization cache. This will make that cached functions requests will make skip the function invocation.

Pre-requisites

To build our intelligent cache we will use the below two libraries:

go-cache: It provides a mechanism to create cache with expiration time. Source code can be found here

beyond: It provides an awesome mechanism to take advantage of AOP. Source code can be found here

1. Code the Memoize advice

Let’s clone the code that will use in this tutorial.

git clone https://github.com/wesovilabs/beyond-examples.git
cd smart-cache

We’ll implement an Around advice to achieve our purpose. An around advice surrounds a function/method invocation.

Let’s see the advice implementation in file advice/memoization.go.

Before method checks if there’re a cache entry for the request. If so, the function won’t be invoked, nor the returning method.

Returning method puts the function results into the cache.

Memoize function creates an instance of Memoization advice

2. Register the advice

Open file cmd/main.go and have a look at function Beyond

As we observe in the above image, we’re registering the Memoization advice for method ListPeopleByCity of type memDBClient in package storage. You can learn more about joinpoints registration here.

Elements will be cached during 5 seconds.

That’s mean that invocations to method ListPoepleByCity in file storage/mem.go will be surrounded by Memoize advice.

Let’s see it in action

To test it, we will use the file test/main.go

The second invocation to listPeople(“MAD”) shows that there’re 1 person living in MAD…. however after the entry is expired from the cache the invocation will show that there’re 2 people living in MAD

  1. Launch the server application with command

beyond run cmd/main.go

2. Runt the client

go run test/main.go

You can visualize the example here

https://www.youtube.com/embed/elEgvqOi5Tc

--

--