Random content redirect benchmarks

<h1>Random content redirects on peterwilson.cc</h1>

<p class="intro">
	WordPress 7.2 picks a random post by looking up 50 random post IDs, up to three
	times, then falls back to a pool of up to 1,000 posts ordered by
	<code>RAND()</code>. This site replaces that with a sample of 100 random candidate
	IDs cached in a transient for twelve hours, checked in PHP, with a
	<code>RAND()</code> query of eligible posts only as the fallback.
</p>

<p class="intro">
	Three versions were measured against the live site: 7.2 RC4, 7.2 RC5 with the
	<code>max_post_id</code> cache fixed, and this site's replacement. Each archive was
	requested on the domain that serves it, peterwilson.cc except short notes, which
	live on peterwilson.me.
</p>

<h2>Averages across all six archives</h2>
<div id="totals"></div>

<h2>Database queries per request</h2>
<p class="note">
	Mean of 50 requests per archive. Lower is better.
</p>
<div id="queries"></div>

<h2>Database time per request</h2>
<p class="note">
	Milliseconds, from <code>SAVEQUERIES</code> timings. A request that runs no query
	counts as zero rather than being left out of the average, which otherwise flatters
	whichever version queries least.
</p>
<div id="dbtime"></div>

<h2>PHP execution time per request</h2>
<p class="note">
	Milliseconds spent generating the response, measured on the server from
	<code>REQUEST_TIME_FLOAT</code>, so it covers all of WordPress but excludes the
	network. Measured from a browser these requests take around 320&nbsp;ms, almost all
	of it the round trip to the origin.
</p>
<div id="php"></div>

<h2>Requests that ran no database query at all</h2>
<p class="note">Of 50 per archive.</p>
<div id="zero"></div>

<h2>Requests that needed a fallback query</h2>
<p class="note">
	Of 50 per archive. When the sampled IDs yield no post, core reads a pool of up to
	1,000 posts ordered by <code>RAND()</code>, and this site re-samples the archive
	for eligible posts only. Either is the most expensive query its version can run.
</p>
<div id="fallback"></div>

<h2>The code</h2>
<p class="note">
	<code>content/mu-plugins/pwcc-performance/inc/random-content.php</code>, the
	version measured above.
</p>
<pre class="source" id="source">&lt;?php
/**
 * Modify WordPress's random content redirects.
 *
 * WordPress 7.2 introduced random content redirects, URLs such as `/random/`
 * and `/random/category/news/` that redirect to a randomly selected post. Core
 * selects the post by looking up a sample of random post IDs between one and
 * the highest post ID, which assumes eligible posts are evenly spread across
 * the ID range. On this site, where a lot of IDs belong to attachments, notes
 * and unpublished posts, that assumption makes the selection unpredictable and
 * can force core to fall back to reading every post in an archive.
 *
 * This replaces core's selection with a simpler one:
 *
 * - The main query asks the database for 100 random post IDs, `ORDER BY RAND()
 *   LIMIT 100`, rather than filtering on a sample of guessed IDs.
 * - The 100 IDs are cached in a transient for twelve hours, keyed by a hash of
 *   the query variables, so each archive runs the query at most twice a day.
 *   The sample is also the set of posts the archive can redirect to while it is
 *   cached, so a shorter life means a wider spread of posts over a day.
 * - The cached IDs short circuit the database query on the `posts_pre_query`
 *   filter.
 * - PHP picks one of the IDs at random and the request redirects to it.
 *
 * The redirect is also sent earlier than core's, on `send_headers` rather than
 * `template_redirect`. Core runs late so plugins restricting access, such as
 * Restricted Site Access, can intervene before a redirect is sent. No such
 * plugin is installed here, so the request can end as soon as the post has been
 * selected.
 *
 * @package pwcc-site
 */

namespace PWCC\Perf\RandomContent;

use WP_Post;
use WP_Query;

/**
 * Number of random posts to select from.
 */
const SAMPLE_SIZE = 100;

/**
 * Number of posts to prime the post cache for before selecting a post.
 *
 * This site doesn't have any posts with passwords set so all posts generated
 * by the initial query should be eligible. The fallback is used as protection
 * in case I add some at a later date.
 */
const INITIAL_PRIME_SIZE = 1;

/**
 * Number of posts to prime the post cache for once the first group is exhausted.
 */
const PRIME_SIZE = 10;

