본문으로 이동

Caches used in running MediaWiki

이 문서는 페미위키:운영팀/개발팀/기술 블로그/32 문서를 번역한 것이며 번역은 100% 완료했습니다.
.
A red squirrel burying a nut in grass strewn with chestnut burrs.
© Peter Trimming, CC BY 2.0

Anyone running MediaWiki runs into the word cache all over the configuration files and documentation. OPcache, APCu, memcached, the parser cache, the localisation cache, the file cache and the CDN: there are so many names that it is easy to lose track of which one holds what. Most of it is covered on MediaWiki.org in the performance tuning manual and the object cache page, but how the defaults actually behave and which settings are often missed sometimes only shows in the code. This post goes through the caches a request passes on its way to a response, from the outside of the web server inwards. Setting names and defaults are as of MediaWiki 1.46.

Browser cache and CDN

A request that never reaches PHP saves the server the most work. In MediaWiki this layer splits in two.

  • ResourceLoader (load.php), which serves JavaScript and CSS, sends a Cache-Control: public, max-age=…, s-maxage=… header of 30 days for requests whose URL carries version= and of 5 minutes for those without it. Browsers read max-age and do not request the resource again during that time, while shared caches such as a CDN follow s-maxage. When a module changes, the version value in its URL changes, so the cache never needs to be cleared.[1] The response is the same regardless of cookies, so it can be left to a CDN as it is.
  • Page HTML sent to logged-out visitors gets headers that let a CDN cache it only when $wgUseCdn = true. The cache time is then $wgCdnMaxAge (18000 seconds, 5 hours, by default).

When a page is edited, MediaWiki sends a request to remove that page's URLs from the cache. By default it sends an HTTP PURGE request to each server listed in $wgCdnServers.[2] PURGE is not a standard HTTP method but a convention accepted by Squid and Varnish, so this setting is for when you run a reverse proxy such as Varnish yourself in front of MediaWiki. A default build of nginx cannot handle PURGE and needs a separate module.

$wgUseCdn = true;
// Address of the Varnish placed in front of MediaWiki
$wgCdnServers = [ '127.0.0.1' ];

$wgCdnServers also serves as the list of proxies whose X-Forwarded-For header is trusted. Proxies that should only be trusted, without receiving PURGE, go in $wgCdnServersNoPurge.[3]

Commercial CDNs such as CloudFront and Cloudflare do not accept PURGE requests and use their own invalidation APIs instead. For Cloudflare there are extensions that call its API from edit hooks: CloudflarePurge and Cloudflare purge Cloudflare only, while MultiPurge purges Varnish and Cloudflare in turn. Extensions for other commercial CDNs such as CloudFront cannot be found on MediaWiki.org, so using such a CDN means writing the code that calls its invalidation API yourself.

MediaWiki also sends the URLs to purge to the cdn-url-purges channel of $wgEventRelayerConfig. The default is EventRelayerNull, which does nothing.[4] One implementation of this channel comes with the EventBus extension, and it assumes a setup like the Wikimedia Foundation's, where daemons running on each cache server purge after the events pass through EventGate and Kafka. MultiPurge also has a PurgeEventRelayer class that receives this channel, but its README does not describe it.[5] For any other commercial CDN you have to write a class yourself that receives this channel and calls the invalidation API. In a cache that purge requests do not reach, edits show up late by up to $wgCdnMaxAge.

Setting $wgCdnReboundPurgeDelay (default 0) above 0 makes MediaWiki, when a page is edited or deleted, send the first purge and then purge the same URLs once more after that many seconds. It corrects cases where a request arriving right after the first purge refills the cache with old content because of replica database lag, or where, in a two-tier CDN setup, the front tier fetches old content again from a back tier that has not been purged yet. The setting's documentation says to set it safely above the maximum replica lag in $wgLBFactoryConf.[6] The second purge goes into the job queue as a delayed job, and the default database job queue does not support delayed jobs, so pushing the job fails with an error. This setting is meant to be used with a queue that supports delayed jobs, such as the Redis job queue.[7]

