Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 39 ยท Quality and Production

Performance and Scaling Large Stores

Keep large WooCommerce stores fast: costly product queries, object cache and transients, session growth, autoloaded options, HPOS, N+1 queries and cache exclusions.

A store with 50 products feels fast no matter how you write the code. A store with 200,000 products, a million orders and a flash sale at noon is a different animal: small inefficiencies are multiplied by thousands of requests. Your extension runs inside that machine, and a careless query in a hook that fires on every page can be the thing that brings it down.

This lesson covers where WooCommerce stores actually slow down and what an extension author can do about it: expensive product queries, caching with transients and the object cache, session and option bloat, the benefits of HPOS, the N+1 query trap, and what must never be cached. The real code needs WordPress, so it is read-only here. The runnable examples measure query counts with SQLite stand-ins, which is the same discipline you apply with Query Monitor (see Development Environment and Tooling). For general WordPress performance, read Performance Optimization first.

Measure first

Do not guess. Install Query Monitor on a staging copy with realistic data and look at three numbers per page: number of queries, slowest queries and time spent in hooks. A page that makes 400 queries is a problem even if each is fast. Fix the biggest cost first, and re-measure.

Product queries: what is expensive

Product data is spread over several tables (posts, post meta, term relationships), so some queries are cheap and some are not.

  • Sorting or filtering by meta values (price ranges, a custom field) joins the meta table and cannot use a good index. WooCommerce keeps a separate lookup table (wc_product_meta_lookup) with price, stock and SKU columns so common filters avoid the slow meta join. Prefer standard queries that use it over your own meta_query on _price.
  • Unbounded queries such as 'limit' => -1 load every product into memory. Always page results.
  • Asking for full objects when you need IDs. wc_get_products( array( 'return' => 'ids', 'limit' => 50 ) ) skips building 50 product objects.
  • orderby => rand forces the database to sort the whole result randomly. On big catalogs, pick a random offset or cache a list instead.
  • Variable products with hundreds of variations are costly to load and price. See Variations, Attributes and Taxonomies.
PHP
<?php
// Cheap: IDs only, bounded, standard fields.
$ids = wc_get_products( array(
    'status'  => 'publish',
    'limit'   => 24,
    'page'    => 1,
    'orderby' => 'date',
    'order'   => 'DESC',
    'return'  => 'ids',
) );

Transients and the object cache

