singleflightx

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Sep 11, 2026 License: MIT Imports: 7 Imported by: 8 modules, 7 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-singleflightx

tag Go Version GoDoc Build Status Go report Coverage Contributors License

x/sync/singleflight but better

✨ Features

This library is inspired by x/sync/singleflight but adds many features:

  • 🧬 generics: type-safe API, no interface{} boxing overhead
  • 🍱 batching: fetch multiple keys in a single callback, with in-flight deduplication
  • 📭 nullable result
  • 🍕 sharded groups
  • ⏱️ per-caller timeout/cancellation, without interrupting other callers sharing the same call
Performance

x/sync/singleflight uses any (aka interface{}) for return values, which means every value must be boxed into an interface on write and type-asserted on read. For value types (structs, ints, etc.), boxing triggers a heap allocation and increases GC pressure — an unnecessary cost in high-throughput or high-concurrency paths.

go-singleflightx uses Go generics so values are stored and returned as their concrete types, eliminating interface boxing and the associated allocations entirely.

🚀 Install

go get github.com/samber/go-singleflightx

This library is v1 and follows SemVer strictly.

No breaking changes will be made to exported APIs before v2.0.0.

💡 Doc

GoDoc: https://pkg.go.dev/github.com/samber/go-singleflightx

🔥 Examples

Here is an example of a user retrieval in a caching layer:

import "github.com/samber/go-singleflightx"

func getUsersByID(userIDs []string) (map[string]User, error) {
    users := []User{}

    // 📍 SQL query here...
    err := sqlx.Select(&users, "SELECT * FROM users WHERE id IN (?);", userIDs...)
    if err != nil {
        return nil, err
    }

    var results = map[string]User{}
    for _, u := range users {
        results[u.ID] = u
    }

    return results, nil
}

func main() {
    var g singleflightx.Group[string, User]

    // 👇 concurrent queries will be dedup
    output := g.DoX([]string{"user-1", "user-2"}, getUsersByID)
}

output is of type map[K]singleflightx.Result[V], and will always have as many entries as requested, whatever the callback result.

type Result[V any] struct {
  	 Value  singleflightx.NullValue[V]  // 💡 A result is considered "null" if the callback did not return it.
  	 Err    error
  	 Shared bool
}

type NullValue[V any] struct {
	Value V
	Valid bool
}
Per-caller timeout, with DoContext / DoXContext

DoContext, DoChanContext, DoXContext and DoChanXContext accept a context.Context that bounds only the calling goroutine's wait — not the shared callback. If a caller's context is done before the callback returns, that caller gets the context's error immediately; every other caller attached to the same key keeps waiting for the real result, and the callback keeps running for them.

The callback's own context is only canceled once every caller of that key has stopped waiting for it (a plain, non-context Do/DoX caller never leaves early, so it always keeps the callback running for as long as it is attached).

var g singleflightx.Group[string, User]

ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
defer cancel()

// If ctx expires, this call returns ctx.Err() right away, but the callback
// keeps running in case another caller is still waiting on "user-1".
user, err, shared := g.DoContext(ctx, "user-1", func(ctx context.Context) (User, error) {
    // 📍 SQL query here...
    var user User
    err := sqlx.GetContext(ctx, &user, "SELECT * FROM users WHERE id = ?;", "user-1")
    return user, err
})
// Same bound, applied per key: a key already resolved keeps its real
// result even if ctx expires before the whole batch completes.
output := g.DoXContext(ctx, []string{"user-1", "user-2"}, func(ctx context.Context, userIDs []string) (map[string]User, error) {
    return getUsersByID(userIDs)
})
Sharded groups, for high contention/concurrency environments
g := singleflightx.NewShardedGroup[K string, User](10, func (key string) uint {
    h := fnv.New64a()
    h.Write([]byte(key))
    return uint(h.Sum64())
})

// as usual, but if the keys match different shards, getUsersByID will be called twice
output := g.DoX([]string{"user-1", "user-2"}, getUsersByID) 
go-singleflightx + go-batchify

go-batchify groups concurrent tasks into a single batch. By adding go-singleflightx, you will be able to dedupe

import (
    "golang.org/x/sync/singleflight"
    "github.com/samber/go-batchify"
)

var group singleflight.Group

batch := batchify.NewBatchWithTimer(
    10,
    func (ids []int) (map[int]string, error) {
        return ..., nil
    },
    5*time.Millisecond,
)

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    idStr := r.URL.Query().Get("id")
    id, _ := strconv.Atoi(idStr)

    value, err, _ = group.Do(idStr, func() (interface{}, error) {
        return batch.Do(id)
    })

    // ...
})

