PracticeVideosBlogFlashcards

4.2 Memorystore and Cache Access Patterns

Key Takeaways

  • Basic/Standard Memorystore for Redis supports RDB persistence, not AOF.

  • A Redis cache and a separate SQL database do not share an automatic atomic transaction.

  • Write-behind can lose acknowledged data if the cache fails before durable persistence.

Last updated: October 2026

2.3 Caching Architectures with Memorystore for Redis and Memcached

High-throughput, low-latency cloud applications cannot afford to execute disk-bound relational queries or expensive document scans on every client transaction. Introducing a distributed, in-memory caching tier reduces database load by orders of magnitude while cutting read latencies from double-digit milliseconds down to sub-millisecond durations. Google Cloud provides managed caching through Memorystore for Redis and Memorystore for Memcached.


Architectural Comparison: Memorystore for Redis vs. Memcached

Selecting between Redis and Memcached depends on data structure complexity, persistence requirements, and thread concurrency.

FeatureMemorystore for RedisMemorystore for Memcached
Core ArchitectureSingle-threaded execution core (atomic commands). Sub-millisecond latency.Multi-threaded, multi-core architecture capable of scaling across multiple vCPUs.
Data StructuresStrings, Hashes, Lists, Sets, Sorted Sets (leaderboards), Bitmaps, HyperLogLogs, Geospatial indexes.Simple key-value store (keys up to 250 bytes; values up to 1 MB).
PersistenceSupported via RDB persistence snapshots; explicit Cloud Storage export is a separate operation ; Basic/Standard Memorystore for Redis does not support AOF. Memorystore for Redis Cluster is a separate product with different persistence options.None. Purely volatile memory. If an instance restarts, all cached data is permanently lost.
High Availability (HA)Standard Tier: Automatic multi-zone failover with an asynchronously replicated standby; around 30 seconds is typical, not a maximum guarantee.None. No automated replication or standby failover. Relies on client-side hashing across nodes.
Read ScalingSupports configured read replicas behind a read endpoint; reads can lag the primary.Scales horizontally by provisioning up to 5 TB across up to 20 independent nodes.
Pub/Sub MessagingNative publish/subscribe channels and Redis Streams.Not supported.
Ideal WorkloadsSession state, gaming leaderboards, real-time counters, queueing, cached database models.Large-scale read-heavy caching of simple objects, HTML fragments, and stateless lookup tables.

Core Application Caching Patterns

How your application interacts with the cache dictates data freshness, write latency, and failure tolerance.

+--------------------------------------------------------------------------+
| Core Application Caching Topologies                                      |
+--------------------------------------------------------------------------+
|                                                                          |
| 1. Cache-Aside (Lazy Loading):                                           |
|    App ---> [ 1. Check Cache ] ---> HIT? Return Data                     |
|     |                                                                    |
|     +-----> MISS? ---> [ 2. Read DB ] ---> [ 3. Populate Cache + TTL ]   |
|                                                                          |
| 2. Write-Through:                                                        |
|    App ---> [ Write Cache ] === Synchronous Lock ===> [ Write DB ]       |
|                                                                          |
| 3. Write-Behind (Write-Back):                                            |
|    App ---> [ Write Cache (Ack Immediately) ]                            |
|                    |                                                     |
|                    v (Asynchronous Background Queue)                     |
|             [ Delayed Batch Write to DB ]                                |
+--------------------------------------------------------------------------+

Cache-Aside (Lazy Loading)

  • Mechanics: The application code is responsible for managing both the cache and the primary database. On a read request:
    1. The application checks the cache for the requested key.
    2. Cache Hit: The cached payload is deserialized and returned immediately to the client.
    3. Cache Miss: The application queries the primary database (e.g., Cloud SQL or Cloud Spanner).
    4. The application writes the returned record into the cache alongside an explicit Time-To-Live (TTL).
    5. The data is returned to the client.
  • Advantages: Highly resilient. If the cache crashes or undergoes maintenance, requests degrade gracefully to querying the database directly. Memory is conserved because only actually requested records are populated in cache.
  • Disadvantages: Initial cache miss penalty on cold starts; potential to serve stale data if backend records are updated out-of-band without cache invalidation.

Write-Through

  • Mechanics: When updating or inserting records, the application updates durable storage and the cache synchronously according to application logic. Redis and a separate SQL database do not share an automatic atomic transaction; handle partial failure and invalidate inconsistent cache entries. The cache is updated immediately before or simultaneously with the persistent store.
  • Advantages: Can improve read freshness when all writers follow the protocol; failures and external writers can still produce stale entries.
  • Disadvantages: Higher write latency because every write must complete against two storage tiers; cache pollution occurs if written data is rarely or never read again.

Write-Behind (Write-Back)

  • Mechanics: The application writes directly to the in-memory cache, which immediately acknowledges success to the client. An asynchronous background process flushes modified ("dirty") entries to the database in batches.
  • Advantages: Ultra-low write latency and massive write absorption (ideal for logging, tracking clicks, or IoT telemetry).
  • Disadvantages: High risk of data loss. If the Redis instance fails before the dirty entries are flushed to Cloud SQL, uncommitted writes are permanently destroyed.

Official references checked October 18, 2026: Google Cloud 1, Google Cloud 2.

Worked Cache Correctness Scenario

Suppose an application caches a product price for five minutes while the authoritative price remains in SQL. A cache hit can return an old display price after an administrator changes the database. The checkout transaction must therefore validate the current authoritative price rather than assume the cache is a financial ledger. The TTL bounds ordinary staleness only if the cache entry was correctly refreshed; it does not make the two stores transactional.

When updating a product, commit the durable database change and then invalidate or refresh the cache using a deliberate failure policy. A crash between those actions can leave stale cache data, so choose a bounded TTL and tolerate a refill. During cache failure, fall back only within the database's capacity; unbounded fallback can turn a cache outage into a database outage. A circuit breaker or stale read is appropriate only when the particular response can tolerate that degraded behavior.

Do not treat Redis Pub/Sub as a durable task queue. Subscribers that are absent can miss transient messages, whereas a business event requiring replay and acknowledgment belongs in a durable messaging design. The cache's useful low latency does not replace persistence, consumer receipts or a transaction boundary.

Test Your Knowledge

A high-volume betting application deployed on Cloud Run requires a shared state store to manage user leaderboard rankings, perform atomic increments of scores, and publish real-time notifications to subscribers. The database must maintain sub-millisecond response times, support automated failover across zones, and support periodic point-in-time snapshots. Which caching solution should the developer implement?

A

Memorystore for Memcached with 5 nodes distributed across multiple zones.

B

Cloud Firestore in Datastore mode with strong consistency enabled.

C

Memorystore for Redis Standard Tier with automated failover and RDB snapshots.

D

Memorystore for Redis Basic Tier with a Serverless VPC Access connector.

Sections you finish are checked off in the contents.