Skip to content

Lock-per-key functionality when using custom loader functions #122

@lukasbindreiter

Description

@lukasbindreiter

Hi,

I was skimming through the code a little bit, trying to figure out if there is support for a use case for locking just a specific key in the cache while a custom loader (thats slow, like e.g. making an HTTP request) is running.

For example, imaging something like this:

websiteLoader := ttlcache.LoaderFunc[string, string](
	func(c *ttlcache.Cache[string, string], key string) *ttlcache.Item[string, string] {
		// load website content
                content := ...  // make http request to fetch url=key
		item := c.Set(key, content)
		return item
	},
)
websiteCache := ttlcache.New[string, string](
	ttlcache.WithLoader[string, string](loader),
)

Now imagine I have three goroutines called at the exact same time:

// goroutine1
content := websiteCache.Get("https://www.some.site")
// goroutine2
content := websiteCache.Get("https://www.other.site")
// goroutine3
content := websiteCache.Get("https://www.some.site")

Is there a way to add a lock-per-cache-key, e.g. to make goroutine3 block while goroutine1 is still running, but let goroutine2 continue as normal? From what I saw in the code, I think not, right?

There is a lockAndLoad parameter here, but if I understood this correctly it locks the whole cache, so in the above example goroutine2 would block while goroutine1 is running, right?

Do you think this would be a feature worth adding?
I was thinking about implementing a wrapper around ttlcache that supports something like that, but then I thought this could be a potential useful feature in general?

Of course one thing about this is that error handling is maybe a bit unclear then, so I also see an argument that this is already too much magic happening by the cache, instead of letting the user implement it, but I would be interested in opinions in any case.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions