← All posts

Simplify Concurrency in Go with Sourcegraph/conc

goconcurrencysourcegraphgoroutinebackend

Go gives you a strong foundation for concurrency, but working with goroutines, channels and wait groups can get messy. Sourcegraph/conc is a library that cleans up that mess and makes concurrency in Go easier to work with. In this post we'll go over the core features of Sourcegraph/conc, why it's worth using, and how it works through practical examples.

What Is Sourcegraph/conc?

Sourcegraph/conc is an open source concurrency library for Go. Instead of replacing Go's built-in concurrency tools (goroutines, channels), it adds a practical layer on top of them. It gives you an API that simplifies things like manual coordination with wait groups, catching panics, and context integration.

Core Features:

  1. Task Coordination: Runs multiple tasks in parallel and waits for them to finish, with panics caught automatically.
  2. Panic Protection: Panics in goroutines don't crash the program, they are returned as errors.
  3. Context Support: Fully compatible with Go's context package, so timeouts and cancellation are easy to handle.
  4. Flexibility: Covers a wide range of use cases, from simple parallel tasks to complex workflows.

In backend applications, for example when fetching data from several APIs or processing files, conc makes management much easier.

Why Should You Use Sourcegraph/conc?

Go's concurrency model is flexible, but the low-level tools sometimes need too much boilerplate. For example, coordinating goroutines with sync.WaitGroup means tracking things by hand, and a single panic can take down the whole program. Sourcegraph/conc solves these problems and makes the code simpler, safer and easier to read.

Advantages:

  • Less Boilerplate: Replaces complex coordination patterns with a few lines of code.
  • Safety: Panics are caught as errors, so the application stays stable.
  • Readability: The code becomes cleaner and easier to maintain.
  • Performance and Flexibility: Works well for anything from small tasks to large-scale workflows.

Getting Started with Sourcegraph/conc

To add the library to your project:

bash
go get github.com/sourcegraph/conc

Below are two practical examples showing how to use Sourcegraph/conc. They are inspired by the Sourcegraph/conc README.

Example 1: Parallel API Calls and Panic Protection

Say you want to fetch data from several APIs. Normally this takes sync.WaitGroup, goroutines and extra code for panic protection. With Sourcegraph/conc the process is pretty simple:

main.gogo
package main

import (
	"context"
	"fmt"
	"time"
	"github.com/sourcegraph/conc/pool"
)

func fetchAPI(ctx context.Context, endpoint string) (string, error) {
	time.Sleep(100 * time.Millisecond) // Simulated API call
	if endpoint == "api3" {
		panic("API 3 failed!")
	}
	return fmt.Sprintf("data received from %s", endpoint), nil
}

func main() {
	ctx := context.Background()
	p := pool.New().WithErrors().WithContext(ctx)

	for _, endpoint := range []string{"api1", "api2", "api3"} {
		endpoint := endpoint // Capture the range variable
		p.Go(func(ctx context.Context) error {
			data, err := fetchAPI(ctx, endpoint)
			if err != nil {
				return err
			}
			fmt.Println(data)
			return nil
		})
	}

	if err := p.Wait(); err != nil {
		fmt.Printf("Error: %v\n", err)
	}
}

Code Explanation:

  • pool.New().WithErrors().WithContext(ctx): This line creates a new task pool (pool) that can collect errors (WithErrors) and works with Go's context package (WithContext). This makes task cancellation and timeouts easy to manage.
  • p.Go(func(ctx context.Context) error { ... }): For each API endpoint, this function starts a parallel goroutine. The conc library automatically catches any panic that happens inside that goroutine and returns it as an error.
  • p.Wait(): Waits for all started goroutines to finish. If any task returns an error or panics, p.Wait() returns that error.

In this code, even though the "api3" endpoint panics, conc catches it gracefully. The results of the other API calls are printed, and the panic is reported as an error without crashing the program. You don't need manual defer or recover statements, so the code stays cleaner and easier to manage.

Example 2: Limiting Concurrency with a Worker Pool

When you want to process a large set of files, it can help to limit concurrency. For example, you want to process 100 files with 5 workers instead of all at once:

main.gogo
package main

import (
	"context"
	"fmt"
	"github.com/sourcegraph/conc/pool"
)

func processFile(ctx context.Context, file string) error {
	fmt.Printf("processing %s\n", file)
	return nil
}

func main() {
	ctx := context.Background()
	p := pool.New().WithMaxConcurrency(5).WithContext(ctx)

	files := []string{"file1.txt", "file2.txt" /* ... up to file100.txt */ }
	for _, file := range files {
		file := file // Capture the range variable
		p.Go(func(ctx context.Context) error {
			return processFile(ctx, file)
		})
	}

	if err := p.Wait(); err != nil {
		fmt.Printf("Error: %v\n", err)
	}
	fmt.Println("All files processed.")
}

Code Explanation:

  • WithMaxConcurrency(5): This method makes the task pool run at most 5 goroutines at the same time. This matters especially on systems with limited resources, or when calling external services without hitting rate limits.
  • Context Support: Thanks to WithContext(ctx), when the parent context is cancelled or times out, all active and pending tasks in the pool are cancelled too. This lets the application shut down in a controlled way.

Result: In this example conc processes the files in parallel within the given limits. The code stays simple and uses system resources efficiently. The WithMaxConcurrency option helps improve the application's performance and stability.

Advantages and Use Cases of Sourcegraph/conc

Sourcegraph/conc improves the developer experience by making concurrency management in Go easier. Use cases:

  • Parallel Data Processing: Collecting data from multiple sources (e.g. API calls).
  • File Processing: Processing large sets of files in parallel.
  • Error Handling: Handling panics and errors in one central place.
  • Resource Optimization: Limiting resource usage with worker pools.

When Should You Use It?

Sourcegraph/conc comes in when you go beyond basic goroutine usage. It's ideal when you need to coordinate lots of goroutines, protect against panics or work with context. For performance, you can tune resource usage with options like WithMaxConcurrency.

Conclusion

Sourcegraph/conc is a great tool for managing concurrency in Go in a simple, safe and powerful way. Features like pool, WithErrors, WithContext and WithMaxConcurrency simplify complex concurrency scenarios. Depending on what your project needs, you can use this library to make your code more readable and robust.

Task Pool Structure

The Mermaid diagram below shows how the Sourcegraph/conc task pool works:

graph TD
    A[Main Program] --> B[conc.Pool]
    B --> C[Goroutine 1]
    B --> D[Goroutine 2]
    B --> E[Goroutine 3]
    C --> F[p.Wait]
    D --> F
    E --> F
    F --> R[Collected Errors]
    R --> A
    B --> G[Timeout/Cancel]
    G --> F

Resources:

Sourcegraph/conc GitHub

Go Concurrency Documentation