Firestore, Memorystore and BigQuery for PCD: leaderboards, offline caching and resilient Redis

13 min read

Section 1 of the Professional Cloud Developer exam (~32%) includes 1.1 "implementing caching solutions (e.g., Memorystore)" and 1.3 "selecting the appropriate storage system based on the volume of data and performance requirements"; section 4.1 (~21%) covers managing connections to datastores. The three newest questions in the bank all revolve around a game: picking stores for a leaderboard, player profiles and clickstream; a leaderboard that is slow on Cloud SQL; and a Redis client that keeps getting disconnected. This post walks through how Firestore, Memorystore and BigQuery behave, with code, gcloud commands, a decision table and example questions. For the exam format and scope, see the PCD study guide; Cloud Run vs GKE, Pub/Sub and authentication are covered in the Cloud Run, GKE and Pub/Sub decision tables post.

Key takeaways

  • "Offline caching on the user's device" means Firestore through the Firebase SDKs (Android, Apple, web). Server-side client libraries have no offline persistence.
  • A leaderboard that must rank many simultaneous players fast belongs in Memorystore for Redis with a Sorted Set, not in a tuned SQL query.
  • Redis disconnections: reconnect with exponential backoff plus jitter, keep the pool bounded, use a cluster-aware client; automatic failover does not replace client-side retries.
  • Clickstream for BI goes to BigQuery, written with the Storage Write API (gRPC) or a Pub/Sub BigQuery subscription.

One game, three data types, three access patterns

A typical exam scenario: a mobile game runs as microservices on GKE and Cloud Run, and nobody knows yet how many players it will have. You need to store a leaderboard, player data (profiles, chats, news feed) and clickstream data (the trail of player actions) for BI. The requirements: easy to use, cost-effective, scalable, and supports offline caching on the user's device.

The right way to split this is by access pattern, not by the name of the data:

  • Per-player data (profiles, chat, feed): small records, flexible structure, real-time sync to the phone, usable without a connection. That fits Firestore, a serverless document database (it stores JSON-like documents).
  • The leaderboard: scores are written all the time, and players ask "who is in the top 10" and "what is my rank". The second question needs the order of every other score, so it is the hard part. An in-memory store such as Memorystore for Redis does it fastest; Firestore can do it within limits (see below).
  • Clickstream: huge numbers of small, append-only events that are later scanned in bulk for reports. That is the job of the BigQuery data warehouse.

The deciding phrase in this kind of question is offline caching on the user's device. Among the usual options (Firestore, Memorystore, Cloud SQL, Spanner, Bigtable, BigQuery), only Firestore has client SDKs that cache data on the device. Memorystore only has private IPs inside a VPC, so a phone cannot reach it directly. When the offline requirement applies to the data the player sees, putting the leaderboard in Firestore too keeps everything in one easy, pay-per-use store. When the question drops the offline requirement and stresses ranking speed, the answer moves to Memorystore. Two questions on the same topic can have different answers because of one phrase.

Spanner and Bigtable scale well too, but you pay for provisioned compute even when no one is playing. For a game with "no projections for user volume", a serverless, per-operation store like Firestore is the more sensible start.

Firestore: offline cache, real-time listeners and write limits

How offline persistence works

