[caching] Memcached vs. Redis?

We're using a Ruby web-app with Redis server for caching. Is there a point to test Memcached instead?

What will give us better performance? Any pros or cons between Redis and Memcached?

Points to consider:

  • Read/write speed.
  • Memory usage.
  • Disk I/O dumping.
  • Scaling.

This question is related to caching web-applications memcached redis

The answer is


I got the opportunity to use both memcached and redis together in the caching proxy that i have worked on , let me share you where exactly i have used what and reason behind same....

Redis >

1) Used for indexing the cache content , over the cluster . I have more than billion keys in spread over redis clusters , redis response times is quite less and stable .

2) Basically , its a key/value store , so where ever in you application you have something similar, one can use redis with bothering much.

3) Redis persistency, failover and backup (AOF ) will make your job easier .

Memcache >

1) yes , an optimized memory that can be used as cache . I used it for storing cache content getting accessed very frequently (with 50 hits/second)with size less than 1 MB .

2) I allocated only 2GB out of 16 GB for memcached that too when my single content size was >1MB .

3) As the content grows near the limits , occasionally i have observed higher response times in the stats(not the case with redis) .

If you ask for overall experience Redis is much green as it is easy to configure, much flexible with stable robust features.

Further , there is a benchmarking result available at this link , below are few higlight from same,

enter image description here

enter image description here

Hope this helps!!


One major difference that hasn't been pointed out here is that Memcache has an upper memory limit at all times, while Redis does not by default (but can be configured to). If you would always like to store a key/value for certain amount of time (and never evict it because of low memory) you want to go with Redis. Of course, you also risk the issue of running out of memory...


We thought of Redis as a load-takeoff for our project at work. We thought that by using a module in nginx called HttpRedis2Module or something similar we would have awesome speed but when testing with AB-test we're proven wrong.

Maybe the module was bad or our layout but it was a very simple task and it was even faster to take data with php and then stuff it into MongoDB. We're using APC as caching-system and with that php and MongoDB. It was much much faster then nginx Redis module.

My tip is to test it yourself, doing it will show you the results for your environment. We decided that using Redis was unnecessary in our project as it would not make any sense.


If you don't mind a crass writing style, Redis vs Memcached on the Systoilet blog is worth a read from a usability standpoint, but be sure to read the back & forth in the comments before drawing any conclusions on performance; there are some methodological problems (single-threaded busy-loop tests), and Redis has made some improvements since the article was written as well.

And no benchmark link is complete without confusing things a bit, so also check out some conflicting benchmarks at Dormondo's LiveJournal and the Antirez Weblog.

Edit -- as Antirez points out, the Systoilet analysis is rather ill-conceived. Even beyond the single-threading shortfall, much of the performance disparity in those benchmarks can be attributed to the client libraries rather than server throughput. The benchmarks at the Antirez Weblog do indeed present a much more apples-to-apples (with the same mouth) comparison.


Memcached is multithreaded and fast.

Redis has lots of features and is very fast, but completely limited to one core as it is based on an event loop.

We use both. Memcached is used for caching objects, primarily reducing read load on the databases. Redis is used for things like sorted sets which are handy for rolling up time-series data.


Memcached will be faster if you are interested in performance, just even because Redis involves networking (TCP calls). Also internally Memcache is faster.

Redis has more features as it was mentioned by other answers.


Redis is better.

The Pros of Redis are ,

  1. It has a lot of data storage options such as string , sets , sorted sets , hashes , bitmaps
  2. Disk Persistence of records
  3. Stored Procedure (LUA scripting) support
  4. Can act as a Message Broker using PUB/SUB

Whereas Memcache is an in-memory key value cache type system.

  1. No support for various data type storages like lists , sets as in redis.
  2. The major con is Memcache has no disk persistence .

Test. Run some simple benchmarks. For a long while I considered myself an old school rhino since I used mostly memcached and considered Redis the new kid.

