A one-time setup script that’s supposed to run exactly once occasionally runs twice, creating duplicate content – despite having what looks like a clear “already run” check right at the top.
A One-Time Seed Script’s “Already Run” Check Needs an Atomic Lock, Not a Read-Then-Write
Field Note #278
⚡ Quick Fix (TL;DR)
The Culprit: Checking get_option() and only calling update_option() afterward if it's not set is a classic check-then-act race condition. On a busy site, two requests can both check the flag – both find it unset – before either one has a chance to write the "done" value, so both proceed to run.
The Fix: Use add_option() as the lock instead. It's atomic – it fails silently and returns false if the option key already exists, rather than reading first – so there's no gap where two requests can both slip through.
if ( ! add_option( 'your_seed_flag', 1 ) ) {
return; // someone already claimed this - stop immediately, no race window
}
// safe to run the one-time setup hereRather not untangle this yourself? Our Done-For-You team handles exactly this kind of thing, start to finish.
See DFY options → Was this helpful? Thanks for the feedback!
Tagged in :