Retry in Go

Orhan Yediyıldız
Nov 3 · 1 min read

When you want to connect to other services from your servers, you need to make sure the service is already ready to accept connections.

I recently encountered a problem when running a server and a database using docker-compose. The database takes a while to start, therefore the server fails to establish a connection to database.

When I was looking for how others deal with this situation, I found the a simple solution here: https://alex.dzyoba.com/blog/go-connect-loop/. This pattern solves the problem. It basically retries connecting to a database for the duration you pass to it.

There are also other solutions such as retry-go. I don’t feel like depending on another package for this simple requirement.

I noticed that I needed to use the same pattern in some other places as well. We can go one step further and make this a bit generic using a closure and re-use the same logic for connecting to other services.

Retry runs the given function until it times out or returns a nil error. The closure function f needs to set the variable db *sql.DB after successfully pinging the database. This results in more code, but we can re-use the Retry function now.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade