Tech Verse Logo
Enable dark mode
Next.js Server Actions: Concurrency and Stale Data

Next.js Server Actions: Concurrency and Stale Data

•Updated •13 min read

An item that appears and then vanishes usually means the action called revalidateTag(tag, 'max'), which serves stale data and doesn't re-render in the action's response, so call updateTag instead. A tab sends its actions one at a time, but the server runs requests from different users concurrently, so protect edits with a version column checked in the UPDATE's WHERE clause.

Two bugs show up once Server Actions meet real users. In the first, someone adds an item, it appears for a moment, vanishes, and comes back a refresh or two later. In the second, two people edit the same record and one of them silently loses their work. Both get blamed on "race conditions", and both are usually fixed with the wrong tool: debouncing, disabling buttons, or router.refresh() sprinkled after every call.

The real causes are more specific. The first comes from how App Router caching interacts with the action's response. The second comes from what the server does with concurrent requests, which is nothing special. This article goes through how actions are dispatched, which cache API gives you read-your-own-writes, how useOptimistic fits in, and how to stop concurrent edits overwriting each other. I ran the key behaviours in a production build to confirm them, and the outputs below are from those runs.

How Next.js dispatches Server Actions

Start with what doesn't happen. A single browser tab doesn't send overlapping actions. The Server Actions guide says the client dispatches them one at a time: the second waits for the first to finish, the third for the second. I tested this with a button that fires three calls to a 500 ms action in a loop, without awaiting any of them:

'use server'

export async function logCall(n: number) {
  console.log(`action ${n} start ${Date.now() % 100000}`)
  await new Promise((resolve) => setTimeout(resolve, 500))
  console.log(`action ${n} end   ${Date.now() % 100000}`)
  return n
}
'use client'

import { logCall } from './actions'

export function FireThree() {
  return (
    <button
      onClick={() => {
        for (const n of [1, 2, 3]) logCall(n)
      }}
    >
      Fire three actions
    </button>
  )
}

The server log, in milliseconds:

action 1 start 74612
action 1 end   75113
action 2 start 75118
action 2 end   75619
action 3 start 75622
action 3 end   76123

Each action starts after the previous one ends. That has two consequences. A double-click on a submit button doesn't create two simultaneous requests; it creates two requests in a row, so you still get two inserts, just not overlapping ones. And Promise.all over several actions doesn't parallelize anything. If you need parallel work, do it inside one action.

The same guide is explicit about the other half: the server doesn't queue anything. Every action is an ordinary POST handled as it arrives. Two tabs, two users, a mobile client retrying after a timeout, or someone calling the endpoint with curl all run concurrently on the server. So the client-side queue protects your UI's consistency, and it does nothing for your data. Data integrity is the database's job, and we'll get there.

Why the action shows stale data

When an action calls updateTag, revalidatePath or refresh, Next.js re-renders the current route on the server and sends the new RSC payload back in the same response as the action's return value. One round trip, and the page reflects the change. That's the behaviour you want after a mutation.

revalidateTag is different, and it's where most "stale data after a Server Action" reports come from. In current Next.js it takes a second argument, and the recommended value is 'max', which means stale-while-revalidate. The tag is marked stale, and the next read is served the old cached value while a fresh one is fetched in the background. The revalidateTag reference describes it that way, and the Server Actions guide adds that it doesn't include a re-render in the action's response at all.

Here's what that looks like. I built a todo list whose data comes from a 'use cache' function tagged todos. The form uses useOptimistic to show the new item immediately, and the action inserts the row and then calls revalidateTag('todos', 'max'):

'use server'

import { revalidateTag } from 'next/cache'
import { pool } from '@/lib/db'

export async function addTodo(formData: FormData) {
  await pool.query('INSERT INTO todos (title) VALUES ($1)', [String(formData.get('title'))])
  revalidateTag('todos', 'max')
}

Adding "beta" to a list that already had "alpha", sampled in headless Chrome:

before submit:     alpha
+150ms:            alpha | beta (saving)
+600ms:            alpha
+3000ms:           alpha
after reload:      alpha
after 2nd reload:  alpha | beta

The optimistic item appeared, then disappeared when the action finished, because the optimistic state is dropped when the transition ends and the props still held the old list. A reload served the stale cache entry and kicked off the background refresh. Only the second reload showed the new row. That's the vanishing-item bug, reproduced exactly, and it's not a race. It's the cache doing what 'max' asks for.

Switching the action to updateTag('todos') fixed it. The same test showed "beta (saving)" at 150 ms and "beta" from then on, including after reloads. updateTag expires the tag immediately, so the re-render inside the action's response waits for fresh data.

Choosing the cache call after a mutation

