DEV Community

Cover image for Building a Zero-Latency Hardware Comparison Engine with Static JSON and URL State
Tile Saw Lab
Tile Saw Lab

Posted on

Building a Zero-Latency Hardware Comparison Engine with Static JSON and URL State

When you build a niche hardware comparison site, your users rarely browse like typical blog readers. A tile contractor standing in a supply aisle—or a homeowner comparing two wet saws on a spotty garage Wi-Fi connection—doesn't want to wait 800ms for a server round-trip every time they toggle a filter from "7-inch blade" to "10-inch blade."

Early on, while building the comparison views for the Tile Saw Lab testing database, we realized that a traditional database-backed search API was completely overkill for a catalog of 30 to 150 benchmarked tools. Worse, introducing client-server latency made side-by-side spec exploration feel sluggish on mobile devices.

Instead of spinning up a search backend or shipping a heavy client-side state library, we moved the entire filtering, sorting, and comparison engine to the browser using a pre-compiled static JSON index, strict unit normalization, and URL query synchronization.

Here is the exact architecture we landed on, along with the edge cases that tripped us up along the way.

1. The Unit Normalization Trap in Hardware Data

Before you write a single line of filtering logic, you have to deal with how messy physical tool specifications are in the real world.

In the power tool industry, manufacturers mix imperial and metric measurements constantly. One spec sheet lists rip capacity as 24-1/2", another writes 24.5 in, and European brands publish 620 mm. The same problem shows up with blade diameters, arbor sizes (5/8" vs. 22.23 mm), and motor ratings (1.5 HP Peak vs. 15 Amp).

If you store those values as raw display strings, range sliders and numeric sorting break immediately. Our rule became simple: store canonical SI or decimal numeric values for computation, and format display strings only at render time.

export interface NormalizedSawRecord {
  id: string;
  name: string;
  brand: string;
  bladeDiameterIn: number;      // e.g., 7, 8, 10
  ripCapacityMm: number;        // Canonical metric value for filtering
  arborRunoutMm: number;        // Measured with dial indicator
  railDeflectionMm: number;     // Measured under lateral load
  rpmRetentionPct: number;      // 0 - 100 under porcelain load
  weightKg: number;             // Canonical weight
  priceTier: 'budget' | 'midrange' | 'pro';
}

export function formatRipCapacity(mm: number, unit: 'imperial' | 'metric'): string {
  if (unit === 'metric') {
    return `${Math.round(mm)} mm`;
  }
  const inches = mm / 25.4;
  // Round to nearest 1/4 inch for practical job-site readability
  const quarterInches = Math.round(inches * 4) / 4;
  return `${quarterInches}"`;
}
Enter fullscreen mode Exit fullscreen mode

Keeping ripCapacityMm and weightKg strictly numeric means our filter predicates never have to parse fractions or strip text units on the fly. It also makes toggling the entire UI between Imperial and Metric a trivial presentation concern.

2. Pre-Compiling a Compact Static Index at Build Time

Each individual tool review page on our site contains long-form testing notes, pros/cons, blade pairing recommendations, and high-resolution test photos. Loading all of that into memory just to power a comparison table would waste hundreds of kilobytes of bandwidth.

During the static build step, we run a small Node script that reads our canonical content files, validates every required benchmark metric, strips out all editorial prose, and emits a single minified benchmarks.index.json file.

For 50+ tested saws and cutters, the entire gzipped JSON payload is under 6 KB—smaller than a single thumbnail image.

// scripts/build-index.mjs
import fs from 'node:fs/promises';
import path from 'node:path';

const DATA_DIR = path.resolve('./src/data/saws');
const OUT_FILE = path.resolve('./public/data/benchmarks.index.json');

async function buildIndex() {
  const files = await fs.readdir(DATA_DIR);
  const index = [];

  for (const file of files) {
    if (!file.endsWith('.json')) continue;
    const raw = JSON.parse(await fs.readFile(path.join(DATA_DIR, file), 'utf-8'));

    // Guardrail: fail the build if core benchmark telemetry is missing
    if (typeof raw.measuredMetrics?.arborRunoutMm !== 'number') {
      throw new Error(`Missing arborRunoutMm in ${file}`);
    }

    index.push({
      id: raw.id,
      name: raw.model,
      brand: raw.brand,
      bladeDiameterIn: raw.bladeDiameterInches,
      ripCapacityMm: Math.round(raw.measuredMetrics.ripCapacityInches * 25.4),
      arborRunoutMm: raw.measuredMetrics.arborRunoutMm,
      railDeflectionMm: raw.measuredMetrics.railDeflectionMm,
      rpmRetentionPct: 100 - raw.measuredMetrics.rpmDropUnderLoadPct,
      weightKg: Number((raw.measuredMetrics.setupWeightLbs * 0.453592).toFixed(1)),
      priceTier: raw.priceTier,
    });
  }

  await fs.mkdir(path.dirname(OUT_FILE), { recursive: true });
  await fs.writeFile(OUT_FILE, JSON.stringify(index));
  console.log(`Generated static index with ${index.length} records.`);
}

buildIndex();
Enter fullscreen mode Exit fullscreen mode

Adding that build-time guardrail (throw new Error(...)) caught more broken data entries than any manual QA pass ever did. If a new review draft is missing a measured metric, the CI pipeline fails before incomplete data ever hits production.

3. Deterministic Client-Side Filtering and Multi-Metric Sorting

Once the static JSON file is fetched (and cached aggressively via HTTP headers), filtering becomes a pure function. Because we only iterate over a few dozen objects, every filter change executes in less than 1 millisecond, even on low-end Android phones.

One subtle UX mistake we fixed early on was unstable sorting. When two saws share the exact same bladeDiameterIn or identical rpmRetentionPct, JavaScript's sort order can feel jumpy unless you define a deterministic tie-breaker.

export interface FilterCriteria {
  minRipMm: number;
  maxWeightKg: number;
  bladeSizes: number[];
  sortBy: 'precision' | 'torque' | 'portability';
}

export function filterAndRankSaws(
  records: NormalizedSawRecord[],
  criteria: FilterCriteria
): NormalizedSawRecord[] {
  const filtered = records.filter((saw) => {
    if (saw.ripCapacityMm < criteria.minRipMm) return false;
    if (saw.weightKg > criteria.maxWeightKg) return false;
    if (
      criteria.bladeSizes.length > 0 &&
      !criteria.bladeSizes.includes(saw.bladeDiameterIn)
    ) {
      return false;
    }
    return true;
  });

  return filtered.sort((a, b) => {
    let diff = 0;

    if (criteria.sortBy === 'precision') {
      // Lower combined runout + rail deflection ranks higher
      const aErr = a.arborRunoutMm + a.railDeflectionMm;
      const bErr = b.arborRunoutMm + b.railDeflectionMm;
      diff = aErr - bErr;
    } else if (criteria.sortBy === 'torque') {
      // Higher sustained RPM under load ranks higher
      diff = b.rpmRetentionPct - a.rpmRetentionPct;
    } else if (criteria.sortBy === 'portability') {
      diff = a.weightKg - b.weightKg;
    }

    // Deterministic tie-breaker by name
    return diff !== 0 ? diff : a.name.localeCompare(b.name);
  });
}
Enter fullscreen mode Exit fullscreen mode

Because filterAndRankSaws is completely decoupled from the DOM, we can unit-test every ranking profile directly in Vitest without mounting any UI components.

4. Syncing Filter State to the URL for Shareable Benchmarks

One of the highest-value features for a technical buying guide is shareability. Contractors frequently send a filtered comparison link to a project manager or post it in a renovation forum saying, "Here are the only 10-inch saws under 75 lbs that can rip 24-inch porcelain."

If your filter state lives only in component memory, copying the URL loses all context. By serializing active filters into URLSearchParams with history.replaceState, every view becomes bookmarkable and shareable without triggering a page reload or polluting the browser's Back button history.

export function syncFiltersToUrl(criteria: FilterCriteria): void {
  const params = new URLSearchParams();

  if (criteria.minRipMm > 0) {
    params.set('minRip', String(criteria.minRipMm));
  }
  if (criteria.maxWeightKg < 100) {
    params.set('maxKg', String(criteria.maxWeightKg));
  }
  if (criteria.bladeSizes.length > 0) {
    params.set('blades', criteria.bladeSizes.join(','));
  }
  if (criteria.sortBy !== 'precision') {
    params.set('sort', criteria.sortBy);
  }

  const query = params.toString();
  const nextUrl = query ? `${window.location.pathname}?${query}` : window.location.pathname;
  window.history.replaceState(null, '', nextUrl);
}
Enter fullscreen mode Exit fullscreen mode

A quick SEO caveat worth noting: if you use query parameters for dynamic client-side filtering, always set a clean <link rel="canonical" href="..."> pointing to the base page URL. Otherwise, search engines may waste crawl budget indexing dozens of arbitrary ?minRip=600&sort=portability permutations.

5. Edge Cases and Real-World Takeaways

Moving to a static-index architecture solved our latency and hosting-cost problems, though a few practical constraints came up along the way:

  1. Missing or N/A metrics: Manual snap tile cutters don't have electric motors or RPM retention numbers. Rather than stuffing 0 into rpmRetentionPct (which silently corrupts sorting), we explicitly type optional fields as number | null and always push null values to the bottom of any metric-specific sort.
  2. Cache invalidation: Whenever we publish a new batch of bench tests, we append a short content hash to the JSON filename (or tie it to the deployment build ID) so returning visitors never read stale rankings from browser cache.
  3. Graceful no-JS fallback: We still render the default top-ranked table directly in the static HTML at build time. That way, both search crawlers and users on flaky mobile connections see meaningful data immediately before client-side hydration finishes.

You can see this static comparison workflow running live in our wet tile saw lab-tested rankings if you want to inspect the payload size and filter responsiveness in DevTools.

For other developers maintaining small-to-medium structured datasets (under 1,000 records): at what point do you usually outgrow a pre-compiled static JSON index and reach for SQLite/WASM or a hosted search service?

Top comments (0)