Skip to content
Abdifatah Artan
All projects

2023 — Shipped

Mosaic

A server-rendered web platform serving 40M monthly visits with edge caching, real-time dashboards, and sub-100ms LCP on a global edge network.

Next.jsPostgreSQLEdgeRedis

Role — Staff Engineer

The problem#

Mosaic's public site was a React SPA that fetched everything client-side. Time-to-interactive was 4+ seconds on mid-range mobile, and bounce rate tracked it almost one-to-one. The business wanted faster, but the team also wanted to stop hand-rolling cache invalidation.

The re-architecture#

We moved the site to server-rendered Next.js with three layers of caching: static pages pre-rendered at build time, dynamic pages cached at the edge with tag-based invalidation, and per-user data streamed in after first paint.

The load-bearing decision was the caching model:

middleware.ts
export function middleware(req: NextRequest) {
  const url = req.nextUrl;
 
  // Public pages: cache at the edge, revalidate on tag invalidation.
  if (isPublicRoute(url.pathname)) {
    return NextResponse.next({
      headers: {
        "x-cache": "edge",
        "cache-control": "public, max-age=0, s-maxage=300",
      },
    });
  }
 
  // Dashboards are dynamic but served stale-while-revalidate.
  return NextResponse.next();
}

The database, honestly#

Most of the win came from SQL, not from the framework. Three changes did the heavy lifting:

  1. Read replicas with query routing — 80% of queries never touch the primary.
  2. Materialized views for dashboard aggregates, refreshed on a 30-second cadence instead of per-request COUNT(*).
  3. Connection pooling tuned per-service — pool exhaustion was the #1 cause of the old site's p95 tail.
migrations/018_dashboard_mv.sql
CREATE MATERIALIZED VIEW dashboard_rollups AS
SELECT
  account_id,
  date_trunc('hour', created_at) AS hour,
  count(*)            AS events,
  sum(amount_cents)   AS volume_cents
FROM events
WHERE created_at > now() - interval '90 days'
GROUP BY 1, 2
WITH NO DATA;
 
CREATE UNIQUE INDEX ON dashboard_rollups (account_id, hour);
98msLCPp75, global
40MVisitsper month
-31%Bouncevs. previous SPA
-38%Infra costafter migration

Edge caching is not free

Tag-based invalidation is elegant until a tag fans out to 40k pages. We learned to model tags at the section level (a feed, a profile) rather than per-entity, and to treat "eventually consistent by 60s" as a product decision, not an engineering accident.

What stuck#

The lesson I repeat most from Mosaic: performance work compounds when you make it visible. We shipped a latency budget into CI — every route declares a p95 budget and a synthetic check enforces it. Regressions get caught in review instead of in the on-call channel.