Two reviewers can edit the same record from the same starting version. Last-write-wins silently discards one person’s work. An expected version lets the service reject the stale write instead.
Read, predict, run
The function compares expectedVersion before returning a new row with an incremented version. In a database, perform that check and update atomically, for example with a conditional UPDATE and an affected-row check:
Before pressing Run, predict what run returns for {"row": {"id": 1, "title": "Old", "version": 2}, "expectedVersion": 1, "title": "New"}, from the
code above. Write your answers down first: after Run, the case table shows the
expected values beside the actual ones.
A Version Detects a Lost UpdateNext.js · 8 filesimport "./globals.css";
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<header>
<strong>Review Queue · Practice lab</strong>
</header>
{children}
</body>
</html>
);
}
import Cases from "./Cases.jsx";
import EditTab from "./EditTab.jsx";
import { readRow } from "@/lib/store.js";
export const dynamic = "force-dynamic";
export default function Page() {
const row = readRow();
return (
<main>
<h1>A Version Detects a Lost Update</h1>
<p>
Two tabs opened the same review at version {row.version}. Each save
goes through the saveTitle Server Action in app/actions.js, which calls
run from lib/contract.js.
</p>
<EditTab name="Grace" row={row} />
<EditTab name="Ada" row={row} />
<Cases />
</main>
);
}
"use server";
import { run } from "@/lib/contract.js";
import { readRow, writeRow } from "@/lib/store.js";
export async function saveTitle(previous, formData) {
const title = String(formData.get("title") ?? "");
const expectedVersion = Number(formData.get("version"));
const current = readRow();
if (formData.get("lastWriteWins") === "on") {
// The unsafe version, for comparison: no check at all.
writeRow({ ...current, title, version: current.version + 1 });
} else {
const result = run({ row: current, expectedVersion, title });
if (!result.ok) {
return { ...previous, message: `Refused: ${result.code}`, stored: current };
}
writeRow(result.row);
}
const stored = readRow();
return { version: stored.version, message: `Saved as version ${stored.version}`, stored };
}
import { run, examples } from "@/lib/contract.js";
const text = (value) => JSON.stringify(value) ?? "undefined";
export default async function Cases() {
const results = await Promise.all(
examples.map(async ([input, expected]) => {
// Record the input before running, to show whether run changed it.
const before = text(input);
const actual = await run(input);
return {
input: before,
expected,
actual,
kept: text(input) === before,
pass: text(actual) === text(expected),
};
}),
);
return (
<section>
<h2>Executable cases</h2>
<p>
Checks: {results.filter((row) => row.pass).length}/{results.length}{" "}
passed
</p>
<table>
<thead>
<tr>
<th>Input</th>
<th>Expected</th>
<th>Actual</th>
<th>Input kept</th>
</tr>
</thead>
<tbody>
{results.map((row, i) => (
<tr key={i}>
<td>
<code>{row.input}</code>
</td>
<td>
<code>{text(row.expected)}</code>
</td>
<td className={row.pass ? "pass" : "fail"}>
<code>{text(row.actual)}</code>
</td>
<td className={row.kept ? "pass" : "fail"}>
{row.kept ? "yes" : "no: run changed it"}
</td>
</tr>
))}
</tbody>
</table>
</section>
);
}
"use client";
import { useActionState } from "react";
import { saveTitle } from "./actions.js";
// One browser tab's edit form. It remembers the version it loaded, as a
// real form's hidden input would, until its own save succeeds.
export default function EditTab({ name, row }) {
const [state, formAction, pending] = useActionState(saveTitle, {
version: row.version,
message: "",
stored: row,
});
return (
<form action={formAction} aria-label={`${name}'s tab`}>
<h2>{name}'s tab</h2>
<input type="hidden" name="version" value={state.version} />
<label>
Title <input name="title" defaultValue={`${name}'s title`} />
</label>{" "}
<label>
<input type="checkbox" name="lastWriteWins" /> Skip the version check
</label>{" "}
<button disabled={pending}>Save from {name}'s tab</button>
<p role="status">{state.message}</p>
<p>
Stored after this save: {state.stored.title} · version {state.stored.version}
</p>
</form>
);
}
body {
font: 16px/1.5 system-ui;
margin: 0;
color: #182b3c;
background: #f4f8fc;
}
header,
main {
max-width: 900px;
margin: auto;
padding: 20px;
}
header {
border-bottom: 1px solid #cbd5e1;
}
a {
color: #075985;
}
button,
input,
textarea,
select {
font: inherit;
padding: 8px;
margin: 4px;
}
button {
cursor: pointer;
}
table {
border-collapse: collapse;
width: 100%;
}
th,
td {
padding: 10px;
border: 1px solid #cbd5e1;
text-align: left;
vertical-align: top;
}
pre,
code {
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.pass {
color: #166534;
}
.fail,
[role="alert"] {
color: #a01818;
}
section {
margin: 16px 0;
padding: 12px;
background: white;
border-radius: 8px;
}
nav {
display: flex;
gap: 16px;
}
export function run({ row, expectedVersion, title }) {
if (row.version !== expectedVersion) return { ok: false, code: "conflict" };
return { ok: true, row: { ...row, title, version: row.version + 1 } };
}
export const examples = [
[
{
row: { id: 1, title: "Old", version: 2 },
expectedVersion: 1,
title: "New",
},
{ ok: false, code: "conflict" },
],
];
// One stored review, shared by every request while the preview runs.
let row = { id: 1, title: "Old", version: 2 };
export function readRow() {
return row;
}
export function writeRow(next) {
row = next;
}
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
The case table computes these results on the server side of the simulation.
It compares values; it does not prove a production deployment or database works.
The failure to avoid
Reading a version, awaiting another operation and then writing without a condition still races. Disabling Save in one browser cannot coordinate two browsers.
Trace a lost update. Ada and Grace both open version 2, titled Old. Grace
saves Grace's title; then Ada saves Ada's title. With last-write-wins,
Ada's save replaces Grace's and nobody is told. With the version check, Grace's
save makes version 3, and Ada's save, still claiming version 2, returns
conflict.
In a database, the check and the write must be one statement, or another save
can land between them:
SQL
UPDATE reviews SET title = ?, version = version + 1WHERE id = ? AND version = ?
If it changed no rows, the version didn't match or the row is gone: answer
conflict (or not_found). Reading the version with a SELECT, comparing in
JavaScript and then running an unconditional UPDATE still races.
See it in two tabs
The lab's page renders two edit forms, Grace's tab and Ada's tab, both
loaded at version 2. Each submits to a real Server Action, saveTitle in
app/actions.js, which reads the stored row and calls run:
JavaScript
const result = run({ row: current, expectedVersion, title });if (!result.ok) { return { ...previous, message: `Refused: ${result.code}`, stored: current };}writeRow(result.row);
Press Save from Grace's tab, then Save from Ada's tab, and predict each
message. Then press Run to start again, tick Skip the version check in
both tabs, and save in the same order.
Two tabs, one reviewNext.js · 8 filesimport "./globals.css";
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<header>
<strong>Review Queue · Practice lab</strong>
</header>
{children}
</body>
</html>
);
}
import Cases from "./Cases.jsx";
import EditTab from "./EditTab.jsx";
import { readRow } from "@/lib/store.js";
export const dynamic = "force-dynamic";
export default function Page() {
const row = readRow();
return (
<main>
<h1>A Version Detects a Lost Update</h1>
<p>
Two tabs opened the same review at version {row.version}. Each save
goes through the saveTitle Server Action in app/actions.js, which calls
run from lib/contract.js.
</p>
<EditTab name="Grace" row={row} />
<EditTab name="Ada" row={row} />
<Cases />
</main>
);
}
"use server";
import { run } from "@/lib/contract.js";
import { readRow, writeRow } from "@/lib/store.js";
export async function saveTitle(previous, formData) {
const title = String(formData.get("title") ?? "");
const expectedVersion = Number(formData.get("version"));
const current = readRow();
if (formData.get("lastWriteWins") === "on") {
// The unsafe version, for comparison: no check at all.
writeRow({ ...current, title, version: current.version + 1 });
} else {
const result = run({ row: current, expectedVersion, title });
if (!result.ok) {
return { ...previous, message: `Refused: ${result.code}`, stored: current };
}
writeRow(result.row);
}
const stored = readRow();
return { version: stored.version, message: `Saved as version ${stored.version}`, stored };
}
import { run, examples } from "@/lib/contract.js";
const text = (value) => JSON.stringify(value) ?? "undefined";
export default async function Cases() {
const results = await Promise.all(
examples.map(async ([input, expected]) => {
// Record the input before running, to show whether run changed it.
const before = text(input);
const actual = await run(input);
return {
input: before,
expected,
actual,
kept: text(input) === before,
pass: text(actual) === text(expected),
};
}),
);
return (
<section>
<h2>Executable cases</h2>
<p>
Checks: {results.filter((row) => row.pass).length}/{results.length}{" "}
passed
</p>
<table>
<thead>
<tr>
<th>Input</th>
<th>Expected</th>
<th>Actual</th>
<th>Input kept</th>
</tr>
</thead>
<tbody>
{results.map((row, i) => (
<tr key={i}>
<td>
<code>{row.input}</code>
</td>
<td>
<code>{text(row.expected)}</code>
</td>
<td className={row.pass ? "pass" : "fail"}>
<code>{text(row.actual)}</code>
</td>
<td className={row.kept ? "pass" : "fail"}>
{row.kept ? "yes" : "no: run changed it"}
</td>
</tr>
))}
</tbody>
</table>
</section>
);
}
"use client";
import { useActionState } from "react";
import { saveTitle } from "./actions.js";
// One browser tab's edit form. It remembers the version it loaded, as a
// real form's hidden input would, until its own save succeeds.
export default function EditTab({ name, row }) {
const [state, formAction, pending] = useActionState(saveTitle, {
version: row.version,
message: "",
stored: row,
});
return (
<form action={formAction} aria-label={`${name}'s tab`}>
<h2>{name}'s tab</h2>
<input type="hidden" name="version" value={state.version} />
<label>
Title <input name="title" defaultValue={`${name}'s title`} />
</label>{" "}
<label>
<input type="checkbox" name="lastWriteWins" /> Skip the version check
</label>{" "}
<button disabled={pending}>Save from {name}'s tab</button>
<p role="status">{state.message}</p>
<p>
Stored after this save: {state.stored.title} · version {state.stored.version}
</p>
</form>
);
}
body {
font: 16px/1.5 system-ui;
margin: 0;
color: #182b3c;
background: #f4f8fc;
}
header,
main {
max-width: 900px;
margin: auto;
padding: 20px;
}
header {
border-bottom: 1px solid #cbd5e1;
}
a {
color: #075985;
}
button,
input,
textarea,
select {
font: inherit;
padding: 8px;
margin: 4px;
}
button {
cursor: pointer;
}
table {
border-collapse: collapse;
width: 100%;
}
th,
td {
padding: 10px;
border: 1px solid #cbd5e1;
text-align: left;
vertical-align: top;
}
pre,
code {
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.pass {
color: #166534;
}
.fail,
[role="alert"] {
color: #a01818;
}
section {
margin: 16px 0;
padding: 12px;
background: white;
border-radius: 8px;
}
nav {
display: flex;
gap: 16px;
}
export function run({ row, expectedVersion, title }) {
if (row.version !== expectedVersion) return { ok: false, code: "conflict" };
return { ok: true, row: { ...row, title, version: row.version + 1 } };
}
export const examples = [
[
{
row: { id: 1, title: "Old", version: 2 },
expectedVersion: 1,
title: "New",
},
{ ok: false, code: "conflict" },
],
];
// One stored review, shared by every request while the preview runs.
let row = { id: 1, title: "Old", version: 2 };
export function readRow() {
return row;
}
export function writeRow(next) {
row = next;
}
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Check your prediction
With the check, Grace's tab says Saved as version 3 and Ada's says
Refused: conflict, and the stored title stays Grace's title. Ada's tab
must reload before it can save, and she sees Grace's change first.
Without it, both say Saved: Ada's tab reports version 4 with
Ada's title, and Grace's edit is gone without anyone being told. That's a
lost update.
Exercise
Extend the contract
Treat an identical title as a no-op: return the row unchanged and do not increment its version. Still reject a stale expectedVersion.
Edit lib/contract.js, then rerun the original cases. If the requested rule
changes an earlier result, update that expected value deliberately. Keep the
other cases. Add the acceptance cases to examples so the preview checks them too.
Your working spaceNext.js · 8 filesimport "./globals.css";
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<header>
<strong>Review Queue · Practice lab</strong>
</header>
{children}
</body>
</html>
);
}
import Cases from "./Cases.jsx";
import EditTab from "./EditTab.jsx";
import { readRow } from "@/lib/store.js";
export const dynamic = "force-dynamic";
export default function Page() {
const row = readRow();
return (
<main>
<h1>A Version Detects a Lost Update</h1>
<p>
Two tabs opened the same review at version {row.version}. Each save
goes through the saveTitle Server Action in app/actions.js, which calls
run from lib/contract.js.
</p>
<EditTab name="Grace" row={row} />
<EditTab name="Ada" row={row} />
<Cases />
</main>
);
}
"use server";
import { run } from "@/lib/contract.js";
import { readRow, writeRow } from "@/lib/store.js";
export async function saveTitle(previous, formData) {
const title = String(formData.get("title") ?? "");
const expectedVersion = Number(formData.get("version"));
const current = readRow();
if (formData.get("lastWriteWins") === "on") {
// The unsafe version, for comparison: no check at all.
writeRow({ ...current, title, version: current.version + 1 });
} else {
const result = run({ row: current, expectedVersion, title });
if (!result.ok) {
return { ...previous, message: `Refused: ${result.code}`, stored: current };
}
writeRow(result.row);
}
const stored = readRow();
return { version: stored.version, message: `Saved as version ${stored.version}`, stored };
}
import { run, examples } from "@/lib/contract.js";
const text = (value) => JSON.stringify(value) ?? "undefined";
export default async function Cases() {
const results = await Promise.all(
examples.map(async ([input, expected]) => {
// Record the input before running, to show whether run changed it.
const before = text(input);
const actual = await run(input);
return {
input: before,
expected,
actual,
kept: text(input) === before,
pass: text(actual) === text(expected),
};
}),
);
return (
<section>
<h2>Executable cases</h2>
<p>
Checks: {results.filter((row) => row.pass).length}/{results.length}{" "}
passed
</p>
<table>
<thead>
<tr>
<th>Input</th>
<th>Expected</th>
<th>Actual</th>
<th>Input kept</th>
</tr>
</thead>
<tbody>
{results.map((row, i) => (
<tr key={i}>
<td>
<code>{row.input}</code>
</td>
<td>
<code>{text(row.expected)}</code>
</td>
<td className={row.pass ? "pass" : "fail"}>
<code>{text(row.actual)}</code>
</td>
<td className={row.kept ? "pass" : "fail"}>
{row.kept ? "yes" : "no: run changed it"}
</td>
</tr>
))}
</tbody>
</table>
</section>
);
}
"use client";
import { useActionState } from "react";
import { saveTitle } from "./actions.js";
// One browser tab's edit form. It remembers the version it loaded, as a
// real form's hidden input would, until its own save succeeds.
export default function EditTab({ name, row }) {
const [state, formAction, pending] = useActionState(saveTitle, {
version: row.version,
message: "",
stored: row,
});
return (
<form action={formAction} aria-label={`${name}'s tab`}>
<h2>{name}'s tab</h2>
<input type="hidden" name="version" value={state.version} />
<label>
Title <input name="title" defaultValue={`${name}'s title`} />
</label>{" "}
<label>
<input type="checkbox" name="lastWriteWins" /> Skip the version check
</label>{" "}
<button disabled={pending}>Save from {name}'s tab</button>
<p role="status">{state.message}</p>
<p>
Stored after this save: {state.stored.title} · version {state.stored.version}
</p>
</form>
);
}
body {
font: 16px/1.5 system-ui;
margin: 0;
color: #182b3c;
background: #f4f8fc;
}
header,
main {
max-width: 900px;
margin: auto;
padding: 20px;
}
header {
border-bottom: 1px solid #cbd5e1;
}
a {
color: #075985;
}
button,
input,
textarea,
select {
font: inherit;
padding: 8px;
margin: 4px;
}
button {
cursor: pointer;
}
table {
border-collapse: collapse;
width: 100%;
}
th,
td {
padding: 10px;
border: 1px solid #cbd5e1;
text-align: left;
vertical-align: top;
}
pre,
code {
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.pass {
color: #166534;
}
.fail,
[role="alert"] {
color: #a01818;
}
section {
margin: 16px 0;
padding: 12px;
background: white;
border-radius: 8px;
}
nav {
display: flex;
gap: 16px;
}
export function run({ row, expectedVersion, title }) {
if (row.version !== expectedVersion) return { ok: false, code: "conflict" };
return { ok: true, row: { ...row, title, version: row.version + 1 } };
}
export const examples = [
[
{
row: { id: 1, title: "Old", version: 2 },
expectedVersion: 1,
title: "New",
},
{ ok: false, code: "conflict" },
],
];
// One stored review, shared by every request while the preview runs.
let row = { id: 1, title: "Old", version: 2 };
export function readRow() {
return row;
}
export function writeRow(next) {
row = next;
}
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Hint 1: the idea
Saving the same title again changes nothing, so it shouldn't look like a change.
A new version tells every other client its copy is stale, which here would be a
false alarm.
Hint 2: a first step
The version precondition comes first, then the no-op comparison.
Show one solution
Replace the exported run function and any constants shown here; keep the
examples export underneath it. Compare the result with your own approach.
JavaScript
export function run({ row, expectedVersion, title }) { if (row.version !== expectedVersion) return { ok: false, code: "conflict" }; return { ok: true, row: row.title === title ? row : { ...row, title, version: row.version + 1 }, };}
The version check stays first, so even a no-op from a stale page is a conflict:
the client's whole view is out of date, not just this field. When the title is
identical the function returns the same row, so the version doesn't move and
no other open form becomes stale. Bumping it anyway would be safe but noisy,
causing conflicts for edits that never collided.
Explain it without the code
Two tabs submit the same unchanged title from version 4, one after the other.
Write what each receives.
Going further
Read the Next.js guide for the framework boundary around this rule.
The preview runs code-playpad's Next.js simulation. Real caching, hydration,
authentication and persistence require the real-server checks described on Day 7.
Completion is saved in this browser only. It does not measure mastery.