Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk10 min

How to Set Up Redis as a Cache for MySQL with PHP on a Linux VPS

A practical Linux VPS guide to using Redis as a private cache in front of MySQL with PHP, covering installation, security, Predis versus PhpRedis, invalidation, stampede locks, and monitoring.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Redis as a fast, private read-through layer in front of MySQL, not as a replacement for your database. The practical pattern is cache-aside: PHP checks a namespaced Redis key, queries MySQL only on a miss, stores the result with a TTL, and deletes that key after a successful MySQL write. On a Linux VPS, a safe deployment also requires a private Redis bind address, authentication, firewall rules, and encrypted transport or a tunnel whenever Redis traffic leaves a trusted host.

What the setup does

MySQL remains the source of truth. Redis is a separate in-memory service that holds temporary copies of data your PHP application reads frequently. A cache hit avoids a database query; a miss reads MySQL and repopulates Redis. Redis documentation describes hot-working-set reads as sub-millisecond qualitatively, but there is no published MySQL/PHP/VPS benchmark that guarantees a particular speed.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Cache-aside gives you two controls over freshness:

  • TTL: every entry expires automatically, bounding how long an invalid entry can survive.
  • Explicit invalidation: your write path deletes affected keys immediately after MySQL commits.

A key namespace such as cache:app:product:123 prevents collisions when several applications or data types share one Redis instance.

Prerequisites and deployment choices

  • A Linux VPS with administrative access and a service manager such as systemd.
  • PHP 7.4 or newer; PHP 8.x is the recommended target in Redis’s PHP tutorial.
  • A working MySQL connection and a PHP dependency workflow (Composer for Predis, or PECL/package management for PhpRedis).
  • Redis installed on the same VPS, on a private network address, or reachable through a private tunnel.

Keeping Redis on the application VPS and binding it to loopback is the simplest topology. A separate Redis host can work, but traffic then crosses a network boundary and must use access controls plus encrypted transport or a secure tunnel.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.

Install Redis on the VPS

Use the package and repository instructions appropriate to your distribution, then make Redis a managed service. The following are typical paths; verify package names and repository versions for your image.

Ubuntu or Debian

sudo apt update
sudo apt install redis-server
sudo systemctl enable --now redis-server
sudo systemctl status redis-server

Rocky Linux or AlmaLinux

sudo dnf install redis
sudo systemctl enable --now redis
sudo systemctl status redis

Docker on a Linux VPS

docker run -d --name redis 
  --restart unless-stopped 
  -p 127.0.0.1:6379:6379 
  redis:latest

Pin a tested Redis image tag instead of relying on latest for repeatable deployments. Do not publish port 6379 on every interface; the loopback mapping above keeps a container accessible only from the VPS itself.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Verify the daemon

redis-cli PING

A healthy local server returns PONG. Also confirm that the service starts after a reboot with systemctl is-enabled redis-server (or redis on distributions using that unit name). Redis recommends a proper init/service installation for real servers rather than running an unmanaged foreground process.

Secure Redis before PHP connects

An internet-exposed, unauthenticated Redis instance is easy to exploit. Treat the following as deployment requirements, not optional hardening.

Bind only required interfaces

Edit the Redis configuration (commonly /etc/redis/redis.conf or /etc/redis.conf) and bind to loopback when PHP runs on the same VPS:

bind 127.0.0.1 ::1
protected-mode yes

If PHP is on another private host, bind only the private interface needed by that application. Never bind Redis to a public interface merely to make troubleshooting easier.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.

Require authentication

Set an access password using the authentication mechanism supported by your Redis version. A legacy configuration uses:

requirepass replace-with-a-long-random-secret

Store the secret outside source control, for example in an environment variable or a protected service secret. Redis versions with ACL support can use a dedicated user with only the commands your application needs instead of sharing the default account.

Apply a firewall rule

Allow TCP 6379 only from the application host or private subnet. For a same-host setup, no inbound firewall rule for 6379 is needed because PHP connects through loopback. Review cloud-provider security groups as well as the VPS firewall.

Encrypt traffic that leaves the trusted host

Use Redis TLS where your server and client support it, or carry the connection through a VPN/SSH tunnel/private network. Authentication alone does not encrypt credentials or cached data in transit. Restart Redis after configuration changes and repeat redis-cli PING with authentication to verify the result.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose a PHP Redis client

