Shopify Liquid Performance: Profile, Then Flatten Loops

Shopify Liquid performance is a server problem first. Shopify renders Liquid on every storefront request, so slow Liquid shows up as a late document, not as a heavy bundle. Profile the page with shopify theme profile or the Theme Inspector, find the sections and loops with the most self time, then flatten nested loops and hoist lookups out of them.

Front-end tuning cannot shorten that wait. Shopify’s performance best practices say Liquid execution time sets the wait for the document, and the browser can do nothing until it arrives. The same page calls nested loops “the most common cause of high TTFB” and warns that loops nested across products, variants or options “grow quadratically with catalog size”. A theme that felt fine on a 20-product demo store can crawl on a client’s real catalogue.

How do you profile Liquid from the command line?

The Shopify CLI has a theme profile command. It requests a storefront page, gets back a Liquid render profile and opens it in a bundled copy of the Speedscope viewer.

# Profile the live theme's home page in the browser
shopify theme profile --store your-store.myshopify.com

# Profile one product page on an unpublished theme, and keep the raw profile
shopify theme profile --store your-store.myshopify.com \
  --theme "Dawn - perf branch" \
  --url /products/classic-leather-jacket \
  --json > before.json

Three details matter in practice.

First, --json writes the profile itself to stdout, not a summary. In CLI 4.9.4 the command sends the page request with an Accept: application/vnd.speedscope+json header and prints the response body, so the file you save is a standard Speedscope document. That makes before-and-after comparisons scriptable. Check the exit code, though: when the command fails, it exits 1 and writes its error as JSON to the same stdout, so before.json ends up holding an error object.

Second, the reference page lists a --password flag for Theme Access or Admin API tokens, but 4.9.4 refuses one for this command with “Unable to use Admin API or Theme Access tokens with the profile command”. You have to log in interactively, so this is a laptop tool rather than a CI job.

Third, it needs real access to the store. When the logged-in account cannot reach a dev store, the command stops with “Looks like you don’t have access to this dev store”. The Theme Inspector docs set the same bar for the Chrome extension: the Themes permission, or a collaborator account with it. Password-protected storefronts take --store-password.

Without --url the command profiles /, and without --theme it picks the live theme; both defaults are in the 4.9.4 source. The Theme Inspector shows the same kind of data inside Chrome DevTools, with a flame graph and a sandwich view sorted by self time. It cannot profile checkout pages.

Which Liquid nodes are actually slow?

Speedscope is good for exploring one profile. It is less good at answering “what changed?” after an edit. This script ranks frames by self time in one profile, or by the change in total time between two:

// Usage: node liquid-profile-top.mjs before.json [after.json]
import { readFileSync } from "node:fs";

const TO_MS = { nanoseconds: 1e-6, microseconds: 1e-3, milliseconds: 1, seconds: 1000 };

function summarise(path) {
  const doc = JSON.parse(readFileSync(path, "utf8"));
  const frames = doc.shared.frames;
  const rows = new Map(); // key -> { self, total, calls }
  const row = (i) => {
    const f = frames[i];
    const key = f.file ? `${f.name}  (${f.file}:${f.line ?? "?"})` : f.name;
    if (!rows.has(key)) rows.set(key, { self: 0, total: 0, calls: 0 });
    return rows.get(key);
  };

  for (const profile of doc.profiles) {
    const scale = TO_MS[profile.unit] ?? 1;
    if (profile.type === "evented") {
      const stack = []; // { frame, at, childTime }
      for (const ev of profile.events) {
        if (ev.type === "O") {
          stack.push({ frame: ev.frame, at: ev.at, childTime: 0 });
          continue;
        }
        const open = stack.pop();
        const elapsed = (ev.at - open.at) * scale;
        const r = row(open.frame);
        r.calls += 1;
        r.self += elapsed - open.childTime;
        // Count total once per frame on the stack, so recursion is not double counted.
        if (!stack.some((s) => s.frame === open.frame)) r.total += elapsed;
        if (stack.length) stack[stack.length - 1].childTime += elapsed;
      }
    } else if (profile.type === "sampled") {
      profile.samples.forEach((sample, i) => {
        const weight = profile.weights[i] * scale;
        for (const f of new Set(sample)) row(f).total += weight;
        if (sample.length) row(sample[sample.length - 1]).self += weight;
      });
    }
  }
  return rows;
}

const ms = (n) => n.toFixed(2).padStart(9);
const [beforePath, afterPath] = process.argv.slice(2);
if (!beforePath) {
  console.error("Usage: node liquid-profile-top.mjs before.json [after.json]");
  process.exit(1);
}
const before = summarise(beforePath);

if (!afterPath) {
  const top = [...before].sort((a, b) => b[1].self - a[1].self).slice(0, 15);
  console.log("     self     total  calls  frame");
  for (const [key, r] of top) {
    console.log(`${ms(r.self)} ${ms(r.total)} ${String(r.calls).padStart(6)}  ${key}`);
  }
} else {
  const after = summarise(afterPath);
  const keys = new Set([...before.keys(), ...after.keys()]);
  const diff = [...keys].map((key) => {
    const b = before.get(key)?.total ?? 0;
    const a = after.get(key)?.total ?? 0;
    return { key, b, a, delta: a - b };
  });
  diff.sort((x, y) => Math.abs(y.delta) - Math.abs(x.delta));
  console.log("   before     after     delta  frame");
  for (const d of diff.slice(0, 15)) {
    console.log(`${ms(d.b)} ${ms(d.a)} ${ms(d.delta)}  ${d.key}`);
  }
}

It handles both Speedscope profile types, evented and sampled, and converts whatever unit the file declares into milliseconds. Frames are keyed by name plus file and line, so an edit that moves code to a different line shows up as one frame vanishing and another appearing. Read the diff with that in mind.

The calls column is the useful one for loops. In the nested-loop profile we tested below, the inner if ran 5,250 times and took 11.8 ms of self time, though no single call was expensive.

Why does TTFB hide Liquid changes on Shopify?

Shopify streams storefront HTML. Its guide to measuring Liquid rendering time explains the catch: the first byte carries the top of <head>, up to {{ content_for_header }}, while your sections are still rendering. So “Waiting for server response” in DevTools can stay flat after a big Liquid fix, because the saving lands in “Content download”.

Compare the document request’s total duration instead, reload several times, and use medians. Add pb=0 to preview URLs so the preview bar stays out of the measurement. In Lighthouse, the same guide says a Liquid change on a streamed page shows in FCP and LCP more than in the Server response time audit. Our Shopify Lighthouse score write-up covers what to put above content_for_header to use that streaming window.

What usually makes Shopify Liquid performance bad?

A loop inside a loop

The classic is an “in cart” badge on a variant list. For each variant, scan every cart line:

{% for variant in product.variants %}
  {% assign in_cart = false %}
  {% for item in cart.items %}
    {% if item.variant_id == variant.id %}
      {% assign in_cart = true %}
      {% break %}
    {% endif %}
  {% endfor %}
  {% if in_cart %}<span>In cart</span>{% endif %}
{% endfor %}

Shopify’s nested loops guide replaces the inner loop with one map before the outer loop and a contains check inside it:

{% assign cart_variant_ids = cart.items | map: "variant_id" %}
{% for variant in product.variants %}
  {% if cart_variant_ids contains variant.id %}
    <span>In cart</span>
  {% endif %}
{% endfor %}

We ran both through the open-source Liquid gem (5.14.0, Ruby 3.2) with its profiler on, using plain hashes for the product and cart. With 250 variants and 20 cart lines, the nested version took a median of 17.3 ms and the flat one 0.73 ms, with identical output. At 50 variants and 5 lines it was 1.1 ms against 0.15 ms. These are not storefront numbers. Shopify’s renderer and its database-backed objects differ from a local gem fed hashes. What carries over is the growth: the nested version does work proportional to variants times cart lines, the flat one to variants plus cart lines.

Metafields and variants inside loops

Every metafield access queries the backend, according to the metafield guide, which puts 50 products with 10 variants at 500 lookups minimum. Read a collection-level metafield once with assign before the loop. For variant metafields, check product.selected_or_first_available_variant instead of every variant.

Variant pickers have the same problem at a larger scale. Shopify supports up to 2,048 variants per product, and the variant over-fetching guide recommends building option pickers from product.options_with_values, which carries available and selected without loading every variant.

A limit that does not limit the fetch

{% for product in collection.products limit: 4 %} fetches four products. The same limit on blog.articles, search.results or product.variants only caps iterations, per the pagination guide. The full default page is still loaded. For those arrays, wrap the loop in {% paginate blog.articles by 4 %} and keep the limit too.

A render argument that drops your comparison

Flattening nested render calls helps on its own (a product card that renders a price and a badge snippet costs three renders per product). The nested renders guide also flags a trap: skip_styles: forloop.index > 1 binds forloop.index and silently discards > 1. We confirmed it in the gem. The snippet received 1, 2 and 3, all truthy, so the “load styles once” guard never loaded them at all. Assign the comparison to a variable first and pass that.

How fast should Liquid render?

The current shopify.dev performance pages we read give no render-time target. The clearest figure we found is in a 2020 Shopify Engineering article on Liquid render analysis with the Theme Inspector, which suggests aiming for 200 ms of total render time and no more than 500 ms. Treat that as a budget, not a pass mark. Render totals also exclude request overhead, so the Theme Inspector docs warn they are not the same number as TTFB.

Profile the three templates that carry the most weight: collection, product and home. The speed score in Shopify’s theme benchmark weights them 43, 40 and 17 per cent. Save a --json profile before you touch anything, fix whatever sits at the top of the self-time list, and diff. Stop when the frames left at the top are cheap per call and run a handful of times. A wholesale rewrite of snippets to save 2 ms each is not worth the review cost. Once the loops are flat, lock them in with linting: our guide to Theme Check in CI covers which checks to fail the build on.

Whoooop does this kind of Liquid profiling and clean-up as part of our Shopify development work, usually on themes that have grown alongside the catalogue. If a collection page gets slower every time the client adds products, we are glad to look at it.

Need this built properly?

Get in touch

Hack the planet!