Fetch many URLs with at most K requests in flight
Implement fetchAll: call fetch for every URL, with at most k calls running at the same time, and return the results in the order of urls. Keep up to k calls running: the next URL starts as soon as a slot frees. If a call returns an error, return nil and the first error, cancel the context passed to the other calls and start no new ones. Requirements: fetchAll returns only after every call it started has finished; cancelling the caller's ctx stops the work; no goroutine leaks; no golang.org/x/sync.
func fetchAll(ctx context.Context, urls []string, k int, fetch func(ctx context.Context, url string) (string, error)) ([]string, error) {
// your code here
}Write the implementation.
Do not add extra imports unless the task says so explicitly.
Use a buffered channel of size k as a semaphore: take a slot before starting each goroutine, release it in defer. Write results into results[i]; derive a cancellable context, cancel it on the first error, stop launching, Wait and return the error.
- Processing in batches of
k, so one slow request leaves the other slots idle - Appending results in completion order instead of writing to
results[i] - Returning on the first error without cancelling or waiting, so goroutines keep running
- How does
errgroupwithSetLimitshorten this code? - What changes if you must collect every error instead of failing fast?
Solution
The limit is a semaphore: a buffered channel of size k. A slot is taken before go and released in a defer inside the goroutine, so at most k goroutines live at once and a freed slot takes the next URL right away (batches of k cannot do that). Each result goes to results[i] — every goroutine owns its index, so no lock is needed and the order matches urls. The first error is recorded through sync.Once and calls cancel: calls in flight get a cancelled context and the launch loop stops taking URLs. When a slot is free and the context is already done, select picks either ready case at random, so after taking a slot the loop checks ctx.Err() once more: if the context is done, it gives the slot back and exits without starting a call. wg.Wait() comes before the return — otherwise the goroutines outlive the function.
func fetchAll(ctx context.Context, urls []string, k int, fetch func(ctx context.Context, url string) (string, error)) ([]string, error) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
results := make([]string, len(urls))
sem := make(chan struct{}, k)
var wg sync.WaitGroup
var once sync.Once
var firstErr error
loop:
for i, u := range urls {
select {
case sem <- struct{}{}: // take a slot
case <-ctx.Done(): // error or cancel: start nothing new
break loop
}
if ctx.Err() != nil { // got a slot, but the context is already done
<-sem
break loop
}
wg.Add(1)
go func() {
defer wg.Done()
defer func() { <-sem }() // release the slot
res, err := fetch(ctx, u)
if err != nil {
once.Do(func() { firstErr = err; cancel() })
return
}
results[i] = res
}()
}
wg.Wait()
if firstErr != nil {
return nil, firstErr
}
if err := ctx.Err(); err != nil { // cancelled from outside
return nil, err
}
return results, nil
}With golang.org/x/sync/errgroup the same takes fewer lines: g.SetLimit(k), g.Go(...), g.Wait().