Concern Predis PhpRedis
Installation Pure PHP library installed with Composer: composer require predis/predis. Compiled PHP extension installed with PECL or the operating system; enable it in php.ini.
Deployment portability Works where Composer dependencies can be deployed; no extension build is required. Requires a compatible binary for the PHP version, architecture, and SAPI on every server.
Operational control Managed with application dependencies and releases. Managed as a PHP module; upgrades require extension/package coordination and usually a PHP-FPM or web-server restart.
Runtime overhead Protocol work is implemented in PHP and may use more CPU than a native extension under heavy load; measure your workload. Native code is generally the lower-overhead choice, but no setup-specific benchmark establishes a guaranteed gain on every VPS.
Best fit Portable applications and hosts where you cannot install PHP extensions. Controlled VPS fleets where you want a native module and can manage PHP binaries.

Both clients connect to the same Redis protocol, normally on port 6379. Pick one for the application and keep connection settings in configuration rather than scattering them through controllers.

Install Predis

composer require predis/predis

Predis connects to an already-running Redis server; Composer does not install the Redis daemon. A password-protected local connection can be created as follows:

Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by
<?php
require __DIR__ . '/vendor/autoload.php';

$redis = new PredisClient([
    'scheme'   => 'tcp',
    'host'     => getenv('REDIS_HOST') ?: '127.0.0.1',
    'port'     => (int) (getenv('REDIS_PORT') ?: 6379),
    'password' => getenv('REDIS_PASSWORD') ?: null,
]);

$redis->connect();
if ($redis->ping() !== 'PONG') {
    throw new RuntimeException('Redis health check failed');
}

Install PhpRedis

sudo pecl install redis

Add extension=redis to the PHP configuration used by your web SAPI and CLI as appropriate, then restart PHP-FPM or the web server. Check the module from the same SAPI that serves the application:

php -m | grep -i redis
sudo systemctl restart php8.2-fpm

Replace the service name with the PHP-FPM version installed on your VPS. A PhpRedis connection looks like this:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<?php
$redis = new Redis();
$redis->connect(getenv('REDIS_HOST') ?: '127.0.0.1', (int) (getenv('REDIS_PORT') ?: 6379));
if ($password = getenv('REDIS_PASSWORD')) {
    $redis->auth($password);
}
if ($redis->ping() !== '+PONG' && $redis->ping() !== true) {
    throw new RuntimeException('Redis health check failed');
}

Implement cache-aside around MySQL

Use a deterministic key, serialize a complete result, and assign a TTL on every write. JSON is convenient for rows returned by PDO; Redis hashes are useful when you need to update or inspect individual fields.

<?php
function productKey(int $id): string {
    return 'cache:app:product:' . $id;
}

function getProduct(PDO $db, $redis, int $id): ?array {
    $key = productKey($id);
    $cached = $redis->get($key);

    if ($cached !== false && $cached !== null) {
        return json_decode($cached, true, 512, JSON_THROW_ON_ERROR);
    }

    $stmt = $db->prepare(
        'SELECT id, name, price, updated_at FROM products WHERE id = ?'
    );
    $stmt->execute([$id]);
    $product = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($product === false) {
        return null;
    }

    $payload = json_encode($product, JSON_THROW_ON_ERROR);
    $redis->set($key, $payload, ['ex' => 300]); // illustrative five-minute TTL
    return $product;
}

The Redis call differs slightly by client. With Predis, set($key, $payload, 'EX', 300) is equivalent. With PhpRedis versions that use positional arguments, $redis->set($key, $payload, 300) sets a 300-second expiration. Confirm the method signature for the client version deployed by your application.

Do not cache failed database responses as if they were valid rows. If you decide to cache “not found” results to protect MySQL from repeated misses, use a short, separate negative-cache TTL and invalidate it when that record is created.

Invalidate after MySQL writes

On a successful update, insert, or delete, remove every key representing the changed data. The safe ordering is:

Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.
  1. Begin and commit the MySQL transaction.
  2. Only after a successful commit, delete the corresponding Redis key.
  3. Let the next read query MySQL and repopulate the key.
$db->beginTransaction();
try {
    $stmt = $db->prepare('UPDATE products SET name = ?, price = ? WHERE id = ?');
    $stmt->execute([$name, $price, $id]);
    $db->commit();

    $redis->del(productKey($id));
} catch (Throwable $e) {
    if ($db->inTransaction()) {
        $db->rollBack();
    }
    throw $e;
}

This follows Redis’s simplest and safest rule: do not attempt to keep cache and primary synchronized by updating both values; delete the cache entry and let the next read repopulate it. If Redis is temporarily unavailable during invalidation, log and retry the deletion (for example, with a durable job or outbox). The TTL remains a fallback, not a reason to ignore failed invalidations.

One logical record can have several keys—an item key, a list key, and a count key. Maintain an explicit invalidation map and delete all affected keys after the transaction. For large key families, use versioned namespaces (for example, cache:app:v42:product:123) and advance the version when a broad invalidation is required; avoid an unbounded production KEYS * scan.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Prevent cache stampedes on hot keys