File cache

For small wikis that cannot run a separate CDN, MediaWiki has a file cache that keeps rendered pages on disk as HTML files.[8]

$wgUseFileCache = true;
$wgFileCacheDirectory = "$IP/cache/html";
  • It is used only for plain page views by logged-out visitors. Special pages, redirects and requests with URL parameters are not cached.
  • It has no expiry. When a page is edited only that page's file is invalidated; to clear everything, set $wgCacheEpoch to the current time or delete the files.
  • There is a known problem where category pages and file description pages are not regenerated when their content changes.

Requests still go through PHP, but the database and the parser are skipped, so the gain is large. For busy wikis the MediaWiki.org manual recommends an external cache such as Varnish.

OPcache

From here on, the request has reached PHP. On every request PHP reads the source files and compiles them into a list of instructions (opcodes) for the Zend engine to run; OPcache (opcode cache) keeps that compiled result in shared memory so later requests skip compilation. Nothing needs to be set on the MediaWiki side; turning on the PHP extension is enough.[9]

The official MediaWiki Docker image maintained by the Wikimedia Foundation adds the following settings.[10]

opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000
opcache.revalidate_freq=60

Yet MediaWiki 1.46 core has 3,824 PHP files even without tests, and the vendor directory shipped with it has 3,211 more. PHP rounds max_accelerated_files up to the first value in a fixed list of primes { 223, 463, 983, 1979, 3907, 7963, 16229, 32531, … } that is greater than or equal to the setting.[11] So the official image's 4000 actually becomes 7,963, which is smaller than PHP's default of 10000 (16,229 in effect). Core and vendor alone come to 7,035 files, so the limit is reached once extensions and skins add about 1,000 more files used by requests. Files beyond the limit are compiled again on every request. The current state can be checked with num_cached_scripts and cache_full from opcache_get_status().

$s = opcache_get_status( false );
var_dump( $s['opcache_statistics']['num_cached_scripts'], $s['cache_full'] );

revalidate_freq=60 means checking every 60 seconds whether files have changed, so if you edit files directly on the server, old code keeps running for up to a minute.

The Wikimedia Foundation's production MediaWiki, which runs on Kubernetes, sets the same values much higher: opcache.memory_consumption is 500 MB, opcache.max_accelerated_files is 32531 and opcache.interned_strings_buffer is 50 MB.[12] opcache.validate_timestamps and opcache.revalidate_freq, which check whether files have changed, are turned on only in development mode, and code changes are shipped by deploying a new image.[13]

APCu

APCu (APC User Cache) is an extension that lets PHP processes store key-value pairs in shared memory. APC (Alternative PHP Cache) was an extension that provided both an opcode cache and a user data cache; since PHP 5.5, OPcache has taken over the opcode cache, and only the user data cache remains as APCu.[14] When it is installed, MediaWiki uses it as the "local server cache" on its own.[15] There is nothing to configure, and it holds things such as ResourceLoader minification results, LESS compilation results and file hashes. MediaWiki detects APCu by whether the apcu_fetch function exists, and falls back to an empty cache that stores nothing when it does not.[16]

APCu is shared only within a single server. With two or more web servers each server would hold different contents, so MediaWiki.org advises against using APCu as the main cache, covered below, in that case.

Object cache

Most of MediaWiki's remaining caches sit on a single framework called the "object cache". The store is chosen with one of the following constants.

  • CACHE_NONE: no caching
  • CACHE_DB: the objectcache table in the database
  • CACHE_ACCEL: APCu
  • CACHE_MEMCACHED: memcached (server addresses in $wgMemCachedServers)
  • CACHE_ANYTHING: whatever is available

What goes where is then set separately for each setting.

