Back to blog

What performance really means in software engineering

A system is never slow in the abstract. Some piece of work is waiting on something specific: the browser's main thread, a TLS handshake, a cold serverless runtime, a connection pool, a row lock, or a GPU scheduler. Performance engineering starts by finding that wait and making its queue visible.

This guide uses one deliberately narrow model: performance is queue ownership. The queues include the human-operated incident process as well as the ones in software and infrastructure. Once a queue has an owner and a budget, the owner can shorten it, bound it, or decide that the work doesn't belong on the user's path at all and move it somewhere the product can afford.

The clock does not outrank correctness, cost, reliability, operability, security, accessibility, consistency, or the hardware users actually hold. Serving stale private data instantly is an incident. Serializing JSON in microseconds does little for a product that ships a 3 MB client bundle. Record token throughput means nothing to a person who is still staring at an empty box. Language rankings, framework leaderboards, and a green Lighthouse screenshot pasted into a launch document can each describe part of the system, but none of them describes the user's wait by itself.

The wait also crosses more layers than it used to. One user action can pass through the browser, the network, a CDN, an edge or serverless runtime, an application service, database pools and locks, queues, third-party dependencies, realtime fanout, analytics paths, and, more and more often, an inference engine. If you treat "the system" as one process, you hide most of the places where latency accumulates.

User-visible request path and queueing pointsA request crosses browser, network, CDN, runtime, and database work. Runtime work can also branch to a queue, third-party API, or AI inference. Dotted loops mark queueing points.main-thread queuerequest queueconnection / lock queueGPU scheduler queueUser intentBrowser workNetwork + DNS + TLS +protocolCDN / edge cacheRuntime / serviceDatabaseQueue / workflowThird-party APIsAI inferencePerceived response

Start with the dominant wait

No stack is "most optimized" for every kind of software. Where the dominant wait sits shapes the architecture more than any language or framework ranking does. A sound default takes that wait off the user's path, so the default changes with the product:

Product shapeDominant waitOptimized default
Public pages, docs, marketing, editorialBrowser work and network deliveryStatic or cache-first HTML, small JavaScript, optimized media, CDN, RUM
Ecommerce browse pathsLCP, third-party scripts, product media, cache invalidationStatic/ISR catalog, CDN cache tags, dynamic regional cart/checkout
CRUD SaaS and B2B dashboardsDatabase access, pool waits, locks, N+1 queries, external callsRegional app near managed PostgreSQL, measured pools, indexes, queues, OpenTelemetry
Realtime collaboration, chat, multiplayer, presenceEvent propagation, ordering, regional room locality, backpressureRoom-oriented WebSocket/WebTransport infrastructure, bounded queues, append logs, ephemeral presence
AI chat, RAG, agents, inference-heavy featuresTTFT, decode cadence, vector retrieval, GPU queueing, prompt sizeStreaming UI, thin gateway, tuned inference/data plane, goodput under SLO
Analytics-heavy SaaSScans, aggregations, data movement, freshness expectationsOLTP/OLAP split, CDC/events, columnar storage, cached dashboards
CPU-bound batch or benchmark-like jobsAlgorithmic work, memory bandwidth, IO, cost/jobNative job binary/container, object storage, batch runner, measured cost
Cost-sensitive productionComplexity, incident risk, staffing, rollback timeCheapest architecture that meets user-facing SLOs with the fewest moving parts

Without more information about a serious web application, I would start here:

HTML-first frontend + CDN/edge cache
regional Go, .NET, Java, Rust, Node, Rails, Django, or Laravel service chosen by team fit
managed PostgreSQL in the same region as the write path
Redis/Valkey only for derived/cacheable state
object storage for files
queue/workflow engine for slow or unreliable work
OpenTelemetry + RUM + explicit SLOs

This default is fast enough for a wide range of products, cheap to operate, observable, and reversible. It also keeps an application from turning into a distributed-systems incident before the workload needs distribution.

Mapping it onto GCP or AWS is mostly mechanical. One version on each cloud:

PieceGCPAWS
Frontend and CDNAstro, SvelteKit, or Next in static or hybrid mode, behind Cloudflare, Fastly, or Cloud CDNCloudFront
ComputeCloud Run, with GKE reserved for workloads that need itECS Fargate or Lambda
DatabaseCloud SQL PostgreSQLRDS PostgreSQL Multi-AZ
CacheMemorystoreElastiCache
Queues and workflowsCloud Tasks, Pub/Sub, and WorkflowsSQS, EventBridge, and Step Functions
Object storageCloud StorageS3

The vendor names can change without changing the shape: deliver HTML first, cache where correctness allows, keep compute near the data it reads and writes, put slow work behind queues, and measure what users receive rather than what a staging machine reports.

Any layer can veto the stack

Any one layer can decide the user's wait on its own, so a performance review has to weigh all of them together, in a matrix like the one above rather than on a leaderboard:

Write the wait as a sum

Each term in the user's wait is a queue that someone can own:

User-visible wait =
  browser scheduling
+ network and protocol setup
+ CDN cache miss / revalidation
+ runtime startup or queueing
+ application execution
+ database connection wait
+ database execution and lock wait
+ downstream dependency wait
+ realtime fanout or inference queueing
+ response transfer
+ browser rendering or token streaming

For end-user software, optimize in this order unless the product has a strong, specific reason to invert it:

  1. Perceived responsiveness: LCP, INP, CLS, time to first useful content, and time to first token for AI.
  2. Tail latency: p75 for web experience, p95 and p99 for APIs, queue age for async work, and goodput under SLO for inference.
  3. Data locality: put compute near the data it must read or write. That often matters more than being near the user.
  4. Browser work: the cost to parse, compile, and execute JavaScript, plus hydration, long tasks, layout shifts, images, fonts, and third-party scripts.
  5. Network delivery: DNS, TLS, HTTP/2 or HTTP/3, CDN hit rate, compression, cache keys, and media transformation.
  6. Backend execution: serialization, allocation, event-loop stalls, pool waits, locks, retries, GC pauses, and cold starts.
  7. Overload behavior: admission control, backpressure, queue bounds, retry policy, load shedding, and circuit breakers.
  8. Operability: observability, rollback speed, restore tests, failure isolation, cost, and incident simplicity.

Averages hide the users who wait longest. The p50 describes a typical observation. The p95 and p99 show the tail, where a system becomes unreliable enough that users stop trusting it, and winning that trust back costs more than the few milliseconds saved elsewhere.

Use public numbers as a baseline

Core Web Vitals are still the most useful public baseline for web experience. The thresholds are Largest Contentful Paint within 2.5 seconds, Interaction to Next Paint at 200 milliseconds or less, and Cumulative Layout Shift at 0.1 or less, each measured at the 75th percentile with mobile and desktop segmented.1 INP replaced First Input Delay (FID) as an official Core Web Vital on March 12, 2024. FID captured only the first interaction, so it missed most of what users experience as responsiveness.2

The public web is improving, but slowly. The 2025 Web Almanac, which draws mainly on HTTP Archive and CrUX measurements from July 2025, reports good Core Web Vitals for only 48% of mobile websites and 56% of desktop websites.3 Page weight is one reason. The median home page is 2,559 KB on mobile and 2,862 KB on desktop, and images are the largest byte category, followed by JavaScript and fonts.4

Some case studies tie speed to business outcomes. A Google-commissioned study by fifty-five and Deloitte found that a 0.1 second improvement in mobile site speed correlated with 8.4% higher retail conversions and 10.1% higher travel conversions.5 Rakuten 24 reported a 53.37% lift in revenue per visitor and a 33.13% lift in conversion rate from its Core Web Vitals A/B test.6 Both are vendor-published case studies, so read them as directional evidence. They are not laws of nature, and they do not promise that a rewrite will pay for itself.

Write the budget before choosing the stack

A budget makes the team define "fast" and name its tradeoffs before an infrastructure choice hardens around vague expectations:

web:
  lcp_p75_mobile: '<= 2.5s'
  inp_p75_mobile: '<= 200ms'
  cls_p75: '<= 0.1'
  initial_js_content_pages_compressed: '<= 150KB target; exceptions require review'
  lcp_image_lazy_loaded: false
  rum_required: true

api:
  common_interaction_p95: '150-300ms regional target'
  common_interaction_p99: '500-800ms regional target'
  dependency_timeout_budget: 'explicit per downstream'
  queue_age_slo: 'route-specific'
  retries: 'bounded, jittered, only where safe'

database:
  pool_wait_p95: 'tracked separately from query execution'
  slow_query_threshold: 'route-specific'
  lock_wait_alerting: true
  connection_pool_policy: 'small, measured, admission-controlled'

realtime:
  sender_to_receiver_p95: 'product-specific'
  per_client_queue_bound: 'hard limit'
  reconnect_recovery_tested: true
  ephemeral_messages_may_drop: true
  durable_messages_sequenced: true

ai:
  ttft_p50: 'route-specific'
  ttft_p95: 'route-specific'
  itl_or_tpot: 'route-specific'
  slo_attainment_target: 'percentage of requests meeting TTFT + TPOT + E2E targets'
  goodput_target: 'requests per second meeting TTFT + TPOT + E2E targets'
  cost_per_successful_request: 'tracked'

The values vary by product, but the structure should stay recognizable. Set these budgets, plus one for operations, before the stack decision, then enforce them in CI, dashboards, and release review. A proposed change that you can't tie to one of the budget lines is still speculative. Without a budget, optimization turns into a series of unrelated local improvements.

In the browser, bytes come before frameworks

Browser performance is mostly a matter of bytes, scheduling, and priority. Before it shows anything useful, the median page asks the browser to download, parse, execute, lay out, paint, hydrate, and coordinate more work than the user's device can comfortably absorb. A different server router removes none of that work.

Ship less JavaScript before the page is useful

JavaScript costs more than its transfer size. The browser has to decompress, parse, compile, and execute it, and it does that while it also coordinates rendering and hydration. Keep code that does not contribute to the first useful interaction off that path:

Real-user measurement belongs in production from the first release:

// rum/web-vitals.ts
import { onCLS, onINP, onLCP, type Metric } from 'web-vitals';

type RumPayload = {
  name: Metric['name'];
  value: number;
  rating: Metric['rating'];
  id: string;
  route: string;
  deviceMemory: number | undefined;
  connection: string | undefined;
  ts: number;
};

function send(metric: Metric) {
  const nav: Navigator & {
    connection?: { effectiveType?: string };
    deviceMemory?: number;
  } = navigator;

  const payload: RumPayload = {
    name: metric.name,
    value: metric.value,
    rating: metric.rating,
    id: metric.id,
    route: document.body.dataset.route ?? 'unknown',
    deviceMemory: nav.deviceMemory,
    connection: nav.connection?.effectiveType,
    ts: Date.now(),
  };

  const body = new Blob([JSON.stringify(payload)], { type: 'application/json' });
  navigator.sendBeacon('/rum/web-vitals', body);
}

onLCP(send);
onINP(send);
onCLS(send);

A sitewide average is only where the analysis starts. Break the data down by route, template, country, device class, network type, logged-in state, and release version, because a regression in one of those slices can disappear inside an acceptable headline number.

Put the LCP element on the critical path deliberately

The LCP element is usually a product image, hero media, a headline block, or a card. The user's first impression waits on it, so its discovery and rendering deserve the same care as an API dependency. A high-priority image path might look like this:

<img
  src="/images/hero-1280.avif"
  srcset="/images/hero-640.avif 640w, /images/hero-1280.avif 1280w, /images/hero-1920.avif 1920w"
  sizes="(max-width: 1280px) 100vw, 1280px"
  width="1280"
  height="720"
  fetchpriority="high"
  alt="Product screenshot showing the main workflow"
/>

A short set of habits prevents most LCP failures. Don't lazy-load the image that is likely to appear above the fold, and don't hide it behind client-only rendering. Give it explicit dimensions so it can't shift the layout. Serve responsive AVIF or WebP variants instead of one oversized original. Preload it only when the browser can't discover it early, because a redundant preload competes with the resources it was meant to prioritize.

Fonts need the same discipline. Use WOFF2, subset aggressively, limit the weights, avoid loading an entire family for one heading, and choose the font-display behavior deliberately. Preloading too many fonts reverses the priority you meant to set.

Use the CDN without leaking state

A CDN shortens the distance to users, reuses connections, terminates TLS near them, caches safe responses, and absorbs bursts. It also brings its own failure modes: cache fragmentation, accidental personalization leaks, Vary explosions, stale pricing, and protocol choices that perform well in a lab and poorly on users' last-mile networks.

Cache each response by its correctness model

Hashed JavaScript, CSS, fonts, and media get a new URL whenever their contents change, so they can be cached for a long time and marked immutable. MDN defines immutable for responses that will not be updated while fresh, and a cache-busted URL fits that definition.7

# /assets/app.4f3a9c.js
Cache-Control: public, max-age=31536000, immutable

HTML is different. It can carry the deploy rollout, personalization, experiments, authentication state, and references to asset hashes. Put HTML or an anonymous API response in a shared cache only when the correctness model for those inputs is explicit.

# Anonymous content page that can tolerate brief staleness
Cache-Control: public, max-age=0, s-maxage=60, stale-while-revalidate=300
# Account-specific page
Cache-Control: private, no-store

A cache that treats a logged-in dashboard like an immutable bundle can put private data into a shared cache.

Keep cache keys small and measured

Configure and measure the CDN itself this way:

Protocol policy should come from your own RUM. The 2025 Web Almanac CDN chapter shows ecosystem patterns, but its DNS, TLS, and TTFB numbers come from simulated Chrome connections on controlled infrastructure, not from real users.8

An anonymous product-list response on Fastly might carry the headers below. They assume a request sent with Fastly-Debug: 1, which stops Fastly from stripping Surrogate-Key before delivery:9

Cache-Control: public, max-age=0, s-maxage=120, stale-while-revalidate=600
Surrogate-Key: category:running-shoes brand:acme catalog:v42
Vary: Accept-Encoding
Server-Timing: cdn-cache;desc="HIT", origin;dur=0

Compare it with this:

Cache-Control: public, s-maxage=3600
Vary: User-Agent, Cookie, Accept-Language, X-Experiment, X-Geo, Authorization

The second response is unlikely to hit cache. Worse, any personalization input that is missing from Vary can leak state. A well-run CDN should show high hit ratios, predictable invalidation, low regional variance, no accidental private data, and enough telemetry to explain a miss.

What framework benchmarks can measure

Synthetic server benchmarks measure routing overhead, JSON serialization, a controlled database access pattern, and whether a technology imposes an obvious ceiling on a specific class of workload. They can't decide whether a product belongs in Go, Rust, .NET, Node, Python, or Rails, because the harness contains none of the team, the production data, or the likely failure modes.

TechEmpower, once the most visible public web-framework benchmark, ended on March 24, 2026, and its repository was archived read-only after more than a decade.10 Round 23 is now historical ceiling data for a narrow workload.

Use benchmarks like it for order-of-magnitude checks, for comparisons between implementation styles inside one ecosystem, and to catch hard ceilings early in specialized workloads. They don't predict p99 under real traffic, choose a product architecture, or justify rewriting an application whose framework was never the bottleneck. Five serial external calls, OFFSET 50000, unbounded database connections, hydration of static content, and no path for slow work will overwhelm any benchmark winner.

Treat serverless cold starts as a design variable

"Convenient but slow" is no longer a useful description of serverless. The platforms make different tradeoffs in startup, isolation, concurrency, and placement, so the mechanics matter more than the label. Results on any of them also depend on region, runtime, traffic shape, warmness, limits, and configuration.

Cloudflare Workers run on V8 isolates, lightweight contexts that start very quickly inside an existing runtime, and one runtime instance can host hundreds or thousands of them.11 The model suits routing, auth gates, personalization, A/B decisions, cache orchestration, and small API facades. It fits less well when the work is CPU-heavy, the dependencies are large, the code assumes that mutable in-memory state is durable, or the request must cross regions to reach a write database.

Vercel Fluid compute lets multiple invocations share one function instance, favors existing idle resources before it allocates new ones, and adds bytecode caching and pre-warming.12 It reduces cold-start effects but does not eliminate them. First requests, newly scaled paths, and cold regions can still pay startup cost. Enable it with "fluid": true in vercel.json when the workload benefits from concurrency, streaming, and warmer instances.

AWS Lambda SnapStart initializes a function version at publish time, takes a Firecracker microVM snapshot of that state, and resumes new execution environments from the encrypted cache instead of initializing each one from scratch.13 It supports Java 11+, Python 3.12+, and .NET 8+. SnapStart reduces startup latency, but it adds no correctness layer. AWS explicitly warns that functions must still handle uniqueness, credentials, sockets, and network connections correctly after a restore.13

Match startup behavior, concurrency, limits, and topology to the workload:

WorkloadStrong defaultWatch for
Static assets and cached HTMLCDNInvalidation, personalization, cache-key design
Routing, auth gates, small transformsEdge isolatesCPU limits, runtime compatibility, data distance
Dynamic APIs and web routesServerless, Fluid, containersCold starts, DB pool pressure, region choice
Long-running jobsQueues + workers / containersIdempotency, retries, cost controls
CPU-heavy servicesContainers / VMs / native jobsAutoscaling, bin packing, deployment complexity
GPU inferenceDedicated inference servingBatching, queueing, model loading, memory

Backend latency accumulates in the database

Once frontend and network costs are under control, backend latency often leads to the database. The usual causes are missing indexes, inefficient pagination, extra round trips, lock contention, long transactions, N+1 queries, and connection pools sized as though the database were a thread pool.

A connection pool is admission control

PostgreSQL's max_connections caps concurrent connections, and the server sizes some resources, including shared memory, directly from that value.14 That makes a connection pool an admission-control mechanism, not a throughput dial. Below saturation, more connections can reduce waiting on the application side. At saturation, they move the queue inside the database, where it is harder to observe. Past that point, a wider pool adds context switching, memory pressure, lock contention, and p99 latency.

HikariCP's pool-sizing guidance reports a case in which shrinking the pool, and changing nothing else, cut application response times from roughly 100 ms to roughly 2 ms.15 Small pools are not faster everywhere. The result applies once the database is saturated and each additional caller slows the rest.

PgBouncer in transaction pooling mode lets many stateless application instances share fewer server connections, because a client holds a server connection only for the duration of a transaction.16

; pool-sizing excerpt from pgbouncer.ini
[databases]
app = host=postgres.internal port=5432 dbname=app

[pgbouncer]
listen_port = 6432
pool_mode = transaction
max_client_conn = 1000
default_pool_size = 25
reserve_pool_size = 5
server_idle_timeout = 60

Transaction pooling breaks some session-based PostgreSQL features, so the application must account for the different semantics. Before you enable it, review session state, session-level advisory locks, temporary-table assumptions, and some prepared-statement behaviors.16

Composite indexes follow the query shape

A multicolumn B-tree index helps when the query's constraints line up with its leading columns. PostgreSQL specifies that equality constraints on those columns, plus an inequality on the first column that has no equality constraint, limit the portion of the index that must be scanned.17

Start with the query:

SELECT id, status, total_cents, created_at
FROM orders
WHERE tenant_id = $1
  AND status = $2
  AND created_at < $3
ORDER BY created_at DESC
LIMIT 50;

Then build the index to match its shape:

CREATE INDEX CONCURRENTLY idx_orders_tenant_status_created_at
ON orders (tenant_id, status, created_at DESC);

Choose indexes from observed predicates, sort order, cardinality, and access frequency, and confirm the plan with EXPLAIN (ANALYZE, BUFFERS).

OFFSET pays for every skipped row

PostgreSQL still computes the rows that OFFSET skips, so a large offset is slow.18 On a hot path, this query is a poor fit:

SELECT *
FROM events
WHERE tenant_id = $1
ORDER BY created_at DESC, id DESC
LIMIT 50 OFFSET 50000;

Keyset pagination starts after the last row the user saw:

SELECT *
FROM events
WHERE tenant_id = $1
  AND (created_at, id) < ($2, $3)
ORDER BY created_at DESC, id DESC
LIMIT 50;

CREATE INDEX CONCURRENTLY idx_events_tenant_created_id
ON events (tenant_id, created_at DESC, id DESC);

Keyset pagination is faster because the database no longer computes and discards 50,000 rows on every click. It also matches the interaction, since the user moves from a known item to the next page. The cursor can be the (created_at, id) of the last row shown. The first page omits the cursor predicate, and created_at must be non-null for the comparison to be total.

Keep slow work out of the request path

Emails, exports, webhooks, billing retries, image processing, AI enrichment, and long third-party calls should almost always run outside the request path. The handler enqueues a job and returns. A worker performs each side effect under its own idempotency key:

// request handler: enqueue and return
await queue.send('order.created', {
  orderId: order.id,
  idempotencyKey: `order.created:${order.id}`,
});