Which one you call depends on who needs to see the change, and how soon:

  • updateTag(tag) for read-your-own-writes: the user who made the change sees it in the response. It only works inside Server Actions.
  • revalidateTag(tag, 'max') when other visitors can see the old value for a little longer: a CMS publish, a price feed, a webhook from your backend. It works in Route Handlers too, which is where it usually belongs.
  • revalidatePath(path) when one route is affected and tagging the data would be overkill.
  • refresh() when the page depends on something outside the cache that the action changed. It re-renders the current route without invalidating any cached data, so if the data you changed is cached, refresh() alone shows the old value.

A single action can mix them. Call updateTag for the data the current user is looking at, and revalidateTag(..., 'max') for listing pages elsewhere that can catch up in the background. If your tags come from a backend that pushes invalidations, the same tags work from a webhook; cache tags and on-demand revalidation covers that side.

On the browser side, the client cache matters less than it used to. Dynamic page segments aren't kept in it by default (the dynamic stale time is 0 seconds), and static ones are kept for five minutes. When an action re-renders the route, the client gets the new payload in the response anyway. If a page looks stale after navigating back to it, check whether its data comes from a cache entry nobody invalidated before blaming the router.

A complete example: a document editor

The rest of the article builds one page: a document with an editable body and a comment list. It uses Postgres through node-postgres's Pool, but the SQL is the important part and translates to any database. The schema has a version column on documents and a unique request_id on comments, and each of those exists to solve one concurrency problem:

CREATE TABLE documents (
  id         bigint PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
  title      text NOT NULL,
  body       text NOT NULL,
  version    integer NOT NULL DEFAULT 1,
  updated_at timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE comments (
  id          bigint PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
  document_id bigint NOT NULL REFERENCES documents (id),
  body        text NOT NULL,
  request_id  uuid NOT NULL UNIQUE,
  created_at  timestamptz NOT NULL DEFAULT now()
);
import 'server-only'
import { Pool } from 'pg'

export const pool = new Pool({ connectionString: process.env.DATABASE_URL })

Reads go through cached functions, each tagged so actions can expire exactly what they changed. pg returns bigint columns as strings, so the read functions convert them. Returning plain objects also keeps the values serializable when they're passed to Client Components:

import 'server-only'
import { cacheTag } from 'next/cache'
import { pool } from './db'

export type DocumentView = { id: number; title: string; body: string; version: number }
export type CommentView = { id: number; body: string }

export async function getDocument(id: number): Promise<DocumentView | null> {
  'use cache'
  cacheTag(`document-${id}`)
  const { rows } = await pool.query<{ id: string; title: string; body: string; version: number }>(
    'SELECT id, title, body, version FROM documents WHERE id = $1',
    [id],
  )
  const row = rows[0]
  return row ? { id: Number(row.id), title: row.title, body: row.body, version: row.version } : null
}

export async function getComments(documentId: number): Promise<CommentView[]> {
  'use cache'
  cacheTag(`document-${documentId}-comments`)
  const { rows } = await pool.query<{ id: string; body: string }>(
    'SELECT id, body FROM comments WHERE document_id = $1 ORDER BY id',
    [documentId],
  )
  return rows.map((row) => ({ id: Number(row.id), body: row.body }))
}

The page loads both in parallel inside a Suspense boundary, which Cache Components requires around request-time data such as params:

import { Suspense } from 'react'
import { notFound } from 'next/navigation'
import { getComments, getDocument } from '@/lib/documents'
import { Comments } from './comments'
import { Editor } from './editor'

async function DocumentPage({ params }: { params: Promise<{ id: string }> }) {
  const id = Number((await params).id)
  const [doc, comments] = await Promise.all([getDocument(id), getComments(id)])
  if (!doc) notFound()

  return (
    <main>
      <h1>{doc.title}</h1>
      <Editor id={doc.id} body={doc.body} version={doc.version} />
      <Comments documentId={doc.id} comments={comments} />
    </main>
  )
}

export default function Page({ params }: { params: Promise<{ id: string }> }) {
  return (
    <Suspense fallback={<p>Loading document…</p>}>
      <DocumentPage params={params} />
    </Suspense>
  )
}

Concurrent edits: check a version, don't trust the order

Here's the lost-update problem in its simplest form. Ana and Ben open the same document. Ana saves. Ben, still looking at the old text, saves a minute later, and Ana's change is gone. No amount of client-side locking helps, because they're on different machines. The fix is optimistic concurrency control: every save says which version it was based on, and the database only applies it if that's still the current version.

'use server'

import { updateTag } from 'next/cache'
import { pool } from '@/lib/db'

export type SaveState =
  | { status: 'idle' | 'saved'; version: number }
  | { status: 'conflict'; version: number; latestBody: string }
  | { status: 'error'; version: number; message: string }

export async function saveDocument(prev: SaveState, formData: FormData): Promise<SaveState> {
  const id = Number(formData.get('id'))
  const version = Number(formData.get('version'))
  const body = String(formData.get('body') ?? '')
  if (!Number.isInteger(id) || !Number.isInteger(version) || body.length > 100_000) {
    return { status: 'error', version: prev.version, message: 'Invalid input' }
  }

  const result = await pool.query<{ version: number }>(
    `UPDATE documents
        SET body = $1, version = version + 1, updated_at = now()
      WHERE id = $2 AND version = $3
      RETURNING version`,
    [body, id, version],
  )

  if (result.rowCount === 0) {
    const { rows } = await pool.query<{ body: string; version: number }>(
      'SELECT body, version FROM documents WHERE id = $1',
      [id],
    )
    if (!rows[0]) return { status: 'error', version, message: 'Document not found' }
    return { status: 'conflict', version: rows[0].version, latestBody: rows[0].body }
  }

  updateTag(`document-${id}`)
  return { status: 'saved', version: result.rows[0].version }
}

export async function addComment(documentId: number, requestId: string, body: string) {
  const text = body.trim()
  if (!text || text.length > 2_000) throw new Error('Comment must be 1 to 2000 characters')

  await pool.query(
    `INSERT INTO comments (document_id, body, request_id)
     VALUES ($1, $2, $3)
     ON CONFLICT (request_id) DO NOTHING`,
    [documentId, text, requestId],
  )

  updateTag(`document-${documentId}-comments`)
}

The WHERE id = $2 AND version = $3 clause is the whole mechanism. Postgres evaluates it atomically with the update, so if two saves based on version 4 arrive together, exactly one matches and bumps the row to 5; the other updates zero rows. There's no read-then-write gap for a race to slip into, which is why you shouldn't implement this as "SELECT the version, compare in JavaScript, then UPDATE". A zero rowCount tells the action that someone else got there first, and it returns the current text instead of overwriting it.

One thing these actions leave out to keep the concurrency logic readable is authorization. Every Server Action is a public POST endpoint, so production code must check the session and that this user may edit this document before touching the row. The trade-offs between actions and Route Handlers as entry points are in where Route Handlers and Server Actions differ.

The editor holds the version in useActionState, so each successful save moves it forward and a conflict replaces it with the latest version:

'use client'

import { useActionState } from 'react'
import { saveDocument, type SaveState } from './actions'

export function Editor({ id, body, version }: { id: number; body: string; version: number }) {
  const [state, formAction, pending] = useActionState<SaveState, FormData>(saveDocument, {
    status: 'idle',
    version,
  })

  return (
    <form action={formAction}>
      <input type="hidden" name="id" value={id} />
      <input type="hidden" name="version" value={state.version} />
      <textarea name="body" defaultValue={body} rows={12} />
      <button type="submit" disabled={pending}>
        {pending ? 'Saving…' : 'Save'}
      </button>
      {state.status === 'saved' && <p role="status">Saved.</p>}
      {state.status === 'error' && <p role="alert">{state.message}</p>}
      {state.status === 'conflict' && (
        <div role="alert">
          <p>Someone saved this document while you were editing. Their version is below. Saving again will replace it.</p>
          <pre>{state.latestBody}</pre>
        </div>
      )}
    </form>
  )
}

I ran this flow with two browser tabs on the same document, using SQLite in place of Postgres with the same UPDATE ... WHERE version = ? statement. Tab A saved and got version 2. Tab B, still holding version 1, got a conflict reporting version 2. Tab A saved again and moved to version 3. Nothing was overwritten without the user being told.

What to do on a conflict is a product decision. This editor shows the other version and lets the user save over it deliberately, because the hidden field now carries the latest version. For structured records you might merge field by field instead. What matters is that a stale write can't succeed silently. The same idea handles out-of-order delivery, where a slow request lands after a newer one: the older write carries an older version, so it fails instead of winning.

Duplicate submissions: make the insert idempotent

Sequential dispatch means a double-click sends two inserts one after the other. Disabling the button while the transition is pending stops the common case, and the comment form does that. It doesn't help when the request succeeded on the server but the response was lost, and the user clicks again. For that you need the server to recognise a repeat.

The comment form generates a request ID the first time a comment is submitted and keeps it until the action succeeds. A retry of the same comment sends the same ID, and ON CONFLICT (request_id) DO NOTHING in the action makes the second insert a no-op. The INSERT reference covers the clause; the unique constraint on the column is what makes it work.

'use client'

import { useOptimistic, useRef, useTransition } from 'react'
import { addComment } from './actions'
import type { CommentView } from '@/lib/documents'

export function Comments({ documentId, comments }: { documentId: number; comments: CommentView[] }) {
  const [optimistic, addOptimistic] = useOptimistic(comments, (current, body: string) => [
    ...current,
    { id: -1, body: `${body} (sending…)` },
  ])
  const [pending, startTransition] = useTransition()
  const requestId = useRef<string | null>(null)

  function submit(formData: FormData) {
    const body = String(formData.get('body') ?? '')
    requestId.current ??= crypto.randomUUID()
    const key = requestId.current

    startTransition(async () => {
      addOptimistic(body)
      await addComment(documentId, key, body)
      requestId.current = null
    })
  }

  return (
    <section>
      <ul>
        {optimistic.map((comment) => (
          <li key={comment.id}>{comment.body}</li>
        ))}
      </ul>
      <form action={submit}>
        <textarea name="body" required />
        <button type="submit" disabled={pending}>
          Comment
        </button>
      </form>
    </section>
  )
}

The ID is created in the submit handler, not during render. crypto.randomUUID() in a render or a useState initializer would run once on the server and once in the browser and produce two different values, a hydration mismatch waiting to happen. If addComment throws, the error goes to the nearest error boundary and the ref keeps its value, so the retry is deduplicated too.

Optimistic UI that doesn't flicker

useOptimistic shows a temporary state while an action's transition is running. When the transition ends, React drops the optimistic state and renders whatever the real props are at that moment. That's the whole contract, and it explains the vanishing item earlier. If the response that ends the transition carries fresh data, the swap from optimistic to real is invisible. If it carries stale data, the item disappears.

So a flicker-free optimistic update needs three things: the optimistic update and the action call inside the same transition, an action that calls updateTag (or revalidatePath) for the data the component displays, and props that come from that data. The comment list does all three. The React useOptimistic reference has more on reducers and multiple pending updates. For forms that need pending and error state too, form state with Server Actions shows how useActionState and useFormStatus fit together.

Don't use useOptimistic for the document editor's body. Optimistic UI suits changes that almost always succeed and are cheap to undo visually, like a comment, a like or a reordered card. A save that can conflict should show the real result, which is why the editor uses useActionState and a pending state instead.

Things that look like concurrency bugs but aren't

A few more symptoms that turn out to have ordinary causes:

  • The UI doesn't update at all after an action. The action called none of updateTag, revalidatePath or refresh, so no re-render came back in the response. Only the return value did.
  • Code after redirect() never runs. redirect throws to stop the action. Call updateTag before it, or the destination page renders from the stale cache.
  • "Failed to find Server Action" after a deploy. A tab running the old build called an action ID that the new build doesn't have. Rolling deploys and a stable NEXT_SERVER_ACTIONS_ENCRYPTION_KEY across instances reduce it. Show a "please refresh" message rather than a crash.
  • An action that's slow under load. Because a client's actions queue, one slow action delays every later one from that tab. If an action does slow work the user doesn't need to wait for, move it out of the request; debugging Server Action timeouts covers that.

WRITTEN BY

Full Stack Software Engineer | Laravel · Next.js · AWS

Full Stack Software Engineer with 7+ years of experience building scalable, secure web applications with Laravel, PHP, React, Next.js, and AWS for SaaS, CRM, telecom, and e-commerce companies. Specialized in cloud telephony (FreeSWITCH, SMPP, WebRTC): increased concurrent call capacity by 40% and cut report queries to under 500 ms. Author of open-source Laravel packages with 10K+ downloads on Packagist. Led a team of 4 engineers and shipped production systems for clients in the UAE, USA, India, Saudi Arabia, and Bangladesh.

How we research, write and check articles

    Latest Posts

    View All

    Next.js Middleware Authentication and Token Refresh Flows

    Next.js Middleware Authentication and Token Refresh Flows

    Livewire Performance Optimization Under High Load

    Livewire Performance Optimization Under High Load

    Configuring Nginx Upstream Keepalive for Node Backends

    Configuring Nginx Upstream Keepalive for Node Backends

    Enforcing Immutable State Patterns in React

    Enforcing Immutable State Patterns in React

    FastAPI Dependency Overrides for Integration Testing

    FastAPI Dependency Overrides for Integration Testing

    Stopping Layout Shifts in Next.js Dynamic Imports

    Stopping Layout Shifts in Next.js Dynamic Imports

    Optimizing Agentic Tool Calling Latency

    Optimizing Agentic Tool Calling Latency

    Fixing React Server Component Serialization Errors

    Fixing React Server Component Serialization Errors

    Next.js Route Handler Streaming with ReadableStream

    Next.js Route Handler Streaming with ReadableStream

    React Form Performance: Uncontrolled Inputs and FormData

    React Form Performance: Uncontrolled Inputs and FormData