🤝 Contributing

Don't hesitate ;)

# Install some dev dependencies
make tools

# Run tests
make test
# or
make watch-test

👤 Contributors

Contributors

💫 Show your support

Give a ⭐️ if this project helped you!

GitHub Sponsors

📝 License

Copyright © 2023 Samuel Berthe.

This project is MIT licensed.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Group

type Group[K comparable, V any] struct {
	// contains filtered or unexported fields
}

Group represents a class of work and forms a namespace in which units of work can be executed with duplicate suppression.

func (*Group[K, V]) Do

func (g *Group[K, V]) Do(key K, fn func() (V, error)) (v V, err error, shared bool)

Do executes and returns the results of the given function, making sure that only one execution is in-flight for a given key at a time. If a duplicate comes in, the duplicate caller waits for the original to complete and receives the same results. The return value shared indicates whether v was given to multiple callers.

func (*Group[K, V]) DoChan

func (g *Group[K, V]) DoChan(key K, fn func() (V, error)) <-chan Result[V]

DoChan is like Do but returns a channel that will receive the results when they are ready.

The returned channel will not be closed.

func (*Group[K, V]) DoChanContext added in v1.0.0

func (g *Group[K, V]) DoChanContext(ctx context.Context, key K, fn func(context.Context) (V, error)) <-chan Result[V]

DoChanContext is like DoChan, but ctx bounds only this caller's channel: if ctx is done before fn returns, the returned channel receives ctx's error instead of fn's result. See DoContext for how fn's own cancellation is derived.

The returned channel will not be closed.

func (*Group[K, V]) DoChanX

func (g *Group[K, V]) DoChanX(keys []K, fn func([]K) (map[K]V, error)) map[K]chan Result[V]

DoChanX is like Do but returns a channel that will receive the results when they are ready.

The returned channel will not be closed.

func (*Group[K, V]) DoChanXContext added in v1.0.0

func (g *Group[K, V]) DoChanXContext(ctx context.Context, keys []K, fn func(context.Context, []K) (map[K]V, error)) map[K]chan Result[V]

DoChanXContext is like DoChanX, but ctx bounds the wait for every key in this call: once ctx is done, the channels for keys still in flight receive ctx's error instead of fn's result. See DoXContext for how fn's own cancellation is derived.

The returned channels will not be closed.

func (*Group[K, V]) DoContext added in v1.0.0

func (g *Group[K, V]) DoContext(ctx context.Context, key K, fn func(context.Context) (V, error)) (v V, err error, shared bool)

DoContext is like Do, but the wait is bounded by ctx: if ctx is done before fn returns, DoContext returns immediately with ctx's error and shared reports whether any other caller was also attached to this key at that moment.

fn itself is not necessarily interrupted: it keeps running for every other caller still attached to the same key. It only receives a canceled context once every caller of this key — across every variant, context-aware or not — has stopped waiting. That context carries the values (but never the cancellation) of whichever caller happened to start it, since fn is shared and must not depend on a single caller's deadline or lifetime.

A plain Do call joining the same key never leaves early, so it prevents fn from ever being interrupted while it is attached.

func (*Group[K, V]) DoX

func (g *Group[K, V]) DoX(keys []K, fn func([]K) (map[K]V, error)) (results map[K]Result[V])

DoX executes and returns the results of the given function, making sure that only one execution is in-flight for a given key at a time. If a duplicate comes in, the duplicate caller waits for the original to complete and receives the same results. The return value shared indicates whether v was given to multiple callers. Even if fn does not return V on some keys, the results map will contain those keys with a `Valid` field set to false.

func (*Group[K, V]) DoXContext added in v1.0.0

func (g *Group[K, V]) DoXContext(ctx context.Context, keys []K, fn func(context.Context, []K) (map[K]V, error)) map[K]Result[V]

DoXContext is like DoX, but ctx bounds the wait for every key in this call. Once ctx is done, keys still in flight get ctx's error immediately; keys that already completed keep their real result. See DoContext for how fn's own cancellation is derived — for a batch, fn shares one context across every key it is asked to resolve, canceled only once every caller of every key in the batch has stopped waiting.

func (*Group[K, V]) Forget

func (g *Group[K, V]) Forget(key K)

Forget tells the singleflight to forget about a key. Future calls to Do for this key will call the function rather than waiting for an earlier call to complete.

func (*Group[K, V]) ForgetX added in v0.3.0

func (g *Group[K, V]) ForgetX(keys []K)

ForgetX tells the singleflight to forget about many keys. Future calls to Do for this key will call the function rather than waiting for an earlier call to complete.

