//Technology

Object Caching 101: Boost Site Speed with Redis & Memcached

Object caching with Redis or Memcached reduces latency, eases database load, and boosts scalability for dynamic sites on AtoZNode VPS.

7 min read
Object Caching 101: Boost Site Speed with Redis & Memcached

Dynamic websites generate content on the fly by querying databases, calling APIs, or rendering templates. When the same data is requested repeatedly, the overhead of those operations can become a bottleneck. Object caching solves this by keeping the results of expensive work in a fast, in-memory store such as Redis or Memcached. This article explains the basics of object caching, compares the two popular engines, and walks through installing and using them on a typical AtoZNode VPS running Debian/Ubuntu or AlmaLinux/Rocky Linux.

What Is Object Caching and Why It Matters

Object caching stores the output of a computationally heavy operation—such as a database query, an API call, or a rendered template—in memory. Subsequent requests for the same data are served directly from the cache, skipping the original work.

  • Reduced latency: Memory reads occur in microseconds, far faster than disk I/O or network round-trips.
  • Lower database load: Fewer queries mean less CPU, memory, and I/O pressure on your primary database.
  • Improved scalability: With the backend relieved, the same hardware can handle more concurrent users.

In practice, an object cache sits between your application code and the data source. When the application needs a piece of data, it first checks the cache. If the data is present (a cache hit), it is returned instantly. If not (a cache miss), the application fetches the data, stores it in the cache, and then serves it.

Redis vs. Memcached: Core Differences

Both Redis and Memcached are in-memory key-value stores, but they differ in features, data structures, and typical use cases.

Feature Redis Memcached
Data types Strings, hashes, lists, sets, sorted sets, bitmaps, hyperloglogs, streams Simple strings only
Persistence Optional snapshot (RDB) or append-only file (AOF) None (purely volatile)
Replication & clustering Built-in master-replica replication, sharding, and cluster mode Limited; typically multiple independent instances
Memory eviction policies LRU, LFU, TTL per key, and more LRU only
Use cases Session storage, leaderboards, pub/sub, job queues, complex objects Simple object caching for web pages, query results

For most PHP or Node.js web applications, Memcached is sufficient when you need a fast, straightforward cache for database rows or rendered fragments. Redis shines when you require richer data structures, durability, or advanced features such as pub/sub.

Installing Redis and Memcached on Debian/Ubuntu

Below are the commands for a fresh AtoZNode VPS running Debian 12 or Ubuntu 22.04. Each block includes a brief explanation of what the command does.

Redis

# Update package index
sudo apt update
# Install Redis server package
sudo apt install -y redis-server
# Enable and start the service
sudo systemctl enable --now redis-server
# Verify that Redis is listening on the default port 6379
sudo ss -tulnp | grep 6379
  • apt update refreshes the local package list.
  • apt install -y redis-server downloads and installs the Redis daemon.
  • systemctl enable --now configures Redis to start at boot and launches it immediately.
  • ss -tulnp shows active listening sockets; filtering for 6379 confirms the service is up.

Memcached

# Update package index
sudo apt update
# Install Memcached and its libmemcached client library
sudo apt install -y memcached libmemcached-tools
# Edit the config to listen on the local interface only (optional but recommended)
sudo sed -i 's/-l 0.0.0.0/-l 127.0.0.1/' /etc/memcached.conf
# Restart the service to apply changes
sudo systemctl restart memcached
# Verify that Memcached is listening on port 11211
sudo ss -tulnp | grep 11211
  • The sed command changes the bind address from all interfaces to 127.0.0.1, limiting exposure.
  • Port 11211 is the default Memcached port.

Installing Redis and Memcached on AlmaLinux/Rocky Linux (RHEL 9-based)

For servers running AlmaLinux 9, Rocky Linux 9, or any RHEL-compatible distribution, use the dnf package manager.

Redis

# Enable the EPEL repository (provides Redis for RHEL 9)
sudo dnf install -y epel-release
# Install Redis
sudo dnf install -y redis
# Start and enable the service
sudo systemctl enable --now redis
# Check that Redis is listening on 6379
sudo ss -tulnp | grep 6379
  • epel-release adds the Extra Packages for Enterprise Linux repository, which contains Redis.
  • systemctl enable --now redis both starts Redis now and configures it to start on boot.

Memcached

