0
0
Firebasecloud~5 mins

Fan-out writes pattern in Firebase - Commands & Configuration

Choose your learning style9 modes available
Introduction
When you want to save the same data in multiple places in your Firebase database to make reading faster, you use the fan-out writes pattern. It helps keep data in sync across different parts of your app without slowing things down.
When you need to show the same user profile info in many parts of your app quickly.
When you want to update a post and all its comments at once to keep them consistent.
When you want to keep a list of user notifications updated in multiple views.
When you want to save a chat message in both the sender's and receiver's message lists.
When you want to reduce the number of database reads by duplicating data where needed.
Commands
This command writes the same post data to two places: the main posts list and the user's personal posts list. It uses fan-out writes to keep both locations updated at once.
Terminal
firebase database:update --data '{"posts/post1": {"title": "Hello World", "author": "user1"}, "user-posts/user1/post1": {"title": "Hello World"}}'
Expected OutputExpected
✔ Data updated successfully.
--data - Specifies the JSON data to write to multiple paths at once.
This command reads the post data from the main posts list to verify the write was successful.
Terminal
firebase database:get /posts/post1
Expected OutputExpected
{ "title": "Hello World", "author": "user1" }
This command reads the duplicated post data from the user's posts list to confirm both places have the same data.
Terminal
firebase database:get /user-posts/user1/post1
Expected OutputExpected
{ "title": "Hello World" }
Key Concept

If you remember nothing else from this pattern, remember: write the same data to all needed places in one operation to keep your app fast and consistent.

Common Mistakes
Writing data to only one location and expecting other places to update automatically.
Firebase does not sync duplicated data automatically, so other places will have old or missing data.
Use fan-out writes to update all relevant paths in a single operation.
Writing fan-out data in separate commands instead of one atomic update.
Separate writes can fail partially, leaving data inconsistent.
Use a single update command with all paths to ensure atomicity.
Summary
Use fan-out writes to save the same data in multiple database locations at once.
Run one update command with all paths to keep data consistent and fast to read.
Verify writes by reading from all duplicated locations to ensure data matches.