perf(db): replace busy-wait spin loop with Atomics.wait in migration lock#596
Open
HUQIANTAO wants to merge 1 commit into
Open
perf(db): replace busy-wait spin loop with Atomics.wait in migration lock#596HUQIANTAO wants to merge 1 commit into
HUQIANTAO wants to merge 1 commit into
Conversation
…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.
|
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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
The
withMigrationLockfunction insrc/lib/db.tsuses a synchronous busy-wait spin loop to implement retry backoff: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 amaxWaitof 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 aSharedArrayBuffer. 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.Atomics.waitis available in all Node.js versions ≥ 8.10 and is the standard way to implement blocking waits in synchronous contexts whereawaitis not available.