With my current company Redis was used as the main cache. When I dug into some performance stats and simply started testing, Redis was, in terms of performance, comparable or minimally slower than MySQL.

Memcached, though simplistic, blew Redis out of water totally. It scaled much better:

  • for bigger values (required change in slab size, but worked)
  • for multiple concurrent requests

Also, memcached eviction policy is in my view, much better implemented, resulting in overall more stable average response time while handling more data than the cache can handle.

Some benchmarking revealed that Redis, in our case, performs very poorly. This I believe has to do with many variables:

  • type of hardware you run Redis on
  • types of data you store
  • amount of gets and sets
  • how concurrent your app is
  • do you need data structure storage

Personally, I don't share the view Redis authors have on concurrency and multithreading.


Memcached is good at being a simple key/value store and is good at doing key => STRING. This makes it really good for session storage.

Redis is good at doing key => SOME_OBJECT.

It really depends on what you are going to be putting in there. My understanding is that in terms of performance they are pretty even.

Also good luck finding any objective benchmarks, if you do find some kindly send them my way.


Use Redis if

  1. You require selectively deleting/expiring items in the cache. (You need this)

  2. You require the ability to query keys of a particular type. eq. 'blog1:posts:*', 'blog2:categories:xyz:posts:*'. oh yeah! this is very important. Use this to invalidate certain types of cached items selectively. You can also use this to invalidate fragment cache, page cache, only AR objects of a given type, etc.

  3. Persistence (You will need this too, unless you are okay with your cache having to warm up after every restart. Very essential for objects that seldom change)

Use memcached if

  1. Memcached gives you headached!
  2. umm... clustering? meh. if you gonna go that far, use Varnish and Redis for caching fragments and AR Objects.

From my experience I've had much better stability with Redis than Memcached


The biggest remaining reason is specialization.

Redis can do a lot of different things and one side effect of that is developers may start using a lot of those different feature sets on the same instance. If you're using the LRU feature of Redis for a cache along side hard data storage that is NOT LRU it's entirely possible to run out of memory.

If you're going to setup a dedicated Redis instance to be used ONLY as an LRU instance to avoid that particular scenario then there's not really any compelling reason to use Redis over Memcached.

If you need a reliable "never goes down" LRU cache...Memcached will fit the bill since it's impossible for it to run out of memory by design and the specialize functionality prevents developers from trying to make it so something that could endanger that. Simple separation of concerns.


A very simple test to set and get 100k unique keys and values against redis-2.2.2 and memcached. Both are running on linux VM(CentOS) and my client code(pasted below) runs on windows desktop.

Redis

  • Time taken to store 100000 values is = 18954ms

  • Time taken to load 100000 values is = 18328ms

Memcached

  • Time taken to store 100000 values is = 797ms

  • Time taken to retrieve 100000 values is = 38984ms


Jedis jed = new Jedis("localhost", 6379);
int count = 100000;
long startTime = System.currentTimeMillis();
for (int i=0; i<count; i++) {
  jed.set("u112-"+i, "v51"+i);
}
long endTime = System.currentTimeMillis();
System.out.println("Time taken to store "+ count + " values is ="+(endTime-startTime)+"ms");

startTime = System.currentTimeMillis();
for (int i=0; i<count; i++) {
  client.get("u112-"+i);
}
endTime = System.currentTimeMillis();
System.out.println("Time taken to retrieve "+ count + " values is ="+(endTime-startTime)+"ms");

It would not be wrong, if we say that redis is combination of (cache + data structure) while memcached is just a cache.


Another bonus is that it can be very clear how memcache is going to behave in a caching scenario, while redis is generally used as a persistent datastore, though it can be configured to behave just like memcached aka evicting Least Recently Used items when it reaches max capacity.

Some apps I've worked on use both just to make it clear how we intend the data to behave - stuff in memcache, we write code to handle the cases where it isn't there - stuff in redis, we rely on it being there.

Other than that Redis is generally regarded as superior for most use cases being more feature-rich and thus flexible.


This is too long to be posted as a comment to already accepted answer, so I put it as a separate answer

