عربي
News
●E-invoicing: the last date to connect for wave 25 is February 1, 2027●WhatsApp Business: service messages are paid after 1,000 free per month●Salla acquires Paylink to strengthen payment solutions for merchants●Google launches a Gemini agent for businesses first, then consumers●Hostinger's White Friday deals continue until December 14

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

  1. Put 104 in a designated counter cell in a test sheet. Use that same address for every run rather than choosing an empty cell.
  2. Obtain LockService.getScriptLock() and call waitLock(5000) before reading. If it times out, record the failure without allocating a number.
  3. Inside a try block read the old value, validate that it is an integer, calculate the next value and store it. Call SpreadsheetApp.flush() to apply pending spreadsheet changes before releasing the lock.
  4. After successful acquisition, use finally to call releaseLock(). Keep email and slow network calls outside the guarded section.
  5. Start two test runs close together. Expect 105 and 106 in acquisition order, or an explicit timeout instead of a repeated number.
  6. 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

  1. developers.google.com
  2. developers.google.com

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