/**
 * Prefix for the transient storing the sampled post IDs.
 */
const TRANSIENT_PREFIX = 'pwcc_random_content_';

/**
 * Kick it off.
 */
function bootstrap() {
	/*
	 * Core adds its own callback to this hook at priority 20, from
	 * WP::handle_random(), so this runs immediately before it.
	 */
	add_action( 'pre_get_posts', __NAMESPACE__ . '\\replace_core_random_query', 19 );
	add_action( 'send_headers', __NAMESPACE__ . '\\maybe_redirect_early', 1 );
}

bootstrap();

/**
 * Replace core's random content query with this site's.
 *
 * Removes core's query modifications, including the sample of random post IDs
 * and the query to find the highest post ID it needs, and replaces them with
 * query variables selecting a random sample of posts.
 *
 * The restrictions core places on the query are retained: only published,
 * unprotected posts of a randomable post type are eligible, regardless of how
 * `pre_get_posts` callbacks modify the archive being randomized.
 *
 * Password protected posts are the exception, they are excluded when the post
 * is selected rather than by the query. The `post_password` column is not
 * indexed, so the `has_password` query variable prevents the database reading
 * the sample from an index: on a blog home or post type archive it turns a
 * covering index scan of `type_status_date` into a lookup of the full row of
 * every published post. Core excludes them the same way when it selects its
 * pool of posts, see {@see wp_random_content_posts_pre_query()}.
 *
 * Core's `posts_fields` filter is also retained, it limits the query to post
 * IDs.
 *
 * Runs on the `pre_get_posts` hook at priority 19.
 *
 * @param WP_Query $query The WP_Query instance (passed by reference).
 */
function replace_core_random_query( $query ) {
	if ( ! wp_is_random_content_query( $query ) ) {
		return;
	}

	remove_action( 'pre_get_posts', 'wp_random_content_pre_get_posts', 20 );
	remove_filter( 'posts_where', 'wp_random_content_posts_where', 20 );
	remove_filter( 'posts_orderby', 'wp_random_content_posts_orderby', 20 );
	remove_filter( 'post_limits', 'wp_random_content_post_limits', 20 );
	remove_filter( 'posts_pre_query', 'wp_random_content_posts_pre_query', 20 );

	add_filter( 'posts_pre_query', __NAMESPACE__ . '\\filter_posts_pre_query', 20, 2 );

	$query-&gt;set( 'post_type', wp_get_random_content_post_types( $query ) );
	$query-&gt;set( 'post_status', 'publish' );
	$query-&gt;set( 'orderby', 'rand' );
	$query-&gt;set( 'posts_per_page', SAMPLE_SIZE );

	/*
	 * Pin the request to the first page of the sample.
	 *
	 * `page` and `paged` are public query variables, so any visitor can ask for
	 * `/random/?paged=2`. Left alone that moves the LIMIT past the sample and
	 * selects nothing on an archive with fewer than twice the sample size of
	 * eligible posts, and, as the cache key is hashed from the query variables,
	 * gives every value its own sample and transient.
	 *
	 * An offset takes precedence over `paged` in WP_Query, so it fixes the
	 * window on the first SAMPLE_SIZE rows, and normalizing the two paging
	 * variables keeps an archive on one cache key however the page was asked
	 * for. See {@see get_cache_key()}.
	 */
	$query-&gt;set( 'offset', 0 );
	$query-&gt;set( 'paged', 1 );
	$query-&gt;set( 'page', 1 );
	$query-&gt;set( 'ignore_sticky_posts', true );
	$query-&gt;set( 'no_found_rows', true );
	$query-&gt;set( 'update_post_meta_cache', false );
	$query-&gt;set( 'update_post_term_cache', false );
	// Core's posts_fields filter limits the query to post IDs, which a suppressed query skips.
	$query-&gt;set( 'suppress_filters', false );
}

/**
 * Select the random post from a cached sample of random posts.
 *
 * The sampled post IDs are stored in a transient for twelve hours. While the
 * transient is set the database is not queried at all, the post is selected from
 * the cached IDs. Otherwise the query built by WP_Query is run to sample the
 * IDs, and the result cached.
 *
 * As the sample may be twelve hours old, posts that have since been unpublished,
 * deleted, password protected or changed to another post type are skipped.
 *
 * If none of the sample's posts are eligible the sample is discarded and
 * replaced by one of eligible posts only, see {@see query_sample_ids()}.
 * That happens when a cached sample has gone out of date, and on archives where
 * password protected posts are common enough that a sample of 100 posts can
 * miss every unprotected one.
 *
 * Runs on the `posts_pre_query` filter at priority 20.
 *
 * @param WP_Post[]|int[]|null $posts Posts short-circuiting the query, or null to run the query.
 * @param WP_Query             $query The WP_Query instance.
 * @return WP_Post[]|int[]|null The selected post, an empty array if no post is eligible,
 *                              or the unmodified value if the query is not for random content.
 */
function filter_posts_pre_query( $posts, WP_Query $query ) {
	if ( null !== $posts || ! wp_is_random_content_query( $query ) || ! is_string( $query-&gt;request ) ) {
		return $posts;
	}

	$post_types = array_filter( (array) $query-&gt;get( 'post_type' ), 'is_string' );
	$cache_key  = get_cache_key( $query );
	$post_ids   = get_transient( $cache_key );

	if ( ! is_array( $post_ids ) ) {
		$post_ids = query_sample_ids( $query );
		set_transient( $cache_key, $post_ids, 12 * HOUR_IN_SECONDS );
	}

	$post = select_random_post( $post_ids, $post_types );

	/*
	 * No post in the sample is eligible, so sample the eligible posts instead
	 * and replace the cached sample with them.
	 *
	 * An empty sample is trusted rather than taken again, it means the archive
	 * had no published posts at all when it was taken. The sample is not
	 * limited to eligible posts, so an archive with posts always samples some.
	 */
	if ( null === $post &amp;&amp; array() !== $post_ids ) {
		$post_ids = query_sample_ids( $query, true );
		set_transient( $cache_key, $post_ids, 12 * HOUR_IN_SECONDS );

		$post = select_random_post( $post_ids, $post_types );
	}

	return null === $post ? array() : array( $post );
}

/**
 * Build the cache key for a random content query.
 *
 * The key is hashed from the query's variables, so each archive, and each
 * variation of an archive produced by `pre_get_posts` callbacks, has its own
 * sample of posts.
 *
 * The `random` query variable is excluded as its value depends on how random
 * content was requested, by the rewrite rules or the query string, rather than
 * on the posts the query selects from.
 *
 * The paging variables are not excluded here, they are normalized before the
 * query runs, see {@see replace_core_random_query()}.
 *
 * @param WP_Query $query The WP_Query instance.
 * @return string Transient name.
 */
function get_cache_key( WP_Query $query ) {
	$query_vars = $query-&gt;query_vars;
	unset( $query_vars['random'] );
	ksort( $query_vars );

	return TRANSIENT_PREFIX . md5( (string) maybe_serialize( $query_vars ) );
}

/**
 * Run the random content query to sample post IDs.
 *
 * The query built by WP_Query is run directly, as with core's random content
 * query, because WP_Query is short circuited by the `posts_pre_query` filter
 * running this. The query selects post IDs, see
 * {@see wp_random_content_posts_fields()}, randomly ordered and limited to the
 * sample size.
 *
 * @global \wpdb $wpdb WordPress database abstraction object.
 *
 * Password protected posts are normally left in the sample and skipped when the
 * post is selected, as the `post_password` column is not indexed and the clause
 * stops the database reading the sample from an index. `$eligible_only` adds the
 * clause back, so every ID returned is an eligible post. It is used only when a
 * sample without it has produced no eligible post, so the archive is read in
 * full on the rare request that needs it rather than on every request.
 *
 * The clause is added to the request WP_Query built, rather than by running a
 * second WP_Query, so the sample comes from exactly the same posts as the main
 * query. Rebuilding the query from its variables would double the clauses WP_Query
 * derives from each other, for example `category_name` and `cat` on a category
 * archive. Core does the reverse to the same request, removing the clause to
 * select its pool of posts.
 *
 * @param WP_Query $query         The WP_Query instance.
 * @param bool     $eligible_only Optional. Whether to exclude password protected
 *                                posts in SQL. Default false.
 * @return int[] Sampled post IDs.
 */