Setting What it holds Default
$wgMainCacheType Main cache. Most data, such as revision text and user information CACHE_NONE
$wgParserCacheType Parser cache. Rendered page HTML CACHE_ANYTHING
$wgMessageCacheType Message cache. Interface messages changed in the MediaWiki: namespace CACHE_ANYTHING
$wgSessionCacheType Login sessions CACHE_ANYTHING

CACHE_ANYTHING looks at the main, message and parser cache settings in turn and uses the first real store it finds, falling back to the database if there is none.[17] So a wiki with nothing configured runs with the main cache off and the parser, message and session caches in the database. When the installer finds APCu, it offers to put $wgMainCacheType = CACHE_ACCEL; in LocalSettings.php, but if you pick something else at that step the main cache stays off.

For a single server without memcached, MediaWiki.org recommends the following combination.

$wgMainCacheType = CACHE_ACCEL;
$wgSessionCacheType = CACHE_DB;
$wgParserCacheType = CACHE_DB;

Switching the main cache to APCu also moves sessions, which follow CACHE_ANYTHING, to APCu, and since APCu is emptied when PHP-FPM restarts, everyone gets logged out. That is why the combination above keeps sessions in the database. With several web servers, or when memcached is available, the combination puts the main cache in memcached.

$wgMainCacheType = CACHE_MEMCACHED;
$wgMemCachedServers = [ '127.0.0.1:11211' ];
$wgSessionCacheType = CACHE_DB;
$wgParserCacheType = CACHE_DB;

Redis can also be used as the main cache. There is no CACHE_* constant for it, so you register RedisBagOStuff, which ships with core, in $wgObjectCaches and point to it by name. PHP needs the phpredis extension.[18]

$wgObjectCaches['redis'] = [
	'class' => 'RedisBagOStuff',
	'servers' => [ '127.0.0.1:6379' ],
];
$wgMainCacheType = 'redis';
$wgSessionCacheType = CACHE_DB;
$wgParserCacheType = CACHE_DB;

If Redis is used only as a cache, set maxmemory and maxmemory-policy on the Redis side so that old keys are removed when memory fills up. The Wikimedia Foundation uses memcached (mcrouter) for the main and message caches and a Cassandra-based service for sessions, and uses Redis not as a cache but for file storage locking.[19]

When choosing between memcached and Redis, these are the differences on the MediaWiki side. MediaWiki.org's performance manual recommends memcached, which is also what the Wikimedia Foundation uses.[20]

Criterion memcached Redis
MediaWiki configuration Has the CACHE_MEMCACHED constant Registered by hand in $wgObjectCaches
PHP extension None needed (built-in pure PHP client). PECL memcached can also be used Needs phpredis
Authentication None. Only the PECL client supports SASL Password (sent in plain text)
On restart Everything is cleared Kept if persistence to disk is on
When memory is full Evicts the least recently used items Writes fail under the default policy (noeviction)
Other uses None Job queue (needs a separate service), locking, PoolCounter
Licence BSD RSALv2/SSPLv1 since 7.4, AGPLv3 added in 8.0. Valkey is a fork that kept BSD

[21][22][23]

With sessions in Redis and persistence to disk turned on, logins survive a Redis restart. With sessions in memcached everyone is logged out on restart, so sessions are often kept in the database as in the earlier examples.

On top of the main cache there is one more layer called WANObjectCache. Unless you write extensions you will rarely deal with it directly, but when the main cache is off this layer stores nothing either. It also holds data that never changes once saved, such as revision text, so just turning on the main cache cuts database queries noticeably.

Parser cache

Turning wikitext into HTML is time-consuming work in MediaWiki. The parser cache stores the result per page and serves it to the next visitor without rendering again. The default retention is a day (86400 seconds), set by $wgParserCacheExpireTime.

