Skip to content

GCP small-scale blueprint: Cloud Run, Cloud SQL and Firebase Auth

Ekanatha Reddy Urivakili8 min1,210 words

1) Context and Scale

This blueprint targets startups and small teams building cloud-native web applications or APIs using Google Cloud Platform (GCP) services optimized for cost and simplicity, serving up to ~1,000 daily active users in a single region. It is ideal for early-stage SaaS MVPs or internal business tools that require a secure backend with user authentication, relational data persistence, and serverless compute.

AssumptionValueNotes
Daily active users~1,000Consistent daily engagement
Peak requests/sec≤ 50Bursts handled with autoscaling
Data volume≤ 10 GBTypical OLTP dataset
Team size1-3 engineersFull-stack developers preferred
Budget<$300/month (GCP costs)Cost-sensitive, pay-as-you-go
Deployment regionSingle region (us-central1 assumed)Simplicity and latency optimized

2) Requirements

Functional requirements

IDRequirementPriority
FR1User signup/login/logout with email/password and social login via Firebase AuthCritical
FR2RESTful HTTP API to create/read/update/delete (CRUD) user-related dataCritical
FR3Role-based user permissions (e.g., admin, standard user)Important
FR4Serverless, scalable backend with near zero-maintenanceCritical
FR5Persist relational data with ACID guarantees and schema migrationsCritical

Non-functional requirements

IDRequirementPriority
NFR1Low latency responses (API < 500ms p95)Important
NFR2High availability (99.9%)Important
NFR3Secure authentication with FirebaseCritical
NFR4Cost optimized for <$300/month GCP spendCritical
NFR5Infrastructure-as-code for reproducible deploysImportant
NFR6Observability with structured logs, metrics, tracingImportant

3) High-Level Design

flowchart LR
  U[User Client] -->|HTTPS| F[Cloud Run API]
  F -->|Authenticated via| A[Firebase Auth]
  F -->|SQL Queries| D[Cloud SQL (PostgreSQL)]
  subgraph GCP
    F
    A
    D
  end

Simplified system flow: users authenticate with Firebase Auth, invoke a Cloud Run service hosting a REST API, which queries Cloud SQL for persistent storage.

4) Cloud Service Mapping

ComponentGCP ServiceAWS EquivalentAzure EquivalentNotes
User AuthenticationFirebase AuthAmazon CognitoAzure AD B2CManaged identity provider with social login
Stateless API BackendCloud RunAWS Lambda + API GatewayAzure Functions + API ManagementServerless container-based compute
Relational DBCloud SQL (PostgreSQL)Amazon RDS (PostgreSQL)Azure Database for PostgreSQLFully managed relational service
Infrastructure as CodeTerraform / Cloud Deployment ManagerTerraform / CloudFormationTerraform / BicepIaC tool of choice
Observability / TracingCloud Logging, Cloud Monitoring, OpenTelemetry SDKCloudWatch + X-RayAzure Monitor + Application InsightsNative integrations

5) Data Design

ER Diagram

erDiagram
  USER {
    string user_id PK
    string email
    string display_name
    string role
    datetime created_at
  }
  ITEM {
    int item_id PK
    string user_id FK
    string name
    string description
    datetime created_at
  }
  USER ||--o{ ITEM : owns >

SQL DDL (PostgreSQL)

CREATE TABLE users (
    user_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    email VARCHAR(255) UNIQUE NOT NULL,
    display_name VARCHAR(255),
    role VARCHAR(50) NOT NULL DEFAULT 'user',
    created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE items (
    item_id SERIAL PRIMARY KEY,
    user_id UUID NOT NULL REFERENCES users(user_id) ON DELETE CASCADE,
    name VARCHAR(255) NOT NULL,
    description TEXT,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX idx_items_user_id ON items(user_id);

6) Low-Level Design

Class Diagram (simplified)

classDiagram
  class User {
    +UUID userId
    +String email
    +String displayName
    +String role
    +DateTime createdAt
    +bool isAdmin()
  }
  class Item {
    +int itemId
    +UUID userId
    +String name
    +String description
    +DateTime createdAt
  }
  class UserService {
    +User getUser(UUID userId)
    +User createUser(User user)
  }
  class ItemService {
    +List<Item> listItems(UUID userId)
    +Item createItem(Item item)
  }
  UserService --> User
  ItemService --> Item
  Item --> User : userId (FK)

Code examples

Language: TypeScript / Node.js with Express and pg client for PostgreSQL. Must run on Cloud Run.

Minimal example: Express REST API for user info

import express from 'express';
import { Pool } from 'pg';

const pool = new Pool();

const app = express();
app.use(express.json());

app.get('/users/:id', async (req, res) => {
  const userId = req.params.id;
  const result = await pool.query('SELECT user_id, email, display_name, role FROM users WHERE user_id = $1', [userId]);
  if (result.rowCount === 0) return res.status(404).send({ error: 'User not found' });
  res.send(result.rows[0]);
});

const port = process.env.PORT || 8080;
app.listen(port, () => console.log(`Listening on port ${port}`));

Notice the minimal use of pg with parameterized queries for SQL injection prevention.

Realistic example: Create item with auth middleware (Firebase Admin SDK integration)

import express from 'express';
import admin from 'firebase-admin';
import { Pool } from 'pg';

const app = express();
app.use(express.json());

admin.initializeApp({
  credential: admin.credential.applicationDefault(),
});

const pool = new Pool();

async function authenticate(req, res, next) {
  const authHeader = req.headers.authorization;
  if (!authHeader?.startsWith('Bearer ')) return res.status(401).send({ error: 'Unauthorized' });
  const token = authHeader.substring(7);
  try {
    const decoded = await admin.auth().verifyIdToken(token);
    req.user = decoded;
    next();
  } catch {
    res.status(401).send({ error: 'Invalid token' });
  }
}

app.post('/items', authenticate, async (req, res) => {
  const userId = req.user.uid;
  const { name, description } = req.body;
  if (!name) return res.status(400).send({ error: 'Name is required' });
  const result = await pool.query(
    'INSERT INTO items (user_id, name, description) VALUES ($1, $2, $3) RETURNING *',
    [userId, name, description || null]
  );
  res.status(201).send(result.rows[0]);
});

const port = process.env.PORT || 8080;
app.listen(port, () => console.log(`Server running on port ${port}`));

Note the Firebase token verification to authenticate users, linking Firebase UID to the database foreign key.

7) Key Flows

User signup and login sequence

sequenceDiagram
  participant User
  participant Client
  participant FirebaseAuth
  participant CloudRunAPI
  participant CloudSQL

  User->>Client: Enter credentials (email/password)
  Client->>FirebaseAuth: Sign up / sign in
  FirebaseAuth-->>Client: ID token
  Client->>CloudRunAPI: Send request with ID token (Authorization header)
  CloudRunAPI->>FirebaseAuth: Validate token
  FirebaseAuth-->>CloudRunAPI: Validated token with UID
  CloudRunAPI->>CloudSQL: Query/Create user record with UID
  CloudSQL-->>CloudRunAPI: User data
  CloudRunAPI-->>Client: User session established

Create item sequence

sequenceDiagram
  participant User as User
  participant Client as Web/Mobile
  participant API as Cloud Run API
  participant DB as Cloud SQL

  User->>Client: Interact with UI to add new item
  Client->>API: POST /items with auth token and item data
  API->>Firebase Auth: Verify token
  Firebase Auth-->>API: Token Valid with UID
  API->>DB: Insert item row with user_id and item info
  DB-->>API: Item created record
  API-->>Client: 201 Created with item data

8) Build and Release

Terraform snippet: Cloud Run + Cloud SQL + IAM role bindings

provider "google" {
  project = var.project_id
  region  = var.region
}

resource "google_sql_database_instance" "postgres" {
  name             = "smallscale-postgres"
  database_version = "POSTGRES_15"
  region           = var.region

  settings {
    tier = "db-f1-micro" # cost optimized, suitable for small apps
    ip_configuration {
      ipv4_enabled = false
      private_network = var.vpc_network
    }
  }
}

resource "google_sql_database" "db" {
  name     = "appdb"
  instance = google_sql_database_instance.postgres.name
}

resource "google_cloud_run_service" "api" {
  name     = "smallscale-api"
  location = var.region

  template {
    spec {
      containers {
        image = var.api_image
        env = [
          { name = "DATABASE_URL", value = "postgresql://${var.db_user}:${var.db_password}@${google_sql_database_instance.postgres.connection_name}/appdb" }
        ]
      }
    }
  }
  traffic { percent = 100, latest_revision = true }
  autogenerate_revision_name = true
}

