Creating Redis connections using Object Pool Design Pattern in Golang

The Object Pool Design Pattern is a creational design pattern in which a pool of objects is initialized and created beforehand and kept in a pool. A client can request an object from the pool, use it, and return it to the pool as an when needed. The object in the pool is never destroyed. This design pattern offers a mechanism to reuse objects that are expensive to create like in the case of creating connections with Redis or a DB. The cost to create each connection object is high due to the network calls involved. Moreover, only a limited number of connections are needed at a time.

The implementation of the object pool design pattern involves the following steps:
1. A reusable object that wraps the limited resource that will be shared by several clients for a limited amount of time.
2. A client object that uses an instance of type Reusable.
3. A reusable pool that creates and manages a pool of reusable objects.

Whenever a reusable object is wanted by a client, the pool performs the following actions:
1. Search for an available reusable object and return it to the client if found
2. If not found try to create a new one. If the creation succeeds, return the new Reusable object to the client.
3. If the pool is unable to create a new Reusable, wait until a reusable object is released.

Let’s now look at how to create the reusable object that wraps the redis connection resource in Golang:

import (
"fmt"
"github.com/gomodule/redigo/redis"
)

The above function creates a new pool of redis connections using the redigo library (please replace the redis variables in the above code snippet with your values). The above function should be called only once and the returned object should be used to establish all connections to redis as in the below code snippet.

var pool = newPool()

It is important to note that the client is responsible for releasing the connection object back to the pool. If this is not done, the reusable object will be lost and considered unavailable by the resource pool.

Software Engineer at AirAsia

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store