Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fetch executes fallback if cached value is nil #285

Closed
karlseguin opened this issue May 12, 2022 · 3 comments
Closed

fetch executes fallback if cached value is nil #285

karlseguin opened this issue May 12, 2022 · 3 comments

Comments

@karlseguin
Copy link

I couldn't find this behavior documented anywhere. The documentation says that the fallback should only be executed "on cache miss". This doesn't seem to be the case though. Obviously it has to do with the fact that get/2 returns {:ok, nil} which is the condition to execute the fallback.

If nil cannot be used as a value, I think it's worth highlighting in the documentation.

> import Cachex.Spec
> Cachex.start_link(:cache, limit: 100, expiration: expiration(default: 10000000))            
{:ok, #PID<0.462.0>}

> Cachex.ttl(:cache, "key")
{:ok, nil}

> Cachex.put(:cache, "key", nil)
{:ok, true}

> Cachex.ttl(:cache, "key")     
{:ok, 9998680}

> Cachex.fetch(:cache, "key", fn -> raise "should not be called" end)             
{:error, "should not be called"}
@whitfin
Copy link
Owner

whitfin commented May 31, 2022

If you want to PR this somewhere in docs, go ahead. The use of nil generally represents no value, so putting nil into the cache is a weird pattern in the first place; the only case I can think of is checking presence, in which case using something like true is probably better.

It's pretty much just a side effect from ETS itself, it's not something done in this lib. If an empty key comes back from ETS, it's nil. There's no other way to communicate a cache miss other than nil.

@whitfin
Copy link
Owner

whitfin commented Jan 30, 2023

I'm going to close this out, because this is pretty much ETS behaviour. If someone places nil in ETS, it's pretty much the same as nothing being there. There's a chance we can figure out a good way to work around it if more people need it, but I would suggest using something other than nil!

@whitfin whitfin closed this as completed Jan 30, 2023
@axelson
Copy link

axelson commented Dec 17, 2023

@whitfin I just spent a good amount of time trying to figure out why values that I expected to be cached were not in fact cached. I wonder if a way to surfaced this issue to users would be to log a warning when the fetch fallback function returns: {:commit, nil} since that result will not actually be committed to the cache. Any thoughts?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants