Skip to content

[00] Subset Sizes, For developers

How Subset Sizes works

Last updated

How Subset Sizes makes a missing image size on first request: the URL handler, the per-image lock, the metadata merge and the hooks at each step.

This page follows a request for an image size that doesn’t exist yet, from the web server to the file on disk. It covers the URL handler, the per-image lock and how the new size is written into attachment metadata, with the hooks you can use at each step.

What happens at upload

WordPress makes every registered size when you upload an image. Subset Sizes filters intermediate_image_sizes_advanced and, when lazy sizes is on, drops every size except the kept ones. The kept sizes are the kept_sizes setting (thumbnail and medium by default), and the subir_kept_sizes filter can change the list in code.

Lazy sizes is the lazy_mode setting. It’s turned on for a fresh install, and a site that updated from an earlier version keeps the value it had. Both settings live in the subir_settings option.

Every size that wasn’t made at upload is made later, the first time something asks for it.

Handing out a URL for a missing size

When a theme calls wp_get_attachment_image() or anything else that ends in image_downsize, Subset Sizes answers with the size’s planned URL, whether or not the file exists. The file name follows the WordPress pattern, photo-800x600.jpg, so the URL is the one WordPress would have used.

What happens next depends on two settings, and on the request. Admin screens, REST, AJAX, cron and WP-CLI requests never make files while rendering, because the media library asks for every size of every image at once. You can change that decision with the subir_can_generate filter.

On a front-end page:

  • By default, nothing is made yet. The browser requests the URL, and the URL handler makes the file.
  • With sync_on_request on, the size is made during the page request, before the URL is printed. If that fails, the URL stays and the handler gets another chance.
  • With async on and Action Scheduler loaded, Subset Sizes queues the size in Action Scheduler (subir_generate_size, group subir) and prints an existing larger file with the same aspect ratio in its place, keeping the missing size’s width and height. If no file can stand in without changing the layout, the size is made now.

Sizes requested as [width, height] arrays rather than by name are added to an allowlist, the subir_allowed_sizes option, before their URL is printed. The list holds at most 200 entries. The URL handler only makes sizes that are registered or on this list.

The URL handler

A request for a missing file only reaches PHP if the web server passes it to index.php. The standard Apache .htaccess does. nginx, Apache on multisite and plain permalinks need a rule, listed under server configuration.

Http\UrlHandler catches the request in two places:

  1. A rewrite rule for files under uploads named {name}-{width}x{height}.{jpg|jpeg|png|gif|webp|avif}. It sets the subir_image query var, and the handler answers on parse_request at priority 0, before WordPress runs the main query.
  2. A fallback on template_redirect at priority 0, for requests that ended as a 404 because the rule never matched. On plain permalinks there are no rewrite rules, so the handler checks the path on parse_request instead.

The handler then works through these checks in order:

  1. The subir_upload_request filter can answer any request under uploads first. Pro uses it to serve AVIF and WebP copies.
  2. A width or height above max_dimension (4096 by default, 0 for no cap) gets a 404.
  3. The file name has to match a size of a real attachment. The handler looks up attachments whose file starts with the same stem, including -scaled and -rotated originals, and asks the planner which registered or allowlisted size has exactly those dimensions. Any other dimensions get a 404 unless the URL carries a valid subir_sig signature, which Pro’s signed transform URLs add.
  4. If the file exists, it’s served. If an offload plugin moved it to remote storage, the subir_remote_size_url filter can return a URL to redirect to.
  5. Each visitor can trigger rate_limit new sizes a minute (60 by default, 0 for no limit). The count is per IP address, or per /64 for IPv6, and the address comes from the subir_client_ip filter. Over the limit, the visitor gets a 429 with Retry-After: 60.
  6. The size is made, through the same Engine\Generator::ensure() every other part of the plugin uses.

A size is served with Cache-Control: public, max-age=31536000, which the subir_cache_control filter can change. The subir_size_response filter gets the response before it’s sent. The file is saved at the requested path, so the next request for it never reaches PHP.

OutcomeResponse
Size made or already on disk200 with the image
Unknown dimensions or over max_dimension404
Over the rate limit429, Retry-After: 60
Another request holds the image’s lock503, Retry-After: 1
The size would be larger than the original404
Making the file failed500, or a redirect from subir_remote_size_url

When the server never passes the request on

If the rule is missing, every URL for a missing size would be a broken image. The self-test (Http\SelfTest) requests a probe file under uploads from the site itself and stores the result in subir_handler_status. It runs from Site Health, after activation and after a permalink change, and from wp subset image-resizer self-test. While the result is unreachable, missing sizes are made while the page renders, and Site Health shows how to fix the server. A failed loopback counts as reachable, because it says nothing about the web server.

The lock

Two visitors can ask for the same image at the same moment, and a page often asks for several sizes of one image at once. Generation runs inside Storage\Lock::synchronized(), which wraps the named lock from subset-core.

The lock is per attachment rather than per size, because every size of an image is recorded in the same metadata array. Its key is _subir_lock_{attachment ID}. Taking it is a single atomic write:

  • With a persistent object cache, wp_cache_add() in the subir_locks group.
  • Without one, an INSERT IGNORE into the options table, where the option name is a unique key. add_option() can’t be used because it upserts.
FilterDefaultWhat it sets
subir_lock_wait10 secondsHow long a request waits for the lock, polling every 0.1 seconds.
subir_lock_ttl60 secondsWhen a held lock counts as abandoned by a crashed request.
subir_lock_use_object_cachewp_using_ext_object_cache()Whether the lock uses the object cache instead of the options table.

Each filter also receives the attachment ID as a string. Turn subir_lock_use_object_cache off if your object cache isn’t shared between web servers.

A request that can’t get the lock in time gets a subir_lock_timeout error, which the URL handler turns into a 503 with Retry-After: 1. By then the other request has usually finished the file. A request that gets the lock after waiting checks the disk again first: if the size now exists, it only records it in the metadata and doesn’t resize anything.

Each lock stores its expiry and a random token. A request releases a lock only if the token still matches, and clears an expired lock only if its value is still the one it read, so a slow request can’t remove a lock another request has since taken. The lock is re-entrant within one request.

Writing the size into metadata

The new size has to be added to _wp_attachment_metadata without losing a size that another request added a moment earlier. Engine\Generator::merge_metadata() runs while the lock is held, and:

  1. Deletes the attachment’s post_meta cache entry, so the next read comes from the database.
  2. Reads the metadata again with wp_get_attachment_metadata().
  3. Sets only sizes[{size name}] to the new file’s entry.
  4. Saves it with wp_update_attachment_metadata().

Because every write for an attachment holds that attachment’s lock and starts from a fresh read, concurrent requests add their sizes one after another instead of overwriting each other. The allowlist uses the same lock with ID 0, which no attachment has, for its own read, change and write.

Around the resize, subir_before_generate fires inside the lock (offload integrations fetch a remote original here), and subir_after_generate fires after every attempt, even one that failed or threw. Once a file has been made and recorded, subir_size_generated fires with the attachment ID, the size name and its metadata entry:

add_action( 'subir_size_generated', function ( int $attachment_id, string $size, array $data ) {
	error_log( "Made {$size} for {$attachment_id}: {$data['file']}" );
}, 10, 3 );

To make missing sizes ahead of time instead of on request, use wp subset image-resizer generate, listed under WP-CLI. It goes through the same generator, lock and metadata merge.