Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using memcache.add() instead of set()

Usually I do:

if not memcache.get('mykey'):
   memcache.set('mykey', item)

However, today I saw memcache.add(), which appears to add an item only if it doesn't already exist. So is this equivalent to the code I have above? Can I just replace the code above with memcache.add()?

Also, and more importantly, I'm using AppStats, and under RPC Call Traces, I get to see if my request calls memcache.set() or get() or datastore.put() or get(). When using the 2 lines of code above, I don't see anything for memcache.set(), which is expected. However, using only memcache.add() (without checking if the item already exists) always calls memcache.set(), even though memcache.add() returned false (meaning a new item was not inserted). Why is this the case?

like image 794
Snowman Avatar asked Nov 05 '12 14:11

Snowman


People also ask

Does memcached support TTL?

The maximum expiration period supported by memcached is 2592000 (30 days: 60*60*24*30 ). For some reason, when I instantiate a MemCacheStore with that period and try to write keys, I get a warning that 2592300 exceeds the maximum Memcache TTL.

What is Memcached in Python?

Memcached is a highly-performant distributed caching system. It is an in-memory key-value data store, which makes it a type of NoSQL database. Memcached is used by tech giants like Facebook, Twitter, Instagram, and Netflix.


1 Answers

Your current code has a race condition: between checking for the presence of a value in memcache and inserting it, another process could have inserted a value, which you'll now overwrite. Using memcache.add does not suffer from this race condition.

I'm not sure what you mean by your second question; calling memcache.add should result only in an add call, never a set call. Can you include the code you're running in that case?

like image 100
Nick Johnson Avatar answered Oct 03 '22 06:10

Nick Johnson