How to Configure MediaWiki to Use Redis for Caching

How to Configure MediaWiki to Use Redis for Caching

Redis is an open‑source, in‑memory key‑value store that MediaWiki can use as a fast, persistent cache. Replacing the default database‑backed cache with Redis can dramatically reduce page‑render time, lower database load, and improve job‑queue performance. This guide walks you through the entire process – from installing Redis and the PHP client to fine‑tuning both MediaWiki and Redis for production use.

Why Redis?

  • Speed: All data lives in RAM, so look‑ups are measured in microseconds.
  • Flexibility: Unlike simple opcode caches, Redis can store large blobs (up to 512 MiB) and supports data structures such as hashes, lists, and sets.
  • Reliability: Optional persistence (RDB snapshots or AOF logs) protects against data loss while still giving you the performance of a pure memory store.

Prerequisites

  1. A working MediaWiki installation (≥ 1.27 recommended).
  2. Root or sudo access on the server to install system packages.
  3. PHP ≥ 7.2 with the php-redis extension (or predis as a fallback).

Step 1 – Install Redis and the PHP client

On Debian/Ubuntu the required packages can be installed in a single command:

sudo apt-get update
sudo apt-get install redis-server php-redis

For other distributions replace the package manager accordingly (e.g. yum install redis php-redis on CentOS). After installation, start and enable the service:

sudo systemctl enable redis-server
sudo systemctl start redis-server

Verify that Redis is listening on the default port (6379):

redis-cli ping
# Expected output: PONG

Step 2 – Configure MediaWiki to talk to Redis

Edit LocalSettings.php (usually located in the root of the wiki). Add the following block before any other cache‑related settings:

/**
 * Redis object cache configuration.
 * See https://www.mediawiki.org/wiki/Redis for full reference.
 */
$wgObjectCaches['redis'] = [
    'class' => 'RedisBagOStuff',
    // One or more servers – you can also use UNIX sockets for local deployments.
    'servers' => [ '127.0.0.1:6379' ],
    // Optional tuning parameters (uncomment if needed):
    // 'connectTimeout' => 1,
    // 'persistent' => true,
    // 'password' => 'your_redis_password',
    // 'automaticFailover' => true,
];

// Make Redis the primary cache for most MediaWiki subsystems.
$wgMainCacheType = 'redis';               // HTML cache, parser cache, etc.
$wgParserCacheType = 'redis';             // Optional – overrides $wgMainCacheType for parser output.
$wgMessageCacheType = 'redis';            // Optional – caches UI messages.
$wgSessionCacheType = 'redis';            // Optional – stores session data.

The $wgObjectCaches array tells MediaWiki which backend class to use (RedisBagOStuff) and where the Redis server lives. All subsequent cache types can reference the string 'redis' instead of the older constants such as CACHE_ACCEL.

Step 3 – (Optional) Use Redis for the job queue

MediaWiki’s background job system can also be backed by Redis, which is especially useful for high‑traffic wikis where the default database queue becomes a bottleneck.

$wgJobTypeConf['default'] = [
    'class' => 'JobQueueRedis',
    'redisServer' => '127.0.0.1:6379',
    // Any additional connection options go here – see Redis docs.
    'redisConfig' => [],
    // Setting daemonized to true requires the mediawiki/services/jobrunner daemon.
    'daemonized' => true,
];

If you enable daemonized mode, install the job‑runner service (mediawiki-services-jobrunner) and configure it with a config.json that points to the same Redis instance. The job runner will pull jobs from the Redis queue and execute them asynchronously.

Step 4 – Tune Redis for cache use

Redis defaults are fine for development, but a production wiki should set memory limits and an eviction policy to avoid OOM crashes. Edit /etc/redis/redis.conf (or the location appropriate for your distro) and adjust the following lines:

# Maximum RAM the instance may use – 1 GB is a common starting point.
maxmemory 1gb
# When maxmemory is reached, evict the least‑recently‑used keys.
maxmemory-policy allkeys-lru
# Optional: enable AOF persistence for durability (append‑only file).
appendonly yes
appendfsync everysec   # Balance safety vs. performance.

After editing, restart Redis:

sudo systemctl restart redis-server

Confirm the settings with:

redis-cli INFO memory
# Look for "maxmemory" and "maxmemory_policy" values.

Step 5 – Verify the integration

  1. HTML cache check: Visit a wiki page, then purge it (?action=purge). The response headers should contain X-Object-Cache: redis (or similar) indicating that the object cache was consulted.
  2. Job queue test (if enabled): Create a dummy job (e.g. edit a page with a heavy parser function) and watch redis-cli KEYS * for keys prefixed with job:. The presence of those keys confirms that jobs are being queued in Redis.

Cache object test: In a PHP shell (or a temporary MediaWiki page), run:

$cache = ObjectCache::getInstance( 'redis' );
$cache->set( 'test-key', 'Redis is working!', 60 );
echo $cache->get( 'test-key' ); // Should output the string.

Step 6 – Monitoring and maintenance

Redis provides built‑in metrics that help you keep the cache healthy. A minimal monitoring script could look like:

#!/usr/bin/env bash
redis-cli INFO | grep -E 'used_memory|connected_clients|evicted_keys|expired_keys'

Integrate this into your existing monitoring stack (Prometheus, Zabbix, etc.) and set alerts for sudden spikes in evicted_keys – a sign that maxmemory is too low.

Common pitfalls and troubleshooting

  • Missing PHP extension: If MediaWiki throws “Class RedisBagOStuff not found”, verify that php-redis is installed and that the PHP‑FPM/Apache process was restarted.
  • Authentication failures: When you set a password in $wgObjectCaches, also add it to $wgJobTypeConf['default']['redisConfig'] if you use the job queue.
  • Persistent connections: Enabling 'persistent' => true reduces connection overhead but can cause stale connections after a Redis restart. Use it only on stable environments.
  • Cache inconsistency after upgrades: Some MediaWiki upgrades change the cache‑key format. After a major version bump, run php maintenance/purgeCache.php --all to clear stale entries.

Best‑practice checklist

TaskDone?
Install Redis server and enable it at boot.
Install PHP Redis extension (or Predis fallback).
Add $wgObjectCaches['redis'] block to LocalSettings.php.
Set $wgMainCacheType = 'redis' (and optional sub‑caches).
Configure job queue (if needed) and install jobrunner daemon.
Set maxmemory and maxmemory-policy in redis.conf.
Restart both Redis and the web server.
Run verification tests (cache object, HTML cache, job queue).
Add monitoring for memory usage, evictions, and client connections.

Conclusion

Switching MediaWiki’s caching layer to Redis is a straightforward upgrade that yields immediate performance gains. By following the steps above – installing Redis, wiring it up in LocalSettings.php, optionally moving the job queue, and tuning memory limits – you end up with a robust, low‑latency cache that scales well under heavy traffic. Remember to monitor the Redis instance continuously and adjust maxmemory as your wiki grows.

For further reading, consult the official MediaWiki page on Redis (Redis – MediaWiki) and the Redis documentation for advanced persistence and clustering options.

Subscribe to MediaWiki Tips and Tricks

Don’t miss out on the latest articles. Sign up now to get access to the library of members-only articles.
jamie@example.com
Subscribe