DevelopmentAugust 22, 20248 min read#nextjs#architecture#performance

Building Resilient Systems with Next.js

Best practices for ensuring high availability and performance in modern web applications.

TL;DR5
  1. Architecture before tooling: resilience is a design property
  2. ISR with stale-while-revalidate keeps pages alive through backend outages
  3. Retries need backoff and jitter — circuit breakers cut off cascading failures
  4. Error boundaries isolate failures to the widget that broke, not the page
  5. Ship fallback UI and offline tolerance as first-class features, not patches
Building Resilient Systems with Next.js

Architecture First

Next.js often serves as the backbone for modern web applications. Ensuring resilience requires a mix of good architectural decisions and proper tooling.

By leveraging Server Components and proper error boundaries, you can build extremely resilient web applications that degrade gracefully instead of crashing entirely.

Static Generation vs SSR

Whenever possible, default to Incremental Static Regeneration (ISR). This guarantees that even if your backend APIs are temporarily unavailable, users will still see the last successfully built version of your page.

The tradeoff is real though: ISR gives you resilience at the cost of freshness. SSR gives you freshness at the cost of a hard dependency on your backend.

// app/blog/[slug]/page.tsx
export const revalidate = 300; // 5 minutes

export default async function Post({ params }) {
  const post = await fetchPost(params.slug); // cached + revalidated
  return <Article post={post} />;
}

When my origin API went down for 40 minutes during a Cloudflare incident last year, every ISR page on y7.hk kept serving stale-but-valid HTML. The SSR pages on the same site returned 500s. That experiment cost me 4% of monthly traffic — and permanently changed how I think about rendering strategy.

Rule of thumb: ISR for anything that can be 5-60 minutes stale (blog posts, product pages, marketing). SSR only when staleness breaks the product (live dashboards, auth state, real-time data).

Error Boundaries Are Isolation Bulkheads

Without boundaries, a single failing widget takes the whole page down. With boundaries, each section fails independently.

// app/components/Section.tsx
'use client';
import { Component, ReactNode } from 'react';

export class Section extends Component<
  { children: ReactNode; fallback?: ReactNode },
  { hasError: boolean }
> {
  state = { hasError: false };

  static getDerivedStateFromError() {
    return { hasError: true };
  }

  render() {
    if (this.state.hasError) {
      return this.props.fallback ?? <div className="opacity-50">Section unavailable</div>;
    }
    return this.props.children;
  }
}

Wrap every independent unit — sidebar widgets, comment sections, analytics dashboards — in its own boundary. The user sees a gray box where the widget was, not a blank screen.

I learned this the hard way on a Web3 dashboard where a single RPC timeout crashed the entire portfolio view. One boundary around the price ticker would have saved the session.

Retry Strategies Need Backoff

Blind retries amplify failures. Exponential backoff with jitter spreads the load and gives the upstream room to recover.

async function fetchWithRetry<T>(
  fn: () => Promise<T>,
  attempts = 3,
  baseDelay = 300
): Promise<T> {
  for (let i = 0; i < attempts; i++) {
    try {
      return await fn();
    } catch (err) {
      if (i === attempts - 1) throw err;
      const jitter = Math.random() * baseDelay;
      await new Promise(r => setTimeout(r, baseDelay * 2 ** i + jitter));
    }
  }
  throw new Error('unreachable');
}

Two rules I follow:

  1. Never retry 4xx. A 404 won’t become a 200 on retry.
  2. Cap total wait. If the user has been staring at a spinner for 8+ seconds, show the fallback UI and let them continue.

Circuit Breakers Stop Cascading Failures

Retries solve transient errors. Circuit breakers solve persistent ones. If your backend has been failing for 30 seconds, stop hammering it — open the circuit and serve degraded responses immediately.

class Breaker {
  private failures = 0;
  private openUntil = 0;
  constructor(private threshold = 5, private cooldown = 30_000) {}

  async call<T>(fn: () => Promise<T>): Promise<T> {
    if (Date.now() < this.openUntil) throw new Error('Circuit open');
    try {
      const result = await fn();
      this.failures = 0;
      return result;
    } catch (e) {
      if (++this.failures >= this.threshold) {
        this.openUntil = Date.now() + this.cooldown;
      }
      throw e;
    }
  }
}

Without a breaker, a slow upstream turns into a fleet of hung Node processes. With one, you get fast failures and a system that can recover the moment the upstream comes back.

Edge Caching with Stale-While-Revalidate

The Cache-Control header is the cheapest resilience layer you have. stale-while-revalidate lets the edge serve the last cached copy while it fetches a fresh one in the background.

Cache-Control: public, s-maxage=60, stale-while-revalidate=600

This is the difference between “the API is down so the site is down” and “the API is down so some users see data that’s up to 10 minutes old.”

Fallback UI as a Feature

Fallbacks aren’t what you show when something breaks — they’re part of the design. Every async section needs three states:

  • Loading: skeleton that matches the final layout (no layout shift).
  • Success: the real content.
  • Error: a degraded version that still lets the user do their job.

If your pricing widget fails, don’t show a red error — show the last cached prices with a small “updated 12 min ago” badge. If the comment system fails, show the read-only thread and hide the input box.

Offline Tolerance

Service Workers aren’t just for PWAs. A minimal SW that caches the app shell and the last 5 visited pages gives you real offline tolerance on flaky hotel wifi and 30,000-foot plane rides — which, if you’re me, is a non-trivial percentage of your browsing.

// sw.ts — cache-first for static, network-first for pages
self.addEventListener('fetch', (e) => {
  const url = new URL(e.request.url);
  if (url.pathname.startsWith('/_next/static/')) {
    e.respondWith(caches.match(e.request).then(r => r ?? fetch(e.request)));
  }
});

Real Failures I’ve Hit

  • Cloudflare edge KV outage: every page that depended on KV returned 500. ISR pages survived.
  • Upstream CMS rate-limited me during a traffic spike. I had no breaker; Next.js kept hammering the CMS until I hit a hard IP ban. Now every external call goes through a breaker with a 30s cooldown.
  • A single <PriceTicker> component crashed the whole dashboard when the WebSocket dropped. After adding a boundary, the rest of the UI stayed live while the ticker silently reconnected.

Resilience Checklist

  • ISR/SSG for content that tolerates 5+ min staleness
  • stale-while-revalidate on every cacheable route
  • Error boundary around every independent widget
  • Exponential backoff + jitter on retries; never retry 4xx
  • Circuit breaker on every external service call
  • Skeleton + fallback + error states for every async UI
  • Service worker caching the app shell
  • A documented kill-switch for non-critical features (analytics, recommendations)

The Point

Resilience isn’t a feature you bolt on at the end. It’s the architecture itself. Every layer — rendering, caching, fetching, UI — gets a failure mode designed upfront. Build those in early, and the incidents that would have been outages become quiet degradations nobody notices.

Animated avatar video
Yakushev Hermann
Visionary Founder · Senior Agentic AI Architect · Networking

More from the blog

Anatomy of a Modern Engineering Post on y7.hk

A stress test for the y7 reading engine: callouts, diff blocks, KaTeX formulas, a circular avatar video, figure galleries, spoilers, and a font switcher.

Oct 15, 2026 · 5 min read

Living Between Time Zones

What 67 countries and four home bases teach you about deep work, jet lag, and building products nobody asked you to build.

Jul 18, 2026 · 6 min read

Keep exploring

Automated High-Frequency Trading Bot

case

Secure Mobile Crypto Wallet

case