How stampede protection works with GetOrFetchBatch
mainFor batch operations, sturdyc provides stampede protection by deduplicating cache misses across multiple batches.
If several concurrent requests (via GetOrFetchBatch) contain overlapping IDs that are currently being fetched, the cache will:
- Deduplicate the misses.
- Assemble the response for each caller by picking records from multiple in-flight requests.
This allows the cache to resolve requests for IDs that belong to different in-flight batches without generating any additional outgoing requests to the data source.
// Example of a batch fetch function
var count atomic.Int32
fetchFn := func(_ context.Context, ids []string) (map[string]int, error) {
count.Add(1)
time.Sleep(time.Second * 5)
response := make(map[string]int, len(ids))
for _, id := range ids {
num, _ := strconv.Atoi(id)
response[id] = num
}
return response, nil
}
// Requesting batches concurrently
for _, batch := range batches {
go func() {
res, _ := cacheClient.GetOrFetchBatch(context.Background(), batch, keyPrefixFn, fetchFn)
log.Printf("got batch: %v\n", res)
}()
}