resource "google_project_iam_member" "cloud_run_sql_client" {
  project = var.project_id
  role    = "roles/cloudsql.client"
  member  = "serviceAccount:${google_cloud_run_service.api.name}-svc@${var.project_id}.iam.gserviceaccount.com"
}

GitHub Actions CI/CD pipeline snippet

name: CI/CD Pipeline
on:
  push:
    branches:
      - main

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Setup Node.js
        uses: actions/setup-node@v3
        with:
          node-version: "18"
      - name: Install dependencies
        run: npm ci
      - name: Run unit tests
        run: npm test
      - name: Build Docker image
        run: docker build -t gcr.io/${{ secrets.GCP_PROJECT }}/smallscale-api:latest .
      - name: Authenticate GCP
        uses: google-github-actions/auth@v1
        with:
          token_format: "access_token"
          workload_identity_provider: ${{ secrets.WORKLOAD_IDENTITY_PROVIDER }}
          service_account: ${{ secrets.SERVICE_ACCOUNT_EMAIL }}
      - name: Push image to Container Registry
        run: |
          docker push gcr.io/${{ secrets.GCP_PROJECT }}/smallscale-api:latest
      - name: Deploy to Cloud Run
        run: |
          gcloud run deploy smallscale-api \
            --image gcr.io/${{ secrets.GCP_PROJECT }}/smallscale-api:latest \
            --region us-central1 \
            --platform managed \
            --quiet

Test strategy

Test LevelFocusToolsNotes
Unit testsBusiness logic, database access layersJest, SupertestMock dependencies, database mocking
Integration testsAPI endpoints with Cloud SQLSupertest + real/test DBUse ephemeral DB instances or Dockerized Postgres
Contract testsFirebase Auth token verification mockFirebase Admin SDK mockEnsure auth contract preserved
Load testsValidate handling of up to ~50 rpsk6, ArtillerySimulate load before releasing

9) Observability

What to log

  • Incoming HTTP request traces (method, path, user_id from Firebase token)
  • Authentication success/failure events
  • Database query errors, transaction commit statuses
  • Cloud Run container start/stop events
  • Detailed error stack traces on failures

Structured log example (JSON)

{
  "timestamp": "2026-10-30T12:34:56.789Z",
  "severity": "INFO",
  "trace": "projects/my-project/traces/abc123def456",
  "httpRequest": {
    "requestMethod": "POST",
    "requestUrl": "/items",
    "status": 201,
    "userAgent": "Mozilla/5.0"
  },
  "auth": {
    "user_id": "firebase:uid123"
  },
  "message": "Item created successfully",
  "item_id": 42
}

Key metrics (RED for API; USE for Cloud SQL)

MetricWhat to measureTarget / Alert condition
RequestsTotal number of incoming API requestsBaseline dependent, alert on >100 rps sustained or drop below 95% request count expected
ErrorsRequest failures (4xx + 5xx)Alert on error rate >2% over 5 min
DurationAPI request latency (p95)Alert if >500ms sustained
CPU usage% CPU busy on Cloud SQL and Cloud RunAlert >70% sustained over 10m
Memory usageCloud Run container memoryAlert >90% memory saturation
Disk I/OCloud SQL disk IO percentageAlert on sustained high IO causing slowdown

OpenTelemetry tracing example (Node.js)

import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node';
import { SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base';
import { ConsoleSpanExporter } from '@opentelemetry/sdk-trace-base';

const provider = new NodeTracerProvider();

/**
 * Register exporter and processor
 * For production, replace ConsoleSpanExporter with a cloud exporter, e.g. Google Cloud Trace
 */
provider.addSpanProcessor(new SimpleSpanProcessor(new ConsoleSpanExporter()));
provider.register();

export const tracer = provider.getTracer('smallscale-cloudrun-api');

Add spans around important operations (e.g., DB queries, Firebase token verification) to create detailed distributed traces.

SLI/SLO examples

SLITarget (SLO)Description
API Availability99.9% uptime/monthHTTP 200-299 responses
API Latency95th percentile < 500msMeasured at Cloud Run service
Authentication Success99.9% valid token verificationFirebase Auth token verification
Database Availability99.9% uptimeCloud SQL instance availability

Alerts worth paging

  • API error rate > 5% over 5 min
  • Autoscaling failures / Cloud Run container crash loops
  • Cloud SQL unavailable or high CPU ready state > 5 min
  • Firebase Auth token validation degraded (rare)

10) Security and Compliance

  • Authentication: Firebase Auth handles user management and token issuance—no passwords or user secrets stored in the backend.

  • Authorization: Enforce roles via claims in Firebase tokens and application logic for API endpoints.

  • Network security: Cloud SQL instance accessed via private IP only; Cloud Run runs in VPC connector with no public direct DB access.

  • Data encryption: Cloud SQL data encrypted at rest and in transit by GCP defaults.

  • Secret management: Use GCP Secret Manager for DB credentials injected into Cloud Run environment variables.

  • Least privilege: Use minimal IAM roles, granting Cloud Run service account only Cloud SQL Client role.

  • Compliance: Ensure user data handling aligns with GDPR if applicable, leverage Firebase's compliant identity services.

  • CORS: Restrict API access to allowed domains only via Cloud Run ingress settings or HTTP middleware.

