Firestore write retries ↔ Cloud Functions onWrite: duplicate‑commit prevention
0 reputation · 13 Jan 2020, 16:09 UTC
0 reputation · 13 Jan 2020, 16:09 UTC
Ensure that a Firestore write retried by the client library does not cause a Cloud Functions onWrite trigger to execute side effects more than once.
set() with merge on a document that may already be partially updated by a concurrent retry can overwrite intended changes.What pattern guarantees exactly‑once processing when a write is retried? How can an idempotency key be scoped so both the client and the function agree on its value? Is there a supported server‑side conditional write that can replace client‑side deduplication?
There is no native exactly-once guarantee. Firestore client retries are at-least-once, and Cloud Functions onWrite invocations are also at-least-once. The practical pattern is application-level deduplication: the client sends a stable idempotency key with the write, and onWrite checks a Firestore dedupe ledger inside a transaction before running the side effect. If the key is already marked processed, the function returns early.
onWrite receives before/after snapshots but no built-in deduplication or originating transaction context.set() with merge does not prevent duplicate function invocations and can overwrite concurrent field updates.idempotencyKey. The same key must be reused on every retry of that logical write.onWrite, read change.after.data().idempotencyKey. If missing, reject or skip according to your policy.processed mark for that key, commit an empty transaction and return without side effects.exports.processWrite = functions.firestore
.document('items/{itemId}')
.onWrite(async (change, context) => {
const after = change.after.data() || {};
const key = after.idempotencyKey;
if (!key) return null;
const ledgerRef = db.doc(`dedupe/${key}`);
await db.runTransaction(async (t) => {
const ledger = await t.get(ledgerRef);
if (ledger.exists && ledger.get('processed')) return;
// perform idempotent side effect here
t.set(ledgerRef, { processed: true, itemId: change.after.id, updatedAt: FieldValue.serverTimestamp() });
});
});
The client and function agree because the key travels in the document payload itself, not in a header or separate channel. The function derives the key from after and looks it up in the same ledger namespace. Do not generate a new key inside the function; that defeats deduplication.
Firestore transactions and security-rule preconditions can enforce document-level conditions, but there is no supported server-side conditional write that replaces client-side deduplication for side effects. Security rules can require the key field to exist, but they cannot easily replace the cross-document ledger check inside a background function. Use update() for targeted field changes rather than set() with merge when concurrent retries are possible.
If the side effect sends email, calls HTTP, or publishes to Pub/Sub, make that call idempotent or use an outbox pattern. A Firestore transaction rolls back document changes but cannot roll back an external call already made.
Does the retrying client resend the same idempotency key and payload, or does it generate a new key per attempt? If it generates a new key, change the client to reuse the key before relying on function-side deduplication.
idempotencyKey, fail the function after the side effect but before ledger commit, then retry the identical write and confirm the side effect runs once.Assumptions: modern Firestore SDK and Cloud Functions background onWrite. Firestore transactions retry automatically, but repeated conflicts may abort and require backoff. Treat "exactly-once" as a practical side-effect guarantee, not a distributed-systems guarantee.
Use comments to ask for clarification. Post a solution as an answer.
36,775 reputation · 14 Jan 2020, 03:07 UTC
When Firestore client libraries retry a write on transient failures, the original event can reach Cloud Functions onWrite more than once because no server‑generated write ID is attached by default. A practical pattern is to embed a client‑generated idempotency key as a top‑level document field (e.g., dedupKey) and have the function open a transaction that checks a processed flag keyed by that value before running side effects; if the flag is already set, the function skips execution. This does not guarantee strict exactly‑once delivery—Firestore’s at‑least‑once model means duplicate invocations must be made idempotent—but it prevents duplicate side effects when the key is consistently reused across retries and the function atomically claims the key within a security‑rule‑enforced transaction. Note that behavior varies across SDK versions (Web, Node, Android), so verify retry semantics with SDK logs and the Emulator Suite before production use.