When several webhooks hit a Google Apps Script web app at the same moment, they can read the same “last row” and overwrite each other, so leads or orders disappear without an error. This tutorial shows how to prevent race conditions in Google Apps Script with LockService, and how to prove the fix with a burst of concurrent test requests.
Quick answer: Wrap the read-and-write part of doPost in a script lock: call LockService.getScriptLock().waitLock(10000), write the row, call SpreadsheetApp.flush(), and release the lock in a finally block.
- Get a script lock with
LockService.getScriptLock(). - Call
waitLock()with a timeout and return an error response if it times out. - Read the last row and write the new row inside the lock.
- Call
SpreadsheetApp.flush(), thenreleaseLock()infinally. - Deploy a new version and send 20 parallel requests to confirm you get 20 rows.
In this guide
- Before You Start
- Why Concurrent Webhooks Overwrite Each Other
- How LockService Prevents Race Conditions
- Step 1: Deploy the Vulnerable Version
- Step 2: Reproduce the Failure With Concurrent Requests
- Step 3: Add LockService and Flush Before Releasing
- Why SpreadsheetApp.flush() Matters
- Handling Lock Timeouts
- Script Lock vs. Document Lock for Webhooks
- If It Still Doesn’t Work
- Frequently Asked Questions
- Next Steps

