Prevent duplicate order numbers with an Apps Script lock
Protect the counter read and write, then rehearse overlapping executions.
The problem
Two submissions land nearly together. Both executions read order counter 104 and try to allocate 105. Timing makes the error intermittent. Put the shared update behind a single lock.
The tool
LockService prevents concurrent execution of a guarded section within the lock's scope. Use a script lock for one project and write the update before releasing it.
The steps
- Put 104 in a designated counter cell in a test sheet. Use that same address for every run rather than choosing an empty cell.
- Obtain
LockService.getScriptLock()and callwaitLock(5000)before reading. If it times out, record the failure without allocating a number. - Inside a
tryblock read the old value, validate that it is an integer, calculate the next value and store it. CallSpreadsheetApp.flush()to apply pending spreadsheet changes before releasing the lock. - After successful acquisition, use
finallyto callreleaseLock(). Keep email and slow network calls outside the guarded section. - Start two test runs close together. Expect 105 and 106 in acquisition order, or an explicit timeout instead of a repeated number.
- Check that every allocator in this project uses the same lock. Test delayed email and numbering separately because they exercise different effects.
The real cost
LockService is included in Apps Script. Waiting consumes execution time. Look for timeouts before moving the change onto a working sheet.
The free alternative
If you only need unique identifiers, consider one that does not rely on a shared counter. Keep sequential allocation in one place when a human-readable sequence matters.
Notes
- We have not tried these steps ourselves yet. They are based on the official docs. Button names may change. If your interface differs, follow the docs.
- The script lock is scoped to that script. It does not coordinate with direct edits or another project.
- A downstream failure can leave a gap in numbering. Track duplicate submissions using a separate identifier.
Sources
Did you like this guide?
The weekly newsletter is being prepared. Leave your email and we'll send it when it launches.
We use your email only to send the newsletter. Privacy policy
