This post assumes you're comfortable with Next.js SSR, HTTP response headers, and a reverse proxy like NGINX.
How Claude was used in writing this post
Short version: the engineering is mine, and so is the first draft. Claude helps me get it published.
- Engineering and source material. All work described here was done by me. The background and technical detail come from reviewing my own PRs, their summaries, and our post-mortems.
- Research. Claude helped gather outside documentation and sources. I read each one myself to judge relevance and applicability before it informed the post.
- Drafting. With the material gathered, I sat down and wrote the rough draft manually in Neovim.
- Editing. Claude then assisted with edits, organization, and structure.
Like most of us I don't have much spare time, and these write-ups happen on weekends. Claude is what lets me actually finish them instead of leaving them half-written. They exist primarily for my own learning and growth as an engineer.
1. Summary
One morning, minutes after a scheduled production deploy, our
monitoring lit up with 502 Bad Gateway errors. The
symptom was specific and bizarre:
users could log in successfully, and then the very next page load
would 502.
Not intermittently. Every full load of an authenticated page, for
every user, deterministically. (The login page itself - also a full
document load - kept working, and the reason why turned out to be
part of the story. Section 3 covers it.)
The application is a data-heavy internal analytics platform built on Next.js (App Router) running on an EC2 instance behind an NGINX reverse proxy, fronted by a load balancer. Nothing about the outage touched application logic, the database, or the API. The entire failure lived in the size of the HTTP response headers our Next.js server was emitting, and a buffer limit in NGINX that we had never configured and never thought about.
| Field | Value |
|---|---|
| Severity | P1 (complete loss of authenticated access) |
| Trigger | A patch-level framework upgrade (Next.js 16.2.1 → 16.2.2) bundled in a routine dependency update |
| User-facing duration | ~47 minutes from first alert to restored service (onset was the deploy itself, a few minutes before detection) |
| Root cause |
Response headers exceeded NGINX's default
proxy_buffer_size (4,096 bytes) by 63 bytes
|
| Underlying cause | 30 font files registered for preload; only 8 were actually used |
| Fix scope | One file. Font config only. Zero component changes. |
| Luck factor | No external customer sessions occurred during the window |
The rest of this post is the chain of small, individually reasonable decisions that stacked into a house of cards, the diagnostic path we took to find it, and the fix.
2. Timeline
Times are relative to the first alert (T+0) to keep this generic. Note that T+0 is detection, not onset - the deploy that introduced the bug landed a few minutes earlier, so total user exposure slightly exceeds the 47-minute figure below. The whole incident, from first report to production restored, was under an hour.
| Time | Event |
|---|---|
| T+0 |
On-call notices 502 Bad Gateway on the deployed
environment. Alerts confirm it is not a blip.
|
| T+7 | Incident acknowledged. A responder confirms the pattern: login works, the next full page load 502s. |
| T+7 to T+16 | Decision made: restore service first, diagnose second. We cut a rollback branch from the last known-good release tag. |
| T+16 | Rollback build packaged. |
| T+37 | Rollback staged and verified on the staging environment. 502 gone on the old build. |
| T+47 | Rollback deployed to production. Service fully restored. |
| T+47 onward | Root-cause investigation begins in earnest on staging, now decoupled from the outage. |
The key call here was ordering. We rolled back before we understood the bug. A rollback to the previous release tag is a known-safe operation; a root-cause fix under incident pressure is not. Restoring service was our first priority, and it let us focus our debugging without the added pressure of a live production outage.
3. The symptoms, and why they were the whole clue
Before the mechanism, review the symptom table.
| Action | Result | Why (in hindsight) |
|---|---|---|
| Load the login page (full document load) | ✅ Works |
Same 30 font preload entries as everywhere else - but
unauthenticated routes skip our middleware, so no
session-refresh Set-Cookie or request-ID
headers. Just under the buffer.
|
| Submit login form | ✅ Works | Login route returns a small JSON response. Tiny headers. |
| Land on the page after login (full document load) | ❌ 502 |
Full SSR HTML render emits a
Link: rel=preload header entry for
every registered font, plus the extra
headers our middleware adds on authenticated routes.
|
Navigate via an in-app <Link> |
✅ Works | Client-side nav fetches an RSC payload (JSON), ~300 bytes of headers, no font preloads. |
| Type that same URL into the address bar and hit enter | ❌ 502 | Now it's a full document load again. Same page, opposite result. |
That last row is the tell. The identical page worked through client-side navigation and failed through a hard navigation.
The first row deserves its own explanation, because in an early
draft of this post I hand-waved it. The login page is a full
document load too, and it carried the
same 30 preload entries as every other page - so
why didn't it 502? Because our middleware's matcher only covers
protected routes. On authenticated pages it refreshes the session
and re-issues the session cookie, so those responses carry a
Set-Cookie header with an encrypted session payload,
plus a request-ID header and a few others. That handful of extra
headers was worth a few hundred bytes - and with the preload block
eating 3,707 of the 4,096-byte buffer, only 389 bytes remained for
everything else. The login page's lean remainder fit; the
authenticated pages' ~452 bytes did not. The failure
boundary traced our authenticated/unauthenticated route split not
because the bug had anything to do with auth, but because that split
determined which responses got the extra headers. That's why it
masqueraded so convincingly as a session bug.
There was even an accidental bypass that deepened the confusion at
first: the post-login redirect used a client-side
router.push(), so the redirect target loaded fine. It was
only when someone refreshed, or opened a page in a new tab, that the
502 appeared. "Works right after login, breaks on refresh" sounds like
a session bug. It wasn't. It was the type of navigation all along.
Concept box: why full loads and client navigations differ
On a full document load, Next.js server-renders the whole HTML page. As part of that response it advertises the fonts the page will need, using HTTP
Link: <url>; rel=preloadheader entries so the browser can start fetching them early. One header entry per registered font face. (For dynamically rendered documents - which, because our root layout reads the session cookie, is every page in our app - Next.js hoists these hints into the HTTP response headers rather than inline<link>tags. That's what puts them in front of the proxy's header buffer.)On a client-side
<Link>navigation, there is no new HTML document. React fetches a React Server Components (RSC) payload - essentially JSON describing what changed - and the browser reuses the fonts it already has. No document, no preload headers.So the two navigation styles produce structurally different response headers for the same page. That's the crack the bug fell through.
4. Root cause analysis
The outage was the collision of two things that were each fine on their own: too many preloaded fonts, and a framework upgrade that made every font URL slightly longer.
4a. The latent problem: 30 fonts, 22 of them dead weight
Early in the project we bought a commercial admin template to skip weeks of boilerplate - login screen, nav shell, a themed component library, and fonts, all pre-wired. We stripped it down to a baseline and built our real product on top.
Here's the part I want to be precise about, because it's easy to pin on the template and that would be wrong: the 30 font files were not something we inherited. We introduced them ourselves.
What the template actually shipped with, font-wise, was small:
two <link> tags pulling two font families from a
hosted font CDN
(think Google Fonts) in the document <head>. Two
network calls. Nothing that would ever trouble an HTTP header buffer.
Later, as the app matured, we decided to move font loading in-house using the framework's built-in local-font system and drop the CDN entirely. The rationale was sound, and it's the generally recommended direction: serving fonts from your own origin removes a third-party DNS/TLS round-trip, closes a privacy leak (every page view otherwise pings the CDN with the user's IP and user-agent), and removes a class of font-swap layout shift.
The catch was in how I did the migration. My first attempt
was actually the right idea: I pointed the local-font API at the
family's variable font file - a single file that
carries the entire weight axis. But I registered it without
declaring its weight range, so the generated
@font-face described a single-weight family, and
headings and bolds came out as browser-synthesized approximations.
The correct fix was one line - declare the range,
weight: '100 900' - but I didn't know that, and I
misdiagnosed the API as not supporting variable fonts at all. So I
fell back to the quick-and-dirty thing: I enumerated every static
weight and style the CDN had been serving, downloaded each file,
registered them one by one, and left a comment in the config warning
future engineers away from variable fonts. That is how two
<link> tags turned into
30 registered local font files - 18 faces of the
primary family (nine weights, normal and italic) and 12 of a
secondary family we barely used.
It rendered correctly, and I told myself the migration was clean. It wasn't silent, though. From that day on, every page load logged a browser console warning for each preloaded-but-unused face - "The resource ... was preloaded using link preload but not used within a few seconds" - up to 22 of them per load. We never saw a single one. At some point I had filtered warnings out of the DevTools console to quiet an unrelated debugging session, and that filter persists - across tabs, restarts, and projects - until someone remembers to turn it back on. Nobody remembers, because a muted filter doesn't announce itself. The channel pointing directly at the future outage was silenced the entire time. A console filter isn't a fix; it's a blindfold that stays on long after you've forgotten you tied it.
Concept box: what "font preloading" actually costs
A preload tells the browser: fetch this now, at high priority, before you've even parsed the CSS that references it.
<link rel="preload" href="/font.woff2" as="font" type="font/woff2" crossorigin>Preloading one or two above-the-fold faces is a clear win - it collapses a serial chain of "download HTML → download CSS → parse CSS → discover font → fetch font" into a head start.
But each preload is a high-priority fetch that competes with genuinely critical resources (JS, CSS, the LCP image). Preload twenty faces the page may never use and you're not optimizing - you're forcing the browser to prioritize bytes nobody needs, and you're bloating the response headers that advertise them. Preloading is a scalpel, not a default-on firehose.
When you register a local font this way, the framework emits a preload
Link header entry for it on every full page render. So
the real trade I'd made wasn't "two network calls for 30 tidy local
files." It was "two network calls for
30 preload header entries stamped onto every server-rendered
response."
I'll own this one. I was a junior engineer at the time, single-handedly building out the frontend, and I didn't have the experience to recognize the code smell. My mental model was shallow - 30 local imports, resolved server-side, fonts render, done - and I never took the step of understanding how the local-font API actually surfaced those files to the browser. The connection I missed is the entire bug: each of those registrations doesn't just load a file, it adds a line to the response headers. The fonts rendered correctly, there were more urgent features in the pipeline, and "good enough" won. It should have been a step-back moment. It wasn't.
Here is what the header block looked like, by the numbers:
| Component | Size |
|---|---|
Link header (30 preload entries) |
3,707 bytes |
| Standard response headers (cookies, content-type, etc.) | ~452 bytes |
| Total response header block | ~4,159 bytes |
4b. The NGINX buffer nobody configured
Our NGINX config never set proxy_buffer_size. That means
it used the platform default, which on 64-bit Linux is
one memory page: 4,096 bytes.
proxy_buffer_size controls the buffer NGINX uses to read
the first part of the upstream response - specifically the
status line and the response headers. If the upstream's headers don't
fit in that single buffer, NGINX doesn't stream them anyway. It gives
up on the response and returns a 502, with this exact log
line:
upstream sent too big header while reading response header from upstream
At 4,159 bytes of headers against a 4,096-byte buffer, we were 63 bytes over. Which raises the obvious question: if we were already over the limit, why did production work at all right up until the deploy?
We weren't over the limit before. We were just under it.
4c. The trigger: longer asset hashes in a patch upgrade
The deploy that morning included a batch of routine dependency updates. Buried in it was a patch-level framework bump (Next.js 16.2.1 → 16.2.2) whose changelog said nothing dramatic. But that release included an upstream change to the bundler (vercel/next.js#91137), summarized as a switch of output-filename hashes from hex to base40 encoding.
I got the mechanism of this wrong in my first draft of this post, and it's worth spelling out because the changelog's framing invites the mistake: an encoding change cannot make a hash longer. Base40 packs more information into each character than hex does (log2 40 ≈ 5.32 bits per character, versus exactly 4 for hex), so re-encoding the same hash in base40 always produces a shorter string. What actually grew was the entropy: the release standardized filename hashes at roughly 69 bits, where asset filenames had previously carried only a 32-bit (8 hex character) hash.
bits per character:
hex (base16): log2(16) = 4.00
base40: log2(40) ≈ 5.32 (denser, so SHORTER for the same hash)
asset filenames (fonts, images):
before: 8 hex chars × 4.00 = 32 bits
after: 13 base40 chars × 5.32 ≈ 69 bits ← entropy grew: +5 chars
JS/CSS chunk filenames:
before: 16 hex chars × 4.00 = 64 bits
after: 13 base40 chars × 5.32 ≈ 69 bits ← same change: 3 chars SHORTER
Two things follow from that table. First, the encoding switch actually softened the blow - ~69 bits rendered in hex would have been an 18-character hash, +10 characters per URL instead of +5. Second, the change didn't uniformly lengthen filenames: chunk filenames got shorter. It just happened that fonts sit in the asset category, the one whose hashes grew.
Each of our 30 font URLs grew by 5 characters:
30 fonts × 5 characters = 150 bytes
4,159 - 150 = 4,009 bytes (before the upgrade: 87 bytes under the 4,096 limit)
4,159 bytes (after the upgrade: 63 bytes over, permanently)
That's the whole bug. A patch-level upgrade that strengthened hash collision resistance silently pushed a header block that had been living 87 bytes under a buffer limit to 63 bytes over it. No application code changed. No font changed. Just the length of some strings in a header.
The full chain
Template shipped 2 CDN font links
│
▼
We migrated fonts in-house → registered 30 local faces = 30 preload Link header entries per full render
│
▼
Header block sits at ~4,009 bytes → quietly under NGINX's 4,096-byte default buffer
│
▼
Framework patch upgrade → asset hash entropy 32 → ~69 bits (8 → 13 chars, +5 per URL)
│
▼
+150 bytes → header block hits 4,159 bytes (63 over)
│
▼
NGINX: "upstream sent too big header" → 502 on every authenticated full page load
5. Diagnosis: how we actually found it
We didn't get to that clean chain on the first try. The morning-of investigation was hypothesis elimination on staging, and it's worth showing because the process is more reusable than the answer.
The suspect deploy bundled several changes. We had three candidates and worked them like a bisect:
- Hypothesis: a circular-dependency cleanup changed module init order. We reverted it on staging. The 502 persisted. Eliminated.
- Hypothesis: an ESLint plugin migration changed build output. We reverted that too, on top of the first revert. The 502 persisted. Eliminated.
- Remaining suspect: the batch of dependency updates (which contained the framework bump), versus a purely feature-level change with no infra footprint.
At this point we stopped guessing at the application layer and read
the NGINX error log. The
upstream sent too big header line reframed the entire
problem. This was never an application bug. It was a
response-header-size bug. From there, connecting "header too big" to
"we emit a preload header per font" to "we register 30 fonts" took one
grep of the font config.
The lesson embedded in the diagnosis: when navigation type determines success, read the proxy logs before you read your own code. We spent our initial efforts reverting application-layer changes because that's the code we own and understand. The answer was one line in a log from the layer we'd never configured.
6. The fix
The root-cause fix was scoped to a single file: the local-font configuration. No component changed, because the fonts we removed were never actually used in rendering - they were registered, preloaded, and ignored.
We reduced font registrations from 30 to 8:
- Kept the primary family at the weights the app genuinely uses.
- Dropped the ultra-light weights (100/200/300) nobody rendered.
- Dropped every italic except the single one in real use.
- Dropped the entire secondary family except one weight, kept only because a theme token still referenced it. (That last face gets its own reckoning in the final remediation below.)
The result:
| Metric | Before | After | Change |
|---|---|---|---|
| Registered fonts | 30 | 8 | -73% |
| Response header block | ~4,159 bytes | ~1,477 bytes | -64% |
| Headroom under 4,096-byte buffer | -63 bytes (over) | +2,619 bytes | Comfortable |
That 2,619 bytes of headroom matters. It absorbs future framework upgrades, deployment-id suffixes on asset URLs, and variable cookie sizes, without flirting with the limit again.
The fork in the road: four ways out
In the first draft of this post I framed the decision as binary: remove the fonts, or bump the NGINX buffer. Writing it up - and having it reviewed - taught me the framework had more to offer than I understood, even a year and a half after the migration. The honest list has four options:
- Remove the unused registrations. This is what we did, and under incident follow-up pressure it was the right call: 22 of the 30 faces were pure dead weight, so deleting them fixed the header bloat, the wasted high-priority fetches, and the console warnings all at once, with zero component changes.
-
Stop preloading fonts you must keep registered.
next/fontacceptspreload: falseper font - the face stays registered and usable, but emits no preload hint and therefore no header entry. I didn't know this option existed at the time; it's exactly the knob the incident was missing. It looked like the right tool for the one face we kept only because a theme token referenced it - but auditing the token showed nothing consumed it either, so the right answer was deletion, not de-prioritization. The bestpreload: falseis the font you delete. -
Variable fonts - the structural fix. One variable
font file per family and style carries the entire weight axis, so
the whole 18-face static matrix collapses to two files (roman and
italic) registered with a weight range
(
weight: '100 900') - two preload entries, no matter how many weights design uses. The embarrassing detail: our primary family ships official variable files, and they had been sitting in our repo the entire time, one directory above thestatic/folder we registered 18 files from. My original migration even used one - then I misread a missing weight-range declaration as "variable fonts don't work" and enumerated the statics instead (section 4a). This option makes the entire class of bug structurally impossible instead of merely unlikely, and it's where the config ends up below. -
Raise the NGINX buffer - the stopgap.
Raising# The defensive one-liner proxy_buffer_size 8k;proxy_buffer_sizeto8kwould have stopped the 502 instantly. But on its own it would have left 22 unused fonts preloading on every page, still bloating headers, still competing for browser fetch priority, still growing with every future upgrade. We'd have paid for the buffer with a slower page and a hidden liability that would resurface at8ksomeday.
The buffer change treats the symptom; options 1-3 treat the disease
at increasing depth. Option 1 was the incident fix - the safe,
scoped change to make under follow-up pressure. Options 2 and 3
pointed at the config's true end state, which is where this story
finishes. Option 4 we documented as a belt-and-suspenders setting
for anyone who wants defense in depth. (If you run Next.js behind
NGINX and can't audit your fonts today, raising
proxy_buffer_size is a perfectly good stopgap - just
don't mistake it for a fix.)
The final remediation: a senior fix for a junior mistake
The incident fix stopped at 8 faces because that was the right scope for incident follow-up. But it still carried the original junior mistake inside it: a static-face matrix standing in for a variable font, and a config comment warning future engineers away from the correct approach. The end state of the config is this:
export const PUBLIC_SANS = localFont({
src: [
{
path: './fonts/Public_Sans/PublicSans-VariableFont_wght.woff2',
weight: '100 900',
style: 'normal',
},
{
path: './fonts/Public_Sans/PublicSans-Italic-VariableFont_wght.woff2',
weight: '100 900',
style: 'italic',
},
],
display: 'swap',
fallback: ['Helvetica', 'Arial', 'sans-serif'],
});
Two registrations, two preload entries. The secondary family is
gone entirely - the theme token that justified keeping one weight
turned out to have no consumers, so the token, the registration,
and the font files left the codebase together. The primary family
is back on the variable files my original migration started with,
plus the one line 2024-me was missing:
weight: '100 900'. The misleading comment came out
too, so the config no longer teaches the next engineer my mistake.
(One refinement on top: the upstream project ships its variable
fonts as TTF only, so we converted them to
WOFF2
with fontTools - the same font tables in a Brotli-compressed
container - cutting each file by roughly 57%.)
That single declaration is the entire distance between the junior version of this migration and the senior one. The junior version worked around a symptom it didn't understand and grew the config to 30 files. The senior version is smaller than the thing it replaces: any weight design ever asks for is already in the file, and there is no static matrix left for a future framework upgrade to multiply against. The junior fix removed the instance of the bug; the senior fix removed the class.
7. Prevention: the dev/prod parity gap
The deepest lesson isn't about fonts. It's about why this was invisible locally.
In local development, your browser talks to the Next.js dev server
directly. There is no reverse proxy in the loop, so there is
no proxy_buffer_size, so there is no buffer to overflow.
The exact same oversized header block that 502s in production sails
through in development, because the component that rejects it isn't
running on your laptop.
This is a dev/prod parity gap, and it hides an entire class of failures. Anything that lives in the proxy layer - header limits, buffer sizes, timeout behavior, body-size caps - is simply absent from the default local stack. You can't catch a bug with a tool you don't run.
We evaluated two prevention options:
Option A: a full-page-load header-size E2E test. A
browser test that navigates via hard loads (not just
<Link> clicks), captures the response headers, and
asserts the total stays under a threshold with margin. The catch: to
be meaningful it needs the proxy in the loop, so it's a manual gate
against a full local stack rather than a cheap CI check.
Option B: run NGINX locally via Docker Compose, mirroring the production defaults. This closes the parity gap directly - a developer who oversizes the headers sees the identical 502 on their machine, before it ever reaches production. The tradeoff is adding Docker as a development dependency and keeping the local proxy config in sync with production.
Both are reasonable. The framing that matters: a bug that can only manifest behind a proxy can only be caught behind a proxy. If production runs a component, your test environment should too.
8. Lessons learned
- Unused dependencies accumulate risk silently. Those 22 dead fonts sat in the config for well over a year, harmless, until an unrelated upgrade turned them into an outage. Dead code isn't neutral. It's a loaded liability waiting for a trigger. And in our case it wasn't even silent - the browser logged a preload-unused warning for every one of them on every page load. We never saw them, because the DevTools console had warnings filtered off, and that setting quietly persists forever. Never leave the warning channel muted: a silenced warning is indistinguishable from a healthy system.
- Patch and minor version bumps can carry outsized side effects. The changelog framed the change as a hash-encoding cleanup; the payload that mattered was more entropy in every asset filename. "It's just a patch bump" is exactly the assumption that lets a five-character string change take down a login flow - and reading the changelog isn't enough if you accept its framing instead of asking what the change does to your outputs.
- Client-side and server-side navigation produce fundamentally different HTTP responses. Internalizing this turns a baffling "works via link, fails via refresh" symptom into an immediate "check response header size" instinct. It's a useful mental model for debugging infrastructure behind a proxy.
- Infrastructure defaults were written for a different era. NGINX's 4,096-byte header buffer - one memory page - is a sensible default for a world of lean, hand-written responses. Modern frameworks emit far richer headers (preloads, early hints, deployment metadata). When a decades-old default meets a framework that treats headers as a resource-optimization channel, the default can quietly become a ceiling.
- Restore first, understand second. Rolling back to a known-good tag before diagnosing turned a P1 into a controlled investigation. Debugging under "the site is down" pressure is how a one-line fix becomes a three-line mistake.
The whole thing came down to 63 bytes. Not a logic error, not a race condition, not a bad query - just a header block that grew five characters at a time until it crossed a line nobody knew was there.
Further Reading
-
NGINX
proxy_buffer_size/proxy_buffers- the buffer at the center of this incident -
Next.js font optimization (
next/font) - how local fonts and preloading work -
next/font/localAPI reference -
MDN: the
LinkHTTP header -
MDN:
rel=preload- the mechanism, and its costs - React Server Components - why client navigation ships JSON, not HTML
- The upstream change that triggered it (vercel/next.js#91137) - hash entropy standardized at ~69 bits, encoded in base40
- MDN: Variable fonts guide - the structural fix we ended on
Written after a real P1. Framework and infrastructure versions and behaviors described are as of early 2026; buffer defaults and framework internals change, so verify against your own stack.