Server Actions and the N+1 Problem Nobody Talks About
Server Actions feel like a free lunch until you profile a page that fires twelve of them on mount. Here's how we found a 3-second TTI regression hiding behind what looked like clean React code.
Server Actions were pitched as the end of the REST boilerplate era: write a function, call it from a component, done. But the moment you start using them the way the docs show — one action per row, one action per toggle, one action per hover-preload — you rebuild the exact waterfall you spent years tuning out of your SPA. We hit this on a dashboard rewrite last quarter, and the fix wasn't in the React layer at all.
The shape of the problem
Here's a component we had in production. It looks fine. It passed review. It passed Lighthouse locally.
// app/(dashboard)/projects/page.tsx
export default async function ProjectsPage() {
const projects = await getProjects();
return (
<ul>
{projects.map((p) => (
<ProjectRow key={p.id} project={p} />
))}
</ul>
);
}
// components/project-row.tsx
'use client';
import { useEffect, useState } from 'react';
import { getProjectStats } from './actions';
export function ProjectRow({ project }: { project: Project }) {
const [stats, setStats] = useState<Stats | null>(null);
useEffect(() => {
getProjectStats(project.id).then(setStats);
}, [project.id]);
return (
<li>
<span>{project.name}</span>
<span>{stats?.openIssues ?? '…'}</span>
</li>
);
}
On a page with 40 projects, that's 40 Server Action POSTs on mount. Each one is a round-trip to the Next.js server, which forwards to the database, which returns, which serializes a React Server Component payload back. In our staging environment, where the client sat behind a transatlantic link, the "ready" state of that list took around 3.2 seconds. On the engineer's MacBook in the office, it took 180ms. Guess which one shipped.
Why Server Actions amplify this
A traditional fetch to an API route has the same N+1 shape, but you can see it. It shows up in the Network tab as /api/projects/123/stats. It has a route handler you wrote. You know it's a request.
Server Actions hide the request. They look like function calls. The network entry is a POST to the current page URL with an opaque Next-Action header. If you're grepping for "api" in devtools, you'll miss them entirely. More importantly, every Server Action invocation re-runs the full RSC render pipeline for the segment that initiated it, because the framework needs to know whether to send you revalidated UI. That's not free. In our traces, a no-op Server Action cost roughly 40–80ms of server time on a warm Node process, before we did any actual work.
How we found it
We found it because a product manager complained that the dashboard "felt laggy" on their home internet. Nobody on the engineering team could reproduce it on the office network. The usual tools weren't much help:
- Vercel Analytics showed healthy LCP because the initial HTML streamed fast.
- Lighthouse showed a decent score because it measures the first viewport, not post-mount hydration fetches.
- Our RUM tracked Core Web Vitals, which don't capture "the list of numbers finally appears".
What worked was adding a single INP-adjacent metric: time from route commit to "all visible rows have data". Once we tracked that in production, the p75 was almost 4 seconds. The p95 was off a cliff.
A quick way to audit your own app
Drop this into a layout during a staging session. It logs every Server Action request initiated from the browser.
// app/debug-actions.tsx
'use client';
import { useEffect } from 'react';
export function ActionAuditor() {
useEffect(() => {
const orig = window.fetch;
window.fetch = async (input, init) => {
const headers = new Headers(init?.headers);
if (headers.has('Next-Action')) {
console.warn('[server-action]', headers.get('Next-Action'), input);
}
return orig(input, init);
};
return () => { window.fetch = orig; };
}, []);
return null;
}
If you see the same action fire more than three or four times on a route transition, you have the problem.
The fixes, ranked by how much we like them
There are four reasonable ways out. We've shipped all of them in different places.
1. Move the data into the RSC parent
The simplest answer is usually the right one: don't fetch per row. Fetch per page. The reason ProjectRow was a client component fetching its own stats was historical — it used to be a separate micro-frontend. Once we collapsed it:
export default async function ProjectsPage() {
const projects = await getProjectsWithStats(); // one query, one JOIN
return (
<ul>
{projects.map((p) => (
<ProjectRow key={p.id} project={p} />
))}
</ul>
);
}
The getProjectsWithStats function is a single SQL query with a LEFT JOIN on an aggregated issues subquery. Server time went up by maybe 30ms. Client-perceived time dropped by 3 seconds. This is almost always the answer when the data is cheap to join.
2. Stream with Suspense, don't useEffect
When the per-row data is genuinely expensive and you want progressive reveal, use RSC + Suspense instead of client-side fetching:
export default async function ProjectsPage() {
const projects = await getProjects();
return (
<ul>
{projects.map((p) => (
<li key={p.id}>
<span>{p.name}</span>
<Suspense fallback={<span>…</span>}>
<ProjectStats id={p.id} />
</Suspense>
</li>
))}
</ul>
);
}
async function ProjectStats({ id }: { id: string }) {
const stats = await getProjectStats(id);
return <span>{stats.openIssues}</span>;
}
This still issues N queries, but it does them on the server, in parallel, over a single streamed response. No N round-trips from the browser. Pair it with a DataLoader-style batcher in your data layer and the N queries collapse into one on the DB side as well.
3. Batch the action on the client
Sometimes you genuinely can't move the fetch to the server — for example, when the IDs are only known after a client-side filter runs. In that case, batch:
// app/actions/stats.ts
'use server';
export async function getProjectStatsBatch(ids: string[]) {
return db.stats.findMany({ where: { projectId: { in: ids } } });
}
'use client';
import { useEffect, useState } from 'react';
import { getProjectStatsBatch } from './actions/stats';
const queue: { id: string; resolve: (s: Stats) => void }[] = [];
let timer: ReturnType<typeof setTimeout> | null = null;
function request(id: string): Promise<Stats> {
return new Promise((resolve) => {
queue.push({ id, resolve });
timer ??= setTimeout(flush, 16);
});
}
async function flush() {
const batch = queue.splice(0, queue.length);
timer = null;
const results = await getProjectStatsBatch(batch.map((b) => b.id));
const byId = new Map(results.map((r) => [r.projectId, r]));
for (const { id, resolve } of batch) {
const found = byId.get(id);
if (found) resolve(found);
}
}
One Server Action request per animation frame, not per row. You can get fancier with AbortController and request deduplication, but 20 lines of code is usually enough.
4. Don't use a Server Action at all
Server Actions are mutations with a return value tacked on. If you're reading data from the client post-mount, a cached route handler or a plain RSC is almost always a better fit. We reserve Server Actions for things that change server state: form submissions, toggles, destructive operations. Reads live in RSCs or in a tiny /api/* surface we can cache at the edge.
The production gotcha we didn't see coming
One more thing worth flagging. When Server Actions are called in parallel from the client, Next.js serializes their effects on revalidation but not their execution. If two actions both call revalidatePath('/projects'), you'll get two revalidations, and the second one's RSC payload will overwrite the first in the client cache — even if the first was initiated later from the user's perspective. We've seen this cause "flashing stale data" on dashboards that call three or four actions on mount. The batching fix in option 3 makes this problem go away too, because there's only one action and one revalidation.
Where we'd start
If you suspect you have this in your codebase, do three things this week. Add the ActionAuditor snippet above to a staging layout and watch the console on your three highest-traffic routes. Add one RUM metric — "time to all-rows-populated" or similar — so you can tell if production users are seeing something your laptop isn't. Then, for each route that fires more than a couple of actions on mount, decide whether the data belongs in the RSC parent (usually yes), in a streamed Suspense boundary, or behind a client-side batcher. In that order. Server Actions are a great primitive. Treating every one as free is the quickest way to rebuild the waterfall you came to the App Router to escape.
If you want a second pair of eyes on a Next.js performance audit, that's the kind of thing our web development team does for clients most weeks.
Want a team like ours?
72Technologies builds production software for the kind of teams who actually read this blog.
Start a projectKeep reading
Why Our Design System's Tokens Broke Dark Mode in Server Components
We shipped a design system with CSS variables, theme toggles, and server components. Then half our pages flashed white on reload and the other half rendered the wrong theme entirely. Here's what we learned.
The Hidden Cost of `revalidateTag` at Scale: Why Our Cache Invalidations Took 40 Seconds
`revalidateTag` looks like a free lunch until you ship it to a site with 80,000 cached entries. Here's what we learned about Next.js tag invalidation when it stopped being instant.
The Edge Runtime Cold Start Myth: Why We Moved Three Routes Back to Node
Edge runtime promised faster cold starts and lower latency. For three of our routes, it delivered the opposite. Here's what we measured, why it happened, and the rules we now use to decide.
