Atomic Operations with Firebase

Introducing Batched Writes

Onboard {
_id: string
user_id: string
status: oneOf<'draft', 'ready', 'fail', 'completed'>
venue: Venue
services: Array<Services>
promotions: Array<Promotions>
... any other information
}
Venue {
_id: string
user_id: string
onboard_id: string
... any other information
}
Services {
_id: string
user_id: string
onboard_id: string
venue_id: string
... any other information
}
Promotions {
_id: string
user_id: string
onboard_id: string
venue_id: string
}
const db = firebase.firestore()
const services = db.collection(`services`).where(`venue_id`, `==`, venueID)
const = db.collection(`promotions`).where(`venue_id`, `==`, venueID)
our onboarding in a nutshell 👩‍🏫
  1. The cloud function needs to manage different status and ensure it does not hang forever in case the onboard is not ready to process or if it fails several times.
  2. We need to call db.batch() in order to group all the operations, we need to execute.
  3. We assume the object is going to be saved as they are, we create _id for each element and make sure we attach the venue_id for each element.
const _id = uuidv1()
const serviceRef = servicesRef.doc(`${_id}`)
batch.set(serviceRef, Object.assign({}, service, { _id, venue_id: venueId }))
batch.commit() 
  • Batches Writes are only for writes, if you need to read data, you will have to use Transactions.
  • This operation can be executed on the client (but it will perform better on the backend).
  • There is a maximum of 500 operations, ideally, keep it around 300.
  • Once again, it’s all or nothing. Everything is copied or everything fails.

When to use it?

  • When you need to create different docs with linked between each other.
  • When you need to do several operations create/update/delete in a single operation.
  • Data migration.

Transactions

  • Reads must precede writes
  • They might run more than once (if a concurrent edit affects a document that the transaction reads)
  • Read operations after write operations
  • Read a document that was modified outside of the transaction
  • Exceeded the maximum request size of 10 MiB
  • Executed on an offline mode
  • You need to exec operations based on a current document state (it should not change during the operation).
  • You need to do multiple reads and writes.
  • You want to impress your peers with new stuff.

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store