sf

package
v0.30.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 4, 2026 License: MIT Imports: 1 Imported by: 0

Documentation

Overview

Package sf provides a generic single-flight mechanism for deduplicating concurrent function calls with the same key.

Single-flight ensures that only one execution of a function is in-flight for a given key at a time. If multiple goroutines call Singleflight.Do with the same key concurrently, only the first call executes the function; subsequent callers block until the first call completes and then receive the same result.

This pattern is useful for:

  • Preventing thundering herd problems on cache misses
  • Deduplicating expensive operations like database queries or API calls
  • Reducing load on backend services during traffic spikes

Usage

sf := sf.New[*User]()

// Multiple concurrent calls with the same key will only execute once
user, err := sf.Do("user:123", func() (*User, error) {
    return db.GetUser(ctx, "123")
})

The generic type parameter T allows type-safe returns without casting.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Singleflight

type Singleflight[T any] struct {
	// contains filtered or unexported fields
}

Singleflight deduplicates concurrent function calls with the same key. Only the first caller executes the function; others wait and receive the same result.

func New

func New[T any]() *Singleflight[T]

New creates a new Singleflight instance for type T.

func (*Singleflight[T]) Do

func (s *Singleflight[T]) Do(key string, fn func() (*T, error)) (*T, error)

Do executes fn for the given key, deduplicating concurrent calls. If a call is already in-flight for this key, Do blocks until it completes and returns the same result. The function fn is guaranteed to execute at most once per key at any given time.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL