Implementing a cache with Redis and Memcached is one of the most effective ways to reduce the database load and significantly increase the response speed of web applications. Both tools store data in RAM memory, thus reducing data access times from disk milliseconds to RAM microseconds. In this practical guide, we will examine the difference between these two technologies, how to install, configure securely and connect them to WordPress, Laravel and Django with real commands so that you can make the right choice for your architecture.

The main idea of ​​the object cache is simple: instead of re-executing a heavy query for each user request, the result is calculated once and stored in memory. Subsequent requests are answered directly from memory. In high-traffic sites, this can reduce the database load by 80% and make page response time several times faster.

What is the difference between Redis and Memcached?

When it comes to caching with Redis and Memcached, the first question is which one to choose. Both are key-value and memory-based, but have important differences that make the choice dependent on your scenario.

FeatureRedisMemcached
data typestring, list, hash, collection, sorted setOnly string
PersistenceYes (RDB and AOF)does not have
multithreadedMostly single-threaded (with multi-threaded I/O)Polygonal
Replicationhas (master-replica)does not have
Pub/Sub and queuehasdoes not have
Memory consumptiona little moreHighly optimized for simple data

In short, if you just need a simple thread cache with minimal overhead and you have multiple CPU cores at your disposal, Memcached is a great performer. But if you need complex data structures, job queues, pub/sub, or data persistence, Redis is a more versatile choice. In practice, Redis is more popular today due to its greater flexibility.

Redis installation and configuration

On Debian and Ubuntu based distributions, installing Redis is just a few commands. It is recommended to always use the official repository to get the new stable version:

sudo apt update
sudo apt install redis-server -y
sudo systemctl enable --now redis-server
redis-cli ping

If you get a PONG response, Redis is ready. Now we need to optimize the configuration file for the production environment.

redis.conf key settings

The configuration file is usually located at /etc/redis/redis.conf. There are three important settings to check: memory limit, deletion policy and security:

maxmemory 512mb
maxmemory-policy allkeys-lru
bind 127.0.0.1 ::1
requirepass "YourStrongPasswordHere"
appendonly yes
appendfsync everysec

The maxmemory parameter sets the Redis memory limit to prevent the server RAM from filling up. The allkeys-lru policy means that when the memory is full, the less frequently used keys are deleted; This policy is ideal for cache. Be sure to set requirepass to a strong password and keep bind to localhost unless you really need remote access.

Security Warning: An unencrypted Redis instance on the Internet is one of the most common causes of server intrusions. Attackers automatically scan port 6379. Always leave a password and close this port in the firewall.

Redis performance test

After configuration, you can measure the performance with the built-in benchmark tool:

redis-benchmark -h 127.0.0.1 -p 6379 -a YourStrongPasswordHere -q -t set,get -n 100000

On a typical virtual server, expect Redis to perform over 100,000 SET and GET operations per second. Much lower numbers can be a sign of a CPU limitation or network problem.

Install and configure Memcached

Installing Memcached is also simple. In addition to the service itself, you also need its PHP plugin:

sudo apt install memcached libmemcached-tools php-memcached -y
sudo systemctl enable --now memcached

Memcached configuration is done in /etc/memcached.conf file. The most important parameters are the amount of memory and the listening address:

-m 256
-l 127.0.0.1
-p 11211
-c 1024
-t 4

where m is the allocated memory in megabytes, l is the local address for security, c is the maximum number of concurrent connections, and t is the number of threads (proportional to CPU cores). Unlike Redis, Memcached is truly multithreaded and can use multiple cores efficiently.

Connecting cache with Redis and Memcached to applications

Now that the services are ready, we need to connect the web application to them. The connection method is different depending on the framework or CMS.

WordPress

For WordPress, the Redis Object Cache plugin is the most popular option. After installing the plugin, add these lines to wp-config.php:

define( 'WP_REDIS_HOST', '127.0.0.1' );
define( 'WP_REDIS_PORT', 6379 );
define( 'WP_REDIS_PASSWORD', 'YourStrongPasswordHere' );
define( 'WP_CACHE_KEY_SALT', 'mysite_' );
define( 'WP_REDIS_MAXTTL', 3600 );

Then, from the plugin dashboard, enable the Enable Object Cache option. On busy WordPress sites, enabling the Redis object cache can reduce the number of database queries per page load from a few hundred to a few dozen.

Laravel

Laravel supports both drivers. Just set the values ​​in the .env file:

CACHE_DRIVER=redis
SESSION_DRIVER=redis
QUEUE_CONNECTION=redis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=YourStrongPasswordHere
REDIS_PORT=6379

Then you can easily use Cache corruption in the code. The advantage of Redis in Laravel is that the same service is used for cache, user session and job queue.

Django

For Django, the redis package is sufficient, and from version 4 onwards, the Redis backend cache is natively supported. In settings.py:

CACHES = {
    "default": {
        "BACKEND": "django.core.cache.backends.redis.RedisCache",
        "LOCATION": "redis://:YourStrongPasswordHere@127.0.0.1:6379/1",
    }
}

After this setting, you can use the cache_page decorator to cache the entire view of a page, or the cache.set and cache.get functions to manually cache the results of heavy queries.

Common patterns and fatal mistakes

