Generating downloadable PDF price sheets on demand inside WordPress and WooCommerce looks harmless on a staging server with one browser tab open. In production on a building-materials or flooring catalog with hundreds of SKUs across dozens of categories, a single bulk price update followed by 30 concurrent contractor downloads or crawler requests can saturate every PHP-FPM worker in seconds.
When we maintain category-level flooring quotation sheets alongside live product catalogs (such as the flooring price guide at 3K Home), a naive "invalidate cache on save, rebuild synchronously on the next GET request" flow routinely creates a cache stampede. Below is a practical, zero-dependency pattern using atomic per-slug locks, stale-while-revalidate disk artifacts, and ETag short-circuiting that keeps TTFB flat without adding a separate queue daemon.
Why Dynamic PDF Endpoints Trigger Thundering Herds
PDF rendering libraries (Dompdf, mPDF, or headless Chromium wrappers) allocate 40 MB to 140 MB of RAM per request and hold a PHP worker for 800 ms to 3,500 ms. A typical stampede happens in three steps:
- An editor runs a bulk CSV import that updates 120 product prices, firing
woocommerce_update_productand purging all cached PDFs. - Within the next two seconds, 25 dealers or search crawlers request
/price-list/laminate-12mm.pdf. - Every request observes a cache miss and starts rendering the exact same 14-page PDF concurrently. PHP-FPM hits
pm.max_children, memory spikes, and unrelated checkout pages stall with HTTP 504.
Adding a simple get_transient() check around the render call fails under concurrency because two requests can both see false before either finishes writing the rendered file.
Design Goals
A resilient WooCommerce PDF generator should satisfy four invariants:
- Single flight per category slug: At most one PHP worker renders a given PDF artifact at any moment.
- Stale-while-revalidate serving: If a previous valid PDF already exists on disk, concurrent visitors receive the stale artifact immediately instead of waiting on a lock.
- Atomic file swap: Readers never observe a half-written PDF file.
-
Conditional HTTP validation: Repeat visitors and CDNs pay near-zero bandwidth via
ETagand304 Not Modified.
Step 1: Decouple Catalog Version Hashing from File Deletion
Never unlink() the existing PDF when a product changes. Instead, store a lightweight integer revision counter per category term (for example, wpdpl_rev_{slug}) and bump it on woocommerce_update_product or save_post_product.
<?php
declare(strict_types=1);
function wpdpl_bump_category_revisions(int $product_id): void {
$terms = get_the_terms($product_id, 'product_cat');
if (empty($terms) || is_wp_error($terms)) {
return;
}
foreach ($terms as $term) {
$key = 'wpdpl_rev_' . sanitize_key($term->slug);
$current = (int) get_option($key, 1);
update_option($key, $current + 1, false);
}
}
add_action('woocommerce_update_product', 'wpdpl_bump_category_revisions', 20, 1);
Notice the third parameter false on update_option(). Keeping revision counters non-autoloaded prevents bloating wp_options autoload memory on unrelated storefront requests.
Step 2: Atomic Per-Slug Lock with Stale Fallback
Store two paths under wp-content/uploads/wpdpl-cache/:
-
{$slug}.pdf: the last completed artifact, always valid to stream. -
{$slug}.rev: a small text file recording which revision integer generated{$slug}.pdf.
When a request arrives, compare the current wpdpl_rev_{slug} option against the value in {$slug}.rev. If they match, stream {$slug}.pdf immediately. If they differ, try to acquire a non-blocking lock.
If you run Redis or Memcached with a persistent object cache drop-in, wp_cache_add() provides an atomic compare-and-set primitive. On single-node VPS deployments without Redis, a local flock($fp, LOCK_EX | LOCK_NB) on a dedicated lock file gives strict kernel-level mutual exclusion without touching MySQL tables.
<?php
declare(strict_types=1);
function wpdpl_serve_pdf(string $raw_slug): void {
$slug = sanitize_key($raw_slug);
$cache_dir = trailingslashit(wp_upload_dir()['basedir']) . 'wpdpl-cache/';
wp_mkdir_p($cache_dir);
$pdf_path = $cache_dir . $slug . '.pdf';
$rev_path = $cache_dir . $slug . '.rev';
$lock_path = $cache_dir . $slug . '.lock';
$target_rev = (int) get_option('wpdpl_rev_' . $slug, 1);
$disk_rev = file_exists($rev_path) ? (int) trim((string) file_get_contents($rev_path)) : 0;
if ($disk_rev !== $target_rev || !file_exists($pdf_path)) {
$fp = fopen($lock_path, 'c');
if ($fp !== false && flock($fp, LOCK_EX | LOCK_NB)) {
try {
// Re-check inside lock in case another worker finished just before us.
$recheck = file_exists($rev_path) ? (int) trim((string) file_get_contents($rev_path)) : 0;
if ($recheck !== $target_rev || !file_exists($pdf_path)) {
$tmp_path = $pdf_path . '.' . getmypid() . '.tmp';
$bytes = wpdpl_render_category_pdf($slug);
if (file_put_contents($tmp_path, $bytes, LOCK_EX) !== false) {
rename($tmp_path, $pdf_path); // Atomic on POSIX filesystems
file_put_contents($rev_path, (string) $target_rev, LOCK_EX);
$disk_rev = $target_rev;
}
}
} finally {
flock($fp, LOCK_UN);
fclose($fp);
}
} elseif ($fp !== false) {
fclose($fp);
// Lock held by another worker: serve stale artifact if available.
if (!file_exists($pdf_path)) {
status_header(503);
header('Retry-After: 3');
exit('Generating price list, please retry shortly.');
}
}
}
wpdpl_stream_with_etag($pdf_path, $slug, $disk_rev);
}
Step 3: Short-Circuit Repeat Downloads with Weak or Strong ETag
Dealers and internal sales reps frequently reopen the same PDF link multiple times a day to verify specifications. Adding a deterministic ETag derived from ($slug, $disk_rev, filesize) lets browsers and reverse proxies validate freshness in microseconds without re-downloading multi-megabyte files.
<?php
declare(strict_types=1);
function wpdpl_stream_with_etag(string $pdf_path, string $slug, int $rev): void {
$size = filesize($pdf_path);
$etag = sprintf('"%s-r%d-%d"', $slug, $rev, $size);
header('Content-Type: application/pdf');
header('Content-Disposition: inline; filename="' . $slug . '-price-list.pdf"');
header('Cache-Control: public, max-age=300, stale-while-revalidate=600');
header('ETag: ' . $etag);
$client_etag = isset($_SERVER['HTTP_IF_NONE_MATCH'])
? trim((string) $_SERVER['HTTP_IF_NONE_MATCH'])
: '';
if ($client_etag === $etag) {
status_header(304);
exit;
}
header('Content-Length: ' . (string) $size);
readfile($pdf_path);
exit;
}
Operational Guardrails Worth Adding Before Production
Before deploying this pattern to a live store, verify four practical edge cases:
-
Bot rate hygiene: Disallow PDF query variants in
robots.txtor enforce strict canonical slugs viasanitize_key()so scanners cannot generate unbounded.lockfiles for non-existent slugs. Validate$slugagainstterm_exists($slug, 'product_cat')before touching the filesystem. -
Orphan
.tmpcleanup: If a PHP worker hitsmemory_limitmid-render, thefinallyblock releasesflock, leaving a.tmpfile. Schedule a dailywp-cronsweep removing.tmpfiles older than 30 minutes. -
Multi-node web tiers: If you run more than one PHP container behind a load balancer without shared NFS locking, replace
flock()withwp_cache_add("wpdpl_lock_{$slug}", 1, 'wpdpl', 30)backed by Redis or MySQLGET_LOCK(). -
Pre-warming heavy categories: After a scheduled bulk price import finishes, enqueue an Action Scheduler job (
as_enqueue_async_action) for the top 5 categories so even the very first visitor after an update hits a warm file.
Summary
Cache stampedes on WooCommerce document generators rarely require heavy external message brokers to fix. Keeping the previous PDF intact during invalidation, bounding regeneration to a single worker via flock() or wp_cache_add(), swapping artifacts atomically via rename(), and responding with 304 Not Modified on matching ETag headers removes PHP-FPM exhaustion while keeping price sheets aligned with catalog updates.
Top comments (0)