The setting's documentation recommends setting the parser cache to CACHE_DB separately even when the main cache is memcached.[24] The parser cache grows with the number of pages, and memcached evicts the oldest items when memory fills up, so the less often a page is visited, the less likely its cache is still there. The database is slower but roomy, and still faster than rendering again. For large wikis the documentation also describes a dedicated parser cache database with expired rows cleaned up by purgeParserCache.php.

Editors can also clear the parser cache of a single page. This is purging: add ?action=purge to the page's address, or enter the page name in Special:Purge. When a template is edited, MediaWiki invalidates the cache of the pages using it through the job queue, and the change shows up late when jobs are backed up. Pages whose output changes over time, such as those with magic words that print the current date, also show old values while cached. Purging is for these cases.

Purging updates the page's page_touched value to invalidate the parser cache, and also removes the page from the file cache and the CDN.[25] Opening the address directly shows a confirmation screen, and the purge runs only when the confirm button sends a POST request.[26] The default rate limit is 30 times per 60 seconds per IP and per user.[27] Purging does not rebuild the link tables that hold categories and link lists, so when a category does not show up, a null edit, saving without changing the content, is needed.

When all cached HTML has to be invalidated at once (for example when a skin or extension changed the HTML structure), setting $wgCacheEpoch to the current time stops any older cache from being used.

$wgCacheEpoch = '20261117000000';

Special page query cache

Special pages that scan the whole wiki, such as Special:WantedPages and Special:LonelyPages, have costly queries and are marked as "expensive query pages". With $wgMiserMode (default false) on, these pages do not run their query on every view but show results stored in the database's querycache table.[28] This table is updated only when maintenance/updateSpecialPages.php runs, so with $wgMiserMode on, the script has to run periodically. Otherwise the special pages keep showing the first results stored. The number of rows stored per page is $wgQueryCacheLimit (1000 by default), and pages the script should skip go in $wgDisableQueryPageUpdate.[29]

Localisation cache

MediaWiki's interface messages are spread over thousands of i18n/*.json files in core and extensions. The localisation cache gathers them per language, and it is different from the message cache above, which holds only messages changed on the wiki through MediaWiki: pages.

The store is chosen with $wgLocalisationCacheConf['store'], and the default is 'detect'.[30]

  • 'detect': 'files' if $wgCacheDirectory is set, 'db' otherwise
  • 'db': the l10n_cache table in the database
  • 'files': CDB files in $wgCacheDirectory
  • 'array': PHP array files in $wgCacheDirectory. OPcache keeps these files in memory, which makes this the fastest, but the documentation still calls it experimental.

The LocalSettings.php generated by the installer has $wgCacheDirectory commented out, so left as it is, every message read queries the database. Setting a single directory switches it to files.

// A directory PHP can write to but the web cannot reach
$wgCacheDirectory = "$IP/cache";

With the default settings, after an extension is added or updated a web request rebuilds the cache, and that request slows down as it rereads every language file. To build the cache ahead of time at deployment and never rebuild it in web requests, do the following.

$wgLocalisationCacheConf['manualRecache'] = true;
php maintenance/run.php rebuildLocalisationCache --force

In exchange, the command has to be run every time extensions change, and if it is forgotten, a new extension's messages show up as ⧼message-name⧽.

Conclusion

To sum up, these are the things a small wiki on a single server can do.

  • Turn on OPcache and set max_accelerated_files above the number of files
  • Install APCu and add $wgMainCacheType = CACHE_ACCEL; (with sessions and the parser cache in CACHE_DB)
  • Set $wgCacheDirectory to move the localisation cache to files
  • Turn on the file cache if no cache can be put in front

MediaWiki.org's performance manual likewise recommends that small wikis start with these three: OPcache, APCu and the main cache.

