Skip to content

perf(db): replace busy-wait spin loop with Atomics.wait in migration lock#596

Open
HUQIANTAO wants to merge 1 commit into
op7418:mainfrom
HUQIANTAO:perf/fix-db-migration-spinlock
Open

perf(db): replace busy-wait spin loop with Atomics.wait in migration lock#596
HUQIANTAO wants to merge 1 commit into
op7418:mainfrom
HUQIANTAO:perf/fix-db-migration-spinlock

Conversation

@HUQIANTAO
Copy link
Copy Markdown

Problem

The withMigrationLock function in src/lib/db.ts uses a synchronous busy-wait spin loop to implement retry backoff:

const waitMs = 50 + Math.random() * 100;
const waitUntil = Date.now() + waitMs;
while (Date.now() < waitUntil) { /* busy wait — better-sqlite3 is sync */ }

This burns CPU cycles in a tight loop with zero yield. When multiple Next.js build workers contend for the migration lock at startup, each worker spins for 50–150ms, repeatedly polling Date.now(). With a maxWait of 10 seconds and retry-after-spin logic, a contended startup can spike CPU usage and delay server readiness.

Fix

Replace the spin loop with Atomics.wait() on a SharedArrayBuffer. This is a cooperative blocking wait — the OS deschedules the thread instead of busy-polling. Functionally identical timing semantics, zero CPU cost during the wait.

const waitMs = 50 + Math.random() * 100;
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, waitMs);

Atomics.wait is available in all Node.js versions ≥ 8.10 and is the standard way to implement blocking waits in synchronous contexts where await is not available.

…lock

The withMigrationLock function used a while(Date.now() < waitUntil) {}
spin loop that burns CPU cycles while waiting for the file lock. On
contended startups (multiple Next.js build workers), each worker spins
for 50-150ms in a tight loop with zero yield, causing CPU spikes.

Replace with Atomics.wait() on a SharedArrayBuffer, which blocks the
thread cooperatively — the OS deschedules it instead of busy-polling.
Functionally identical timing semantics, zero CPU cost during wait.
@vercel
Copy link
Copy Markdown

vercel Bot commented Jun 4, 2026

Someone is attempting to deploy a commit to the op7418's projects Team on Vercel.

A member of the Team first needs to authorize it.

@HUQIANTAO HUQIANTAO changed the base branch from worktree-product-refactor-research to main June 5, 2026 05:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant