1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Firebase Cloud Functionsのレスポンス速度を上げる方法

Posted at

はじめに

Firebase Cloud Functions は便利なサーバーレス機能ですが、私のプロジェクトにて、ユーザー体験を損なうレベルの遅延が発生していました。
今回はレスポンス速度を劇的に速くすることができたのでその内容を記事にします。

結論、リージョンをデフォルトの us-central1(アイオワ)から asia-northeast1(東京)へ変更するだけで、レスポンス時間が早くなりました。

開発者ツールで見てみる

Supabaseからデータを取得する処理が書かれた関数で0.87秒もかかっています。
スクリーンショット 2025-04-13 2.27.45.png

改善後は0.05秒まで早くなりました
スクリーンショット 2025-04-13 2.03.16.png

速度改善後のコード実装例

1. バックエンド側 (Cloud Functions)

Cloud Functions V2 APIを使用した場合のリージョン設定方法です:

setGlobalOptions({
  region: "asia-northeast1",
})

を入れることにより、リージョンを変更できます。

import { setGlobalOptions } from 'firebase-functions/v2';
import { onCall } from "firebase-functions/v2/https";
setGlobalOptions({
  region: "asia-northeast1", // デフォルトの us-central1 から東京リージョンに変更
})

export const getData = onCall(
  {cors: true,}, 
  async () => {
    const { data, error } = await supabaseClient
      .from('users')
      .select('*')
    }
    return data
  }
)

特定の関数だけ異なるリージョンを指定したい場合は、個別に設定することもできます:

export const getData = onCall.region('europe-west1')(
  {cors: true},
  async (request) => {
    // 関数の処理...
  }
)

2. フロントエンド側 (Nuxtアプリの例)

クライアント側からのCloud Functions呼び出し方法です:

import { initializeApp } from 'firebase/app'
import { defineNuxtPlugin } from '#app'
import { getFunctions, httpsCallable } from 'firebase/functions'

export default defineNuxtPlugin(async () => {
  const firebaseConfig = {
    apiKey: fbApiKey,
    authDomain: fbAuthDomain,
    projectId: fbProjectId,
    storageBucket: fbStorageBucket,
    messagingSenderId: fbMessagingSenderId,
    appId: fbAppId,
    measurementId: fbMesurementId
  }
  const app = initializeApp(firebaseConfig)

  const cloudFunction = getFunctions(app, 'asia-northeast1') // asia-northeast1を指定

  const getExternalData = httpsCallable(cloudFunction, 'getExternalData')
  
  const result = await getExternalData({
    resourceName: 'items',
    limit: 5
  }) 
  console.log('データ取得成功:', result.data)
})

まとめ

Firebase Cloud Functionsのパフォーマンス問題は、多くの場合適切なリージョン設定だけで大幅に改善できます。
私の実装では、東京リージョンへの変更だけでレスポンス時間が速くなり、ユーザー体験が格段に向上しました。

追伸

私の環境で初回呼び出しのみレスポンスが遅い状況が発生しています。
Cloud Functions関数はアイドル状態で待機し、呼び出されると起動している状態が続くようです。
ここの改善ができたらまた記事にしようと思います。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?