![]() ![]() It performs several critical functions for us: The derived Context is canceled the first time a function passed to Go returns a non-nil error or the first time Wait returns, whichever occurs first.Ĭreate a new Group and associated context:Īn errgroup.Group unifies error propagation and context cancelation. WithContext returns a new Group and an associated Context derived from ctx. What is an error group? As the doc states:Ī Group is a collection of goroutines working on subtasks that are part of the same overall task. This is where errgroup.WithContext() becomes our best friend. In the real world, returning partial results is often better than failing completely, but for our example, let’s assume that if any part of the process fails, we’d like to immediately exit the entire operation and return the error for whatever piece failed. Any of these individual network calls might fail, time out, or otherwise produce an error. (Note that in this trivial example, we could have just used a sync.Mutex to update the response object directly from the mappers but for the purposes of illustration let’s have a separate reducer routine.) Using errgroupĪs you may have surmised from the code comments, we have a problem-no error propagation. Everything happens with maximum concurrency. The mappers submit each friend profile to the final reducer. Each mapper looks up a single profile at a time, so we can look up as many profiles at a time as we have mappers. This executes much faster! Using a channel, we pass each friend id along to multiple mapper routines as soon as we get it. (Once upon a time, this might have been done in SQL with a table join, but in the era of microservices, let’s assume the Friend and Profile services are two different things.) Here’s a simple implementation of the server logic. To get the actual details (like name, email, etc), we look up each friend’s id with the Profile service. In our system, each user has a list of friend ids which refer to another user, and we can get a friend id iterator from the Friend service. Suppose we have a web app that produces a list of friends for the logged in user. If this sounds familiar, let me introduce you to your new friend, errgroup.WithContext() found in /x/sync/errgroup. Have you ever written a Go server handler that could be parallelized, but you left it as a linear sequence of operations? Parallelizing your Go server handlers can provide a huge improvement in end user latency, but it’s easy to pass up the opportunity because it seems like managing goroutines, correctly propagating errors and values, and cleaning up afterwards isn't worth the extra code complexity. How you can shave a few more precious milliseconds off end user latency by parallelizing your Go server handlers. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |