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.
| Assumption | Value | Notes |
|---|---|---|
| Daily active users | ~1,000 | Consistent daily engagement |
| Peak requests/sec | ≤ 50 | Bursts handled with autoscaling |
| Data volume | ≤ 10 GB | Typical OLTP dataset |
| Team size | 1-3 engineers | Full-stack developers preferred |
| Budget | <$300/month (GCP costs) | Cost-sensitive, pay-as-you-go |
| Deployment region | Single region (us-central1 assumed) | Simplicity and latency optimized |
2) Requirements
Functional requirements
| ID | Requirement | Priority |
|---|---|---|
| FR1 | User signup/login/logout with email/password and social login via Firebase Auth | Critical |
| FR2 | RESTful HTTP API to create/read/update/delete (CRUD) user-related data | Critical |
| FR3 | Role-based user permissions (e.g., admin, standard user) | Important |
| FR4 | Serverless, scalable backend with near zero-maintenance | Critical |
| FR5 | Persist relational data with ACID guarantees and schema migrations | Critical |
Non-functional requirements
| ID | Requirement | Priority |
|---|---|---|
| NFR1 | Low latency responses (API < 500ms p95) | Important |
| NFR2 | High availability (99.9%) | Important |
| NFR3 | Secure authentication with Firebase | Critical |
| NFR4 | Cost optimized for <$300/month GCP spend | Critical |
| NFR5 | Infrastructure-as-code for reproducible deploys | Important |
| NFR6 | Observability with structured logs, metrics, tracing | Important |
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
endSimplified 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
| Component | GCP Service | AWS Equivalent | Azure Equivalent | Notes |
|---|---|---|---|---|
| User Authentication | Firebase Auth | Amazon Cognito | Azure AD B2C | Managed identity provider with social login |
| Stateless API Backend | Cloud Run | AWS Lambda + API Gateway | Azure Functions + API Management | Serverless container-based compute |
| Relational DB | Cloud SQL (PostgreSQL) | Amazon RDS (PostgreSQL) | Azure Database for PostgreSQL | Fully managed relational service |
| Infrastructure as Code | Terraform / Cloud Deployment Manager | Terraform / CloudFormation | Terraform / Bicep | IaC tool of choice |
| Observability / Tracing | Cloud Logging, Cloud Monitoring, OpenTelemetry SDK | CloudWatch + X-Ray | Azure Monitor + Application Insights | Native 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 Level | Focus | Tools | Notes |
|---|---|---|---|
| Unit tests | Business logic, database access layers | Jest, Supertest | Mock dependencies, database mocking |
| Integration tests | API endpoints with Cloud SQL | Supertest + real/test DB | Use ephemeral DB instances or Dockerized Postgres |
| Contract tests | Firebase Auth token verification mock | Firebase Admin SDK mock | Ensure auth contract preserved |
| Load tests | Validate handling of up to ~50 rps | k6, Artillery | Simulate 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)
| Metric | What to measure | Target / Alert condition |
|---|---|---|
| Requests | Total number of incoming API requests | Baseline dependent, alert on >100 rps sustained or drop below 95% request count expected |
| Errors | Request failures (4xx + 5xx) | Alert on error rate >2% over 5 min |
| Duration | API request latency (p95) | Alert if >500ms sustained |
| CPU usage | % CPU busy on Cloud SQL and Cloud Run | Alert >70% sustained over 10m |
| Memory usage | Cloud Run container memory | Alert >90% memory saturation |
| Disk I/O | Cloud SQL disk IO percentage | Alert 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
| SLI | Target (SLO) | Description |
|---|---|---|
| API Availability | 99.9% uptime/month | HTTP 200-299 responses |
| API Latency | 95th percentile < 500ms | Measured at Cloud Run service |
| Authentication Success | 99.9% valid token verification | Firebase Auth token verification |
| Database Availability | 99.9% uptime | Cloud 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)
| Service | Estimated Usage | Monthly Cost Estimate (USD) | Notes |
|---|---|---|---|
| Cloud Run | ~50k requests/month, avg 256 MiB RAM, 1 vCPU | ~$60 | Based on ~50 rps peaks with idle scaling |
| Cloud SQL (db-f1-micro, 10 GB storage) | Persistent storage + 1 instance | ~$45 | Includes storage + backups |
| Firebase Auth | 1000 monthly active users | ~$20 | Free tier generous; estimate assumes social auth usage |
| Network Egress | Minimal (<10 GB) | ~$5 | In-region egress minimal |
| Cloud Logging & Monitoring | Moderate daily log, traces volume | ~$10 | Lightweight 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
| Phase | Description | Deliverables | Duration |
|---|---|---|---|
| 1. Prototype | Build minimal REST API, Firebase Auth integration, simple DB schema | Minimal API, simple Cloud Run deploy | 1-2 weeks |
| 2. Feature complete | Add full CRUD, role-based auth, production-ready error handling | Full API, tests, infra as code | 2-3 weeks |
| 3. Performance & observability | Integrate structured logging, tracing, monitoring; rehearse load tests | Logging, OpenTelemetry, alerting | 1-2 weeks |
| 4. Security & compliance | Harden auth, add secret management, review IAM & network policies | Security audit, secret rotation | 1 week |
| 5. Production launch | Deploy to production with CI/CD pipeline, 24/7 monitoring setup | Release pipeline, runbooks | 1 week |
| 6. Scale monitoring & iteration | Monitor traffic growth, tune DB, plan for caching or scaling | Operational dashboards | Ongoing |
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.