DEV Community

Dmitry Maslyukov
Dmitry Maslyukov

Posted on

I have created yet another cache go library

I have recently been frustrated by one thing: there is practically no library for caching singleton values.

The thing is most caches are designed to keep a lot of things in one caching container.

What if I did not need the key-value generic map?
So on one hand there was complexity and generic implementations of caching with ttl, but nevertheless well-maintained, but on the other hand there were no solutions for caching singletons.

So I have decided to create one myself. This was not very painful, but I feel strange that practically no-one has done this before.

Sincerely, I am writing this post in a thought that someone comes across it and has same demand.

I will be happy to get someone's day easier. Do not spend AI tokens for this boilerplate, just download it.

The license is MIT, so you can use, fork or do whatever you want in any kind of product.

GitHub logo maslyukov0 / single_value_cache

Blazingly fast library that allows safe singleton caches. Built with generics and type safety

Single Value Cache

This is a tiny, focused Go library designed for those moments when you need to cache just one thing the best way, that cache libraries do not provide.

Whether it's a configuration object, a token, or a result from a heavy database query, this library helps you handle it without the boilerplate of a full-blown key-value store.

Why use this?

Caching can be tricky. You often have to deal with:

  • Race conditions: Multiple goroutines trying to update the same value.
  • Thundering herds: A sudden spike in requests when the cache expires, all hitting your database at once.
  • Type safety: Casting any back and forth.

This library solves these problems by combining Generics, TTL (Time-To-Live), and Singleflight protection in a simple, human-friendly package.

Features

  • Type Safe: Built with Go Generics, so no more type assertions.
  • Smart Loading: Using golang.org/x/sync/singleflight, it ensures that even if 100…


package your_best_program

import "github.com/maslyukov0/single_value_cache"

func loadData(ctx context.Context) (int, error) {
    select {
    case <- time.After(time.Minute):
       return 42
    case <- ctx.Done():
       return errors.New("my most liked error")
    }
}

var cache = cache.NewSingleValueCache[int](time.Hour, loadData)

func main() {

    // It will propagate context.Cancelled or any other error from    your loader
    value, err := cache.Get(context.Background())
    fmt.Printf("Value = %v, error = %v\n", value, err)
}


Enter fullscreen mode Exit fullscreen mode

As you can see, it is simple as hell.

I have already got it into action into product I am building: there is a domain access whitelist and it works fine.

Also feel free to open an issue or comment a question.

Happy developing day!

Top comments (0)