Google Cloud

Cloud Run + Firestore で SaaS バックエンド構築チュートリアル

2026-05-24
NicheeLab編集部

Cloud Run + Firestore はモダン SaaS バックエンドの定番構成です。 サーバレス + 完全マネージド + 無料枠寛大で、個人開発から本格 SaaS まで対応可能。本記事ではマルチテナント設計から課金まで実装例を網羅します。

アーキテクチャ全体

Web/Mobile (React/Flutter)
        |
   Firebase Auth (認証)
        |
   Firebase Hosting (フロント CDN) → Cloud Run (API)
                                          |
                                          v
                              Firestore (主 DB)
                              Cloud Storage (ファイル)
                              Pub/Sub (非同期処理)
                              Cloud Tasks (遅延処理)
                              Stripe Webhook → Cloud Run
                              SendGrid (メール)
                              Cloud Scheduler (定期バッチ)

Step 1: Firestore マルチテナント設計

// 構造
/tenants/{tenant_id}
  /users/{user_id}
  /subscriptions/{sub_id}
  /resources/{resource_id}

// または
/tenants/{tenant_id}/{collection}/{doc}

// Security Rules (例)
match /tenants/{tenant_id}/{document=**} {
  allow read, write: if request.auth.token.tenant_id == tenant_id;
}

Step 2: Cloud Run API (Node.js / Express)

import express from "express";
import { initializeApp, applicationDefault } from "firebase-admin/app";
import { getAuth } from "firebase-admin/auth";
import { getFirestore } from "firebase-admin/firestore";

initializeApp({ credential: applicationDefault() });
const app = express();
app.use(express.json());

// Firebase Auth 検証 Middleware
app.use(async (req, res, next) => {
  const idToken = req.headers.authorization?.split("Bearer ")[1];
  if (!idToken) return res.status(401).send("Unauthorized");
  try {
    const decoded = await getAuth().verifyIdToken(idToken);
    req.user = decoded;
    next();
  } catch (e) {
    res.status(401).send("Invalid token");
  }
});

app.post("/api/posts", async (req, res) => {
  const db = getFirestore();
  const ref = await db.collection(`tenants/${req.user.tenant_id}/posts`).add({
    title: req.body.title,
    authorId: req.user.uid,
    createdAt: new Date(),
  });
  res.json({ id: ref.id });
});

app.listen(process.env.PORT || 8080);

Step 3: Stripe 課金連携

import Stripe from "stripe";
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);

// Checkout Session 作成
app.post("/api/checkout", async (req, res) => {
  const session = await stripe.checkout.sessions.create({
    mode: "subscription",
    customer_email: req.user.email,
    line_items: [{ price: "price_xxx", quantity: 1 }],
    success_url: "https://app.example.com/success",
    cancel_url: "https://app.example.com/cancel",
    client_reference_id: req.user.tenant_id,
  });
  res.json({ url: session.url });
});

// Webhook 受信
app.post("/webhooks/stripe", express.raw({ type: "application/json" }),
  async (req, res) => {
    const event = stripe.webhooks.constructEvent(
      req.body,
      req.headers["stripe-signature"]!,
      process.env.STRIPE_WEBHOOK_SECRET!
    );

    if (event.type === "checkout.session.completed") {
      const session = event.data.object;
      await getFirestore()
        .collection(`tenants/${session.client_reference_id}/subscriptions`)
        .doc("current")
        .set({ status: "active", stripeCustomerId: session.customer });
    }
    res.json({ received: true });
  }
);

Step 4: Cloud Scheduler バッチ

# Cloud Scheduler → Cloud Run Job 起動
gcloud scheduler jobs create http daily-backup \
  --schedule="0 3 * * *" \
  --uri="https://my-api.run.app/jobs/backup" \
  --http-method=POST \
  --oidc-service-account-email=scheduler-sa@PROJECT.iam.gserviceaccount.com

Step 5: Firestore バックアップ

# Cloud Scheduler → Cloud Functions → Firestore Export
gcloud firestore export gs://my-backup-bucket/${TIMESTAMP} \
  --collection-ids=tenants

# Lifecycle Rule で 90 日後に Archive、365 日後に削除

Step 6: 監視・アラート

  • Cloud Monitoring SLO: 99.9% Availability + P95 < 500ms
  • Burn Rate Alert: Fast burn (14.4x, 1h) → PagerDuty
  • Cloud Logging: Structured Logging (jsonPayload)
  • Error Reporting: Crash 自動グルーピング
  • Uptime Check: 5 拠点から HTTP 監視

料金例 (月 10K MAU)

サービス月額
Cloud Run (~5M req/月)~$15
Firestore (~2M read + 500K write)~$5
Cloud Storage (10 GB)~$0.20
Firebase Auth (10K MAU)無料
Firebase Hosting~$0 (無料枠内)
Cloud Logging (10 GB)無料
Cloud Scheduler (1 ジョブ)無料
合計~$20/月

ベストプラクティス

  • Firebase Auth + Custom Claims (tenant_id / role)
  • Firestore Security Rules でテナント分離強制
  • Min Instances 0 (Cold Start 許容で月額削減)
  • 重要 API のみ Min Instances 1+
  • Secret Manager で API キー管理
  • Workload Identity で SA キー不要
  • Stripe Webhook の冪等性 (event.id で重複処理排除)
  • Firestore Composite Index 事前定義

Cloud Run + Firestore で SaaS は作れる?

可能。スケール自動 + 完全マネージド + リアルタイム DB + 無料枠寛大で、月数千ユーザーまで月額数千円で運用可能。

認証は何を使う?

Firebase Authentication (Google / Email / Apple / SAML 等) が標準。Cloud Run の前段に IAP も併用可能。

マルチテナント設計は?

Firestore で Collection を tenant_id でパーティション、Security Rules で IAM 強制。Cloud Run は単一サービスで分離。

スケールはどこまで?

Cloud Run = 1000 インスタンス自動、Firestore = 10K writes/s/Collection、Cloud Storage = 無制限。SaaS で 100K MAU まで一般的に対応可。

サブスクリプション課金は?

Stripe / Pay.jp / Paddle が標準。Webhook を Cloud Run で受け取り Firestore に状態同期。

メール送信は?

SendGrid / Postmark / Resend / Amazon SES などの SaaS が標準。Firebase Extensions で SendGrid 連携テンプレあり。

バックアップは?

Firestore は Managed Export を Cloud Scheduler で日次実行 → GCS にエクスポート。Point-in-time Recovery (7 日) も自動。

Vercel / Netlify と比べてどう?

フロント = Vercel / Netlify + バック = Cloud Run + DB = Firestore がモダンな構成。フロントは Firebase Hosting (CDN 内蔵) でも対応可能。

関連記事・SaaS 開発

Cloud Scheduler + Cloud Functions/Run で定期バッチ自動化チュートリアル (GCP)

Google Cloud Scheduler と Cloud Functions / Cloud Run Job で定期バッチ自動化。cron 形式、OIDC 認証、リトライ、Dead Letter、Workflows 連携、Cloud Run Job 並列実行を 2026 年最新版で解説。

GCP Professional Cloud Developer (PCD) 完全ガイド|Cloud Run・GKE・CI/CD・APM

Google Cloud Professional Cloud Developer の試験範囲、Cloud Run / GKE / Cloud Build / Cloud Trace、AWS DVA / Azure AZ-204 比較、学習ロードマップを徹底解説。

Cloud Deploy 完全ガイド|Canary・Blue-Green・GKE/Cloud Run プログレッシブデプロイ (GCP)

Google Cloud Cloud Deploy の全機能解説。Delivery Pipeline、Canary / Blue-Green、Approval Gate、Verify、Skaffold 統合、GKE / Cloud Run / Anthos 対応、AWS CodeDeploy / ArgoCD 比較を網羅。

GCP Professional Cloud Network Engineer (PCNE) 完全ガイド|VPC・Interconnect・Load Balancing

Google Cloud Professional Cloud Network Engineer の試験範囲、VPC / Cloud Interconnect / Cloud Load Balancing / Cloud Armor、AWS ANS・Azure AZ-700 比較を詳解。

※ Google Cloud、Firebase は Google LLC、Stripe は Stripe, Inc. の登録商標です。

この記事で学んだ内容を問題で確認しましょう

16,000問以上の問題で実力チェック

GCP 試験対策ページを見る
この記事の著者

NicheeLab編集部

データエンジニアリング・クラウド資格の専門家。Databricks・Snowflake等の認定資格を保有し、実務経験に基づいた問題作成・解説を行っています。NicheeLab運営。


関連記事
Google Cloud

Google Cloud (GCP) 認定資格ロードマップ 2026 完全版|全 15 試験を体系化

Google Cloud 認定資格 全 15 試験 (Foundational 2 + Associate 3 + Pr...

Google Cloud

Cloud Digital Leader (CDL) 完全ガイド|出題範囲・学習リソース・合格戦略

Google Cloud Cloud Digital Leader (CDL) の完全ガイド。6 ドメイン 92 bul...

Google Cloud

Generative AI Leader (GAIL) 完全ガイド|Google Cloud 生成 AI 認定

Google Cloud Generative AI Leader (GAIL、2025-05-14 リリース) の完全...

Google Cloud

Vertex AI 入門|Google Cloud 統合 ML プラットフォームの全機能

Google Cloud Vertex AI の入門解説。Vertex AI Studio / Agent Builde...

Google Cloud

GCP Associate Cloud Engineer (ACE) 完全ガイド|試験範囲・受験料・学習ロードマップ

Google Cloud Associate Cloud Engineer (ACE) の試験範囲・受験料 125 US...

Google Cloudの記事一覧 (102件)
© 2026 NicheeLab All rights reserved.