Google Cloud Database Guide: Firebase & Cloud SQL Complete Tutorial

Google Cloud Database Guide: Firebase & Cloud SQL Complete Tutorial
Want to use Google's database services but unsure whether to choose Firebase or Cloud SQL? This is a common struggle for many developers.
Google Cloud's database product line is actually quite clear: Firebase is suitable for rapid development and mobile apps, while Cloud SQL is suitable for traditional relational data needs. This article will comprehensively introduce both services, from free tiers to advanced features, teaching you step by step how to create your first Google Cloud database.
Related reading: Cloud Database Complete Guide | Understand basic cloud database concepts
Google Cloud Database Services Overview
GCP Database Product Line Introduction
Google Cloud offers multiple database services, each with different positioning:
| Service | Type | Use Case | Difficulty |
|---|---|---|---|
| Firebase Realtime Database | NoSQL | Real-time sync, mobile apps | Easy |
| Cloud Firestore | NoSQL (Document) | Mobile apps, web apps | Easy |
| Cloud SQL | Relational | Traditional apps, MySQL/PostgreSQL | Medium |
| Cloud Spanner | NewSQL | Globally distributed, financial-grade | Advanced |
| Bigtable | Wide-column | Big data analytics, IoT | Advanced |
| AlloyDB | Relational | PostgreSQL high-performance | Medium |
| Memorystore | Cache | Redis/Memcached | Medium |
For most developers, Firebase (Firestore) and Cloud SQL can satisfy 90% of needs.
Firebase vs Cloud SQL: Which Should You Choose?
This is the most frequently asked question. Simple decision principles:
Choose Firebase / Firestore:
- Developing mobile apps (iOS, Android, Flutter)
- Need real-time sync features (chat, collaboration)
- Small team, want rapid development
- Flexible data structure, frequently changing
Choose Cloud SQL:
- Traditional web applications
- Data has complex relationships (need JOINs)
- Team is familiar with SQL
- Need transactional consistency (ACID)
- Migrating from existing MySQL/PostgreSQL
Use Both:
- Firebase handles real-time interactions (chat, notifications)
- Cloud SQL handles core business data (orders, accounting)
Differences from AWS and Azure
Want to understand the complete comparison across three major platforms? See: AWS, GCP, Azure Database Complete Comparison
GCP's unique advantages:
- Firebase: Best real-time sync, most complete mobile SDKs
- Spanner: Global distributed consistency, no equivalent product on other platforms
- BigQuery: Serverless analytics queries, very competitive in speed and cost
- Taiwan Data Center: Data center in Changhua, low latency, data residency
GCP's disadvantages:
- Fewer database services than AWS
- Less community resources and documentation than AWS
- Some advanced features released later
Firebase Database Complete Tutorial
Firebase is Google's app development platform, with the database being its core feature.
Realtime Database vs Firestore Comparison
Firebase has two databases that many people confuse:
| Comparison | Realtime Database | Cloud Firestore |
|---|---|---|
| Data Model | JSON tree structure | Document-Collection |
| Query Capability | Limited | Stronger (compound queries, sorting) |
| Offline Support | ✅ | ✅ (more complete) |
| Scalability | Single region | Multi-region, auto-scaling |
| Pricing Model | By data volume and downloads | By read/write operations and storage |
| Recommendation | Maintain legacy projects | First choice for new projects |
Conclusion: Use Firestore directly for new projects. Realtime Database is the old version with more limited features.
Firebase Free Tier Details
Firebase's free quota is quite generous. More free options: Free Cloud Database Complete List
Firestore Free Quota (Spark Plan):
| Item | Free Quota |
|---|---|
| Storage | 1 GB |
| Document reads | 50,000/day |
| Document writes | 20,000/day |
| Document deletes | 20,000/day |
| Network egress | 10 GB/month |
Realtime Database Free Quota:
| Item | Free Quota |
|---|---|
| Storage | 1 GB |
| Download traffic | 10 GB/month |
| Simultaneous connections | 100 |
These quotas are sufficient for:
- Personal projects and side projects
- MVP validation
- Small applications (hundreds to thousands of users per day)
Creating Your First Firebase Database
Step 1: Create a Firebase Project
- Go to Firebase Console
- Click "Add Project"
- Enter project name
- Choose whether to enable Google Analytics (recommended)
- Complete creation
Step 2: Create Firestore Database
- Click "Firestore Database" in the left menu
- Click "Create Database"
- Choose mode:
- Test mode: Anyone can read/write (for development)
- Production mode: Need to set security rules
- Choose location:
asia-east1(Taiwan) - Click "Create"
Step 3: Add Data
Add directly in the Console interface:
- Click "Start collection"
- Enter collection ID (e.g.,
users) - Add document (auto-generate ID or custom)
- Add fields and values
Or use code:
// Web SDK
import { initializeApp } from 'firebase/app';
import { getFirestore, collection, addDoc } from 'firebase/firestore';
const firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_PROJECT.firebaseapp.com",
projectId: "YOUR_PROJECT_ID",
};
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
// Add data
async function addUser() {
const docRef = await addDoc(collection(db, "users"), {
name: "John Doe",
email: "[email protected]",
createdAt: new Date()
});
console.log("Document ID:", docRef.id);
}
Step 4: Query Data
import { getDocs, query, where } from 'firebase/firestore';
// Query all users
const querySnapshot = await getDocs(collection(db, "users"));
querySnapshot.forEach((doc) => {
console.log(doc.id, " => ", doc.data());
});
// Conditional query
const q = query(
collection(db, "users"),
where("email", "==", "[email protected]")
);
const results = await getDocs(q);
Data Structure Design Best Practices
Firestore's data structure is very different from SQL, requiring a different mindset:
Principle One: Denormalization
SQL habit is to split data apart and combine with JOINs. Firestore recommends putting commonly used data together.
// SQL mindset (not recommended)
// users collection
{ id: "user1", name: "John Doe" }
// orders collection
{ id: "order1", userId: "user1", product: "iPhone" }
// Firestore mindset (recommended)
// orders collection - directly includes user info
{
id: "order1",
product: "iPhone",
user: {
id: "user1",
name: "John Doe"
}
}
Principle Two: Use Subcollections to Organize Data
// User's orders use subcollection
// users/{userId}/orders/{orderId}
// Add subcollection document
await addDoc(
collection(db, "users", "user1", "orders"),
{ product: "iPhone", price: 999 }
);
Principle Three: Avoid Deep Nesting
Firestore recommends 2-3 levels maximum. Too deep affects query performance and maintainability.
Security Rules Configuration
Firestore security rules determine who can read and write data. Test mode is dangerous - you must configure rules before going live.
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
// Users can only read/write their own data
match /users/{userId} {
allow read, write: if request.auth != null
&& request.auth.uid == userId;
}
// Orders: only logged-in users can read, only owner can write
match /orders/{orderId} {
allow read: if request.auth != null;
allow write: if request.auth != null
&& request.auth.uid == resource.data.userId;
}
// Public data anyone can read
match /public/{document=**} {
allow read: if true;
allow write: if false;
}
}
}
Cloud SQL Complete Tutorial
Cloud SQL is Google Cloud's managed relational database service, supporting MySQL, PostgreSQL, and SQL Server.
Cloud SQL Supported Database Engines
| Engine | Supported Versions | Features |
|---|---|---|
| MySQL | 5.7, 8.0 | Most widely used, abundant resources |
| PostgreSQL | 12-16 | Most powerful features, many extensions |
| SQL Server | 2017-2022 | Microsoft ecosystem integration |
Selection recommendations:
- Already experienced: Choose the engine you're familiar with
- New project: PostgreSQL has the most complete features
- Migrating: Choose the same engine as the source
Creating a Cloud SQL Instance
Step 1: Enter Cloud SQL
- Log into GCP Console
- Search for "Cloud SQL"
- Click "Create Instance"
Step 2: Choose Database Engine
Choose MySQL, PostgreSQL, or SQL Server. Using MySQL as an example here.
Step 3: Configure Instance
Instance ID: my-mysql-db (custom, cannot change later)
Password: Set root password (remember it!)
Database version: MySQL 8.0
Region: asia-east1 (Taiwan)
Zone availability:
- Single zone: Cheaper, for development
- Multi-zone (high availability): Recommended for production
Step 4: Configure Machine Specifications
Machine type:
- Shared core: Cheapest, for testing
- Lightweight: Small applications
- Standard: General purpose
- High memory: Large databases
Recommendation: Start with smallest spec, upgrade later as needed.
Step 5: Configure Storage
Storage type: SSD (recommended) or HDD
Storage capacity: As needed, can auto-increase
Enable automatic storage increase: Recommended
Step 6: Configure Connectivity
Public IP:
- Unchecked: Only connect from within GCP (more secure)
- Checked: Can connect from outside (need to set authorized networks)
Private IP: Recommended (connect from within VPC)
Authorized networks: Add your IP (if using public IP)
Step 7: Create
Click "Create Instance" and wait about 5-10 minutes.
MySQL Connection Setup
Detailed MySQL connection tutorial: MySQL Cloud Integration Complete Guide
Method 1: Cloud SQL Proxy (Recommended)
The most secure connection method, no need to set up public IP.
# Download Cloud SQL Proxy
curl -o cloud-sql-proxy https://storage.googleapis.com/cloud-sql-connectors/cloud-sql-proxy/v2.8.0/cloud-sql-proxy.linux.amd64
chmod +x cloud-sql-proxy
# Run (need to set up gcloud authentication first)
./cloud-sql-proxy --port 3306 PROJECT_ID:REGION:INSTANCE_NAME
# Connect from another terminal
mysql -u root -p -h 127.0.0.1
Method 2: Public IP Connection
# First set authorized networks in Console (your IP)
# Then connect directly
mysql -u root -p -h [CLOUD_SQL_PUBLIC_IP] --ssl-mode=REQUIRED
Method 3: Code Connection
# Python + SQLAlchemy
from sqlalchemy import create_engine
# Using Cloud SQL Proxy
engine = create_engine(
'mysql+pymysql://user:[email protected]:3306/database'
)
# Or using public IP + SSL
engine = create_engine(
'mysql+pymysql://user:password@PUBLIC_IP:3306/database',
connect_args={
'ssl': {
'ca': 'server-ca.pem',
'cert': 'client-cert.pem',
'key': 'client-key.pem'
}
}
)
Performance Tuning and Monitoring
1. Use Cloud SQL Insights
GCP's built-in performance analysis tool:
- View CPU, memory, connection count trends
- Find slow queries
- Analyze query plans
Click "Query Insights" on the instance page in Console.
2. Adjust Database Parameters
In "Database flags" you can adjust MySQL parameters:
innodb_buffer_pool_size: Increase to improve performance
max_connections: Adjust as needed
slow_query_log: Enable to find slow queries
3. Set Up Alerts
Set up alerts in Cloud Monitoring:
- CPU > 80% for 5 minutes
- Memory > 85%
- Storage > 80%
- Connection count approaching limit
Other GCP Database Services
Cloud Spanner (Globally Distributed)
Spanner is Google's proprietary technology - a globally distributed database that simultaneously guarantees strong consistency.
Suitable scenarios:
- Global applications requiring multi-region deployment
- Financial systems requiring strong consistency
- Ultra-large scale requiring horizontal scaling
Pricing: Expensive, starting at about $0.9 per node per hour. Not suitable for small projects.
Bigtable (Big Data Analytics)
Bigtable is Google's internal big data database, supporting services like Gmail and YouTube.
Suitable scenarios:
- IoT data collection (tens of thousands of writes per second)
- Time-series data analysis
- Large-scale machine learning feature storage
Pricing: Charged by nodes and storage, minimum several hundred dollars per month.
Memorystore (Redis/Memcached)
Managed in-memory cache service.
Suitable scenarios:
- Session storage
- Caching hot data
- Leaderboards, counters
Pricing: More expensive than self-hosted Redis, but saves operations time. Small projects can consider using Firestore or application-layer caching instead.
GCP Database Pricing Analysis
Billing Methods Explained
Firestore Billing:
- Document reads: $0.06 / 100,000
- Document writes: $0.18 / 100,000
- Document deletes: $0.02 / 100,000
- Storage: $0.18 / GB / month
- Network egress: $0.12 / GB
Cloud SQL Billing:
- Compute: Charged by vCPU and memory
- Storage: $0.17 / GB / month (SSD)
- Network: Free within same region, charged cross-region
- Backup: Charged after exceeding free quota
Free Quotas and Trial Credits
| Service | Free Content |
|---|---|
| Firestore | 1GB storage + 50k reads/day (permanent) |
| Cloud SQL | No free quota |
| New GCP Account | $300 trial credits (90 days) |
$300 trial credits can run a small Cloud SQL instance for about 2-3 months.
Cost Optimization Tips
1. Choose the Right Service
- Use Firestore for small projects, free quota is sufficient
- Only use Cloud SQL when you need SQL
2. Choose the Right Specs
- Start with smallest specs
- Monitor actual usage before upgrading
3. Use Committed Use Discounts
- If you're sure about long-term use, buy 1-year or 3-year commitment
- Save 25-52%
4. Save on Development Environment
- Use smallest specs for development
- Stop instances when not in use (note: storage still charged)
Not sure whether to choose Firebase or Cloud SQL? Choosing wrong means difficult migration later. Schedule a free consultation and let us help you evaluate the best solution.
Use Cases and Recommended Solutions
Mobile Applications
Recommended: Firebase (Firestore)
Reasons:
- Complete SDK, supports iOS/Android/Flutter
- Real-time sync, data changes update the app immediately
- Offline support, works without network
- Well-integrated with Firebase Auth, Cloud Messaging
Architecture example:
Mobile App ←→ Firestore (main data)
←→ Firebase Auth (login)
←→ Cloud Storage (images)
Web Applications
Choose based on situation:
Simple SPA / JAMstack: Firestore
- Frontend connects directly to Firestore
- Use security rules for access control
- Free quota usually sufficient
Traditional Server-side Application: Cloud SQL
- Backend connects to Cloud SQL
- Complete SQL functionality
- Suitable for complex business logic
Hybrid Architecture: Use both
- Cloud SQL stores core data (orders, accounting)
- Firestore handles real-time features (notifications, chat)
Enterprise Applications
Recommended: Cloud SQL + High Availability Configuration
Configuration recommendations:
- Enable high availability (Multi-AZ)
- Set up read replicas
- Enable automatic backup, retain 30 days
- Use private IP, don't enable public IP
- Configure Cloud Armor protection
If you need global deployment:
- Consider Cloud Spanner
- Or use multiple Cloud SQL instances + application-layer routing
FAQ
Is Firebase's Free Quota Enough?
For most small applications, yes. 50,000 reads per day can support:
- About 500-1,000 daily active users (normal usage)
- About 100-200 daily active users (heavy reading)
Exceeding free quota will automatically charge (if on Blaze plan). Recommend setting budget alerts in Console.
What's the Difference Between Cloud SQL and Self-Hosted MySQL?
| Item | Cloud SQL | Self-Hosted MySQL |
|---|---|---|
| Hardware Maintenance | Google's responsibility | Your responsibility |
| Security Updates | Automatic | Your responsibility |
| Backup | Built-in automatic backup | You need to configure |
| High Availability | Just check a box | Build it yourself |
| Cost | Monthly payment | Hardware depreciation + labor |
| Flexibility | Scale up/down anytime | Need to buy new machines |
Summary: Cloud SQL saves effort but requires monthly payment, self-hosting saves money but costs time to maintain.
Can I Migrate from Firebase to Cloud SQL?
Yes, but it's not simple. Firebase (NoSQL) and Cloud SQL (SQL) have completely different data models:
Things you need to do:
- Redesign data structure (denormalization → normalization)
- Write migration scripts to transform data
- Modify application's data access logic
- Test all features
Recommendation: Think clearly about which to use from the start. If uncertain, Firestore's query capability is closer to SQL, making future migration easier than Realtime Database.
Conclusion
Google Cloud's database choices are actually quite clear:
| Need | Recommended Service |
|---|---|
| Mobile app development | Firebase (Firestore) |
| Need real-time sync | Firebase (Firestore) |
| Need full SQL | Cloud SQL |
| Migrating from MySQL/PostgreSQL | Cloud SQL |
| Globally distributed | Cloud Spanner |
| Big data analytics | Bigtable + BigQuery |
Quick Start Recommendations
- Beginners / Small projects: Start with Firestore, free quota is sufficient
- Need SQL: Use Cloud SQL, start with smallest specs
- Uncertain: First use Firestore for MVP, evaluate migration when SQL features are needed
Let Google Cloud Save You Money and Effort
Google Cloud's product line is rich. Choosing the right service can save you a lot of money and time. But choosing wrong means wasting money and going down the wrong path.
CloudInsight Free Cloud Consultation can help you:
✅ Requirements Analysis: Understand your application needs, recommend the most suitable services ✅ Architecture Design: Plan Firebase + Cloud SQL hybrid architectures ✅ Cost Optimization: Ensure you don't pay for features you don't use ✅ Migration Assistance: Planning and execution for migrating to GCP from other platforms
We are a Google Cloud Partner, familiar with all GCP services.
Schedule a Free Consultation
Click to Schedule 30-Minute Free Consultation
Whether you're just starting to evaluate GCP or want to optimize your existing architecture, we can give you professional advice.
Related Reading
- Cloud Database Complete Guide
- Free Cloud Database Complete List
- AWS vs GCP vs Azure Database Complete Comparison
- MySQL Cloud Database Integration Guide
References
- Google Cloud - Cloud SQL Documentation
- Firebase - Cloud Firestore Documentation
- Google Cloud - Choosing a Database
- Firebase Pricing Calculator
- Google Cloud Pricing Calculator
- Google Cloud - Best Practices for Cloud SQL
Need Professional Cloud Advice?
Whether you're evaluating cloud platforms, optimizing existing architecture, or looking for cost-saving solutions, we can help
Book Free ConsultationRelated Articles
What is Cloud Database? 2025 Complete Guide | Free Plans, Platform Comparison, Setup Tutorial
Complete analysis of cloud database definition, pros/cons, and use cases. Compare AWS, GCP, Azure platforms, recommend free plans, and step-by-step guide to creating your first cloud database.
Cloud DatabaseCloud Database Comparison: AWS vs GCP vs Azure 2025 Complete Review
In-depth comparison of AWS RDS, GCP Cloud SQL, and Azure SQL Database. Complete analysis from performance, pricing, features to use cases to help you choose the best solution.
Cloud Database2025 Complete Free Cloud Database List | 7 Best Free Options for Beginners
Curated selection of 7 free cloud database options including Firebase, PlanetScale, and Supabase, with detailed free tier comparison tables to help you find the best free solution.