Firebase Admin SDK (Node.js) - Time & Space Complexity
When using the Firebase Admin SDK in Node.js, it's important to understand how the number of operations grows as you interact with your database or services.
We want to know how the time it takes changes when we handle more data or requests.
Analyze the time complexity of the following operation sequence.
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();
async function getUsersData(userIds) {
const usersData = [];
for (const id of userIds) {
const doc = await db.collection('users').doc(id).get();
usersData.push(doc.data());
}
return usersData;
}
This code fetches user data from Firestore for each user ID in a list, one by one.
Identify the API calls, resource provisioning, data transfers that repeat.
- Primary operation: Firestore document read via
doc(id).get()call. - How many times: Once for each user ID in the input list.
Each user ID causes one separate read request to Firestore, so the total number of reads grows directly with the number of user IDs.
| Input Size (n) | Approx. API Calls/Operations |
|---|---|
| 10 | 10 document reads |
| 100 | 100 document reads |
| 1000 | 1000 document reads |
Pattern observation: The number of API calls increases linearly as the input size increases.
Time Complexity: O(n)
This means the time to complete grows directly in proportion to the number of user IDs you fetch.
[X] Wrong: "Fetching multiple documents one by one is as fast as fetching them all at once."
[OK] Correct: Each separate fetch makes its own network call, so doing many one-by-one calls takes longer than batching or parallel fetching.
Understanding how your code scales with more data is a key skill. It shows you can write efficient cloud code that handles growth smoothly.
"What if we changed the code to fetch all user documents in a single batch call? How would the time complexity change?"
Practice
Solution
Step 1: Understand Firebase Admin SDK role
The Admin SDK is designed for server-side use to manage Firebase services securely.Step 2: Differentiate from client SDKs
Client SDKs run on user devices for app interaction, while Admin SDK runs on servers for management tasks.Final Answer:
To securely manage Firebase services from a server environment -> Option BQuick Check:
Admin SDK = server management [OK]
- Confusing Admin SDK with client SDK
- Thinking Admin SDK runs in browsers
- Assuming Admin SDK builds UI
serviceAccountKey.json?Solution
Step 1: Load service account JSON correctly
The service account JSON must be imported using require to pass the object, not a string path.Step 2: Use admin.credential.cert with the JSON object
Pass the imported JSON object to admin.credential.cert for proper initialization.Final Answer:
const admin = require('firebase-admin'); admin.initializeApp({credential: admin.credential.cert(require('./serviceAccountKey.json'))}); -> Option AQuick Check:
Use require() to load JSON for cert [OK]
- Passing file path string instead of JSON object
- Using applicationDefault() when service account is needed
- Incorrect property name like 'serviceAccount'
const admin = require('firebase-admin');
admin.initializeApp();
admin.auth().getUser('user123')
.then(userRecord => console.log(userRecord.uid))
.catch(error => console.log('Error:', error.message));Solution
Step 1: Understand getUser() behavior
getUser() returns a Promise resolving to a user record if the user exists.Step 2: Check the then() callback output
The code logs userRecord.uid, which will be 'user123' if the user exists.Final Answer:
user123 -> Option AQuick Check:
getUser() returns user data, logs UID [OK]
- Assuming getUser() returns error if user exists
- Expecting undefined or null instead of UID
- Not handling Promise correctly
const admin = require('firebase-admin');
admin.initializeApp({
credential: admin.credential.cert(serviceAccountKey.json)
});
admin.auth().createUser({
email: 'user@example.com',
password: 'secret123'
}).then(userRecord => console.log(userRecord.uid));Solution
Step 1: Check initialization of credential
admin.credential.cert() expects a JSON object, not a string path. The file must be loaded with require().Step 2: Validate other parameters
Password length and displayName are optional or valid; initializeApp() accepts credential property.Final Answer:
The service account JSON file path should be required, not passed as a string -> Option DQuick Check:
Use require() to load JSON for cert [OK]
- Passing string path instead of JSON object
- Assuming password length error
- Thinking displayName is mandatory
Solution
Step 1: Initialize Admin SDK properly
Admin SDK must be initialized with credentials to access Firebase services securely.Step 2: Create message object and send
Build a message with device token and notification details, then use admin.messaging().send() to send it.Final Answer:
Initialize Admin SDK with credentials, build a message object with token and notification, then call admin.messaging().send(message) -> Option CQuick Check:
Use admin.messaging().send() with message object [OK]
- Using auth() instead of messaging() for notifications
- Trying to send without initializing SDK
- Using database() to send notifications
Ready to prove it?
Pass the test and this pattern moves unknown
