Tesserex
Tesserex

Reputation: 17314

Memcache with transactions?

Although I couldn't find anything on it, I thought I would double check - does memcache support transactions?

If not, which I'm betting is the likely answer, then what is the correct method to work with memcache in an environment with transactions? Wouldn't you have to read from the DB every time you plan to update, even if the data is in cache, just so you can set your locks? For example, a script that updates some data would look like this:

  1. BEGIN; SELECT ... FOR UPDATE;
  2. Calculate...
  3. UPDATE TABLE ...;
  4. Update cache
  5. COMMIT;

I think you have to update cache after you run your update query, in case you hit a deadlock and need to rollback. But you should also update cache before committing, in case any other thread is waiting to read your data and may accidentally update it's cache with even newer data before you, resulting in your now-out-of-date data overwriting it.

Is this the correct sequence of steps? Is there any way to not have to hit the db on reads for update?

Upvotes: 6

Views: 6115

Answers (2)

Alister Bulman
Alister Bulman

Reputation: 35169

Memcache does have an operator called CAS (Check And Set - or Compare And Swap) which may help you. The PHP manual has some documentation on it, Memcached::cas, but it should also be supported in other libraries and languages.

Upvotes: 5

vissi
vissi

Reputation: 2334

Memcached does not support transactions in this sense, although its operations are atomic. You can use your database transactioning mechanism and update cache manually (as you specified), or use transactioned wrapper like this.

Upvotes: 0

Related Questions