According to the Firestore docs, offline persistence keeps a copy of the data your app is actively using. While the device is offline, the app can still read, write, listen to and query that cached data. When the device reconnects, Firestore syncs local changes to the backend; if the same document changed several times, the last write wins. The details the exam likes:

  • It is available only in Android, Apple and web apps, through the Firebase integration. The server-side client libraries (C#, Go, Java, Node.js, PHP, Python, Ruby) do not support offline persistence.
  • It is on by default for Android and Apple, and off by default for the web, where you enable a persistent cache. On the web it is supported only in Chrome, Safari and Firefox.
  • The web cache is not cleared between sessions, so for sensitive data the docs suggest asking whether the user is on a trusted device first.
  • For Enterprise edition databases, offline persistence works with Core operations only; Pipeline operations don't support it.

A web example (modular SDK): turn on a persistent multi-tab cache and listen to the top 10 scores in real time.

import { initializeFirestore, persistentLocalCache,
  persistentMultipleTabManager, collection, query,
  orderBy, limit, onSnapshot } from "firebase/firestore";

const db = initializeFirestore(app, {
  localCache: persistentLocalCache({
    tabManager: persistentMultipleTabManager() })
});

const top10 = query(collection(db, "scores"),
  orderBy("score", "desc"), limit(10));
onSnapshot(top10, (snap) => {
  render(snap.docs.map((d) => d.data()));
});

onSnapshot is a real-time listener: the first call returns the current data, and the callback fires again every time the data changes. Offline, the listener keeps working on cached data. For chat and feeds this is the reason to pick Firestore: no hand-written WebSockets or polling.

Write limits: why a single "total" document gets congested

Firestore applies each write synchronously across a quorum (majority) of replicas before acknowledging it. The best-practices page says the maximum rate for updating one document depends on the workload; write too often to the same document and you get contention, higher latency and errors. Concrete rules from the docs:

  • Distributed counters: instead of one counter document, create N shard documents and sum them on read. Write throughput grows linearly with the number of shards, so 10 shards handle 10 times as many writes.
  • Avoid hotspots: monotonically increasing document IDs, or an indexed monotonically increasing field such as a timestamp, create hotspots. A collection with an indexed field of sequential values is limited to 500 writes per second; if you don't query on that field, exempt it from indexing. Firestore's automatic IDs are scattered and avoid this.
  • Ramp up gradually: Firestore splits key ranges based on load after a few minutes of sustained traffic; with evenly spread load, write throughput can double every few minutes. Don't slam a brand-new collection with full traffic on launch day.

Leaderboards on Firestore: top N is easy, rank is hard

The top 10 query above is fast because it uses an index. "What is my rank" means counting players with a higher score. The count() aggregation query avoids downloading documents, but the docs are clear: it scales with the size of the dataset and the index entries scanned, is billed one read per batch of up to 1,000 index entries, returns DEADLINE_EXCEEDED if it can't finish within 60 seconds, and can't be used with real-time listeners or offline queries. Instant ranking for very many players is not where Firestore shines.

Memorystore for Redis: a leaderboard with a Sorted Set

Memorystore for Redis is Redis managed by Google; data sits in memory, so access is sub-millisecond. The Memorystore overview uses exactly the gaming example: build the leaderboard with a Sorted Set (Redis keeps members ordered by score, and each member is unique), and keep frequently read player profiles in a Hash.

# Add points after a match (creates the member if new)
ZINCRBY lb:season1 120 player:8842
# Top 10, highest score first
ZRANGE lb:season1 0 9 REV WITHSCORES
# One player's rank (0 = first place)
ZREVRANK lb:season1 player:8842

Because the Sorted Set is always kept in order, a rank lookup doesn't scan the whole dataset like a SQL COUNT(*). That is why, when a question says "the leaderboard tallies top scores too slowly, many simultaneous players, the stack uses Cloud SQL for PostgreSQL, improve performance as much as possible", the answer is to move the leaderboard to Memorystore for Redis. Tuning queries, upgrading PostgreSQL or migrating to AlloyDB still leaves a relational database that has to sort and lock under concurrent writes; they help somewhat, but not "as much as possible".

Choosing a Memorystore flavor

OptionWhat the docs sayGood for
Memorystore for Redis, Basic TierStandalone instance, no replicaDev/test, a cache you can afford to lose
Memorystore for Redis, Standard TierReplica in another zone, automatic failover, 99.9% SLA, up to 300 GB, up to 5 read replicasModerate production load, one simple endpoint
Memorystore for Redis ClusterMultiple shards; each has 1 primary and 0–5 replicas spread across zones; 99.99% SLA for multi-zone HA clustersData or throughput beyond one node; horizontal scaling
Memorystore for ValkeyGoogle-managed Valkey with Cluster Mode Enabled or DisabledNew projects choosing Valkey; older questions may not mention it

Creating a Standard Tier instance and a cluster with gcloud:

gcloud redis instances create game-cache \
  --size=5 --region=us-central1 --tier=standard

gcloud redis clusters create game-lb \
  --region=us-central1 \
  --network=projects/PROJECT/global/networks/default \
  --shard-count=3 --replica-count=1

Memorystore only has private IPs. A Cloud Run service needs a path into the VPC; the docs recommend Direct VPC egress (lower latency, no connector instances to pay for) over a Serverless VPC Access connector, with a subnet of /26 or larger. Redis Cluster uses Private Service Connect, so set up networking before you create it.

gcloud run deploy leaderboard-api \
  --image=REGION-docker.pkg.dev/PROJECT/game/lb:v1 \
  --region=us-central1 \
  --network=default --subnet=default \
  --set-env-vars=REDISHOST=10.0.0.3,REDISPORT=6379

Common real mistakes: Redis calls from Cloud Run time out because VPC egress was never configured. Another is treating Redis as the only copy. Memorystore replication is asynchronous, and the docs warn that acknowledged writes can be lost during a failover. Keep the source scores in a durable database (Firestore, Cloud SQL) so you can rebuild the Sorted Set when needed.

Resilient Redis connections: backoff, jitter and failover

An app using Memorystore for Redis Cluster will lose connections now and then: maintenance, failovers, adding shards. The exam asks how to handle client disconnections "gracefully" with minimal disruption. The answer has two parts: reconnect with exponential backoff with jitter, and use a client-side cache to serve data during brief outages.

Why jitter matters

Exponential backoff means waiting longer between retries (100 ms, 200 ms, 400 ms… up to a cap). Jitter adds a random amount to each wait. Without jitter, hundreds of Pods that lost their connection at the same moment all retry at the same moment, hitting the server in waves. The Redis Cluster best-practices page describes exactly this mistake: clients that reconnect and run discovery repeatedly without backoff can leave the Redis server unresponsive for a long time with very high CPU. The docs recommend:

  • A cluster-aware client that keeps a map of hash slots to nodes and refreshes it on MOVED (for example after a failover or resharding), CLUSTERDOWN or READONLY errors, plus periodic topology refreshes.
  • A connection pool with a small, finite size so connection counts stay bounded.
  • On timeout disconnects, retry with exponential backoff and jitter.
  • The cluster's discovery endpoint for node discovery; it is highly available and load balanced across nodes. The docs recommend CLUSTER SHARDS over the deprecated CLUSTER SLOTS.
  • TCP keepalive and TCP user timeout settings to detect dead connections. The docs' example: keepalive time 30 seconds, interval 10 seconds and 3 probes reset unresponsive idle connections within a minute.

An example with redis-py (the Memorystore docs recommend version 5.1 or later): automatic retries with jittered backoff, plus a short-lived local cache as a fallback.

import time
from redis.cluster import RedisCluster
from redis.backoff import ExponentialWithJitterBackoff
from redis.retry import Retry
from redis.exceptions import ConnectionError, TimeoutError

rc = RedisCluster(
    host=DISCOVERY_IP, port=6379,
    retry=Retry(ExponentialWithJitterBackoff(
        base=0.1, cap=5.0), retries=6),
    socket_keepalive=True, socket_timeout=2)

local = {}  # local cache: key -> (value, expires_at)

def top10():
    try:
        v = rc.zrange("lb:season1", 0, 9,
                      desc=True, withscores=True)
        local["top10"] = (v, time.time() + 30)
        return v
    except (ConnectionError, TimeoutError):
        v, exp = local.get("top10", (None, 0))
        if v and time.time() < exp:
            return v  # a few seconds stale is fine
        raise

For Java, the Lettuce sample in the docs sets reconnectDelay with Delay.fullJitter (100 ms to 5 seconds).

Automatic failover does not replace retries

A popular distractor is "use Memorystore's automatic failover to keep the cache available in a secondary zone". Failover does exist when you have replicas, but it happens on the server side. The Memorystore for Redis docs say that during a failover all connections to the primary endpoint are dropped, and the instance is unavailable for an average of 30 seconds during automated repairs and 15 seconds for maintenance; the application must reconnect, ideally with exponential backoff so it doesn't overload the instance. Failover only helps if the client retries well.

Killing the app on disconnect causes more disruption; a fixed 60-second delay is too long and makes every client retry at once. Run a manual failover in a test environment to see how your app reacts (instances with read replicas enabled don't support the manual failover API).

BigQuery for clickstream: writing data for analytics

Clickstream for BI lands in BigQuery, which matches 1.3 "writing data to BigQuery for analytics and AI/ML workloads" in the exam guide. Bigtable handles huge write volumes, but it is a low-latency store read by row key, not the place for aggregate SQL. Three common ways in:

  • Storage Write API (gRPC): recommended for new projects, with lower ingestion pricing. The default stream suits continuously arriving data, makes rows queryable immediately and is at-least-once (duplicates possible). For exactly-once, create a committed-type stream and use stream offsets.
  • Storage Write API (REST): the new name for the legacy tabledata.insertAll method ("streaming inserts" in older questions); new projects should use the gRPC version.
  • Pub/Sub BigQuery subscription: the game service just publishes events to Pub/Sub, and the subscription writes them to an existing BigQuery table, with no subscriber code or Dataflow job. It is at-least-once only; for complex transforms or windowed aggregation, use Dataflow.
gcloud pubsub subscriptions create clicks-to-bq \
  --topic=game-clicks \
  --bigquery-table=PROJECT.analytics.clicks

The Pub/Sub service account needs roles/bigquery.dataEditor on the target table; forgetting it is a common mistake. Both the default stream and BigQuery subscriptions are at-least-once, so send an event ID and deduplicate during analysis.

Decision table: choosing a data store by scenario

Signal in the questionChooseWhy
Offline caching on the device, sync when back onlineFirestore (Firebase SDKs)Only Firestore has a client-side cache on Android, Apple and web
Fastest leaderboard for many simultaneous playersMemorystore for Redis (Sorted Set)In memory, always sorted
Leaderboard plus offline requirement, fewest componentsFirestoreOne store with a client cache; top N via an indexed query
A Firestore counter written very oftenDistributed counterThroughput grows with the number of shards
Clickstream for BI, aggregate SQLBigQueryData warehouse built for analytics
Redis client disconnectionsExponential backoff + jitter, client-side cacheNo retry storms; serve data during brief outages

Common traps

  • Scenario: a leaderboard on Cloud SQL for PostgreSQL is slow with many simultaneous players and you must improve it as much as possible. "Optimize the queries" or "migrate to AlloyDB" helps only partly; the answer is Memorystore for Redis. See practice question #371.
  • Scenario: a Redis Cluster client keeps disconnecting and you pick "reconnect after a fixed 60 seconds" or "rely on automatic failover". The right move is jittered backoff plus a client-side cache. See question #377.
  • Scenario: the question requires offline support on the device, but an option stores user data in Memorystore or Cloud SQL. Neither has a client-side cache; Firestore does.
  • Scenario: choosing Bigtable for clickstream because "it handles lots of writes". If the goal is BI, choose BigQuery.
  • Scenario: one Firestore document holds a server-wide total and hits contention at peak. Use a distributed counter or move the hot counter to Redis.

Reading the question

  • Offline, on the user's device: Firestore. This phrase often decides the whole question.
  • Leaderboard, as fast as possible, many simultaneous players, sub-millisecond: Memorystore for Redis.
  • Gracefully, disconnections: client-side retries with backoff and jitter.
  • BI, clickstream: BigQuery. No projections for user volume plus cost-effective: serverless, pay-per-use services.

Start practicing

Try 60 free Professional Cloud Developer questions, then a timed exam (Pro). For an overview of the four exam sections, see the PCD study guide.

Official sources