11) Cost: Monthly Estimate (Assumptions)

ServiceEstimated UsageMonthly Cost Estimate (USD)Notes
Cloud Run~50k requests/month, avg 256 MiB RAM, 1 vCPU~$60Based on ~50 rps peaks with idle scaling
Cloud SQL (db-f1-micro, 10 GB storage)Persistent storage + 1 instance~$45Includes storage + backups
Firebase Auth1000 monthly active users~$20Free tier generous; estimate assumes social auth usage
Network EgressMinimal (<10 GB)~$5In-region egress minimal
Cloud Logging & MonitoringModerate daily log, traces volume~$10Lightweight sampling

Total Approximate Monthly Cost: $140

12) Failure Modes, Resilience, and Disaster Recovery

  • Cloud Run failure: Auto-restart and multiple instances ensure high availability; implement exponential backoff on client retries.

  • Cloud SQL failure: Use daily automated backups; enable PITR (point-in-time recovery) within cost limits.

  • Firebase Auth outage: Cached tokens valid for 1 hour reduce impact; build graceful reject or offline modes.

  • Network partitions: Design API clients to handle transient failures and retry gracefully (idempotent POST logic).

  • Data consistency: Use PostgreSQL ACID guarantees; avoid distributed transactions to maintain simplicity.

  • Disaster recovery: Periodic export of database backups to GCS; test restore procedures quarterly.

13) Evolving to the Next Scale

When usage exceeds roughly:

  • 1,000 daily active users or >50 RPS sustained, consider:

    • Adding Cloud Memorystore (Redis) caching layer to reduce SQL load.

    • Splitting monolithic API into microservices on Cloud Run or GKE.

    • Introducing Pub/Sub for async processing of longer-running tasks.

    • Multi-region deployments with Cloud SQL read replicas for global latency reduction.

    • Adding logging sampling or external tracing backend (e.g., Google Cloud Trace, Datadog).

    • Using Firebase's advanced identity features for stricter compliance (MFA, user data export).

  • Database scale-up options:

    • Moving from db-f1-micro to db-g1-small or larger Cloud SQL tiers.

    • Adding read replicas for analytic queries.

  • Cost control may shift to reserved instances or committed use discounts.

14) Phased Implementation Plan

PhaseDescriptionDeliverablesDuration
1. PrototypeBuild minimal REST API, Firebase Auth integration, simple DB schemaMinimal API, simple Cloud Run deploy1-2 weeks
2. Feature completeAdd full CRUD, role-based auth, production-ready error handlingFull API, tests, infra as code2-3 weeks
3. Performance & observabilityIntegrate structured logging, tracing, monitoring; rehearse load testsLogging, OpenTelemetry, alerting1-2 weeks
4. Security & complianceHarden auth, add secret management, review IAM & network policiesSecurity audit, secret rotation1 week
5. Production launchDeploy to production with CI/CD pipeline, 24/7 monitoring setupRelease pipeline, runbooks1 week
6. Scale monitoring & iterationMonitor traffic growth, tune DB, plan for caching or scalingOperational dashboardsOngoing

This detailed blueprint provides experienced engineers with a production-ready small-scale GCP architecture leveraging Cloud Run, Cloud SQL, and Firebase Auth. It balances simplicity, cost, and operational excellence, serving as a strong foundation for startup MVPs and small teams aiming to build scalable cloud-native applications.