Firestore批量写入触发Quota Exceeded错误,寻求解决方案
问题描述
我用Firestore作为ReactJS应用的后端,通过writeBatch方法批量添加约1200条数据,代码如下:
export async function batchAddProduct(data) { const batches = []; data.forEach((datum, i) => { if (i % 500 === 0) { batches.push(writeBatch(db)); } const productRef = doc(collection(db, "product")); const batch = batches[batches.length - 1]; batch.set(productRef, datum); }); return await Promise.all(batches.map((batch) => batch.commit())) .then(() => { return { data: true, error: null }; }) .catch((err) => { return { data: null, error: err }; }); }
首次执行成功,Firestore控制台显示写入了1.2K条数据。但删除这些数据后,再次执行相同批量添加操作时,触发以下错误:
Firestore (9.15.0): FirebaseError: [code=resource-exhausted]: Quota exceeded. Firestore (9.15.0): Using maximum backoff delay to prevent overloading the backend.
我已经等待了约12小时,问题仍未解决。想请教:
- Firestore是否有每日写入硬限额?
- 我尝试将数据拆分为每次最多500条执行,仍会触发相同错误,该如何处理?
解决方案
关于Firestore的写入限额
Firestore免费层级(Spark计划)确实有每日写入硬限额:每天允许5万次写入操作,批量写入里的每个单独操作都会计入这个限额。但你的操作仅1200条,远低于免费限额,所以你遇到的不是每日限额耗尽的问题。
你触发的resource-exhausted错误,本质是Firestore的流量控制机制——短时间内密集的写入请求被后端判定为过载,从而触发限流,和每日硬限额无关。即使删除数据后重试,短时间内的高频写入依然会触发这个机制。
限流问题的优化方案
- 串行提交批次并添加间隔
不要用Promise.all同时提交所有批次,改为串行提交,且在批次之间添加延迟,降低写入频率:export async function batchAddProduct(data) { const batches = []; data.forEach((datum, i) => { if (i % 500 === 0) { batches.push(writeBatch(db)); } const productRef = doc(collection(db, "product")); const batch = batches[batches.length - 1]; batch.set(productRef, datum); }); try { for (const batch of batches) { await batch.commit(); // 添加1秒延迟避免触发限流 await new Promise(resolve => setTimeout(resolve, 1000)); } return { data: true, error: null }; } catch (err) { return { data: null, error: err }; } } - 排查额外写入流量
去Firebase控制台的「使用情况」页面查看写入统计,确认是否有其他高频写入操作(比如实时同步、监听触发的自动写入)占用了配额,这些操作都会累计计入写入次数。 - 使用专业导入工具
如果是一次性大量数据导入,推荐用Firebase CLI的firebase firestore:import命令,这个工具针对批量导入做了优化,比前端代码提交更稳定,不容易触发限流。 - 调整批次大小与等待时间
可以尝试将批次拆得更小(比如每次100条),同时延长批次间的等待时间(比如2秒);或者等待24小时后再尝试,给Firestore足够的后台清理时间(删除大量数据后,后端需要时间完成索引更新等操作)。
内容的提问来源于stack exchange,提问作者Owenn
相关产品推荐
相关产品推荐