// worker: derive one stable key per idempotent side effect
const { idempotencyKey, orderId } = job.data;
await withIdempotency(`${idempotencyKey}:receipt`, () => sendReceipt(orderId));
await withIdempotency(`${idempotencyKey}:index`, () => updateSearchIndex(orderId));
await withIdempotency(`${idempotencyKey}:warehouse`, () => notifyWarehouse(orderId));

The receipt still has to be sent, so the queue doesn't erase any work. It bounds the user-facing path, allows safe retries, and turns queue age into an explicit product-health metric.

Defaults for web products

The first three rows of the opening table each imply a different operating model.

Public content, docs, marketing, editorial

Astro, Eleventy, Hugo, or static Next/SvelteKit
static HTML on a CDN
image pipeline (Cloudflare Images, imgix, Cloudinary, or equivalent)
headless CMS with webhook rebuild or on-demand revalidation
RUM for Core Web Vitals

Public pages are mostly read-only, so their HTML can be generated ahead of time and can deliver meaningful content before any JavaScript arrives. For these pages, avoid full client-side rendering when SEO or performance matters, dynamic SSR for content that can be cached or regenerated, hydration of static content, and lazy-loading the LCP image.

Ecommerce and product catalogs

Astro or Next.js/SvelteKit hybrid
static/ISR catalog, product, category, and editorial pages
edge CDN with cache tags or surrogate keys
dynamic regional cart, checkout, payment, and inventory service
image CDN with responsive AVIF/WebP transforms
RUM tied to conversion metrics

A catalog runs on four rules:

CRUD SaaS, internal tools, and B2B dashboards

HTML-first frontend or a disciplined SPA
regional service in Go, .NET, Java, Rust, Node, Python, Ruby, or PHP by team fit
managed PostgreSQL in the same region
PgBouncer, RDS Proxy, or a managed equivalent for bursty clients
Redis/Valkey for derived reads, sessions, and rate limits
queue or workflow engine for slow work
OpenTelemetry traces, metrics, and logs

In most SaaS products, users spend their time waiting on queries, connections, row locks, frontend waterfalls, and external APIs, not on the application language. One well-run region usually outperforms a premature global distribution. The operating rules follow from that:

Edge compute fits routing, auth gates, locale selection, cacheable reads, and bot protection. An edge function that immediately calls a distant primary database restores the latency it was meant to remove.

Realtime design starts above the transport

Selecting WebSockets answers only the transport question. A realtime design also has to specify who owns room state, how ordering works, which events require durability and which may be dropped, what happens after a reconnect, how missed events are replayed, how fanout is bounded, and what one slow client costs everyone else.

WebSocket is still the compatibility baseline. It is reliable, ordered, and bidirectional, it deploys nearly everywhere, and many products need nothing more.

MDN marks WebTransport as Baseline as of March 2026.19 Over HTTP/3 it offers reliable streams alongside unreliable, UDP-like datagrams, which suits games, live cursors, telemetry streams, and collaborative interactions in which some events may be dropped. Browser support does not guarantee a path through every enterprise proxy, old device, or corporate firewall, though. A public product should feature-detect WebTransport, handle connection failure, and fall back to WebSocket:

type RealtimeTransport = {
  send(data: ArrayBuffer | string): void;
  close(): void;
};

export async function connectRealtime(url: string): Promise<RealtimeTransport> {
  if ('WebTransport' in globalThis && url.startsWith('https://')) {
    try {
      const transport = new WebTransport(url);
      await transport.ready;

      // Use a reliable, ordered byte stream to match the WebSocket fallback's
      // delivery guarantees. Message framing, heartbeats, and reconnect are omitted.
      const stream = await transport.createUnidirectionalStream();
      const writer = stream.getWriter();

      return {
        send(data) {
          const bytes = typeof data === 'string' ? new TextEncoder().encode(data) : data;
          void writer.ready.then(() => writer.write(bytes)).catch(() => transport.close());
        },
        close() {
          transport.close();
        },
      };
    } catch {
      // Fall through to WebSocket. Browser support is not the same as network support.
    }
  }

  const wsUrl = new URL(url);

  if (wsUrl.protocol === 'https:') {
    wsUrl.protocol = 'wss:';
  } else if (wsUrl.protocol === 'http:') {
    wsUrl.protocol = 'ws:';
  } else if (wsUrl.protocol !== 'wss:' && wsUrl.protocol !== 'ws:') {
    throw new Error(`Unsupported realtime protocol: ${wsUrl.protocol}`);
  }

  const socket = new WebSocket(wsUrl);

  await new Promise<void>((resolve, reject) => {
    socket.onopen = () => resolve();
    socket.onerror = () => reject(new Error('WebSocket failed'));
  });

  return {
    send(data) {
      socket.send(data);
    },
    close() {
      socket.close();
    },
  };
}

The example omits authentication, reconnect, heartbeats, backoff, replay, and capability negotiation. Production code needs all of them, and the fallback should be designed at the same time as the preferred transport.

Durable Objects and room authority

A Cloudflare Durable Object can coordinate many WebSocket clients from one instance. With the Hibernation API, clients stay connected while the object is evicted from memory. An incoming message wakes the object, but the object has lost its in-memory state and must rebuild it from serialized attachments or storage.20 The model fits chat rooms, multiplayer lobbies, presence channels, and collaborative sessions that have a natural object boundary.

The smallest version of a room:

import { DurableObject } from 'cloudflare:workers';

export class Room extends DurableObject {
  fetch(_request: Request): Response {
    const pair = new WebSocketPair();
    const [client, server] = Object.values(pair);
    this.ctx.acceptWebSocket(server);
    return new Response(null, { status: 101, webSocket: client });
  }

  webSocketMessage(ws: WebSocket, message: string | ArrayBuffer): void {
    for (const peer of this.ctx.getWebSockets()) {
      if (peer !== ws) {
        peer.send(message);
      }
    }
  }
}

A production room also needs sequence numbers, per-client queue bounds, authentication, replay, rate limits, and durable append logs for messages that cannot be lost.

Broadcast, presence, and database changes are different tools

Supabase Realtime's benchmark documentation treats Broadcast, Presence, and Postgres Changes separately and reports k6 results against explicit cluster topologies. It also notes that Postgres Changes must check access for every subscribed user, and it recommends Broadcast patterns for higher-scale fanout.21

The distinction holds outside Supabase too. Broadcast handles application-level fanout. Presence holds ephemeral state, such as who is online. A database change stream notifies consumers about durable state. It is not a general-purpose, high-volume pub/sub bus. Collaborative editing needs CRDTs or operational transform. Yjs-style systems pair naturally with append-only update logs, snapshots, and compaction, and their performance budget covers merge cost, replay cost, storage growth, and cold-client catch-up as well as bytes on the wire.

A realtime default

Collaboration: Yjs + Tiptap/CodeMirror/Lexical; Liveblocks, Hocuspocus,
  Y-Sweet, PartyKit, or your own room actors; append-only persistence
  with snapshots and compaction; presence outside durable document state

Chat/notifications: Phoenix Channels or Go/Node/Elixir room services;
  PostgreSQL for durable messages; NATS or managed fanout for regional
  distribution; Redis only where at-most-once ephemeral behavior is fine

Multiplayer/live cursors: an authoritative room process; bounded
  per-client queues; deltas instead of full state; database outside
  the tick loop

In each case, put active rooms near active users, sequence durable events per room, coalesce cursor and presence updates, and drop ephemeral events for slow clients instead of buffering them without a bound.

Measure AI inference by goodput under the SLO

One aggregate number cannot describe interactive LLM serving. The relevant metrics pull in different directions, so keep them separate:

MetricMeaningWhy it matters
TTFTTime to first tokenPerceived responsiveness for chat, copilots, agents
ITL / TPOTTime between output tokensSmoothness of streamed generation
E2E latencyFull request completion timeNon-streaming tasks, summaries, batch jobs
TPSTokens per secondAggregate generation capacity
RPSRequests per secondRequest-level serving capacity
GoodputRequests per second meeting SLOsUseful throughput under latency constraints

Anyscale distinguishes raw throughput, the work performed each second, from goodput, the SLO-compliant work completed each second.22 A system that raises tokens per second by making users queue longer is busier, and its interactive performance is no better.

Stream interactive responses by default

Streaming leaves the model's speed unchanged, but it shows progress, and that shortens the perceived wait. A long answer that begins quickly is easier to tolerate than a shorter one hidden behind a silent spinner. A minimal SSE proxy can expose generation as it happens:

import * as v from 'valibot';

const modelRequestSchema = v.strictObject({
  messages: v.array(
    v.strictObject({
      role: v.picklist(['system', 'user', 'assistant']),
      content: v.pipe(v.string(), v.minLength(1)),
    }),
  ),
});

export async function POST(request: Request): Promise<Response> {
  const body: unknown = await request.json().catch(() => undefined);
  const input = v.safeParse(modelRequestSchema, body);

  if (!input.success) {
    return Response.json({ error: 'invalid_request' }, { status: 400 });
  }

  const modelUrl = process.env.MODEL_URL;
  const modelApiKey = process.env.MODEL_API_KEY;

  if (modelUrl === undefined || modelApiKey === undefined) {
    return Response.json({ error: 'model_not_configured' }, { status: 500 });
  }

  const upstream = await fetch(modelUrl, {
    method: 'POST',
    headers: {
      authorization: `Bearer ${modelApiKey}`,
      'content-type': 'application/json',
    },
    body: JSON.stringify({ messages: input.output.messages, stream: true }),
    signal: request.signal,
  });

  if (!upstream.ok || upstream.body === null) {
    return Response.json({ error: 'model_unavailable' }, { status: 502 });
  }

  return new Response(upstream.body, {
    headers: {
      'content-type': 'text/event-stream; charset=utf-8',
      'cache-control': 'no-store',
      'x-accel-buffering': 'no',
    },
  });
}

The proxy forwards the incoming abort signal, so client cancellation reaches the upstream model explicitly instead of depending on runtime-specific stream teardown.

KV cache memory is a first-order constraint

During autoregressive decoding, transformer serving keeps attention keys and values in memory, and that memory is often a tighter constraint than the computation itself. vLLM's PagedAttention work targeted this constraint and reported up to 24x higher throughput than HuggingFace Transformers in its benchmark setting.23 Its v0.6.0 update reported 2.7x throughput and 5x faster TPOT on Llama 3 8B versus v0.5.3, plus 1.8x throughput and 2x lower TPOT on 70B.24

Those multipliers belong to their benchmark configurations. The transferable finding is that memory layout, cache fragmentation, batching, scheduling, and the distributions of prompt and output lengths all shape serving performance. A self-hosted server exposes those choices as configuration:

vllm serve meta-llama/Llama-3.1-8B-Instruct \
  --max-model-len 8192 \
  --max-num-seqs 128 \
  --gpu-memory-utilization 0.90

Test the flags against your prompt lengths, output lengths, hardware, and SLOs. Their useful values vary enough that guessing wastes GPU time.

Batching trades latency for throughput

NVIDIA Triton uses dynamic batching to combine inference requests and increase throughput, primarily for stateless models. Stateful workloads use its sequence batcher instead.25

# config.pbtxt
max_batch_size: 8

dynamic_batching {
  max_queue_delay_microseconds: 5000  # 5 ms; tune against your TTFT SLO
}

Batching spends queue time to buy accelerator utilization. Too much delay degrades p95 TTFT even while utilization improves, so for an interactive workload, goodput under SLO decides whether the trade is worthwhile.

An inference dashboard should report each of these separately: queue time, prefill time, TTFT, ITL/TPOT, token counts, GPU and KV-cache utilization, batch size distribution, cancellation rate, goodput, and cost per successful request. The product determines which of them leads:

ProductPrimary feel metricTypical optimization
ChatTTFT + smooth ITLStreaming, prompt trimming, prefix caching, batching bounds
Code completionVery low TTFT and short-output latencySmall/fast model path, context pruning, aggressive timeouts
Batch summarizationCost and E2E throughputLarger batches, lower-priority queues, offline workers
AgentsTTFT + predictable long-running costTool cache, idempotent steps, budgeted planning, cancellation
Search/rerankingTight p99 for small modelsColocated retrieval, small model replicas, admission control

Benchmark inference engines with your model, hardware, prompt distribution, batching policy, and SLO. A winner under someone else's inputs may lose under yours.

Start vector search inside PostgreSQL

For many products, pgvector inside PostgreSQL is the right first choice. Embeddings, metadata, permissions, tenancy, and transactional state stay together, operations stay simple, and small-to-medium RAG systems run comfortably.

A dedicated vector system becomes justified when any of these holds:

Qdrant, Milvus, Pinecone, Weaviate, or another dedicated serving path can then take over retrieval. Until one of those conditions creates a measured bottleneck or a real operational risk, a separate vector database adds an operational boundary without removing one.

An AI product default

streaming UI over SSE
thin gateway in Go, Rust, Node, or FastAPI
hosted model API for fast iteration, or vLLM/SGLang/TensorRT-LLM for control
for self-hosting, GPUs colocated with the app and data path
PostgreSQL for app state; pgvector for small/medium RAG
queue or workflow engine for long jobs
OLAP store for product analytics

On interactive paths, stream by default, keep prompts short, place stable prompt prefixes first when prefix caching is available, separate online inference from batch enrichment, and keep vector search near inference.

Self-hosting fits steady, high-volume traffic, privacy or residency requirements, and teams that can tune batching, KV cache, and scheduling. Hosted models fit early iteration, bursty traffic, and periods when model quality changes faster than infrastructure tuning can repay its cost.

Keep analytics scans off the transactional database

Transactional databases serve writes, point reads, constraints, and consistency. Analytics brings scans, aggregations, joins, and time windows. If both run on the OLTP primary, analytical demand degrades the write path.

A typical analytics-heavy stack:

PostgreSQL for OLTP
CDC or event stream into ClickHouse, BigQuery, Snowflake, or Redshift
object storage with Parquet
DuckDB for embedded/local/ad hoc analysis
cached dashboard queries with honest freshness labels

Once analytics matters to users, separate it from transactions. Pre-aggregate the common dashboard paths, use materialized views where the freshness tolerance permits them, run exports as background jobs, and show freshness in the UI. "Updated 3 minutes ago" is usually better than an 8-second wait for data that did not need to be live.

Build CPU-bound batch work around the job

CPU-bound jobs often don't need the web stack. A practical default is a Rust, C, C++, Zig, or Go binary in a container on Cloud Run Jobs, AWS Batch, ECS RunTask, or bare metal. Object storage holds the input and output, and a queue or manifest table assigns the work:

wordfreq \
  --input 's3://raw-corpus/2026-06/*.txt.zst' \
  --output s3://derived/wordfreq/2026-06-23/result.parquet \
  --shards 32

Track bytes per second, records per second, CPU seconds, peak memory, and cost per job. A good native binary on one machine is often enough. Distribution becomes necessary only when that machine misses a real SLO. A job that consumes a file, CPU, and memory to produce an artifact has no inherent need for Kafka, Kubernetes, or a service mesh.

What I would avoid by default

My default answer to these patterns is no, because teams often adopt them before the workload has earned their cost:

Measure before you change the stack

Few performance mistakes cost more than changing the easiest layer instead of the limiting one. Before you touch the stack, make the limiting queues visible. Route-level instrumentation exposes much of what you need. The appendix lists the signals for each layer and includes a small OpenTelemetry wrapper.

For an ordinary web application, I investigate in this order:

1. Frontend payload, rendering, hydration, images, fonts, third-party scripts
2. CDN/cache behavior and network distance
3. Data access shape: indexes, pools, locks, queues, N+1s
4. Architecture of the critical path
5. Tail latency and overload behavior
6. Backend framework/runtime
7. Backend language

