- read

Go Errgroup: You Haven’t Used Goroutines Effectively Unless You’ve Used This Package

Phuong Le (@func25) 101

Go Errgroup: You Haven’t Used Goroutines Effectively Unless You’ve Used This Package

Have you ever written a function that’s long because it does many tasks, even if they don’t rely on each other?

Phuong Le (@func25)
Level Up Coding
Published in
5 min read18 hours ago

--

Photo by Andrew George on Unsplash

Have you ever written a function that’s long because it does many tasks, even if they don’t rely on each other? I’ve been in your shoes.

Think about this, you have a function to do 3 things:

  • Fetching user details from a database by userID.
  • Calling an external service to get the user’s recent activity by userID
  • Accessing a logging service to get the user’s last login details by userID
func FetchUserData(userID string) error {
g := errgroup.Group{}

userDetail, _ := fetchUserDetails(userID)

userAct, _ := fetchUserActivity(userID)

userLoginInfo, _ := fetchUserLoginDetails(userID)

// ...
}

All these tasks just need the userID and don’t use data from the others.

So, doing them at the same time would save time, right? you may try using goroutines for this, but you need to handle the details yourself. Let’s answer these question:

  • Synchronize: How do you make sure everything finishes?
  • Error handling: What do you do if one task goes wrong? Or if two out of three don’t work?
  • Cancellation: If one task has a problem, how do you stop all the other running goroutines?
  • Limiting: Have you thought about setting a limit on how many goroutines run at the same time?
  • Reusuable: Once you find a solution, how can you use it again in similar situations?

There’s a lot to think about, right? What if I told you there’s already a solution for this? A tool you can use in many parts of your code. Let’s talk about errgroup, learn how to use it, and find out why it can help.

1. What is errgroup?

The errgroup package lets you handle many tasks at once.

It makes it easy to run things together in a safe way, keep them in sync, deal with errors, and control when to stop…