Tutorial

Performance Optimization: From Profiling to Deployment

Find and fix performance bottlenecks with profiling, then lock in the gains with caching, budgeting, and continuous monitoring from local to production.

On this page

  1. Introduction
  2. Measure Before You Optimize
  3. Fixing Backend Bottlenecks
  4. Fixing Frontend Bottlenecks
  5. Caching: The Multiplier
  6. Budgets and Continuous Monitoring
  7. Database Query Optimization and Image Delivery
  8. Conclusion

Introduction

Performance optimization is a loop, not a task: measure, find the bottleneck, fix it, measure again, and stop when the user is happy. The teams that get into trouble are the ones that optimize by intuition — caching things that were not slow, rewriting a function that was 0.1% of the runtime — because without a measurement they cannot tell a bottleneck from a hunch. This article walks the loop from profiling a slow request to deploying the fix and monitoring that the gain holds, with the tools and the discipline that make optimization evidence-based rather than superstitious.

Measure Before You Optimize

The first rule of optimization is that you are almost always wrong about where the time is going. A function that looks slow is often negligible; a function that looks trivial is often the hot path. Before changing anything, measure. For a backend, that means profiling a representative request under realistic load. For a frontend, it means recording a Lighthouse or Chrome DevTools trace of the page on a throttled connection. The profile tells you where the milliseconds actually are, and the fix is almost always surprising.

// Node.js: profile a request with the built-in inspector.
// Run: node --inspect, open chrome://inspect, start a CPU profile, hit the endpoint, stop.
// Or use clinic.js for a flame graph:
// clinic flame -- node server.js  ->  clinic flame --visualize

A flame graph is the most readable profile: the width of a box is the time spent in that function, the stack is the call hierarchy, and the widest box at the top of a tall stack is your bottleneck. Look for wide boxes first; everything else is noise until the wide box is gone. On the frontend, the Lighthouse trace’s “Main thread” flame chart shows the parse, style, layout, and script time in the order the browser incurred it — the long task that blocks the main thread is your target.

Fixing Backend Bottlenecks

The common backend bottlenecks fall into a few categories, each with a characteristic fix. The first is the N+1 query: a list of items fetched with one query, then each item’s detail fetched in a separate query inside a loop. The profile shows a hundred database round trips for one request. The fix is to batch or join — fetch all the details in one query with an IN clause or a join, and the hundred round trips become one. An ORM that lazy-loads relations is the usual culprit; configure eager loading or write the query explicitly.

// N+1: one query for posts, then one per post for the author.
const posts = await db.posts.findMany(); // 1 query
for (const p of posts) p.author = await db.users.findUnique({ where: { id: p.authorId } }); // N queries

// Fixed: one query with a join (Prisma relation load).
const posts = await db.posts.findMany({ include: { author: true } }); // 1 query

The second is synchronous work on the hot path: a JSON.parse of a huge payload, a crypto operation, a compression step, all blocking the event loop so no other request can progress. The fix is to move the work off the event loop — use async streams, worker threads for CPU-bound work, or a separate process. The third is unindexed database queries: a query that scans a million rows because the column has no index. The profile shows the database dominating the request time. The fix is an index, and the proof is EXPLAIN ANALYZE showing the scan become an index lookup.

Fixing Frontend Bottlenecks

Frontend performance is dominated by three metrics: the Largest Contentful Paint (LCP), the Cumulative Layout Shift (CLS), and the Interaction to Next Paint (INP). LCP is the time until the largest visible element renders; the fix is usually to ship less — render the critical HTML on the server, preload the hero image, defer non-critical scripts. CLS is the visual instability from late-loading elements shifting the layout; the fix is to reserve space — set width and height on images and ads, avoid injecting content above the fold. INP is the responsiveness of interactions; the fix is to break long tasks and yield to the main thread.

// Break a long task so the main thread can paint and respond.
async function processLargeList(items: Item[]) {
  const CHUNK = 50;
  for (let i = 0; i < items.length; i += CHUNK) {
    processChunk(items.slice(i, i + CHUNK));
    if (i % 500 === 0) await scheduler.yield(); // yield to let the browser respond to input
  }
}

Code splitting is the frontend’s analog of the backend index: ship only the code the current route needs, and load the rest on demand. A 500KB JavaScript bundle that the user must parse before the page is interactive is a bottleneck; splitting it into a 50KB critical chunk and lazy-loaded routes turns the parse cost into a per-route cost. Measure the bundle with a bundle analyzer, find the largest chunks, and split the routes and the heavy libraries.

Caching: The Multiplier

Caching is the highest-leverage optimization when applied at the right layer, and a source of bugs when applied at the wrong one. The layers, from closest to the user to closest to the data, are: the browser cache (HTTP Cache-Control), the CDN edge, the server in-memory cache, and the database query cache. Each layer is cheaper to hit than the one below it, so cache as high as you can while still serving fresh data. A static asset with a content hash in its filename can be cached at the CDN for a year; a user-specific API response can be cached in memory for seconds with a tag-based invalidation.

// HTTP caching for a hashed asset: immutable, cache forever.
res.setHeader("Cache-Control", "public, max-age=31536000, immutable");

// In-memory cache for an expensive computation with TTL.
const cache = new Map<string, { value: Result; expires: number }>();
async function getCached(key: string, ttlMs: number, compute: () => Promise<Result>) {
  const hit = cache.get(key);
  if (hit && hit.expires > Date.now()) return hit.value;
  const value = await compute();
  cache.set(key, { value, expires: Date.now() + ttlMs });
  return value;
}

The hard part of caching is invalidation, and the rule that makes it tractable is cache with explicit keys and invalidate by key. Tag-based caching (each cache entry carries tags; invalidate a tag and all tagged entries drop) lets you invalidate “all products” when a product changes without knowing every key. Never cache without an invalidation strategy — a cache you cannot invalidate is a cache that serves stale data forever.

Budgets and Continuous Monitoring

An optimization that is not enforced regresses. The bundle that was 150KB grows to 200KB one dependency at a time, because nobody notices. A performance budget turns the regression into a build failure: set a budget for the bundle size, the LCP, the blocking time, and fail the CI build when the budget is exceeded. The budget is a contract between the team and the user, enforced automatically.

// A budget check in CI (conceptual).
const budget = { bundleGzipKb: 150, lcpMs: 2000, cls: 0.05 };
const actual = await measureBuild();
if (actual.bundleGzipKb > budget.bundleGzipKb) {
  console.error(`Bundle ${actual.bundleGzipKb}KB exceeds budget ${budget.bundleGzipKb}KB`);
  process.exit(1);
}

In production, monitor the real-user metrics (RUM) — the LCP and INP actual users experience, not the synthetic Lighthouse score — because the synthetic test on a fast CI runner does not represent the user on a mid-range phone on a 3G connection. Alert when the p75 LCP degrades, because a regression that affects 25% of users is a regression worth fixing even if the median is fine. The optimization loop never really ends; the budget and the monitor keep the gains you made.

Database Query Optimization and Image Delivery

After the N+1 and the missing index, the next backend bottleneck is the query that is correct but slow — a join across three tables with a sort and a limit, run a thousand times a minute. The tool is EXPLAIN ANALYZE, which shows the plan the database chose and the actual time each step took. Read the plan from the inside out: the deepest node is the first operation, and a “Seq Scan” (sequential scan of the whole table) on a large table is the signal that an index is missing or unusable. A “Index Scan” or “Index Only Scan” is what you want; a “Bitmap Heap Scan” is a middle ground that fetches rows by index then reads the heap.

EXPLAIN ANALYZE
SELECT orders.*, customers.name FROM orders
JOIN customers ON orders.customer_id = customers.id
WHERE orders.status = 'pending' AND orders.created_at > NOW() - INTERVAL '7 days'
ORDER BY orders.created_at DESC LIMIT 50;

The plan reveals the specific inefficiency. If the filter on status and created_at does a Seq Scan, a composite index on (status, created_at DESC) lets the database seek directly to the pending rows in the last week in the sorted order, and the LIMIT 50 is satisfied by reading the first 50 index entries rather than scanning and sorting the whole table. If the join to customers is a nested loop with a lookup per order, an index on customers(id) (which exists if it is the primary key) makes each lookup an index seek. The plan before and after the index is the proof that the index helped — never add an index without measuring, because every index speeds reads and slows writes, and an index that does not speed the target query is pure write overhead.

For the frontend, images are usually the largest assets on the page and the dominant factor in LCP. Serve them in a modern format (WebP, AVIF) which is 25–50% smaller than JPEG at the same quality, and serve them at the size they are displayed, not the size they were uploaded. A 4000-pixel-wide image displayed at 400 pixels is ten times the bytes it needs to be; generate responsive variants at the sizes the layout uses and serve the right variant with the srcset attribute so the browser downloads the smallest image that fills the display.

<img
  src="/photo-800.webp"
  srcset="/photo-400.webp 400w, /photo-800.webp 800w, /photo-1200.webp 1200w"
  sizes="(max-width: 600px) 400px, 800px"
  width="800" height="600"
  loading="lazy" decoding="async"
  alt="...">

The width and height attributes reserve the box before the image loads, which prevents the layout shift that inflates CLS. loading="lazy" defers offscreen images until they are near the viewport, so the browser does not download images the user may never scroll to. decoding="async" lets the browser decode the image off the main thread, so a large image does not block interaction. For the hero image that determines LCP, do the opposite: preload it (<link rel="preload" as="image">), serve it eagerly, and fetch priority high, so it begins loading as early as possible. The combination — modern format, right size, reserved box, lazy for below-the-fold, eager for the hero — is the image optimization that moves LCP from seconds to hundreds of milliseconds.

Automate the variant generation and format conversion in the build or at the CDN, so the developer drops in one source image and the pipeline produces the responsive WebP/AVIF variants. A CDN with on-the-fly image transformation (Cloudflare Images, Cloudinary, imgix) does this without a build step: request /photo.jpg?w=800&format=webp and the CDN transforms and caches. This moves the work to the edge and out of your build, and it lets the layout request any size without pre-generating every variant.

Conclusion

Performance optimization is measure, fix, measure, budget, monitor. Profile to find the real bottleneck, fix it with the targeted tool for its category (batch the N+1, index the scan, split the bundle, cache at the highest valid layer), measure again to confirm the gain, set a budget so the gain does not regress, and monitor real-user metrics so you see the next regression before the users do. The discipline is in the measurement: optimize what the profile says is slow, not what your intuition says is slow, and the rest follows.

Related Examples