One thing also to consider is whether you expect to have a hard upper memory limit on your cache instance.

Since redis is an nosql database with tons of features and caching is only one option it can be used for, it allocates memory as it needs it — the more objects you put in it, the more memory it uses. The maxmemory option does not strictly enforces upper memory limit usage. As you work with cache, keys are evicted and expired; chances are your keys are not all the same size, so internal memory fragmentation occurs.

By default redis uses jemalloc memory allocator, which tries its best to be both memory-compact and fast, but it is a general purpose memory allocator and it cannot keep up with lots of allocations and object purging occuring at a high rate. Because of this, on some load patterns redis process can apparently leak memory because of internal fragmentation. For example, if you have a server with 7 Gb RAM and you want to use redis as non-persistent LRU cache, you may find that redis process with maxmemory set to 5Gb over time would use more and more memory, eventually hitting total RAM limit until out-of-memory killer interferes.

memcached is a better fit to scenario described above, as it manages its memory in a completely different way. memcached allocates one big chunk of memory — everything it will ever need — and then manages this memory by itself, using its own implemented slab allocator. Moreover, memcached tries hard to keep internal fragmentation low, as it actually uses per-slab LRU algorithm, when LRU evictions are done with object size considered.

With that said, memcached still has a strong position in environments, where memory usage has to be enforced and/or be predictable. We've tried to use latest stable redis (2.8.19) as a drop-in non-persistent LRU-based memcached replacement in workload of 10-15k op/s, and it leaked memory A LOT; the same workload was crashing Amazon's ElastiCache redis instances in a day or so because of the same reasons.


Here is the really great article/differences provided by Amazon

Redis is a clear winner comparing with memcached.

Only one plus point for Memcached It is multithreaded and fast. Redis has lots of great features and is very fast, but limited to one core.

Great points about Redis, which are not supported in Memcached

  • Snapshots - User can take a snapshot of Redis cache and persist on secondary storage any point of time.
  • Inbuilt support for many data structures like Set, Map, SortedSet, List, BitMaps etc.
  • Support for Lua scripting in redis

Examples related to caching

Disable nginx cache for JavaScript files How to prevent Browser cache on Angular 2 site? Curl command without using cache Notepad++ cached files location Laravel 5 Clear Views Cache Write-back vs Write-Through caching? Tomcat 8 throwing - org.apache.catalina.webresources.Cache.getResource Unable to add the resource Chrome - ERR_CACHE_MISS How do I use disk caching in Picasso? How to clear gradle cache?

Examples related to web-applications

Spring - No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call How do I choose the URL for my Spring Boot webapp? Difference between MEAN.js and MEAN.io External VS2013 build error "error MSB4019: The imported project <path> was not found" How to unpackage and repackage a WAR file IntelliJ, can't start simple web application: Unable to ping server at localhost:1099 Using form input to access camera and immediately upload photos using web app Pass user defined environment variable to tomcat ASP.NET: HTTP Error 500.19 – Internal Server Error 0x8007000d Best practices when running Node.js with port 80 (Ubuntu / Linode)

Examples related to memcached

Curl command without using cache get all keys set in memcached Memcached vs. Redis? configure: error: C compiler cannot create executables How to stop and restart memcached server? PHP memcached Fatal error: Class 'Memcache' not found Apache is "Unable to initialize module" because of module's and PHP's API don't match after changing the PHP configuration Memcache Vs. Memcached When should I use Memcache instead of Memcached? Good examples of python-memcache (memcached) being used in Python?

Examples related to redis

System has not been booted with systemd as init system (PID 1). Can't operate Could not connect to Redis at 127.0.0.1:6379: Connection refused with homebrew How to connect to remote Redis server? WRONGTYPE Operation against a key holding the wrong kind of value php How to store and retrieve a dictionary with redis Start redis-server with config file Linux - Install redis-cli only how to check redis instance version? MISCONF Redis is configured to save RDB snapshots How to get all keys with their values in redis