When a popular key expires, many PHP workers can miss simultaneously and all run the same MySQL query. Use a short single-flight lock around the refill. The lock TTL must be longer than the worst-case MySQL read plus serialization time, and every lock value must contain an ownership token so one request cannot delete another request’s lock.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
$key      = productKey($id);
$lockKey  = $key . ':lock';
$token    = bin2hex(random_bytes(16));
$lockTtl  = 10; // must exceed the worst observed database read

if ($redis->set($lockKey, $token, ['nx', 'ex' => $lockTtl])) {
    try {
        $value = loadProductFromMySQL($db, $id);
        if ($value !== null) {
            $redis->set($key, json_encode($value, JSON_THROW_ON_ERROR), ['ex' => 300]);
        }
        return $value;
    } finally {
        // Delete only if this request still owns the lock.
        $redis->eval(
            "if redis.call('get', KEYS[1]) == ARGV[1] then " .
            "return redis.call('del', KEYS[1]) else return 0 end",
            [$lockKey, $token],
            1
        );
    }
}

// Another worker is filling the key. Retry with jitter, then use a bounded fallback.
usleep(random_int(20000, 80000));
$retry = $redis->get($key);
if ($retry !== false && $retry !== null) {
    return json_decode($retry, true, 512, JSON_THROW_ON_ERROR);
}
throw new RuntimeException('Cache refill is busy; retry request');

Use bounded retries and jitter rather than an unending wait. For very hot data, refresh before expiry, add a small random component to TTLs so related keys do not expire together, or serve a briefly stale value while one worker refreshes it. Those policies trade freshness for lower database pressure and should be chosen per data type.

Observe hits, misses, TTLs, and failures

Instrumentation should distinguish a Redis failure from a normal cache miss. Record counters for cache hits, misses, MySQL reads caused by misses, successful invalidations, lock contention, Redis errors, and query latency. Include the namespace and operation, but do not put customer data or secrets in logs.

# String value
redis-cli GET cache:app:product:123
redis-cli TTL cache:app:product:123

# Hash value
redis-cli HGETALL cache:app:product:123
redis-cli TTL cache:app:product:123

# Basic server check
redis-cli INFO stats

TTL returns the remaining lifetime in seconds; a negative result indicates no expiration or a missing key, depending on the value. Every application-created cache key should have an intentional expiration. If you use hashes, set the TTL on the key after populating its fields; individual hash fields do not expire independently.

Alert on sustained Redis connection errors, memory pressure, evictions, a sudden miss-rate increase, lock contention, and MySQL load returning to its uncached level. A cache that silently fails open can preserve availability while increasing database cost, so make that behavior explicit and monitor it.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Common failures and fixes

Connection refused

Check systemctl status redis-server (or redis), confirm the process is listening on the expected interface and port, and verify that a container port is mapped to loopback. Test from the same PHP runtime that serves requests; CLI and PHP-FPM can load different configuration files.

NOAUTH Authentication required

The server requires a password but the client did not send one, or the application is using a stale secret. Update the environment or secret store, reconnect, and test with an authenticated redis-cli session. Do not remove authentication to make a health check pass.

Keys never expire

Inspect the write path and ensure every SET or hash population is followed by an expiration. Check with TTL. A missing expiration can consume memory until Redis evicts data or fails writes.

Fresh MySQL data is not visible

Confirm that invalidation runs only after a committed write, covers every derived key, and reports deletion errors. Check for multiple Redis databases or hosts in configuration, and verify that readers and writers use the same namespace.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

MySQL load spikes when entries expire

Add the single-flight lock, jitter TTLs, and inspect lock contention. Increase the lock TTL only enough to cover the worst refill time; an excessively long lock delays recovery after a crashed worker.

Production checklist

  • Redis is installed as a managed service and starts after reboot.
  • redis-cli PING succeeds from the application host.
  • Redis binds only to required private interfaces, has authentication, and is shielded by a firewall.
  • Traffic crossing a host or trust boundary uses TLS or a private tunnel.
  • PHP 7.4+ is installed (PHP 8.x preferred), and the selected client is enabled in the serving SAPI.
  • Keys are namespaced, every value has a deliberate TTL, and payloads have a defined serialization format.
  • Successful MySQL writes delete all affected keys; failed invalidations are retried and alerted.
  • Hot-key refills use an ownership-token lock with a bounded TTL and jittered retries.
  • Hit, miss, database-read, invalidation, eviction, error, and lock-contention metrics are visible.
  • Recovery is tested: the application can continue against MySQL when Redis is unavailable, with an understood performance impact.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.