An onDocumentCreated trigger in Cloud Functions for Firebase decrements stock for each new order, and stock sometimes drops twice for one order; why, and how do you fix it?
answer
- at least once, not exactly once
- retry is off by default
- a dedupe key: event.id or order ID
- marker read and write in one transaction
- a 24-hour retry window in 2nd gen
basics
~20 sFirestore events are delivered at least once, so one order can run the trigger twice, and retries replay failures. Make it idempotent: check and write a marker keyed by the order or event.id in the decrement's transaction.
solid answer
~40 sFirebase documents that Firestore triggers are delivered at least once: one event can cause several invocations, in no guaranteed order. Separately, enabling retries (`retry: true` in 2nd gen) replays any invocation that throws, with exponential backoff for up to 24 hours (7 days on 1st gen); without it, a failed event is dropped. So the handler must be idempotent. In an Admin SDK transaction, read a marker document keyed by the order ID or `event.id`; if it exists, return; otherwise apply `FieldValue.increment(-qty)` to each stock document and write the marker in the same transaction. Side effects outside Firestore, such as the confirmation email, need their own idempotency key. Enable `retry` only once the handler is idempotent, return instead of throwing for permanent errors, and drop events whose `event.time` is too old.
code
typescript · 34 linesimport { onDocumentCreated } from "firebase-functions/firestore";
import { logger } from "firebase-functions";
import { initializeApp } from "firebase-admin/app";
import { getFirestore, FieldValue } from "firebase-admin/firestore";
initializeApp();
const db = getFirestore();
type Line = { sku: string; qty: number };
export const reserveStock = onDocumentCreated(
{ document: "orders/{orderId}", retry: true },
async (event) => {
const order = event.data?.data();
const lines = order?.lines as Line[] | undefined;
if (!Array.isArray(lines) || lines.length === 0) {
// Permanent problem: log and return so the event is not retried for 24 hours.
logger.error(`Order ${event.params.orderId} has no lines`, { eventId: event.id });
return;
}
const marker = db.doc(`stockEvents/${event.params.orderId}`);
await db.runTransaction(async (tx) => {
const seen = await tx.get(marker); // reads come before writes
if (seen.exists) {
return; // a duplicate delivery or a retry after a successful commit
}
for (const { sku, qty } of lines) {
tx.update(db.doc(`stock/${sku}`), { available: FieldValue.increment(-qty) });
}
tx.set(marker, { eventId: event.id, at: FieldValue.serverTimestamp() });
});
// Transient errors (contention, unavailable) throw and are retried.
},
);go deeper
Recall that Firestore triggers are delivered at least once and that retries are off unless you set retry: true.
Explain the retry window and backoff, why a dropped event can still look successful, and how a transaction makes a marker check safe.
Show that you choose the dedupe key deliberately, separate permanent from transient errors, and give external side effects their own idempotency.
Set the team default: every event-driven function idempotent by review, retry enabled only with an end condition, and duplicates exercised in tests.
## Why one order can decrement stock twice The stock function is an event-driven function, and Firebase is explicit about Firestore events: they are **delivered at least once**, and "a single event may result in multiple function invocations." Several paths lead to a second run for the same order: - **Duplicate delivery.** Even with retries off, the platform can invoke the handler twice for one event. - **Retries.** With `retry: true`, an invocation that throws or returns a rejected promise is run again, including one that applied some of its writes before failing. - **Overlapping deployments.** The documented way to rename a function or move it to another region deploys the new function before deleting the old one, so for a while both process the same writes. A handler that decrements stock unconditionally turns each of these into a double decrement. ## Retry semantics in firebase-functions | | 1st gen | 2nd gen | |---|---|---| | How to enable | `failurePolicy: true` in `runWith()` | `retry: true` in the trigger options | | Default | off | off | | Retry window | 7 days | 24 hours | Retries back off exponentially, between 10 and 600 seconds. Two consequences follow from the default: - **Without `retry`**, a failed invocation's event is **dropped**, and the platform may still log the execution as successful (`200 OK`), so the handler must log its own errors. - **With `retry`**, a permanent failure such as a bug or a malformed order is retried until the window closes, billed every time. The only ways out of a stuck retry loop are redeploying or deleting the function. ## Making the handler idempotent The fix is to make a second run of the same work a no-op: 1. Choose a **dedupe key**: `event.id`, which Firebase recommends as the key for external APIs that accept one, or a business key such as the order ID. 2. Open a Firestore **transaction** with the Admin SDK. 3. **Read** a marker document keyed by it first, because a transaction does its reads before its writes. 4. If the marker exists, return: the work was already applied. 5. Otherwise apply each line with `FieldValue.increment(-qty)` and **write the marker in the same transaction**, so both commit or neither does. A crash before commit leaves nothing applied; a crash after commit leaves the marker that turns the retry into a no-op. A plain `get()` followed by `update()` outside a transaction is not enough, because two concurrent invocations can both see "no marker" and both decrement. ## Choosing the dedupe key `event.id` covers redelivery and retries of one event. The order ID is stronger when two different functions might handle the same order, as during a rename or region move, because the order is the same whatever the event says. That is why the code example keys the marker on the order and stores `event.id` only for tracing. Keep markers small, and delete old ones on a schedule if their volume matters. ## Side effects outside Firestore The confirmation email cannot join a Firestore transaction. Two options: - Pass the dedupe key as the **idempotency key** if the email provider's API accepts one; the Firebase docs recommend the event ID for exactly this. - Otherwise **claim** a marker with the Admin SDK's `create()`, which fails when the document already exists, before sending. That trades a rare lost email (a crash between claim and send) for no duplicates; writing the marker after sending makes the opposite trade. Choose the failure the product can live with. ## Retry-safe error handling - Turn on `retry` only after the handler is idempotent and has been exercised without it. - Catch errors that can never succeed, such as validation failures or a missing field, log them and **return**, so they are not retried. - Let transient errors, such as transaction contention or an unavailable dependency, throw so the platform retries them. - Add an **end condition**: compare `event.time` with the current time and drop events older than a limit you choose, accepting that the dropped work must be repaired another way. - Test duplicates on purpose: in a unit test, call the wrapped handler twice with the same event and assert that stock moved once. The same discipline applies to every event-driven function here, from Auth's `onUserCreated` to Storage's `onObjectFinalized`, because all of them are delivered at least once.
- Why not just set retry: true and stop there?Retry replays every thrown error until the invocation succeeds or the 24-hour window ends. A non-idempotent handler then double-applies whatever it wrote before failing, and a permanent error, such as a malformed order, becomes a billed retry loop that only redeploying or deleting the function ends. Make the handler idempotent first, return on permanent errors, and enable retry for the transient ones.
- The confirmation email still goes out twice now and then. How do you deduplicate a side effect that is not a Firestore write?If the email provider accepts an idempotency key, pass the order ID or `event.id`. If not, claim a marker with the Admin SDK's `create()`, which fails when the document exists, before sending. A crash between the claim and the send then loses one email instead of sending two; recording the marker after sending makes the opposite trade. Pick the failure the business prefers.
- Does setting maxInstances to 1 stop the double decrement?No. It limits how many instances run at once, but a duplicate delivery or a retry can still arrive later on the same instance and decrement again. Concurrency is not the cause; repeated invocation is, and only an idempotent handler fixes it.
A cloakroom ticket: before handing over a coat, the attendant checks whether ticket 42 was already redeemed and marks it in the same motion, so presenting the same ticket twice never produces two coats.
- Firestore triggers run exactly once per write unless retries are enabled.
- Event-driven functions retry failures by default.
- With retry: true, a failing trigger gives up after three attempts.
- A successful execution in the logs proves the trigger did its work.
- Checking a processed flag with a plain get before updating prevents duplicates.
- Setting maxInstances to 1 makes a trigger idempotent.