Firestore の runTransaction でアプリ内通貨の購入を原子的に処理する
アプリ内ショップで「コインを払って所有アイテムを得る」処理を、複数の書き込みが同時に発火しないように原子化したい。Firestore の runTransaction を使うと、読み込み→検証→書き込みの一連を1つのトランザクションにまとめられる。
結論(先に)
const newCoins = await runTransaction(db, async (tx) => {
const profileSnap = await tx.get(profileRef);
const ownedSnap = await tx.get(ownedRef);
if (ownedSnap.exists()) throw new Error("already_owned");
const current = profileSnap.data()?.coins ?? 0;
if (current < item.price) throw new Error("insufficient_coins");
const next = current - item.price;
tx.update(profileRef, { coins: next });
tx.set(ownedRef, { itemId: item.id, purchasedAt: serverTimestamp() });
return next;
});
ポイント:
- トランザクション内で
tx.getを使う(通常のgetDocではない) - 検証(残高・既購入)を必ず読み込み後に行う
- 失敗時は
throwで全ての書き込みをロールバックする - 戻り値で UI に反映する新値を返す
課題: 残高チェック→消費→所有付与の競合
シンプルに書くと:
const profile = await getDoc(profileRef);
if ((profile.data()?.coins ?? 0) < price) return;
await updateDoc(profileRef, { coins: increment(-price) });
await setDoc(ownedRef, { itemId });
これは2つの問題がある:
- 残高チェックと消費の間にラグ: 同じユーザーが別タブで連打すると、両方が「残高十分」で通って二重消費する
- 所有書き込みが失敗してもコインだけ減る: 部分失敗で不整合が残る
トランザクションにまとめると両方が解消する。
試した順番
1. increment(-price) だけで済ませる → ダメ
await updateDoc(profileRef, { coins: increment(-price) });
increment は原子的だが、結果が負になる可能性を防げない。残高 50 で 100 のアイテムを買おうとすると -50 になる。事前チェックが必須。
2. 事前チェック + increment → 部分的にダメ
const snap = await getDoc(profileRef);
if (snap.data().coins < price) return;
await updateDoc(profileRef, { coins: increment(-price) });
await setDoc(ownedRef, ...);
事前チェックは入ったが、読み込みと書き込みの間でラグがある。連打や別端末からの並列アクセスで二重消費が起きる。
3. runTransaction で読み込み→検証→書き込みを atomic に → 正解
runTransaction は内部的に楽観的ロックで動く。トランザクション中に読んだドキュメントが他で書き換わっていたら、トランザクション全体がリトライされる。
const newCoins = await runTransaction(db, async (tx) => {
const profileSnap = await tx.get(profileRef);
const ownedSnap = await tx.get(ownedRef);
if (ownedSnap.exists()) throw new Error("already_owned");
const current = profileSnap.data()?.coins ?? 0;
if (current < item.price) throw new Error("insufficient_coins");
const next = current - item.price;
tx.update(profileRef, { coins: next });
tx.set(ownedRef, {
itemId: item.id,
category: item.category,
purchasedAt: serverTimestamp(),
});
return next;
});
これで:
- 連打しても2回目はトランザクション内で残高不足を検知して失敗する
- 所有付与が失敗したらコインも戻る(ロールバック)
- 同期的な読み込みとして書ける
エラーハンドリング
呼び出し側は理由別の文字列で UI に出し分けたいので、throw new Error("...") で識別子を投げて catch で振り分ける。
try {
const next = await runTransaction(...);
return { ok: true, newCoins: next };
} catch (e) {
const msg = e instanceof Error ? e.message : "error";
if (msg === "already_owned" || msg === "insufficient_coins") {
return { ok: false, reason: msg };
}
return { ok: false, reason: "error" };
}
これで UI 側は:
if (result.reason === "insufficient_coins") showToast("🌱が足りないよ");
else if (result.reason === "already_owned") showToast("もう持ってるよ");
と表示できる。
注意点
tx.getを1つでも忘れてgetDocで読むと、楽観的ロックの対象外になり、原子性が崩れるtx.settx.updateは書き込みキューに入るだけで、トランザクションが完了するまで反映されない- トランザクション中に副作用(外部APIコール等)を入れない。リトライで複数回走る前提
- 書き込み数の上限は 500 件(バッチと同じ)
教訓
- アプリ内通貨や残高ベースの処理は
incrementだけでは不十分 - 事前チェックを入れるなら、読み込み→検証→書き込みを atomic にする必要がある
runTransactionは楽観的ロックなので競合時に自動リトライされ、開発者は同期的なロジックを書くだけでいい
同じパターンは「在庫減算→注文確定」「ポイント消費→特典付与」などにも応用できる。
この記事は、開発の記録をもとに Claude Code が下書きし、私が確認して公開しています。