For consumer web, that order usually becomes this sequence of fixes: reduce critical bytes, fix the LCP resource, remove render-blocking and hydration bottlenecks, put correct content behind the CDN, reduce origin TTFB, repair queries and pool behavior, and only then move compute closer to the user or the data, when the distance is material.

Internal tools and specialized systems reorder the work around their own dominant wait. AI puts the model and data path before the web framework, realtime puts event topology before the database, analytics puts storage layout before the API language, and CPU batch starts with the algorithm and runtime. Framework and language still matter, but starting with them usually leaves a larger constraint unexamined. Whatever the order, a bottleneck outside the critical path isn't worth optimizing.

Prefer changes that are easy to reverse. Removing unused JavaScript, compressing images, fixing cache headers, adding an index for an observed query, replacing hot-path OFFSET with keyset pagination, capping an overloaded connection pool, and putting a queue in front of a fragile dependency are all low-regret. Framework rewrites, database swaps, CDN migrations, new realtime transports, new vector databases, new inference engines, Kubernetes, and multi-region active-active have a larger blast radius, so they require stronger evidence.

Weigh each source by what it measured

The sources here are mostly primary documentation and ecosystem reports: Google's web performance docs, HTTP Archive's Web Almanac, vLLM's posts, Anyscale's benchmarking guidance, and documentation from AWS, Vercel, Cloudflare, PostgreSQL, PgBouncer, and NVIDIA. Their limits affect how to read the claims, so match each source to the question it can answer.

Core Web Vitals describe public web experience. The Web Almanac is an annual ecosystem baseline, not a measurement of your site. Framework benchmarks reveal ceilings, not product architecture. Database and inference benchmarks become relevant only with your schema, data distribution, query mix, model, prompt lengths, hardware, and SLOs. A valid benchmark can still be irrelevant to the workload, and treating it as decisive directs effort toward the wrong layer.

Keep the critical path short

For most web products, the HTML-first frontend, regional service, and regional PostgreSQL default is still a sensible starting point. Specialize only when the dominant wait requires it: static-first for public pages, regional-database-first for SaaS, room-first for realtime, inference-first for AI, OLAP-first for analytics, and native-job-first for CPU batch.

A benchmark score almost never identifies the fastest stack. Measurements of the user's path do. They show which queue to expose, where to bound it, and whether to shorten the work or move it off the path. The architecture that comes out of those measurements should keep that path short, observable, and resilient.

Appendix: the operational checklist

If your telemetry is missing any of these signals, add it before you change the stack.

Browser and frontend

CDN and network

Runtime and application

A minimal tracing wrapper for route handlers:

import { SpanStatusCode, trace } from '@opentelemetry/api';

const tracer = trace.getTracer('app-api');

export async function instrumentedRoute<T>(name: string, fn: () => Promise<T>): Promise<T> {
  return tracer.startActiveSpan(name, async (span) => {
    try {
      return await fn();
    } catch (error) {
      span.recordException(error instanceof Error ? error : String(error));
      span.setStatus({ code: SpanStatusCode.ERROR });
      throw error;
    } finally {
      span.end();
    }
  });
}

Add attributes for tenant, route template, cache result, database pool wait, downstream service, cold start, and queue time. Do not put secrets or raw user input in spans.

Database

Realtime

AI inference

References

Footnotes

  1. Google, "Web Vitals," source ↩

  2. Google, "Interaction to Next Paint becomes a Core Web Vital on March 12," source ↩

  3. HTTP Archive, "The 2025 Web Almanac: Performance," source ↩

  4. HTTP Archive, "The 2025 Web Almanac: Page Weight," source ↩

  5. Google, "Milliseconds Make Millions," source ↩

  6. Google, "How Rakuten 24's investment in Core Web Vitals increased revenue per visitor by 53.37% and conversion rate by 33.13%," source ↩

  7. MDN Web Docs, "Cache-Control," source ↩

  8. HTTP Archive, "The 2025 Web Almanac: CDN," source ↩

  9. Fastly Documentation, "Surrogate-Key," source ↩

  10. TechEmpower FrameworkBenchmarks GitHub issue #10932, "Sunsetting the TechEmpower Framework Benchmarks," source ↩

  11. Cloudflare Docs, "How Workers works," source ↩

  12. Vercel Docs, "Fluid compute," source ↩

  13. AWS Lambda Developer Guide, "Improving startup performance with Lambda SnapStart," source ↩ ↩2

  14. PostgreSQL Documentation, "Connections and Authentication," source ↩

  15. HikariCP Wiki, "About Pool Sizing," source ↩

  16. PgBouncer, "Features," source ↩ ↩2

  17. PostgreSQL Documentation, "Multicolumn Indexes," source ↩

  18. PostgreSQL Documentation, "LIMIT and OFFSET," source ↩

  19. MDN Web Docs, "WebTransport API," source ↩

  20. Cloudflare Docs, "Use WebSockets," source ↩

  21. Supabase Docs, "Realtime Benchmarks," source ↩

  22. Anyscale Docs, "Understand LLM latency and throughput metrics," source ↩

  23. vLLM Blog, "vLLM: Easy, Fast, and Cheap LLM Serving with PagedAttention," source ↩

  24. vLLM Blog, "vLLM v0.6.0: 2.7x Throughput Improvement and 5x Latency Reduction," source ↩

  25. NVIDIA Triton Inference Server Documentation, "Dynamic Batching & Concurrent Model Execution," source ↩