從 CDN 提供捆綁的 Firestore 內容

許多應用程式在首頁加載時向所有用戶提供相同的內容。例如,新聞網站可能會顯示最新的故事,或者電子商務網站可能會顯示最暢銷的商品。

如果此內容由 Cloud Firestore 提供,則每個使用者在載入應用程式時都會發出新的查詢以獲得相同的結果。由於這些結果不會在用戶之間緩存,因此應用程式比實際需要的速度更慢且成本更高。

解決方案:捆綁

Cloud Firestore 套裝組合可讓您使用 Firebase Admin SDK 從後端的常見查詢結果組裝資料包,並提供這些快取在 CDN 上的預先計算的 Blob。這將為您的用戶帶來更快的首次載入體驗,並降低您的 Cloud Firestore 查詢成本。

在本指南中,我們將使用 Cloud Functions 產生捆綁包,並使用 Firebase 託管來動態快取和提供捆綁包內容。有關捆綁包的更多資訊可在指南中找到。

首先建立一個簡單的公共 HTTP 函數來查詢 50 個最新的「故事」並將結果作為一個套件提供。

Node.js
exports.createBundle = functions.https.onRequest(async (request, response) => {
  // Query the 50 latest stories
  const latestStories = await db.collection('stories')
    .orderBy('timestamp', 'desc')
    .limit(50)
    .get();

  // Build the bundle from the query results
  const bundleBuffer = db.bundle('latest-stories')
    .add('latest-stories-query', latestStories)
    .build();

  // Cache the response for up to 5 minutes;
  // see https://firebase.google.com/docs/hosting/manage-cache
  response.set('Cache-Control', 'public, max-age=300, s-maxage=600');

  response.end(bundleBuffer);
});
      
爪哇

package com.example;

import com.google.auth.oauth2.GoogleCredentials;
import com.google.cloud.firestore.Firestore;
import com.google.cloud.firestore.FirestoreBundle;
import com.google.cloud.firestore.Query.Direction;
import com.google.cloud.firestore.QuerySnapshot;
import com.google.cloud.functions.HttpFunction;
import com.google.cloud.functions.HttpRequest;
import com.google.cloud.functions.HttpResponse;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.cloud.FirestoreClient;
import java.io.BufferedWriter;
import java.io.IOException;

public class ExampleFunction implements HttpFunction {

  public static FirebaseApp initializeFirebase() throws IOException {
    if (FirebaseApp.getApps().isEmpty()) {
      FirebaseOptions options = FirebaseOptions.builder()
          .setCredentials(GoogleCredentials.getApplicationDefault())
          .setProjectId("YOUR-PROJECT-ID")
          .build();

      FirebaseApp.initializeApp(options);
    }

    return FirebaseApp.getInstance();
  }

  @Override
  public void service(HttpRequest request, HttpResponse response) throws Exception {
    // Get a Firestore instance
    FirebaseApp app = initializeFirebase();
    Firestore db = FirestoreClient.getFirestore(app);

    // Query the 50 latest stories
    QuerySnapshot latestStories = db.collection("stories")
        .orderBy("timestamp", Direction.DESCENDING)
        .limit(50)
        .get()
        .get();

    // Build the bundle from the query results
    FirestoreBundle bundle = db.bundleBuilder("latest-stores")
        .add("latest-stories-query", latestStories)
        .build();

    // Cache the response for up to 5 minutes
    // see https://firebase.google.com/docs/hosting/manage-cache
    response.appendHeader("Cache-Control", "public, max-age=300, s-maxage=600");

    // Write the bundle to the HTTP response
    BufferedWriter writer = response.getWriter();
    writer.write(new String(bundle.toByteBuffer().array()));
  }
}
      

接下來,透過修改firebase.json配置 Firebase Hosting 以提供並快取此雲端功能。透過此配置,Firebase Hosting CDN 將根據雲端功能設定的快取設定提供捆綁包內容。當快取過期時,會再次觸發該函數來刷新內容。

firebase.json
{
  "hosting": {
    // ...
    "rewrites": [{
      "source": "/createBundle",
      "function": "createBundle"
    }]
  },
  // ...
}

最後,在您的 Web 應用程式中,從 CDN 取得捆綁的內容並將其載入到 Firestore SDK 中。

// If you are using module bundlers.
import firebase from "firebase/app";
import "firebase/firestore";
import "firebase/firestore/bundle" // This line enables bundle loading as a side effect.

async function fetchFromBundle() {
  // Fetch the bundle from Firebase Hosting, if the CDN cache is hit the 'X-Cache'
  // response header will be set to 'HIT'
  const resp = await fetch('/createBundle');

  // Load the bundle contents into the Firestore SDK
  await db.loadBundle(resp.body);

  // Query the results from the cache
  // Note: omitting "source: cache" will query the Firestore backend.
  
  const query = await db.namedQuery('latest-stories-query');
  const storiesSnap = await query.get({ source: 'cache' });

  // Use the results
  // ...
}

預計節省

考慮一個新聞網站,每天有 100,000 個用戶,每個用戶在初始加載時加載相同的 50 個熱門故事。如果沒有任何緩存,這將導致每天從 Cloud Firestore 讀取 50 x 100,000 = 5,000,000 份文件。

現在假設該網站採用上述技術並將這 50 個結果快取最多 5 分鐘。因此,不是為每個使用者載入查詢結果,而是每小時準確載入 12 次結果。無論有多少使用者造訪該站點,對 Cloud Firestore 的查詢數量都保持不變。該頁面每天將使用 12 x 24 x 50 = 14,400 次文件讀取,而不是 5,000,000 次文件讀取。 Firebase 託管和雲端功能的少量額外成本很容易被 Cloud Firestore 成本節省所抵銷。

雖然開發者從成本節省中受益,但最大的受益者是使用者。從 Firebase Hosting CDN(而不是直接從 Cloud Firestore)載入這 50 個文件可以輕鬆地將頁面內容載入時間縮短 100-200 毫秒或更多。研究一再表明,快速的頁面意味著更快樂的用戶。