Sobes.tech
Middle+

Racontes-moi la dernière erreur — qu'est-ce qui s'est passé, comment l'avez-vous trouvée et comment l'avez-vous résolue?

sobes.tech AI

Vastus AI-lt

In one of our recent projects in Go, we encountered a memory leak issue in a service that processed a large number of parallel requests. The system started to slow down gradually and eventually crashed with an out-of-memory error.

The cause was incorrect use of goroutines: we launched a goroutine for each request but did not control their completion nor free resources associated with the context.

The problem was detected using the pprof profiler, which showed an increase in the number of goroutines and memory consumption.

Solution:

  • Added a context with timeout and cancellation for goroutines.
  • Rewrote request handling to ensure goroutine completion.
  • Implemented a goroutine pool to limit the maximum number of concurrently running goroutines.

Example of using context to cancel a goroutine:

ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
go func(ctx context.Context) {
    select {
    case <-ctx.Done():
        // cleanup and termination
        return
    // processing
    }
}(ctx)