Bir CDN'den paketlenmiş Firestore içeriği sunun

Birçok uygulama, ilk sayfa yüklemesinde tüm kullanıcılara aynı içeriği sunar. Örneğin bir haber sitesi en son haberleri gösterebilir veya bir e-ticaret sitesi en çok satan ürünleri gösterebilir.

Bu içerik Cloud Firestore'dan sunuluyorsa her kullanıcı, uygulamayı yüklediğinde aynı sonuçlar için yeni bir sorgu düzenleyecektir. Bu sonuçlar kullanıcılar arasında önbelleğe alınmadığı için uygulama olması gerekenden daha yavaş ve daha pahalıdır.

Çözüm: Paketler

Cloud Firestore paketleri, Firebase Admin SDK'yı kullanarak arka uçtaki ortak sorgu sonuçlarından veri paketleri oluşturmanıza ve bir CDN'de önbelleğe alınan bu önceden hesaplanmış blob'ları sunmanıza olanak tanır. Bu, kullanıcılarınıza çok daha hızlı bir ilk yükleme deneyimi sağlar ve Cloud Firestore sorgu maliyetlerinizi azaltır.

Bu kılavuzda paketler oluşturmak için Bulut İşlevlerini, paket içeriğini dinamik olarak önbelleğe almak ve sunmak için Firebase Hosting'i kullanacağız. Paketler hakkında daha fazla bilgiyi kılavuzlarda bulabilirsiniz.

Öncelikle en son 50 "hikayeyi" sorgulamak ve sonucu bir paket olarak sunmak için basit bir genel HTTP işlevi oluşturun.

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);
});
      
Java

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()));
  }
}
      

Daha sonra firebase.json dosyasını değiştirerek bu Bulut İşlevini sunacak ve önbelleğe alacak şekilde Firebase Hosting'i yapılandırın. Bu yapılandırmayla Firebase Hosting CDN, paket içeriğini Bulut İşlevi tarafından belirlenen önbellek ayarlarına göre sunacaktır. Önbelleğin süresi dolduğunda, işlevi yeniden tetikleyerek içeriği yeniler.

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

Son olarak web uygulamanızda, paketlenmiş içeriği CDN'den alın ve Firestore SDK'ya yükleyin.

// 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
  // ...
}

Tahmini Tasarruflar

Günde 100.000 kullanıcıya ulaşan ve her kullanıcının ilk yüklemede aynı 50 önemli haberi yüklediği bir haber sitesini düşünün. Herhangi bir önbelleğe alma olmadan bu, Cloud Firestore'dan günde 50 x 100.000 = 5.000.000 belge okumasıyla sonuçlanır.

Şimdi sitenin yukarıdaki tekniği benimsediğini ve bu 50 sonucu 5 dakikaya kadar önbelleğe aldığını varsayalım. Yani her kullanıcı için sorgu sonuçlarının yüklenmesi yerine, sonuçlar saatte tam 12 kez yüklenir. Siteye kaç kullanıcı gelirse gelsin Cloud Firestore'a yapılan sorguların sayısı aynı kalır. Bu sayfada 5.000.000 belge okuması yerine günde 12 x 24 x 50 = 14.400 belge okuması kullanılacaktır. Firebase Barındırma ve Bulut İşlevleri için küçük ek maliyetler, Cloud Firestore maliyet tasarruflarıyla kolayca dengelenir.

Maliyet tasarruflarından geliştirici yararlanırken, en büyük yararlanan ise kullanıcı oluyor. Bu 50 belgenin doğrudan Cloud Firestore yerine Firebase Hosting CDN'sinden yüklenmesi, sayfanın içerik yükleme süresini kolayca 100-200 ms veya daha fazla kısaltabilir. Araştırmalar, hızlı sayfaların daha mutlu kullanıcılar anlamına geldiğini defalarca göstermiştir.