How to Prevent Duplicate Orders in Google Sheets
Reuse one order ID across retries and put the Sheets lookup and append under one Apps Script lock. Test concurrent requests and lost responses.
Table of Contents9 sections

The order screen times out after someone taps Save. They tap Retry. The sheet now contains two rows for the same purchase, even though each row has a different ID. The ID generator did its job: it produced two identifiers. The app failed to recognize the retry as another attempt to save the same order.
Quick solution: Persist one order ID and one immutable create payload before the first send. Reuse both on retries. In a single Apps Script project, take a script lock, look up that ID, and append only if it is absent. Flush the pending write before releasing the lock. If the ID already exists with the same payload, return the existing order.
First request order 8ca1… quantity 2 → append; response lost
Retry same ID order 8ca1… quantity 2 → return existing order
Retry changed order 8ca1… quantity 3 → conflict; do not append
New purchase order e902… quantity 2 → append a separate order
Identify the purchase before you identify the row
An order ID represents something somebody intended to buy. A row number represents where the sheet happens to show it. Keep them separate. Generate a random UUID once when the app turns a draft into a pending order, not inside a function that makes a network attempt. Persist the ID and the validated create fields together. If the app restarts before receiving an answer, the next worker should be able to pick up that same pending record and submit it without asking the user to create it again.
This approach can use the order ID as the create operation’s idempotency key: sending the same operation repeatedly should not create additional orders. That works when a create is tied to a single immutable order record. It does not mean the SKU or the payload by itself is a valid key. Someone might deliberately buy two identical items in two separate transactions. Conversely, two submissions from separate devices that each create a fresh ID are two distinct operations to this design. Connecting those devices to one shared cart or applying a business-specific duplicate review rule solves a different problem.
Our Google Sheets as an Android backend architecture guide covers stable row identity, repository boundaries, and authentication. Here the problem is narrower: what happens between checking an ID and creating it, and how the application acts if it cannot tell whether the operation finished. A stable ID is necessary for both. It is not a uniqueness constraint.
Close the gap between lookup and append
Lookups outside a shared lock are insufficient. Imagine attempt A and attempt B with the same ID. A searches the sheet and finds no match. Before it appends, B searches and also finds no match. Both workers append because both searches were accurate at the time. Disabling the Save button may prevent a double tap on one screen, but it cannot prevent overlapping jobs, another instance of the app, or a retry while an earlier request is still finishing.
Put the lookup and the append in the same critical section. The first request that holds the lock checks and writes. A later request cannot check until that section is finished. Google’s LockService reference distinguishes a script lock from a user lock. The latter is scoped to a user, so it is not the right choice for a shared order table. A document lock is also not available in a standalone script or web app outside a containing document. For this example, one script lock covers all writers that participate in the same Apps Script project.
Keep the section short. Parse and validate the request before acquiring the lock; do not render a response, send email, or fetch another service while holding it. If acquisition times out, return a busy result and keep the pending order intact. This is ordinary contention, not proof that the original request failed or that the order is safe to recreate with a new ID. The timeout is an app-level choice, not a promised latency.
Keep the order row and its create evidence together
For a small, single-tenant internal tool, use a dedicated Orders tab. Assume the header starts in row one and the columns are order ID, original SKU, original quantity, and creation time. Do not edit the original fields in place after creation. Track later fulfillment or corrections separately, or store immutable create fields next to mutable current fields. Comparing a retry against current quantity after a legitimate adjustment would incorrectly reject the original request.
The function below is a writer helper, not a deployable public endpoint. Supply a trusted Sheet from the server, authenticate and authorize the caller before reaching it, and use one writer project. The sample restricts input to a canonical lowercase ID, a fixed SKU format, and an integer quantity; it does not accept user formulas or evaluate arbitrary text. The lock protects lookup and append only while all callers follow the same contract.
// Call only after authenticating and authorizing the writer.
function createOrder(sheet, id, sku, qty) {
if (typeof id !== 'string' ||
!/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/.test(id) ||
typeof sku !== 'string' || !/^SKU-[A-Z0-9]{1,24}$/.test(sku) ||
!Number.isInteger(qty) || qty < 1 || qty > 1000) {
return { result: 'invalid' };
}
const lock = LockService.getScriptLock();
if (!lock.tryLock(1500)) return { result: 'busy' };
try {
const n = sheet.getLastRow() - 1; // Row 1 is the header.
const rows = n > 0 ? sheet.getRange(2, 1, n, 3).getValues() : [];
const matches = rows.filter(row => row[0] === id);
if (matches.length > 1) return { result: 'integrity_error' };
if (matches.length === 1) {
const [, savedSku, savedQty] = matches[0];
return savedSku === sku && savedQty === qty
? { result: 'existing', orderId: id }
: { result: 'conflict' };
}
sheet.appendRow([id, sku, qty, new Date().toISOString()]);
SpreadsheetApp.flush();
return { result: 'created', orderId: id };
} finally {
lock.releaseLock();
}
}
Google’s Sheet reference documents what appendRow does. It does not check uniqueness for you. The Lock reference recommends flushing pending spreadsheet changes before releasing the lock. That is why the flush occurs inside the try block, and the release is in finally. Flushing is not a database transaction or a guarantee across unrelated writers. If a write or flush throws, treat the result as unknown and retry with the same ID. Do not turn that exception into a fresh order.
Scanning the first three columns is acceptable only while the sheet is small enough and the data region follows the header contract. Do not put unrelated tables in the same tab. A second index in another tab can make lookup faster, but now you have to explain what happens if one write succeeds and the other does not. Keeping the ID and the order together avoids that split in the example. Before deploying a version of the helper, test the deployed script and its actual spreadsheet settings, not just a local mock.
Treat an ambiguous timeout as pending, not rejected
The most important retry happens when a write may already have succeeded. If a device loses its network after the append, it cannot distinguish “the server saved it but I did not get the response” from “the server never saw it.” A status lookup can help the screen show a confirmed result, but a not-found lookup is not permission to start a new create. A previous attempt may still be running. Sending the original create again through the locked writer handles both cases without requiring the app to guess which one occurred.
On Android, an outbox row can carry the ID, original create payload, attempt count, and a status such as pending or confirmed. A background worker reads it rather than reconstructing it from whatever the user is currently viewing. Treat both created and existing as success for that pending order. Keep busy, network failure, and unknown results pending with bounded backoff. Treat conflict or integrity error as a reason to stop automatic retries and ask for investigation. A permanent validation error needs a fix, not a timer.
If a user edits a pending purchase during an uncertain attempt, do not silently turn the new contents into a retry. First resolve whether the original order exists. Then apply an explicit adjustment or cancellation according to the application’s rules. This also matters for notifications or fulfillment: code that sends a new receipt every time an existing result is returned recreates the duplicate at another layer. Give those effects an identity and a retry policy of their own.
Draw the boundary around every writer
A script lock protects code that acquires the same lock. It does not reserve the entire spreadsheet against a human editor, an integration calling the Sheets API directly, or a separate Apps Script project with its own lock. Audit who and what can add orders, including sheet imports and scheduled jobs. Route legitimate creates through the same writer. If a copy-and-paste import needs to become a real order, give it a supported ingestion path rather than treating write access to the tab as an API.
Limit manual edits on the authoritative tab and use a separate view or export for sorting and reporting. Operators still need a way to correct issues, but a protected create identity should not change casually. In a larger system that has multiple teams or tenants, apply authorization and lookup scope server-side, not solely by trusting a caller-supplied ID. The helper assumes a single authorized namespace and does not implement tenant isolation.
Protect the minimum evidence that retries need. If you move old rows out of the searched table, deleting the only record of an ID makes a delayed retry look new. Set a clear retry horizon before archiving, or keep a durable index of retired IDs over the supported window. If you must manually resolve duplicates, first preserve the affected rows and related fulfillment history. Detecting multiple matches and refusing another create is safer than quietly guessing which row is real.
Exercise the failures that normal demos miss
In a disposable spreadsheet, submit two overlapping requests with the same valid ID and payload. Assert that exactly one matching row exists afterward. The responses should be created and existing, or created and busy followed by existing when the busy attempt is retried. If two matching rows exist, inspect whether both requests used the same deployed project and writer path. Counting rows is stronger evidence than checking that both requests reported success.
Then simulate losing the response after a successful write. In a test harness, allow the writer to complete and discard the result before the caller confirms the outbox item. Restart the client or the test worker, resend the saved request, and verify the same row is discovered. Test the complementary case too: omit the first send entirely and verify that retry creates one row. Both cases are indistinguishable to a caller waiting for a result, which is why they should use the same retry logic.
Try the same ID with a different quantity, two different IDs with identical payloads, and an input that cannot pass validation. Verify that an edited payload is rejected, a genuine second order is accepted, and invalid input changes nothing. Finally, seed two rows with the same ID in the scratch sheet and confirm the integrity error creates no other row. Include a test where a busy response occurs; the retry should wait rather than loop immediately or generate a new key. These scenarios describe what to validate in a deployed scratch environment, not results from a live order system.
Know when the spreadsheet is no longer the write store
Every concurrent create competes for the same lock, and each lookup grows with the sheet. As order count rises, lock wait time and busy responses can rise even if each client is using the design correctly. Watch actual latency, retry rates, and the time spent inside the critical section. If the system needs lower latency, concurrent writes from independent services, or atomic updates across inventory, orders, and payments, move the authoritative write to a database with an enforced unique key and transactions where needed.
Sheets can remain the place people browse orders after that migration. Make it a view or periodic export rather than the arbiter of whether an order already exists. Keep the client-side pending ID and retry behavior. The point of migrating is to move the uniqueness guarantee to infrastructure that enforces it, not to lose the application contract that lets a phone recover safely from a timeout.
Check the one-order contract
- Persist one ID and one create payload before the first attempt.
- Send every create through the same authorized, locked writer.
- Search by ID, append if absent, and flush before releasing the lock.
- Return the existing order on an exact retry; reject changed input.
- Prove concurrent attempts and lost responses leave exactly one row.
- Preserve ID evidence until retries are no longer accepted.
The right result is not “every request appends successfully.” It is “each intended order is recorded once, even if the network makes the client repeat itself.” That distinction gives the user a safe Retry button and the operator a sheet they can actually trust.
You Might Also Like
View all articles
Google Sheets as an Android Backend: Architecture and API Guide
Use Google Sheets as a lightweight backend for an internal Android app without turning spreadsheet access, row updates, and credentials into production liabilities.

How to Queue Android Bluetooth Print Jobs Without Duplicate Receipts
Build an Android receipt queue that deduplicates taps, retries pre-write connection failures, and requires review after an uncertain send.

PagingSource Random API Duplicate Empty Batch Refresh
An exploration of why random data endpoints break standard pagination contracts, how PagingSource handles empty batches, and what trade-offs exist when pagination keys lack stable ordering.