2

What is the correct way to commit multiple batches in a Cloud Function for Firestore? (To ensure the batches run in the background after the function completes execution)

If writing a single batch of <= 500 writes I would have the Cloud Function return the promise returned by batch.commit().

However if you need to exceed the 500 write limit, you need to chunk writes into batches of 500 and commit each, as demonstrated in the answer on this SO post. I'm just wondering what the Cloud Function should return to ensure all the batches run smoothly in the background. Currently I'm just returning an array of promises returned by each batch.commit(), but not sure if that'll cut the mustard.

saricden
  • 2,084
  • 4
  • 29
  • 40
  • 3
    There is no coordination of commits across multiple batches. But if all you want is correctly signaling when all batches are done (either resolved or rejected), then you can use Promise.all. – Frank van Puffelen Mar 19 '18 at 23:13

1 Answers1

3

If you're asking how to "ensure the batches run in the background after the function completes execution", there's no way to reliably run code in Cloud Functions after the function terminates. The final termination signal for background functions is the resolution of the promise you return from it (or the response sent in HTTP functions).

So, if you have some work going on that continues after the returned promise resolves, it may not finish. Cloud Functions will clean up and move on to the next event.

If you want to use Promise.all() to get a promise that resolves after all the batches are complete, that's fine. But they won't complete in the background. The function won't terminate until they all finish, and you will be billed for the time they take.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441