function query_sample_ids( WP_Query $query, $eligible_only = false ) {
	global $wpdb;

	// The placeholder escape string is unique to each request, see wpdb::placeholder_escape().
	$request = $wpdb-&gt;remove_placeholder_escape( $query-&gt;request );

	if ( $eligible_only ) {
		$where_clause = 'WHERE 1=1';

		/*
		 * WP_Query opens every WHERE clause with `WHERE 1=1`. The password clause
		 * is only added if it appears exactly once, as a filter may have added a
		 * subquery containing another one. Otherwise the sample is taken as if
		 * `$eligible_only` was not requested, and the protected posts in it are
		 * skipped when the post is selected.
		 */
		if ( 1 === substr_count( $request, $where_clause ) ) {
			$request = str_replace(
				$where_clause,
				$where_clause . " AND {$wpdb-&gt;posts}.post_password = ''",
				$request
			);
		}
	}

	// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- The request is prepared by WP_Query::get_posts() and the result cached in a transient.
	return array_map( 'intval', $wpdb-&gt;get_col( $request ) );
}

/**
 * Select a random eligible post from sampled post IDs.
 *
 * The IDs are shuffled and the first eligible post returned, so each post in
 * the sample is equally likely to be selected.
 *
 * The post cache is primed in small groups as the posts are needed, rather than
 * for the whole sample or for each post in turn. The first group is
 * `INITIAL_PRIME_SIZE` posts: the first post checked is nearly always eligible,
 * so the usual cost of the selection is a single query for that group. Once a
 * group is exhausted the next `PRIME_SIZE` posts are primed, and so on until
 * the sample runs out.
 *
 * Priming skips posts already in the object cache, so a group is only queried
 * for the posts missing from it and a fully cached group is not queried at all.
 * Deleted posts are not cached, by priming or otherwise, so each one costs a
 * query of its own when it is reached.
 *
 * @param int[]    $post_ids   Sampled post IDs.
 * @param string[] $post_types Post types eligible for selection.
 * @return WP_Post|null The selected post, or null if none of the posts are eligible.
 */
function select_random_post( array $post_ids, array $post_types ) {
	shuffle( $post_ids );

	$total      = count( $post_ids );
	$offset     = 0;
	$prime_size = INITIAL_PRIME_SIZE;

	while ( $offset &lt; $total ) {
		$group = array_slice( $post_ids, $offset, $prime_size );

		// Term and meta caches are not primed, the post is only used for its permalink.
		_prime_post_caches( $group, false, false );

		foreach ( $group as $post_id ) {
			$post = get_post( (int) $post_id );

			if (
				$post instanceof WP_Post
				&amp;&amp; 'publish' === $post-&gt;post_status
				&amp;&amp; '' === $post-&gt;post_password
				&amp;&amp; in_array( $post-&gt;post_type, $post_types, true )
			) {
				return $post;
			}
		}

		$offset    += $prime_size;
		$prime_size = PRIME_SIZE;
	}

	return null;
}

/**
 * Redirect random content requests before the template is loaded.
 *
 * Core sends the redirect on `template_redirect` at priority 100, late enough
 * for plugins restricting access to intervene. No such plugin is installed, so
 * the redirect is sent as soon as the main query has selected a post, on
 * `send_headers`, skipping the `wp` action and template loading entirely.
 *
 * The redirect itself is core's, so the headers preventing it being cached or
 * indexed are sent with it and the post is validated once more before it is.
 *
 * Runs on the `send_headers` hook at priority 1.
 */
function maybe_redirect_early() {
	// Core only adds the callback once the main query has selected a post.
	if ( false === has_action( 'template_redirect', 'wp_random_content_redirect' ) ) {
		return;
	}

	remove_action( 'template_redirect', 'wp_random_content_redirect', 100 );

	/*
	 * Batcache caches redirects, see the `cache_redirects` setting in wp-config.php,
	 * which would serve every visitor the same post for the life of the cache. Its
	 * per-request opt-out is checked before the response is stored, so cancelling
	 * here leaves the rest of the site's redirects cached.
	 */
	if ( function_exists( 'batcache_cancel' ) ) {
		batcache_cancel();
	}

	wp_random_content_redirect();
}
</pre>