When a result is expensive and does not change every second (a sales total, an external API's answer), cache it. WordPress offers two layers:

  • The object cache (wp_cache_get/set) lives for one request unless a persistent backend such as Redis or Memcached is installed; with one, it is shared across requests and is very fast.
  • Transients (get_transient/set_transient) are cache entries with an expiry time. With a persistent object cache they go to Redis; without one they are stored in the options table, which means a database write for each one and leftover rows when they expire. That is fine for a few, and harmful for thousands of keys.
PHP
<?php
function acme_top_sellers( int $limit = 5 ): array {
    $key = 'acme_top_sellers_' . $limit;
    $cached = get_transient( $key );
    if ( false !== $cached ) {
        return $cached;
    }
    $data = acme_expensive_query( $limit );
    set_transient( $key, $data, 15 * MINUTE_IN_SECONDS );
    return $data;
}
// Invalidate when the underlying data changes.
add_action( 'woocommerce_order_status_completed', fn() => delete_transient( 'acme_top_sellers_5' ) );

Rules: always give a transient an expiry and a way to invalidate it on change, use a bounded set of keys (never one per user per page without a limit), and treat a cache miss as normal: the code must work with an empty cache. Never cache anything user-specific in a shared key.

PHP A cache-aside helper and its hit rate

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Twelve requests cost only three slow computations: the first fill, the refill after expiry, and the refill after invalidation.

Options, sessions and other silent growth

Some slowdowns creep in over months:

  • Autoloaded options. Every row in wp_options with autoload set is loaded on every request. A plugin that stores a 2 MB array as an autoloaded option makes every page slower. Store large or rarely used data with autoload off (add_option( $name, $value, '', false ) or update_option( $name, $value, false )), or in your own table.
  • The sessions table. WooCommerce stores customer sessions (cart contents) in woocommerce_sessions. Each visitor, including bots, can create a row. Expired sessions are removed by a scheduled cleanup, but on huge traffic the table still grows large and the cleanup can lag. Do not create a session for visitors who do nothing; avoid calling WC()->session or setting cookies on pages that do not need them. See The Cart and Session.
  • Scheduled actions and logs. Old completed actions and big log files pile up; keep logging at a sensible level and prune.
  • Cart fragments. An AJAX call that refreshes the mini-cart on every page can be a bottleneck. Many themes remove it, or they load it only where needed.

HPOS: why orders got faster

Historically, orders were custom post types with their details in the post meta table, the same tables as blog posts. A large order list meant heavy joins on a table with millions of rows, and order queries competed with everything else. High-Performance Order Storage (HPOS) moves orders to dedicated tables with real columns for totals, status, customer and dates, and proper indexes. Listing and searching orders becomes much cheaper, and writes are lighter. For your code, this means: always use wc_get_orders() and the order CRUD methods, never get_post_meta() or direct wp_posts queries on orders, and declare HPOS compatibility. Details are in Orders and High-Performance Order Storage.

The N+1 query trap

The most common self-inflicted wound: loading a list, then running a query for each row. Showing 50 orders and calling a function that queries the customer, then the items, then a meta value, can produce 150+ queries. This is the N+1 problem: one query for the list plus N more.

flowchart LR
  subgraph Slow["N+1"]
    A["1 query: list 50 orders"] --> B["50 queries: one customer each"]
  end
  subgraph Fast["Batched"]
    C["1 query: list 50 orders"] --> D["1 query: all customers<br/>WHERE id IN (...)"]
  end

Same data, 51 queries versus 2. The batched version scales with the page, not with the row count.

Fixes: fetch related data in one query with IN (...) and index it by ID in PHP; ask for only the fields you need; use functions that prime caches in bulk (WordPress can load the meta for many posts in one go with update_meta_cache() or _prime_post_caches(), and many core functions do this when you use them instead of per-item calls).

PHP N+1 versus a batched query, counted

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Fifty-one queries became two. With 5,000 rows on a slower database the difference would be seconds.

Caching a store: what to exclude

A CDN or page cache (Cloudflare, a caching plugin, server-side cache) makes anonymous pages fast, but a shop has pages that are personal. Always exclude from full-page caching:

  • the cart, checkout and my-account pages,
  • any URL with WooCommerce AJAX parameters such as ?wc-ajax=,
  • requests carrying cart or session cookies (WooCommerce sets cookies such as woocommerce_items_in_cart, woocommerce_cart_hash and wp_woocommerce_session_*).

Caching the checkout would show one shopper another's cart. Rely on caching for catalog pages and make sure your own code does not put personal data into otherwise cacheable pages; load it with a small uncached request instead. Also keep premium or user-specific output out of shared caches. The same principle applies on this very site: cached pages stay identical for everyone and personal bits load separately.

PHP Which requests may a page cache serve?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the N+1 query problem?

    The list query is the "1"; the per-row follow-up queries are the "N". Batch the related data into one IN (...) query instead.
  2. 2. Where are transients stored when the site has no persistent object cache?

    Without Redis or Memcached, transients become option rows, so many keys mean many database writes and leftover rows.
  3. 3. Why can a large autoloaded option hurt every page?

    Autoload means WordPress reads the value on every request whether the code needs it or not. Store big or rare data with autoload off.
  4. 4. Which page must a full-page cache never serve to different shoppers?

    Cart, checkout and account pages contain personal, session-specific data and must bypass the page cache.

Summary

  • Measure with Query Monitor on realistic data; reduce query counts and the slowest queries first.
  • Use bounded, ID-only product queries, avoid meta-heavy filters and rand ordering on large catalogs.
  • Cache expensive results with expiry and invalidation; know that transients live in the options table without a persistent object cache.
  • Watch for silent growth: autoloaded options, session rows, old actions and logs.
  • HPOS gives orders their own indexed tables; always go through the order APIs.
  • Fix N+1 patterns by batching related lookups; exclude cart, checkout, account and session-cookie requests from page caches.

Next: Compatibility, Upgrades and Distribution