type Hasher added in v0.2.0

type Hasher[K any] func(key K) uint64

Hasher is responsible for generating unsigned, 16 bit hash of provided key. Hasher should minimize collisions. For great performance, a fast function is preferable.

type NullValue

type NullValue[V any] struct {
	Value V
	Valid bool // Valid is true if Value is not NULL
}

NullValue represents a V that may be null.

type Result

type Result[V any] struct {
	Value  NullValue[V]
	Err    error
	Shared bool
}

Result holds the results of Do, so they can be passed on a channel.

type ShardedGroup added in v0.2.0

type ShardedGroup[K comparable, V any] struct {
	// contains filtered or unexported fields
}

ShardedGroup is a duplicate of singleflight.Group, but with the ability to shard the map of calls.

func NewShardedGroup added in v0.2.0

func NewShardedGroup[K comparable, V any](count uint, hasher Hasher[K]) *ShardedGroup[K, V]

func (*ShardedGroup[K, V]) Do added in v0.2.0

func (sg *ShardedGroup[K, V]) Do(key K, fn func() (V, error)) (v V, err error, shared bool)

Do executes and returns the results of the given function, making sure that only one execution is in-flight for a given key at a time. If a duplicate comes in, the duplicate caller waits for the original to complete and receives the same results. The return value shared indicates whether v was given to multiple callers. Even if fn does not return V on some keys, the results map will contain those keys with a `Valid` field set to false.

func (*ShardedGroup[K, V]) DoChan added in v0.2.0

func (sg *ShardedGroup[K, V]) DoChan(key K, fn func() (V, error)) <-chan Result[V]

DoChan is like Do but returns a channel that will receive the results when they are ready.

The returned channel will not be closed.

func (*ShardedGroup[K, V]) DoChanContext added in v1.0.0

func (sg *ShardedGroup[K, V]) DoChanContext(ctx context.Context, key K, fn func(context.Context) (V, error)) <-chan Result[V]

DoChanContext routes to the shard responsible for key. See Group.DoChanContext.

The returned channel will not be closed.

func (*ShardedGroup[K, V]) DoChanX added in v0.2.0

func (sg *ShardedGroup[K, V]) DoChanX(keys []K, fn func([]K) (map[K]V, error)) map[K]chan Result[V]

DoChanX is like Do but returns a channel that will receive the results when they are ready.

The returned channel will not be closed.

func (*ShardedGroup[K, V]) DoChanXContext added in v1.0.0

func (sg *ShardedGroup[K, V]) DoChanXContext(ctx context.Context, keys []K, fn func(context.Context, []K) (map[K]V, error)) map[K]chan Result[V]

DoChanXContext routes keys to their shards, calling fn once per shard they span. See Group.DoChanXContext.

The returned channels will not be closed.

func (*ShardedGroup[K, V]) DoContext added in v1.0.0

func (sg *ShardedGroup[K, V]) DoContext(ctx context.Context, key K, fn func(context.Context) (V, error)) (v V, err error, shared bool)

DoContext routes to the shard responsible for key. See Group.DoContext.

func (*ShardedGroup[K, V]) DoX added in v0.2.0

func (sg *ShardedGroup[K, V]) DoX(keys []K, fn func([]K) (map[K]V, error)) (results map[K]Result[V])

DoX executes and returns the results of the given function, making sure that only one execution is in-flight for a given key at a time. If a duplicate comes in, the duplicate caller waits for the original to complete and receives the same results. The return value shared indicates whether v was given to multiple callers.

func (*ShardedGroup[K, V]) DoXContext added in v1.0.0

func (sg *ShardedGroup[K, V]) DoXContext(ctx context.Context, keys []K, fn func(context.Context, []K) (map[K]V, error)) map[K]Result[V]

DoXContext routes keys to their shards, calling fn once per shard they span, and reports each key's result the same way Group.DoXContext does — except a panic or runtime.Goexit in fn is always delivered as a Result here (as DoChanXContext already does), never re-raised in the caller's own goroutine, since this method is built on the channel-based DoChanXContext.

func (*ShardedGroup[K, V]) Forget added in v0.3.0

func (sg *ShardedGroup[K, V]) Forget(key K)

Forget tells the singleflight to forget about a key. Future calls to Do for this key will call the function rather than waiting for an earlier call to complete.

func (*ShardedGroup[K, V]) ForgetX added in v0.3.0

func (sg *ShardedGroup[K, V]) ForgetX(keys []K)

ForgetX tells the singleflight to forget about many keys. Future calls to Do for this key will call the function rather than waiting for an earlier call to complete.

Jump to

Keyboard shortcuts

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