Back to HomeCloud Database

Google Cloud Database Guide: Firebase & Cloud SQL Complete Tutorial

15 min min read
#Google Cloud#Firebase#Cloud SQL#Firestore#GCP#NoSQL#MySQL#PostgreSQL#Cloud Database#App Development

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:

ServiceTypeUse CaseDifficulty
Firebase Realtime DatabaseNoSQLReal-time sync, mobile appsEasy
Cloud FirestoreNoSQL (Document)Mobile apps, web appsEasy
Cloud SQLRelationalTraditional apps, MySQL/PostgreSQLMedium
Cloud SpannerNewSQLGlobally distributed, financial-gradeAdvanced
BigtableWide-columnBig data analytics, IoTAdvanced
AlloyDBRelationalPostgreSQL high-performanceMedium
MemorystoreCacheRedis/MemcachedMedium

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:

ComparisonRealtime DatabaseCloud Firestore
Data ModelJSON tree structureDocument-Collection
Query CapabilityLimitedStronger (compound queries, sorting)
Offline Support✅ (more complete)
ScalabilitySingle regionMulti-region, auto-scaling
Pricing ModelBy data volume and downloadsBy read/write operations and storage
RecommendationMaintain legacy projectsFirst 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):

ItemFree Quota
Storage1 GB
Document reads50,000/day
Document writes20,000/day
Document deletes20,000/day
Network egress10 GB/month

Realtime Database Free Quota:

ItemFree Quota
Storage1 GB
Download traffic10 GB/month
Simultaneous connections100

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

  1. Go to Firebase Console
  2. Click "Add Project"
  3. Enter project name
  4. Choose whether to enable Google Analytics (recommended)
  5. Complete creation

Step 2: Create Firestore Database

  1. Click "Firestore Database" in the left menu
  2. Click "Create Database"
  3. Choose mode:
    • Test mode: Anyone can read/write (for development)
    • Production mode: Need to set security rules
  4. Choose location: asia-east1 (Taiwan)
  5. Click "Create"

Step 3: Add Data

Add directly in the Console interface:

  1. Click "Start collection"
  2. Enter collection ID (e.g., users)
  3. Add document (auto-generate ID or custom)
  4. 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

EngineSupported VersionsFeatures
MySQL5.7, 8.0Most widely used, abundant resources
PostgreSQL12-16Most powerful features, many extensions
SQL Server2017-2022Microsoft 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

  1. Log into GCP Console
  2. Search for "Cloud SQL"
  3. 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

ServiceFree Content
Firestore1GB storage + 50k reads/day (permanent)
Cloud SQLNo 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?

ItemCloud SQLSelf-Hosted MySQL
Hardware MaintenanceGoogle's responsibilityYour responsibility
Security UpdatesAutomaticYour responsibility
BackupBuilt-in automatic backupYou need to configure
High AvailabilityJust check a boxBuild it yourself
CostMonthly paymentHardware depreciation + labor
FlexibilityScale up/down anytimeNeed 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:

  1. Redesign data structure (denormalization → normalization)
  2. Write migration scripts to transform data
  3. Modify application's data access logic
  4. 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:

NeedRecommended Service
Mobile app developmentFirebase (Firestore)
Need real-time syncFirebase (Firestore)
Need full SQLCloud SQL
Migrating from MySQL/PostgreSQLCloud SQL
Globally distributedCloud Spanner
Big data analyticsBigtable + BigQuery

Quick Start Recommendations

  1. Beginners / Small projects: Start with Firestore, free quota is sufficient
  2. Need SQL: Use Cloud SQL, start with smallest specs
  3. 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


References

  1. Google Cloud - Cloud SQL Documentation
  2. Firebase - Cloud Firestore Documentation
  3. Google Cloud - Choosing a Database
  4. Firebase Pricing Calculator
  5. Google Cloud Pricing Calculator
  6. 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 Consultation

Related Articles