Correct implementation of cache is as important as installing it. You should know some common patterns and mistakes.

  • Cache Stampede: When a popular key expires, dozens of simultaneous requests try to regenerate it, flooding the database. The solution is to use lock or early recomputation.
  • Incorrectly specifying TTL: Too short a TTL reduces cache efficiency, and too long a TTL causes stale data to be displayed. For semi-static data, values ​​of 5 to 60 minutes are usually a good balance.
  • Invalidation: After changing the data in the database, you must delete the associated cache key, otherwise the user will see the old data.
  • Caching specific user data in the public key: This mistake can reveal the information of one user to another user; Always include the user ID in the cache key.

To monitor cache hit rate, you can use the following command in Redis:

redis-cli -a YourStrongPasswordHere info stats | grep keyspace

The desired hit rate is usually above 90%; If the hit rate is low, it means your keys are expiring early or the access pattern is not suitable for the cache. In such a case, you should check whether the data you cache is really read frequently; Caching read-only data not only doesn't help, it wastes memory.

Another important principle is to define a readable and structured cache key. Using standard prefixes and separators like user:1024:profile will help you group keys, easily invalidate a group of them, and quickly understand what each key is for when debugging. Clutter in key naming in large projects can quickly turn into a management nightmare.

Data persistence and backup in Redis

One of the important differences between Redis and Memcached is the persistence of data on disk. Redis has two mechanisms for this: RDB, which periodically takes a snapshot of the entire data, and AOF, which records each write operation in a log file. Choosing between the two depends on your needs.

RDB is great for fast backups and restores and has little overhead, but data between snapshots can be lost in the event of a crash. AOF is more secure because it records almost every write, but the file becomes larger and requires periodic rewriting. For many applications, enabling both together gives the best balance between safety and performance:

save 900 1
save 300 10
save 60 10000
appendonly yes
appendfilename "appendonly.aof"
aof-use-rdb-preamble yes

The save line 900 1 means that if at least one change occurs in 900 seconds, a snapshot will be taken. Note that if you're using Redis purely as a pure cache (no need for persistence), you can disable both mechanisms to maximize write performance; In this case, if the service is restarted, the cache will be rebuilt, which is not a problem.

Memory and performance monitoring

To ensure the health of the cache server, you should monitor memory consumption and key deletion behavior. The command info memory gives a detailed picture of the situation:

redis-cli -a YourStrongPasswordHere info memory | grep -E "used_memory_human|maxmemory_human|mem_fragmentation_ratio"

The mem_fragmentation_ratio index is very important; If this number is consistently above 1.5, it means that the memory is heavily scattered and the RAM is consumed more than necessary. Also, if the number of evicted_keys increases rapidly, it means that the allocated memory is not enough and you should increase the maxmemory or review the TTL of the keys.

Choosing the right server for the cache

Caching services are completely dependent on RAM. Before implementing, make sure your server has enough RAM for both the application and cached data. A rule of thumb is to set aside at least 25% of server RAM for the cache layer. For growing projects, it is important to choose a server with easy RAM upgrades; You can purchase a virtual server with dedicated and high-speed RAM and increase resources in the future without migration. Also find more guides in Rapido Server Articles.

Widely used scenarios beyond simple caching

Due to its diverse data structures, Redis has applications beyond simple query cache that can simplify your application architecture. Knowing these scenarios will help you use a single service for multiple purposes and reduce infrastructure complexity.

  • Session Management: Storing user sessions in Redis instead of a file or database increases speed and enables horizontal scaling of multiple servers, as all servers have access to a common session resource.
  • Rate Limiting: With Redis atomic counters, you can limit the number of requests per user or IP in a time frame and prevent abuse.
  • Job Queue: Redis lists are ideal for implementing background job queues such as email sending or image processing, taking the load off the main user request.
  • Ranking and leaderboard: The sorted set structure allows high-efficiency maintenance of an ordered list based on points, which is great for games and scoring systems.

This versatility is the main reason why Redis is more popular than Memcached in modern projects. With a single service, you can cover several different needs, without having to install and maintain multiple tools separately.

In summary, Redis and Memcached are mature and proven tools that work at the heart of the world's largest websites. With proper installation, secure configuration, and correct cache patterns, you can drastically reduce database load and provide a much faster user experience. The key to success is to start simple, measure hit rates and gradually improve your caching strategy based on real data.

Frequently asked questions

For WordPress, Redis or Memcached is better?

For WordPress, Redis is usually recommended because it has more mature plugins, supports data persistence, and can be used for sessions and queuing in addition to the object cache. Memcached also works but is less flexible for more complex scenarios.

Can I use Redis and Memcached at the same time?

Yes, but in most cases it is not necessary. Some architectures use Memcached for simple page caching and Redis for queues and data structures. For most sites, choosing one of these two is sufficient and will be easier to manage.

How much RAM is enough for Redis?

It totally depends on the cache data size. For an average WordPress site, 256 to 512 MB of dedicated space is usually sufficient. Be sure to set maxmemory so that Redis does not exceed a certain limit and eat up the RAM of the main application.

If the Redis service goes down, will my site go down?

In a proper implementation, the cache should act as a performance improvement layer, not a critical dependency; That is, if the cache is not available, the application must fall back to the database (albeit slower). Most plugins and frameworks have this fallback behavior by default, but it's better to test it.