References

  1. ↑ “includes/ResourceLoader/ResourceLoader.php”. 《GitHub》 (영어). 2026년 11월 17일에 확인함. 
  2. ↑ “includes/Deferred/CdnCacheUpdate.php”. 《GitHub》 (영어). 2026년 11월 18일에 확인함. 
  3. ↑ “includes/MainConfigSchema.php”. 《GitHub》 (영어). 2026년 11월 18일에 확인함. 
  4. ↑ “includes/MainConfigSchema.php”. 《GitHub》 (영어). 2026년 11월 18일에 확인함. 
  5. ↑ “includes/PurgeEventRelayer.php”. 《GitHub》 (영어). 2026년 11월 19일에 확인함. 
  6. ↑ “includes/MainConfigSchema.php”. 《GitHub》 (영어). 2026년 11월 21일에 확인함. 
  7. ↑ “includes/JobQueue/JobQueue.php”. 《GitHub》 (영어). 2026년 11월 21일에 확인함. 
  8. ↑ “Manual:File cache”. 《MediaWiki》 (영어). 2026년 11월 17일에 확인함. 
  9. ↑ “Manual:Performance tuning”. 《MediaWiki》 (영어). 2026년 11월 17일에 확인함. 
  10. ↑ “mediawiki-docker/1.46/fpm/Dockerfile”. 《GitHub》 (영어). 2026년 11월 17일에 확인함. 
  11. ↑ “OPcache Runtime Configuration”. 《PHP Manual》 (영어). 2026년 11월 19일에 확인함. 
  12. ↑ “helmfile.d/services/_mediawiki-common_/global.yaml”. 《GitHub》 (영어). 2026년 11월 19일에 확인함. 
  13. ↑ “charts/mediawiki/templates/mediawiki/container.yaml.tpl”. 《GitHub》 (영어). 2026년 11월 19일에 확인함. 
  14. ↑ “APCu Introduction”. 《PHP Manual》 (영어). 2026년 11월 19일에 확인함. 
  15. ↑ “Object cache”. 《MediaWiki》 (영어). 2026년 11월 17일에 확인함. 
  16. ↑ “includes/ObjectCache/ObjectCacheFactory.php”. 《GitHub》 (영어). 2026년 11월 17일에 확인함. 
  17. ↑ “includes/ObjectCache/ObjectCacheFactory.php”. 《GitHub》 (영어). 2026년 11월 17일에 확인함. 
  18. ↑ “Redis”. 《MediaWiki》 (영어). 2026년 11월 19일에 확인함. 
  19. ↑ “wmf-config/CommonSettings.php”. 《GitHub》 (영어). 2026년 11월 19일에 확인함. 
  20. ↑ “Manual:Performance tuning”. 《MediaWiki》 (영어). 2026년 11월 19일에 확인함. 
  21. ↑ “Licenses”. 《Redis》 (영어). 2026년 11월 19일에 확인함. 
  22. ↑ “Manual:Memcached”. 《MediaWiki》 (영어). 2026년 11월 19일에 확인함. 
  23. ↑ “Redis”. 《MediaWiki》 (영어). 2026년 11월 19일에 확인함. 
  24. ↑ “includes/MainConfigSchema.php”. 《GitHub》 (영어). 2026년 11월 17일에 확인함. 
  25. ↑ “includes/Page/WikiPage.php”. 《GitHub》 (영어). 2026년 11월 19일에 확인함. 
  26. ↑ “includes/Actions/PurgeAction.php”. 《GitHub》 (영어). 2026년 11월 19일에 확인함. 
  27. ↑ “includes/MainConfigSchema.php”. 《GitHub》 (영어). 2026년 11월 19일에 확인함. 
  28. ↑ “includes/SpecialPage/QueryPage.php”. 《GitHub》 (영어). 2026년 11월 19일에 확인함. 
  29. ↑ “includes/MainConfigSchema.php”. 《GitHub》 (영어). 2026년 11월 19일에 확인함. 
  30. ↑ “Manual:$wgLocalisationCacheConf”. 《MediaWiki》 (영어). 2026년 11월 17일에 확인함.