<h2>Notes</h2>
<ul class="notes">
	<li>
		<strong>The difference is short notes.</strong> Once the <code>MAX(ID)</code>
		query is gone, RC5 and this site are within 0.04 queries a request of each
		other on four of the six archives: both reach a cached sample and read one
		post out of it. Short notes is where they part, 2.00 against 0.74 across
		2,106 published posts, and it is the case this site's approach was built
		for.
	</li>
	<li>
		<strong>No visitor could tell these apart.</strong> PHP execution time sits
		within 1.1&nbsp;ms across all three versions, against a round trip of roughly
		320&nbsp;ms from a browser. The argument for any of this is database load, not
		the speed of a single response.
	</li>
	<li>
		<strong>The cached sample is also the pool of posts an archive can
		return.</strong> While the transient is set, every visitor is redirected to
		one of the sampled IDs, so its twelve hour life caps how many distinct posts
		an archive serves. It matters on one archive here: short notes has 2,106
		eligible posts, so a sample of 100 reaches under 5% of them. Every other
		archive on the site has fewer than 146 eligible posts and is returning nearly
		all of them. The sample's lifetime changes how often it is taken, not what a
		request costs while it is cached.
	</li>
	<li>
		<strong>The first prime is a single post.</strong> The sample is shuffled and
		the first eligible post wins, so the post cache is primed for one post,
		<code>INITIAL_PRIME_SIZE</code>, before the first eligibility check. A post is
		only skipped if it has since been unpublished, deleted, protected or moved to
		another post type, and this site has no password protected posts, so the first
		ID is all but always the one returned. Priming more would fetch rows no
		request reads. Where the first post is not eligible, the sample is worked
		through in groups of <code>PRIME_SIZE</code>, ten, which is what covers a
		stale sample or protected posts being added later.
	</li>
	<li>
		<strong>Redirecting early is not only about speed.</strong> Core sends its
		redirect on <code>template_redirect</code> at priority 100, so any earlier
		callback that redirects wins and core's work is thrown away. Two on this site
		do. The multi-domain redirect, on <code>template_redirect</code> at priority
		10, sends a request for short notes from peterwilson.cc to peterwilson.me, so
		core serves that archive in two requests rather than one and costs twice what
		one row shows; the figures above ask peterwilson.me directly, which is the
		fair comparison. Yoast SEO redirects author archives to the home page on the
		<code>wp</code> hook, earlier again, so under core <code>/random/author/…/</code>
		returns no post at all. That archive is left out of the figures for that
		reason. This site's version redirects on <code>send_headers</code>, before
		both, which is why it returns a post on archives where core does not.
	</li>
	<li>
		<strong>What this does not measure.</strong> Core refreshes its 1,000 post pool
		every ten minutes, so over a day that is around 144 <code>ORDER BY RAND()</code>
		queries per archive against the whole archive. This site takes one 100 row
		sample per archive per day. Only three pool queries landed inside the measured
		window, so the sustained cost of that refresh is not in these figures.
	</li>
	<li>
		<strong>Each version is measured in a cache of its own.</strong> A post one
		version fetches would otherwise sit in the object cache for the others to read
		for free, so whichever asked first would pay for all three. Each version is
		given its own key space instead, so each pays its own cold start. The versions
		are still interleaved, a round at a time with the order rotating, which evens
		out anything that drifts over the length of a run. One trap is left to avoid
		in the figures themselves: averaging database time only over requests that ran
		a query makes the version that queries least look slowest, so a request that
		ran none counts as zero here.
	</li>
	<li>
		<strong>Environment.</strong> Run against production on 3 December 2026: PHP 8.4
		and MySQL 8.0, with a Redis object cache, Batcache page caching and CloudFront
		in front, both bypassed per request so every request reached PHP. The run
		started from a cold object cache without emptying the one visitors are served
		from: the benchmark requests carry a <code>WP_CACHE_KEY_SALT</code> no earlier
		request has used, which gives them their own empty key space in Redis, one per
		version. Each archive then received one discarded warm-up request per version.
		50 rounds per archive, the three versions interleaved, 900 measured requests in
		total.
	</li>
	<li>
		<strong>The RC5 column is simulated.</strong> This site has never run a build
		containing the fix. The benchmark reads core's cached highest post ID, casts it
		and writes it back before the main query, so core's own
		<code>wp_cache_get()</code> returns an integer, passes its check and skips the
		query. The effect on queries is the same as the commit below, reached from
		outside core rather than by patching it.
	</li>
	<li>
		<strong>Core 7.2 RC4 queried <code>MAX(ID)</code> on every request.</strong>
		<a href="https://github.com/WordPress/wordpress-develop/commit/9f4283fde73a311752582b837edff9db07e62ab2">WordPress/WordPress-Develop@9f4283fde7</a>
	</li>
</ul>

Previous Code Bin

WordPress 7.2 about page: translatable /random URL