So today my code went crazy and wrote to Firestore database 1000 times and read back about 50k docs within a span of a few seconds. It was due to a bug in calling write operations which then cause the Firebase snapshots() stream to fire 1000 times with about 50 reads each time. So, then it lead me to chasing some details on how to prevent this from happening in the future.
I looked into RxDart package here around throttling streams, but it is said that using this feature just simply discards the data, which means that the data is still being read. So if a looping write is not caught, it will potentially be disastrous from a cost perspective.
Stream<T> throttle( Stream window( T event ), {bool trailing = false, bool leading = true} )
Emits a value from the source Stream, then ignores subsequent source values while the window Stream is open, then repeats this process.
If leading is true, then the first item in each window is emitted. If trailing is true, then the last item in each window is emitted.
You can use the value of the last throttled event to determine the length of the next window.
I know that I can prevent this using Firestore rules, but honestly, this is not a server problem, it is a client problem, so I'd like to address it client side first. The server solution would be more to prevent misuse rather than catching errors.