Before You Start
- A test spreadsheet: use a copy, not your live sheet. The test below writes 20 rows, and the broken version deliberately loses some.
- Apps Script editor: open it from the sheet with Extensions > Apps Script.
- A terminal with curl for the load test: Terminal on macOS, any Linux shell, or WSL / Git Bash on Windows.
- Time: about 20 minutes.
Why Concurrent Webhooks Overwrite Each Other
Each request to a deployed web app runs as its own separate execution of your doPost(e) function. Under light traffic they rarely overlap. Once you receive leads, orders or alerts in bursts (from a CRM such as GoHighLevel, a payment provider or a form tool), several executions run at once.
If you use Google Sheets as a database with Apps Script, your code probably reads the sheet, works out the next empty row and writes to it. Two executions that run together read the same last row, pick the same next row, and the second write replaces the first. No error is thrown. This is a race condition: the result depends on which execution happens to finish first.
How LockService Prevents Race Conditions
Google’s LockService class is a mutex (mutual exclusion lock). Only one execution can hold the lock at a time; the others wait until it is released or until their timeout runs out.
LockService offers three scopes:
- Script Lock: Prevents concurrent execution of the script across all users. This is the most common lock for public webhooks.
- Document Lock: Prevents concurrent execution within a single container-bound spreadsheet or document. It returns
nullin a standalone script or web app. - User Lock: Prevents concurrent execution by the same user, useful for user-facing add-ons or web apps.
The pattern is always the same: get the lock object, wait for it with a timeout, do the spreadsheet work, then release it. First, here is the code that fails.
Step 1: Deploy the Vulnerable Version
This is a typical webhook receiver that logs incoming JSON to a sheet. It looks correct, and it works fine until two requests overlap. Paste it into Code.gs in your test spreadsheet’s Apps Script project:
function doPost(e) {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var lastRow = sheet.getLastRow();
var nextRow = lastRow + 1;
var payload;
try {
payload = JSON.parse(e.postData.contents);
} catch (err) {
payload = { id: "unknown", status: "malformed_json" };
}
// Simulate heavy processing latency
Utilities.sleep(500);
sheet.getRange(nextRow, 1, 1, 3).setValues([[
new Date(),
payload.id || "N/A",
payload.status || "pending"
]]);
return ContentService.createTextOutput(JSON.stringify({ status: "success", row_written: nextRow }))
.setMimeType(ContentService.MimeType.JSON);
}The 500-millisecond Utilities.sleep() stands in for real work such as an external API call. It widens the window in which two executions overlap, so the race condition is easy to reproduce.
Deploy it as a web app:
- Click Deploy > New deployment, then the gear icon next to Select type, and choose Web app.
- Set Execute as to yourself and Who has access to Anyone, so external senders can call it without a Google login.
- Click Deploy, authorize the script when asked, and copy the web app URL (it ends in
/exec).
Step 2: Reproduce the Failure With Concurrent Requests
Send the endpoint a burst of parallel POST requests, each with a unique transaction ID. Any HTTP client that can send requests in parallel and follow redirects will do. Apps Script answers through a redirect to script.googleusercontent.com, so a tool that does not follow redirects reports every request as a 302 instead of the real response.
Run this in your local terminal after replacing the URL with your own web app URL. It sends 20 requests, 10 at a time:
seq 1 20 | xargs -P 10 -I{} curl -s -L -o /dev/null \
-H "Content-Type: application/json" \
-d '{"id":"tx-{}","status":"paid"}' \
"https://script.google.com/macros/s/YOUR_DEPLOYMENT_ID/exec"The command prints nothing because -o /dev/null discards the responses. Now count the rows in the sheet. Every request reported "status": "success", yet you will typically find fewer than 20 rows. Requests that ran together read the same lastRow and wrote to the same row, and the later write silently replaced the earlier one. Nothing in the responses tells the sender that data was lost.
Step 3: Add LockService and Flush Before Releasing
The fix wraps the read-and-write logic in a lock. The script requests a script lock, waits up to 10 seconds for it, writes the row, and calls SpreadsheetApp.flush() so the write is committed before the lock is released.
Replace the whole doPost function with this thread-safe version:
function doPost(e) {
var lock = LockService.getScriptLock();
try {
// Attempt to acquire lock, waiting up to 10000 milliseconds (10 seconds)
lock.waitLock(10000);
} catch (lockError) {
// Return a custom error payload if the lock times out
return ContentService.createTextOutput(JSON.stringify({
status: "error",
message: "Lock timeout: System busy, please retry request later."
})).setMimeType(ContentService.MimeType.JSON);
}
try {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var lastRow = sheet.getLastRow();
var nextRow = lastRow + 1;
var payload;
try {
payload = JSON.parse(e.postData.contents);
} catch (err) {
payload = { id: "unknown", status: "malformed_json" };
}
// Perform spreadsheet write
sheet.getRange(nextRow, 1, 1, 3).setValues([[
new Date(),
payload.id || "N/A",
payload.status || "pending"
]]);
// CRITICAL: Flush all pending spreadsheet updates before releasing the lock
SpreadsheetApp.flush();
return ContentService.createTextOutput(JSON.stringify({ status: "success", row_written: nextRow }))
.setMimeType(ContentService.MimeType.JSON);
} catch (error) {
return ContentService.createTextOutput(JSON.stringify({ status: "error", message: error.toString() }))
.setMimeType(ContentService.MimeType.JSON);
} finally {
// Always release the lock, even if an error occurred during execution
lock.releaseLock();
}
}Deploy it as a new version so the URL stays the same: open Deploy > Manage deployments, click the pencil icon, choose New version and click Deploy. Clear the test rows and run the same curl command again.
If it worked, the sheet now has exactly 20 new rows, one for each ID from tx-1 to tx-20 (not necessarily in that order). The requests ran one at a time, so each got its own row.
The endpoint still accepts writes from anyone who has the URL. For real data, have the sender include a shared secret and compare it with a value stored in Script Properties before writing.
Why SpreadsheetApp.flush() Matters
The easiest mistake with LockService is forgetting to call SpreadsheetApp.flush().
Apps Script batches spreadsheet writes such as setValues() and may apply them later in the execution. If you release the lock before those writes are flushed, the next waiting execution takes the lock and can read the old state of the sheet, then write to the same row. Google’s own reference for releaseLock() recommends flushing first, so always call SpreadsheetApp.flush() right before you release the lock.
Handling Lock Timeouts
waitLock() throws an exception if it cannot get the lock within the timeout you pass (10 seconds in the code above). Under a heavy webhook stream, requests queue behind the lock, and any request that waits longer than the timeout gets the “System busy” error response instead of a row.
A longer timeout lets more requests through, but many webhook senders give up on slow responses. Keep the locked section as short as you can: parse the payload and call external APIs before you take the lock, and lock only the read-last-row-and-write part.
The sender should also read the response body and retry when it sees the lock-timeout error, ideally with exponential backoff (waiting longer after each failed attempt). If you control the sender, the webhook retry system with exponential backoff shows one way to build that side.
Script Lock vs. Document Lock for Webhooks
getScriptLock() is the right choice for a webhook: it applies to the whole script project, whoever the caller is. The cost is that it is a single lock, so if one project handles webhooks for several unrelated spreadsheets, they all queue behind each other.
getDocumentLock() is not a way around that in a webhook. According to Google’s reference it returns null when called from a standalone script or a web app, so it only helps code that runs inside a document, such as menu items or edit triggers in a container-bound script. If unrelated webhooks slow each other down, split them into separate script projects, each with its own script lock.
This is a different problem from the single-threaded model in the MDN Event Loop documentation. Each Apps Script request runs as its own separate execution, which is why you need a lock that works across executions.
If It Still Doesn’t Work
- curl gets an HTML Google sign-in page instead of JSON: the deployment’s Who has access is not set to Anyone. Edit the deployment and change it.
- You still lose rows after the fix: the URL is still serving the old code. Saving the script does not update a deployment; publish a new version under Manage deployments.
- Rows land on the wrong tab: in a web app,
getActiveSheet()returns the first tab. Move your log tab to the first position, or change the code togetSheetByName("Your tab name"). - A row says
unknown/malformed_json: the request body was not valid JSON. This also happens if you click Run ondoPostin the editor, because there is no request to read; test through the web app URL instead. - Some requests return the “System busy” error: they waited longer than 10 seconds for the lock. Shorten the locked section or have the sender retry.
Frequently Asked Questions
Does LockService guarantee the exact order of execution?
No. Google does not document any ordering guarantee for LockService, so do not rely on requests getting the lock in the order they arrived. If order matters, store the sender’s own timestamp or sequence number in the row and sort by that column.
Can I lock a specific cell or range instead of the entire sheet?
No. Apps Script does not support cell-level or range-level locking; LockService locks a section of code for the whole script, document or user. For finer control you would need your own scheme, such as a dedicated “locks” sheet or an external database.
What happens if my script crashes before reaching the releaseLock() line?
The lock is still released. Code in a try...finally block’s finally section runs even when the write throws an error. If the execution stops completely, for example at the runtime limit, Apps Script releases the lock automatically when the script terminates.
Can I use LockService to prevent double-submits in web forms?
Not on its own. A lock only makes the two submissions run one after the other; both still write a row. To drop the duplicate, check inside the locked section whether a row with the same submission ID already exists before writing it.
Next Steps
Add the lock to every Apps Script endpoint that appends or updates rows, keep the locked section short, and check the sheet with the 20-request test after each change. For the receiving-side patterns that pair with this one (authentication, idempotency and retries), read the API integrations and webhooks guide. For quotas, triggers and other building blocks, see the Google Apps Script automation guide.
Disclosure: This post may contain affiliate links. If you purchase through our link, we may earn a commission at no extra cost to you.