# Install Memcached and the client tools
sudo dnf install -y memcached libmemcached
# Edit the config to bind only to localhost (optional)
sudo sed -i 's/-l 0.0.0.0/-l 127.0.0.1/' /etc/sysconfig/memcached
# Restart Memcached to apply the change
sudo systemctl restart memcached
# Verify the listening socket
sudo ss -tulnp | grep 11211
  • The configuration file for Memcached on RHEL-based systems is /etc/sysconfig/memcached.

Integrating the Cache with Your Application

Once the services are running, the next step is to connect your web application to the cache. Below are brief examples for PHP (using the php-redis and memcached extensions) and Node.js.

PHP Example

// Redis
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$cached = $redis->get('user:42');
if ($cached === false) {
    // Cache miss – fetch from database
    $data = $db->query('SELECT * FROM users WHERE id = 42')->fetch();
    $redis->setex('user:42', 300, json_encode($data)); // store for 5 minutes
} else {
    $data = json_decode($cached, true);
}

// Memcached
$mem = new Memcached();
$mem->addServer('127.0.0.1', 11211);
$cached = $mem->get('profile:42');
if ($mem->getResultCode() == Memcached::RES_NOTFOUND) {
    $data = $db->query('SELECT * FROM profiles WHERE id = 42')->fetch();
    $mem->set('profile:42', $data, 300); // TTL 5 minutes
}

Key points:

  • Use a consistent naming scheme (e.g., entity:id) to avoid collisions.
  • Set an appropriate TTL (time-to-live) so stale data is eventually refreshed.
  • Handle cache misses gracefully by falling back to the database.

Node.js Example

// Redis (node-redis)
const { createClient } = require('redis');
const client = createClient({ url: 'redis://127.0.0.1:6379' });
await client.connect();

let cached = await client.get('post:123');
if (!cached) {
    const data = await db.query('SELECT * FROM posts WHERE id = $1', [123]);
    await client.setEx('post:123', 300, JSON.stringify(data));
    cached = data;
} else {
    cached = JSON.parse(cached);
}

// Memcached (memjs)
const memjs = require('memjs');
const mem = memjs.Client.create('127.0.0.1:11211');

let result = await mem.get('comment:456');
if (!result.value) {
    const data = await db.query('SELECT * FROM comments WHERE id = $1', [456]);
    await mem.set('comment:456', JSON.stringify(data), { expires: 300 });
    result = { value: JSON.stringify(data) };
}
const comment = JSON.parse(result.value);

Both snippets illustrate the same pattern: check cache → on miss, query the database → store result → use the data.

Best Practices for Production-Ready Caching

  • Limit cache size: Configure maxmemory in Redis or -m in Memcached to prevent the server from exhausting RAM.
  • Choose eviction policies wisely: Redis offers allkeys-lru, volatile-ttl, etc. Pick the one that matches your workload.
  • Secure the service: Bind to 127.0.0.1 unless remote access is required, and consider firewall rules (e.g., ufw allow from 10.0.0.0/8 to any port 6379).
  • Monitor hit-rate: Tools like redis-cli INFO stats or memcached-tool show hits vs. misses. Aim for a high hit ratio.
  • Graceful fallback: If the cache service becomes unavailable, your application should continue operating using the database, albeit slower.

When to Use Both Redis and Memcached Together

Some architectures benefit from a hybrid approach:

  • Simple key-value caching: Use Memcached for cheap, volatile objects where persistence is unnecessary.
  • Complex data structures or session storage: Use Redis for user sessions, shopping carts, or real-time analytics.

Running both services on the same VPS is feasible as long as you allocate sufficient memory (e.g., 2 GB for Memcached, 2 GB for Redis on a 4 GB VPS). Separate them by port and bind address to avoid conflicts.

Conclusion

Object caching with Redis or Memcached can dramatically improve the responsiveness of dynamic websites hosted on AtoZNode VPS instances. By keeping frequently accessed data in memory, you reduce latency, ease database load, and create room for more concurrent users. Choose the engine that matches your data-access patterns, follow the installation steps for your Linux distribution, integrate the cache into your code with clear naming and TTLs, and apply production-grade safeguards. With these fundamentals in place, your site will feel noticeably faster to visitors across India and beyond.

object cachingredismemcacheddebianubuntualmalinuxrocky linuxphp caching

Try it on your own server

Follow along on a Cloud VPS with full root access, or read the step-by-step knowledge base guides.