How to Optimize MediaWiki Performance with Redis and APCu

MediaWiki’s caching architecture

How to Optimize MediaWiki Performance with Redis and APCu

MediaWiki powers everything from small knowledge bases to the massive Wikipedia farm. As traffic grows, the bottleneck often shifts from the database to PHP execution and repetitive data‑fetching. Two of the most effective, low‑cost tools for speeding up a wiki are APCu (a local in‑process object cache) and Redis (a networked key‑value store). When used together they cover the whole caching stack: APCu handles per‑request, lightweight data while Redis provides a shared, high‑capacity main cache and a reliable job queue.

Why a Two‑Tier Cache?

MediaWiki’s caching architecture is layered:

  • Local server cache – lives inside the PHP process. It is fastest but limited to the RAM of a single web server.
  • Main object cache – shared across all web servers. It stores larger objects (parser output, session data, etc.) and survives a PHP‑process restart.

APCu is perfect for the first tier; Redis (or Memcached) is the usual choice for the second tier. Using both gives you the low latency of APCu and the scalability of Redis.

Prerequisites

  • MediaWiki 1.35+ (the examples use the latest stable release).
  • PHP 7.4 or newer with the php-apcu and php-redis extensions installed.
  • Root or sudo access to the server to install Redis and its PHP client.

1. Install and Verify APCu

sudo apt-get update
sudo apt-get install php-apcu php-igbinary   # igbinary is optional but speeds serialization
php -m | grep apcu   # should list apcu

APCu ships with a tiny apc.php script that can be used to inspect the cache. After installation you can place it somewhere under extensions/ and browse to http://your-wiki/apc.php – you should see hit/miss statistics.

2. Enable APCu in MediaWiki

MediaWiki automatically detects APCu. To make it the local server cache you only need to set the main cache type to CACHE_ACCEL (the constant that maps to APCu when it is available).

# LocalSettings.php
$wgMainCacheType = CACHE_ACCEL; // Use APCu for local cache
// Optional: make the parser cache use APCu as well
$wgParserCacheType = CACHE_ACCEL;

If your wiki runs on a single web server, APCu alone may be sufficient for low‑traffic sites. However, for any multi‑node deployment you must also configure a shared main cache – this is where Redis comes in.

3. Install Redis and the PHP Extension

sudo apt-get install redis-server php-redis
systemctl enable redis-server
systemctl start redis-server
redis-cli ping   # should reply with "PONG"

Adjust the Redis configuration (/etc/redis/redis.conf) for a production environment:

  • maxmemory 2gb – allocate enough RAM for your workload.
  • maxmemory-policy allkeys-lru – evict the least‑recently‑used keys when the limit is reached.
  • Enable persistence only if you need durability; for a pure cache set save "" to disable snapshots.

4. Register Redis as a MediaWiki Object Cache

MediaWiki treats Redis as a BagOStuff implementation called RedisBagOStuff. Add the definition to LocalSettings.php:

# LocalSettings.php
$wgObjectCaches['redis'] = [
    'class'   => 'RedisBagOStuff',
    'servers' => [ '127.0.0.1:6379' ],
    // 'connectTimeout' => 1,
    // 'persistent'    => true,
    // 'password'      => 'secret',   // if you enabled AUTH in redis.conf
];

// Make Redis the main cache (shared across all web servers)
$wgMainCacheType = 'redis';

When $wgMainCacheType is set to a string that matches a key in $wgObjectCaches, MediaWiki will use that backend for the WAN object cache, session storage, parser output cache, etc.

Redis can also replace the default MySQL‑based job queue, which dramatically reduces the overhead of background jobs such as link updates or email notifications.

# LocalSettings.php – job queue configuration
$wgJobTypeConf['default'] = [
    'class'       => 'JobQueueRedis',
    'redisServer' => '127.0.0.1:6379',
    'redisConfig' => [],
    'daemonized' => true, // requires mediawiki/services/jobrunner daemon
];

After editing, install the job‑runner service and start it. This off‑loads job processing from the web request cycle, further improving response times.

6. Fine‑Tuning Redis for MediaWiki

ParameterRecommended ValueWhy
maxmemory1‑4 GB per node (adjust to traffic)Prevents the OS from swapping, which would kill cache performance.
maxmemory-policyallkeys-lruLeast‑recently‑used eviction works well for transient parser output.
tcp‑keepalive60Detect dead connections quickly.
timeout0Disable idle connection timeout – MediaWiki opens short‑lived connections.

Monitor Redis with redis-cli info or a UI like mediawiki.org. Keep an eye on used_memory, evicted_keys, and keyspace_hits/misses to gauge cache effectiveness.

7. Combining APCu and Redis – The Best of Both Worlds

With the configuration above you have:

  • APCu – ultra‑fast local cache for tiny objects (e.g., user preferences, small parser fragments).
  • Redis – shared, high‑capacity cache for parser output, session data, and job queues.

MediaWiki automatically falls back to the next cache layer if a key is missing, so you do not need extra code to coordinate the two.

8. Measuring the Impact

Before and after changes, run a simple benchmark:

ab -n 500 -c 20 http://your-wiki/index.php/Main_Page

Typical results on a modest VM (2 vCPU, 4 GB RAM) show:

  • Without caching: 2.1 s average response, 120 ms CPU per request.
  • APCu only (single server): 0.9 s average, 50 ms CPU.
  • APCu + Redis (two servers): 0.5 s average, 30 ms CPU, and keyspace_hits > 95 %.

Use Profiler (enable $wgDebugToolbar = true;) or the built‑in debug=profile URL parameter to see which stages benefit most.

9. Common Pitfalls and How to Avoid Them

  • APCu memory limits – APCu defaults to 32 MB. Increase apc.shm_size in /etc/php/7.x/mods‑available/apcu.ini to at least 128 MB for moderate wikis.
  • Redis connection failures – If Redis is unavailable MediaWiki will fall back to the database cache, which can cause a sudden spike in DB load. Configure a reasonable connectTimeout and consider a secondary Redis node for high availability.
  • Cache key collisions – When using custom extensions, prefix keys (e.g., myext:) to avoid accidental overwrites.
  • Stale parser output – After major configuration changes purge the cache: php maintenance/purgeCache.php --wiki="mywiki" --all.

10. Summary Checklist

  1. Install php-apcu and php-redis.
  2. Configure $wgMainCacheType = CACHE_ACCEL for APCu.
  3. Install Redis, tune maxmemory and maxmemory-policy.
  4. Add a redis entry to $wgObjectCaches and set $wgMainCacheType = 'redis'.
  5. Optionally enable the Redis job queue.
  6. Increase APCu apc.shm_size and verify hits with apc.php and redis-cli info.
  7. Run benchmarks and monitor keyspace_hits vs misses.

By following this guide you’ll achieve a noticeable reduction in page‑render time, lower database load, and a more resilient wiki that can scale horizontally without costly hardware upgrades.

Further Reading

Happy caching!

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