Questions about Cachex

Hello!

Sorry if this is obvious, but I couldn’t find an answer in the docs.

I am using the Cachex library. How does one go about locking a row? Is it done via transaction/4? Is there a more lightweight version where I can just lock a row, perform some operation, and then unlock it?

Thanks!

1 Like

If by locking a row you mean locking a key/value entry? That would be an Action Block. The execution block just runs the code in the context of the cache itself, thus much faster, though not transactional across ‘everything’, the transactional is transactional on the state of the cache however. Or are you referencing something?

Yes! Sorry for not being clear, I mean locking writes (but not reads) for a certain key.

So Action block would be the way to go? Basically I want to do something like:

lock(:my_cache, key)
Cachex.get_and_update(:my_cache, key, fn value -> {:commit, value+1} end)
unlock(:my_cache, key)

Looks like Action Block suggests using execute/3. But I am not sure I see how it would prevent other processes from overwriting the key’s value in between the read and write.

That’s what the Action Block transaction would be. execute just runs in the cache process for speed, but does not synchronization, transaction is what does synchronization. :slight_smile:

2 Likes

Cool! So just to confirm, that is Cachex.transaction/4 right?

Thanks!

Or /3 if no options needed yep:
https://hexdocs.pm/cachex/action-blocks.html#transaction-blocks
https://hexdocs.pm/cachex/Cachex.html#transaction/4

2 Likes

Perfect, thanks @OvermindDL1!

1 Like

Just for posterity’s sake, Cachex.get_and_update/4 has an implicit transaction underneath. So for this particular operation, transactions are not needed, but @OvermindDL1 's answer is the way to go for operations that do need transactions.

1 Like