Memorystore in Google Cloud: Managed In-Memory Data for Speed at Scale
A deep, plain-English guide to Memorystore: its Redis, Valkey and Memcached engines, how caching really works, how tiers and clusters provide availability, and the patterns that keep an in-memory layer fast, safe and affordable.
Imagine a busy library. Every time someone asks for a popular book, the librarian walks to the deep archive in the basement, finds it, and carries it up. If the same book is requested a hundred times an hour, that is a hundred trips. A smart librarian keeps the most requested books on a cart right at the front desk. The cart holds only a few books, but it answers most requests instantly. Memorystore is that cart for your applications: a fast, always-ready place, held in memory, where the data you need most can be handed over in a fraction of a millisecond.
1What Memorystore Is and Why It Exists
Memorystore is Google Cloud’s fully managed in-memory data service, built on popular open source engines.
Computers store data in two broad ways. Disks, including solid state drives, keep data safely but respond in milliseconds or more. Memory, the RAM inside a server, responds in microseconds but is smaller, more expensive and empties when power or the process stops. An in-memory data store keeps its data in RAM so that reads and writes are extremely fast, and it exposes that data over the network so many application servers can share it.
Running such a store yourself is real work. You must install the software, choose machine sizes, set up replicas, configure failover, patch security issues, tune memory settings, and monitor everything around the clock. Memorystore takes over that work. You ask for an instance of a given size and engine, and Google provisions, secures, patches and monitors it, while you simply connect your application to it.
Cooking at home means shopping, cleaning and repairing the oven. A catered kitchen delivers hot food to your door. Memorystore is the catered kitchen for in-memory data: you decide what to serve and how much, and the provider keeps the equipment running.
The problems it solves
The first problem is slow databases under heavy read load. When thousands of users request the same product page, asking the main database every time wastes its capacity. A cache in front answers repeat requests quickly and shields the database. The second problem is shared fast state, such as user sessions, shopping carts, rate limit counters and leaderboards, that many servers must read and update at high speed. The third problem is real-time messaging and counting, where speed matters more than long-term storage.
Because Memorystore speaks the standard protocols of its open source engines, ordinary client libraries work, and applications can often move between Memorystore and other compatible services with limited changes.
2Core Concepts You Must Know Cold
A short vocabulary unlocks every later chapter, so learn each term properly now.
Each concept below is explained by what it is, why it exists and where you will meet it. Terms such as cache hit and eviction appear constantly in design discussions.
Cache
A fast, temporary copy of data that lives closer to the application than the original source, used to avoid repeating slow work.
Cache hit and miss
A hit means the requested data was found in the cache. A miss means it was not, so the application must fetch it from the original source.
Key and value
Data is stored as pairs. The key is the name you look it up by, and the value is the data attached to that name.
TTL
Time to live. A countdown attached to a key after which it expires and disappears automatically.
Eviction
The automatic removal of keys when memory fills up, following a chosen policy, to make room for new data.
Shard
One slice of a dataset in a clustered setup. Data is divided across shards so the total capacity and throughput can grow.
Replica
A live copy of a primary node kept in sync for availability or extra read capacity.
Failover
The automatic promotion of a replica to primary when the primary fails, so service continues.
Think of a coat check. The ticket number is the key, the coat is the value, and the attendant hands it back instantly. If the rack is full, an old coat is moved out to make room, which is eviction. If a coat is not on the rack, the attendant must fetch it from the storage room, which is a miss.
Cache versus database
A cache is not a database. A database promises to keep data safely and answer questions about it. A cache promises only speed, and it is allowed to forget. This distinction guides nearly every design decision: the true source of truth should live in a durable database, while the cache holds copies that can always be rebuilt.
Many teams start by using Memorystore as their main database because it is fast and convenient. Without careful persistence and backup planning, a restart or failure can lose that data. Treat it as a speed layer unless you have designed for durability.
3The Memorystore Product Family
Memorystore is not one product but a family, and choosing the right member is your first decision.
Memorystore offers managed services for several engines. The lineup has evolved over time, so always confirm the current list and feature support in the official documentation. The broad picture is stable and is described below.
Memorystore for Redis
The classic offering with a single-primary design, available in a Basic tier and a Standard tier with a replica. Suitable for many caching and session workloads.
Memorystore for Redis Cluster
A sharded design that spreads data across many nodes for higher capacity and throughput, with replicas for availability.
Memorystore for Valkey
A managed service for Valkey, the open source fork of Redis maintained under the Linux Foundation, offering a cluster-style architecture.
Memorystore for Memcached
A simple, multi-node cache for plain key and value data. No persistence or replication, designed for pure caching.
| Feature | Redis (Basic and Standard) | Redis Cluster and Valkey | Memcached |
|---|---|---|---|
| Data model | Rich data structures | Rich data structures | Simple key and value strings |
| Scaling style | Larger instance, optional read replicas | Add shards for capacity and throughput | Add nodes to the instance |
| High availability | Standard tier replica with automatic failover | Replicas per shard | None built in |
| Persistence | Snapshot options on supported tiers | Persistence options available | None, memory only |
| Best for | Caches, sessions, smaller state stores | Large scale, high throughput, demanding availability | Simple, disposable caching |
flowchart TD
Q["What do you need?"] --> A{"Rich data structures or persistence?"}
A -- No --> M["Memorystore for Memcached"]
A -- Yes --> B{"Need very large scale or high throughput?"}
B -- No --> R["Memorystore for Redis"]
B -- Yes --> C["Memorystore for Redis Cluster or Valkey"]
A word on Redis and Valkey
Redis is an extremely popular in-memory engine. In 2024, changes to Redis licensing led the community to create Valkey as an open source fork under neutral governance, and cloud providers, including Google, added support for it. For most application code the two behave very similarly, since Valkey began as a continuation of Redis. Check the current compatibility notes if your application relies on newer or specialized features.
For a brand new design that expects significant growth, many teams start with a clustered offering so that scaling out later does not require redesigning how keys are distributed.
4Architecture and Components
Behind a single connection address sits a small distributed system that Google runs for you.
A Memorystore instance consists of one or more nodes, each a virtual machine running the in-memory engine, placed in a Google-managed environment connected to your network. Your application servers, running on Compute Engine, Google Kubernetes Engine, Cloud Run or elsewhere, connect to the instance using private network addresses. You never see or manage the underlying machines.
flowchart LR
APP1["App Server 1"] --> EP["Instance Endpoint"]
APP2["App Server 2"] --> EP
APP3["App Server 3"] --> EP
EP --> P["Primary Node"]
P --> R1["Replica Node in another zone"]
CP["Google Managed Control Plane"] -.provisions, patches, monitors.-> P
CP -.-> R1
P --> DB["Source of Truth Database"]
The control plane and the data plane
As with many managed services, there are two layers. The control plane handles creating, resizing, updating and repairing instances. It is the part you talk to when you issue management commands. The data plane is the part that actually serves reads and writes to your application. Separating them means a management operation does not slow down normal traffic, and a busy cache does not block administration.
Zones and regions
An instance lives in a region, and its nodes live in zones within that region. In a highly available setup, the primary and replicas are placed in different zones so that the loss of one zone does not take the service away. Your applications should be in the same region to keep latency low, and ideally in the same zone as the primary for the fastest responses.
Endpoint
The stable network address your application connects to, which hides where the nodes actually are.
Primary node
The node that accepts writes and holds the authoritative in-memory copy.
Replica node
A synchronized copy that can take over if the primary fails, and in some setups can serve reads.
Control plane
Google’s management system for provisioning, patching, scaling and repair.
A restaurant’s front door and host stand are the endpoint. The kitchen crew are the nodes. The restaurant management that hires and replaces crew members is the control plane. Customers deal only with the host stand and never see the internal staffing changes.
5Request Flow and Data Path
Following one request from the application to the cache and back shows where time is spent.
When your application needs a piece of data, it builds a key, sends a command to Memorystore over a network connection, and waits for the reply. Because the data is already in memory, the engine simply looks the key up and returns the value. Most of the elapsed time is actually the network trip between your server and the cache, not the lookup itself. That is why keeping applications close to the instance matters so much.
sequenceDiagram
participant U as User
participant A as Application
participant C as Memorystore Cache
participant D as Database
U->>A: Request product page
A->>C: GET product key
alt Cache hit
C-->>A: Value returned quickly
else Cache miss
C-->>A: Not found
A->>D: Query database
D-->>A: Product data
A->>C: SET key with TTL
end
A-->>U: Page response
Connection reuse
The application keeps long-lived connections in a pool. Opening a new connection for every request wastes time and can exhaust limits.
Command and key routing
The command goes to the endpoint. In clustered setups, the client library works out which shard owns the key and talks to that node.
In-memory execution
The engine executes the command against its data in RAM. Simple commands finish in microseconds.
Replication of writes
If a replica exists, writes are copied to it. Replication is usually asynchronous, which matters for failure behavior.
Response to the application
The result travels back over the network and the application uses it or falls back to the database on a miss.
Why the engine is fast but single-minded
Redis-style engines traditionally execute commands on a main thread, one at a time. That keeps behavior simple and predictable and is the reason simple commands are so quick. It also means one slow command, such as scanning every key in a very large dataset, can make every other client wait. Fast access, then, depends on keeping commands small and cheap.
Running commands that touch huge numbers of keys at once during busy hours. A single heavy command can stall the whole instance for everyone. Use incremental scanning methods and keep operations bounded.
6Caching Patterns That Actually Work
Caching is easy to start and hard to get right, and the pattern you choose decides how right.
A caching pattern is a rule for how data moves between your application, the cache and the database. Each pattern trades simplicity, freshness and write speed differently.
| Pattern | How it works | Strength | Weakness |
|---|---|---|---|
| Cache-aside | The application checks the cache first, and on a miss loads from the database and fills the cache | Simple, resilient to cache failure | First request after a miss is slow, data can go stale |
| Read-through | The cache layer itself loads missing data from the database | Application code is simpler | Needs a loader component, less flexible |
| Write-through | Every write goes to the cache and the database together | Cache stays fresh | Slower writes, caches data that may never be read |
| Write-behind | Writes go to the cache and are saved to the database later | Very fast writes | Risk of losing data if the cache fails before saving |
| Refresh-ahead | Popular entries are refreshed before they expire | Avoids latency spikes on hot data | Extra complexity and wasted refreshes |
Cache-aside is the usual starting point
Cache-aside is the most common pattern because it is easy to reason about and fails gracefully. If the cache is empty or unavailable, the application still works, only more slowly, by reading from the database. It is the safe default for most applications.
Invalidation: the famously hard problem
When the underlying data changes, the cached copy becomes stale. There are two main strategies. One is to set a time to live so entries expire on their own, accepting a short window of staleness. The other is to delete or update the cached entry whenever the data changes. Many systems use both: explicit invalidation on writes, with a TTL as a safety net in case an invalidation is missed.
flowchart TD
W["Data is updated in the database"] --> I{"Invalidation strategy"}
I --> E["Delete cache entry now"]
I --> T["Wait for TTL to expire"]
I --> U["Write new value to cache"]
E --> N["Next read reloads fresh data"]
T --> S["Short stale window accepted"]
U --> F["Cache is fresh immediately"]
The cache stampede
Imagine a very popular entry expires, and a thousand requests arrive at the same instant. All of them see a miss and all of them hit the database simultaneously. This surge is called a cache stampede, and it can overwhelm the very database the cache was protecting. Defenses include adding random variation to TTLs so entries do not expire together, allowing only one request to rebuild an entry while others wait, and refreshing hot entries before they expire.
If a popular bakery’s bread runs out at exactly noon, a huge crowd rushes the back kitchen at once. Baking a fresh batch just before noon, or letting one baker handle the rush while others wait, prevents the chaos. A cache stampede is that noon rush on your database.
Always set a TTL on cached entries, even a long one. A cache without expiry slowly fills with stale and unused data, and eventually hits memory limits at the worst time.
7Data Structures and Uses Beyond Caching
Redis-style engines are much more than a simple key and value box.
Memcached stores plain strings. Redis and Valkey store several rich data types, and these types let you solve whole categories of problems directly inside the data store with fast, atomic operations. Atomic means an operation happens completely or not at all, with no other client able to see it half done.
Strings and counters
Plain values and numbers. Counters can be increased atomically, ideal for page views and rate limits.
Hashes
A key holding many named fields, like a small record. Good for user profiles and session data.
Lists
Ordered sequences. Useful for queues, recent activity feeds and simple job lists.
Sets
Unordered collections of unique items. Good for tags, unique visitors and membership checks.
Sorted sets
Unique items ranked by a score. The classic tool for leaderboards and priority queues.
Streams
Append-only logs of events with consumer groups, suited to lightweight messaging and event processing.
Geospatial and probabilistic types
Location lookups and compact estimates of large counts, with small memory use.
Publish and subscribe
Messages sent to a channel are delivered to all current subscribers. Fast, but messages are not stored for absent listeners.
Popular non-cache uses
Session storage
Web applications with many servers need a shared place for login sessions. A hash or string per session with a TTL gives fast lookups and automatic cleanup of expired sessions.
Rate limiting
Atomic counters with expiry let an API count requests per user per time window and reject excess traffic. Because the counters are shared, limits apply across all servers.
Leaderboards and rankings
Sorted sets keep scores ordered automatically, so fetching the top ten players or a user’s rank is a quick operation, even with millions of entries.
Distributed locks and coordination
Short-lived keys can act as locks so only one worker performs a task at a time. These need careful design, because failures and timing can break naive locks.
Real-time counters and analytics
Counting events, unique users and recent activity in real time is a natural fit for fast in-memory counters and compact probabilistic structures.
A basic cache is a single drawer. Redis-style data types are a whole toolbox with a ruler, a stopwatch and a sorted scoreboard. Choosing the right tool means the work is done inside the data store, instead of in your application code.
Using the publish and subscribe feature as a reliable message queue. Messages are not stored for subscribers that are offline, so they can be lost. Use streams or a dedicated messaging service when delivery must be guaranteed.
8Memory Management: Sizing, TTL and Eviction
Memory is the scarce resource, and everything about Memorystore reflects that.
An in-memory store can hold only as much as its memory allows. When it runs short, one of two things happens: it removes some data according to an eviction policy, or it refuses new writes and returns errors. Understanding which behavior you have configured is essential, because the wrong choice either loses data you wanted or breaks your application.
Eviction policies
| Policy style | What gets removed | Good for |
|---|---|---|
| No eviction | Nothing; new writes fail when memory is full | Stores where losing data is unacceptable |
| All keys, least recently used | Any key that has not been used for the longest time | Pure caches where every key is disposable |
| Volatile keys, least recently used | Only keys that have a TTL, oldest use first | Mixed use: cache entries have TTLs, important keys do not |
| Least frequently used variants | Keys used the least often, not just least recently | Workloads with stable popular items |
| Random variants | Randomly chosen keys | Rare cases where simplicity is preferred |
| Shortest TTL first | Keys closest to expiring | Time-sensitive data |
For a pure cache, an all-keys policy based on recent or frequent use is usually right. For a mixed store, where some keys are cache entries and others are important state, a policy that evicts only keys with a TTL protects the important ones. The default policy of an instance may not match your needs, so choose deliberately.
Sizing the instance
Sizing begins with the working set, the amount of data you want to keep hot. Add overhead for the engine’s internal structures, which means that a thousand small keys cost more memory than their raw data alone. Then add headroom. Features such as replication, snapshots and the way memory is allocated need spare room, which is why Google recommends not filling an instance to the brim. Keep a comfortable margin below the maximum, and watch the memory usage metrics rather than guessing.
Estimate the working set
Count the entries you want cached and multiply by average entry size. Measure real sizes rather than assuming.
Add engine overhead
Every key carries bookkeeping costs. Small values suffer proportionally more overhead than large ones.
Reserve headroom
Leave spare memory for replication buffers, snapshots, fragmentation and growth.
Pick the instance size
Choose a capacity that comfortably holds the total, and confirm network throughput limits match your traffic.
Observe and adjust
Watch memory usage, hit rate and evictions after launch, and resize before pressure builds.
A suitcase holds only so much. When it is full, you either throw out the least useful item or refuse to pack anything more. An eviction policy is your packing rule for when the suitcase is full.
Evictions are not automatically bad in a cache, but a high and rising eviction rate with falling hit rate means the cache is too small for its job. That is a signal to resize or to cache less.
9Tiers, Availability and Failover
How much downtime you can tolerate decides which tier or architecture you need.
Servers fail. Memory modules fail, hosts get replaced, and zones occasionally have trouble. An availability design decides what happens to your cache when that occurs. Memorystore offers different levels of protection.
Basic tier
The Basic tier of Memorystore for Redis is a single node with no replica. It is the cheapest option and suits caches where a restart is acceptable. If the node fails, or during maintenance and certain scaling operations, the cache is unavailable and its contents are lost, so the application must fall back to the database and rebuild the cache. It does not carry the availability commitment of the replicated tier.
Standard tier
The Standard tier adds a replica in a different zone. The replica receives a continuous stream of writes from the primary. If the primary fails, the service promotes the replica to primary automatically, and the endpoint continues to serve traffic. Because replication is asynchronous, a very small amount of the most recent writes may be lost at the moment of failure. Standard tier is the normal choice for production caches and session stores. It also carries a service level objective, so check the current availability terms.
flowchart TD
A["Primary in Zone A serving traffic"] --> R["Replica in Zone B stays in sync"]
A -. "Primary fails" .-> F["Failure detected"]
F --> P["Replica promoted to primary"]
P --> E["Endpoint continues serving"]
P --> N["New replica created and synced"]
Clustered offerings
Clustered services divide data into shards, and each shard can have one or more replicas placed across zones. A failure affects only the shard involved, and its replica takes over. Clusters also allow capacity and throughput to grow by adding shards. They are the choice for large datasets and for workloads where even brief unavailability of a big instance is unacceptable.
Replicated Setups Give You
- Automatic failover without manual action
- Protection from single node and single zone failures
- Smoother maintenance with limited disruption
- In some setups, extra read capacity from replicas
Replicated Setups Cost You
- Higher price because of the extra memory and nodes
- Possible loss of the very latest writes in a failover
- Brief reconnection period for clients during failover
- Stale reads if you read from replicas
Client behavior during failover
Failover is only seamless if clients handle it well. During the switch, connections are dropped and a short period of errors can occur. A robust client library retries failed commands with a small delay, reconnects automatically, and refreshes its view of the cluster topology. Applications should expect brief errors and handle them gracefully rather than crashing.
Choosing the Basic tier for a store that holds sessions or other state that users would notice losing. A restart then logs everybody out. Use a replicated tier, or design for graceful loss.
10Scaling: Up, Out and Read Replicas
Growing a cache means more memory, more throughput, or both, and each has its own tool.
As traffic and data grow, a single node eventually runs out of memory or network capacity. There are three ways to grow, and the right one depends on what is running short.
Scale up
Increase the memory size of the instance. Simple, and keeps the design unchanged, but is limited by the largest available size and can involve a brief disruption.
Add read replicas
In supported setups, extra replicas serve read requests, spreading read load. Writes still go to one primary, and replica reads can be slightly stale.
Scale out with shards
In clustered services, add shards to divide data and traffic across more nodes. This raises both capacity and throughput.
Add nodes to a Memcached instance
Memcached grows by adding nodes, with clients spreading keys across them.
How keys are distributed in a cluster
Clustered Redis-style engines divide the key space into a fixed number of hash slots. Each shard owns a range of slots. A hash of the key decides which slot, and therefore which shard, holds it. This is automatic, but it creates a rule you must respect: operations that touch several keys at once must have all their keys in the same slot. Designers use hash tags, a marker inside the key name, to force related keys into the same slot when they need multi-key operations.
| Symptom | Likely cause | Best response |
|---|---|---|
| Memory usage near the limit | Dataset outgrew the instance | Scale up or add shards, or reduce cached data |
| High read traffic, writes fine | Read load on a single node | Add read replicas or add shards |
| High CPU on one node only | Hot key or uneven key distribution | Redesign keys or split the hot item |
| Network throughput saturated | Instance size limits bandwidth | Move to a larger size or more shards |
If one checkout lane is too busy, you can make the cashier faster, which is scaling up, open more lanes, which is scaling out, or add helpers who only answer questions, which is adding read replicas. Each fixes a different kind of queue.
Scale before you must. Resizing a nearly full or overloaded instance under pressure is riskier than resizing a calm one. Set alerts at comfortable thresholds and plan changes in quiet periods.
11Persistence, Backups and Durability
Memory forgets, so any data you cannot afford to lose needs a plan.
The key fact about in-memory stores is that their primary copy is volatile. If a process restarts without any saved state, the memory is empty. Some Memorystore options provide persistence features that periodically write data to disk so it can be restored, and others do not. The details differ by engine and tier and change over time, so confirm them in the current documentation.
Snapshot persistence
Periodic point-in-time copies of the dataset. Recovery returns to the last snapshot, so changes since then can be lost.
Append-only logging
Records every write operation so the dataset can be rebuilt almost to the moment of failure, at a cost in disk work and size.
Import and export
Copy a dataset to and from Cloud Storage, useful for backups, migrations and seeding new instances.
None
Pure memory only, as with Memcached. Everything is rebuilt from the source after any restart.
Choosing a durability stance
| Stance | Meaning | Suitable when |
|---|---|---|
| Disposable cache | Everything can be rebuilt from the database | Typical caching, where loss only costs warm-up time |
| Recoverable state | Snapshots or logs allow restoring after failure | Session stores, counters, where small loss is tolerable |
| Authoritative data | Cache holds the only copy | Rarely recommended; requires strong persistence and external backups |
For most designs, the cleanest approach is the disposable cache, where durability is irrelevant because the source of truth lives elsewhere. If you do keep important state, such as session data you would rather not lose, use a replicated tier with persistence and take regular exports to Cloud Storage. Practice restoring from them, because an untested backup is only a hope.
Assuming replication equals backup. A replica faithfully copies mistakes too, such as an accidental flush of all keys. Backups protect against human error, replicas protect against hardware failure.
12Networking and Connectivity
Memorystore is private by design, so connecting to it is a networking question first.
Memorystore instances do not live on the public internet. They receive private addresses and are reachable only from inside connected networks. Depending on the engine, connectivity is provided through private services access, which creates a private peering between your network and Google’s service network, or through Private Service Connect, which creates a dedicated private endpoint in your own network. The details differ by product, so follow the documentation for your engine.
flowchart LR
subgraph YourVPC["Your VPC Network"]
GCE["Compute Engine VMs"]
GKE["GKE Pods"]
CR["Cloud Run via VPC egress"]
end
GCE --> PRIV["Private connection"]
GKE --> PRIV
CR --> PRIV
PRIV --> MS["Memorystore Instance"]
OnPrem["On-premises network via VPN or Interconnect"] --> PRIV
Reaching it from different compute platforms
Compute Engine
VMs in the connected network and region connect directly using the private address.
Google Kubernetes Engine
Pods reach the instance through the cluster’s network, provided routing and firewall rules allow it.
Cloud Run and serverless services
Need a private egress path into the VPC, such as direct VPC egress or a connector, since they are not on the network by default.
On-premises systems
Can connect over VPN or dedicated interconnect, with routing configured to reach the private range.
Latency and placement
Since most of a cache request’s time is the network trip, placement matters. Keep applications in the same region as the instance, and where possible in the same zone as the primary. Calls that cross regions add tens of milliseconds and defeat the purpose of a cache. Calls that cross zones add a small but measurable delay and may incur network charges.
A private phone line between two offices in the same building gives instant conversations. The same line stretched across the country feels slow no matter how fast each person talks. Distance, not processing, dominates.
Trying to connect to Memorystore from a laptop or an unconnected network over the public internet. It will not work by design. Use a bastion VM, a VPN or another private path for administration.
13Security: Authentication, Encryption and Access
An in-memory store often holds sessions and personal data, so it deserves the same care as a database.
Security for Memorystore has several layers. The first is network isolation: instances have private addresses and are reachable only from permitted networks. The second is authentication at the engine level, where clients must present credentials before running commands. The third is encryption of data in transit between clients and the instance. The fourth is access control for administration, using Google Cloud IAM to decide who may create, change or delete instances.
Network isolation
Private addresses and firewall rules limit which machines can even attempt a connection.
Client authentication
Authentication settings require credentials, and some offerings support identity-based authentication using IAM. Turn it on rather than relying on network location alone.
Encryption in transit
Transport encryption protects data traveling between application and instance. Enable it, especially for sensitive data.
Encryption at rest and keys
Data at rest is encrypted, and some offerings allow customer-managed encryption keys for stricter control. Check support for your engine.
IAM for administration
Grant management permissions to a small group, using roles that separate creators, operators and viewers.
What to keep out of the cache
The speed of a cache tempts teams to put everything in it, including data that should never be copied around. Consider carefully whether highly sensitive values, such as full payment details or secrets, belong in a cache at all. Where you must cache personal data, apply short TTLs, encrypt in transit, restrict access tightly, and ensure that data deletion requests also clear cached copies.
| Data type | Cache it? | Precaution |
|---|---|---|
| Public product or page content | Yes | Normal TTLs |
| User session identifiers | Yes | Authentication on, encryption in transit, sensible expiry |
| Personal profile data | With care | Short TTL, access control, honor deletion requests |
| Passwords, secrets, full card numbers | Avoid | Use dedicated secret and payment services instead |
A secure office has a locked building, badge access to each floor, and private rooms for sensitive files. Memorystore’s network isolation, authentication and encryption are the building lock, the badge reader and the private room.
Put the cache keys’ naming scheme to work for security too. Include the tenant or user identifier in keys, so a bug in key construction cannot easily return one customer’s data to another.
14Performance Tuning and Classic Pitfalls
Most Memorystore performance problems come from a small set of repeating causes.
Hot keys
A hot key is a single key receiving a disproportionate share of traffic. Because a key lives on one node, a hot key can overload that node even when the cluster as a whole is idle. The fix is to spread the load: replicate the value under several keys and pick one randomly on reads, cache the value inside the application for a short time as well, or restructure the data so no single key bears the whole load.
Big keys
A big key is a single key holding a huge value or collection, such as a list with millions of items. Reading or deleting it takes a long time, and because commands run one at a time, everyone else waits. Break large structures into smaller pieces and delete them incrementally.
Too many connections and no pooling
Each connection consumes memory and processing on the instance. Applications that open a new connection per request, or that scale to hundreds of servers each with many connections, can hit connection limits and waste resources. Use connection pooling, reuse connections, and limit the pool size per application instance.
Many small round trips
Making one network call per key is slow because each call pays the network delay. Group commands together using pipelining, where many commands are sent before waiting for replies, or use batch commands that fetch several keys at once. In clusters, keep batches to keys on the same shard when possible.
Hot key
One key overloads one node. Spread the load across copies or add a local application cache.
Big key
One huge value blocks everyone. Split it into smaller pieces.
Blocking commands
Whole-keyspace scans freeze the instance. Use incremental iteration.
No connection pooling
Constant reconnection wastes time and resources. Reuse connections.
Chatty access
Too many tiny round trips add up. Pipeline and batch.
Large values everywhere
Bigger values use more memory and bandwidth. Compress or store references to large objects.
A single popular vending machine with a long queue is slow even if the rest of the hall is empty. Adding more machines stocked with the same snack, which is a hot key fix, spreads the crowd evenly.
Blaming the service for slowness when the real cause is a single heavy command or hot key from the application. Look at slow command logs and per-node metrics before resizing.
15Monitoring and Operations
A cache that is quietly failing looks, from the outside, like a slow database, so you must watch it directly.
Memorystore publishes metrics to Cloud Monitoring and records administrative activity in Cloud Audit Logs. The right set of metrics tells you whether the cache is healthy, full, effective or under stress.
Memory usage ratio
How full the instance is. Alert before it nears the limit, leaving headroom for replication and snapshots.
Cache hit ratio
Share of lookups that found their key. A drop means more load on your database.
Evicted keys
How many keys were removed for lack of space. Sustained evictions indicate too little memory for the workload.
Connected clients
Shows connection count and helps catch leaks or missing pooling.
CPU and command rate
Shows how busy the engine is, and whether one node is overloaded.
Replication lag and role changes
Shows replica health and records when failovers occur.
Alerts worth having
| Alert | What it warns about | Typical action |
|---|---|---|
| Memory usage above a safe threshold | Instance nearing capacity | Scale up, add shards, or reduce data |
| Hit ratio falling | Cache is becoming ineffective | Check TTLs, key changes, evictions |
| Evictions rising | Memory pressure | Resize or trim cached data |
| Failover or role change event | A node was replaced | Verify clients reconnected cleanly |
| Connection count climbing | Leak or lack of pooling | Fix client pooling |
Maintenance and updates
Google periodically updates instances to patch security issues and apply improvements. You can often choose a preferred maintenance window so updates happen at quiet times. Replicated and clustered setups handle maintenance with limited disruption, while single-node instances may be briefly unavailable. Plan applications to tolerate short reconnections, and watch the maintenance notifications.
Drills and testing
Test what happens when the cache is empty, when it is slow, and when it disappears. Simulate failover. Measure how the database copes with a cold cache. These drills reveal whether the cache is a helpful accelerator or a hidden single point of failure.
A hospital monitors multiple vital signs because any single reading can mislead. Memory, hit rate, evictions and connection count are the cache’s vital signs, and together they tell you its true condition.
Graph the cache hit ratio next to database load on the same dashboard. When the hit ratio falls, the database load rises, and the connection becomes obvious at a glance during an incident.
16The Cost Model
Memorystore is priced mainly by how much memory you provision and for how long.
You are billed for the capacity of each instance for every hour it exists, whether or not it is busy. Larger instances cost more. Replicated tiers cost roughly in proportion to the extra memory they hold, since the replica is a second copy of the data. Clustered offerings are billed by the nodes that make up the shards and replicas. Additional charges can apply to network traffic that crosses zones or regions, to backups stored in Cloud Storage, and to the compute that connects to the instance. Pricing and discount programs, including possible committed use discounts, change over time, so check the current pricing page.
Cost versus value
The cost of a cache should be compared with what it saves. A well-placed cache can reduce the size and cost of a database, because the database handles far fewer requests. It can also improve user experience and conversion through faster pages. Conversely, a cache that is oversized, rarely hit, or holding data nobody reads is pure waste. The hit ratio is the cleanest measure of whether the money is working.
Ways the Cache Saves Money
- Smaller or fewer database instances needed
- Lower per-request cost on pay per query services
- Fewer compute resources spent on repeated work
- Improved user experience and conversion
Ways the Cache Wastes Money
- Oversized capacity that never fills
- Replicated tiers for data that does not need them
- Low hit ratio from poor key design or short TTLs
- Cross-region access that adds transfer charges
- Forgotten test instances left running
Right-size from metrics
Use real memory and hit ratio data to choose capacity, and revisit regularly.
Match tier to need
Use replicated tiers for production state, and simpler options for disposable development caches.
Shrink what you store
Cache compact values, compress large ones and avoid caching rarely read data.
Delete unused instances
Remove test and abandoned instances, and label every instance with an owner.
A front-desk cart is worth its space only if it holds books people really ask for. Stuffing it with rarely requested titles uses valuable room for no benefit, just like caching data nobody reads.
17Design Patterns and Anti-Patterns
A few patterns appear again and again in healthy systems, and a few traps appear in broken ones.
Patterns that work well
Look-aside cache in front of a database
The application checks Memorystore first and falls back to the database, filling the cache on a miss. The database remains the source of truth, and the cache can be lost without harm.
Two-level caching
A tiny in-process cache inside each application server absorbs the hottest keys, while Memorystore serves the wider set. This reduces network trips and protects against hot keys.
Shared session store
Stateless application servers keep user sessions in Memorystore with expiry, so any server can serve any user and servers can be added or removed freely.
Centralized rate limiter
Shared atomic counters enforce per-user or per-key limits across all servers of an API, protecting backends from overload and abuse.
Precomputed results
Expensive calculations, such as ranked lists or aggregated dashboards, are computed in the background and stored in Memorystore, so user requests simply read the finished result.
Anti-patterns to avoid
Problem
The cache is treated as the only home of important data, with no durable copy elsewhere.
Why It’s Harmful
A failure, restart or accidental flush destroys the data permanently, and replication offers no protection against human error.
Correct Approach
Keep the source of truth in a durable database. Use the cache as a speed layer, and add persistence and external backups if any state must survive.
Problem
Cache entries are created with no expiry, and no eviction policy suits the workload.
Why It’s Harmful
Memory fills with stale data, and eventually writes fail or useful entries are evicted unpredictably.
Correct Approach
Set TTLs on cached entries, choose an eviction policy on purpose, and monitor memory use.
Problem
The application depends on the cache being available and crashes or becomes unusably slow when it is not.
Why It’s Harmful
The cache becomes a single point of failure, and a cache outage becomes a full outage, or a database meltdown from sudden load.
Correct Approach
Design a fallback path with timeouts, circuit breakers and limits on database load, and rehearse the cache-down scenario.
Problem
Large collections are stored under a single key and accessed with whole-collection commands.
Why It’s Harmful
Reads and deletes of such big keys block the engine, causing latency spikes for all clients and uneven load in clusters.
Correct Approach
Split collections into smaller keys or buckets, access them incrementally and keep operations small.
18Memorystore Compared with Other Options
Memorystore is one of several ways to make data fast, and each way fits different needs.
| Option | What it is | Strength | Limitation |
|---|---|---|---|
| Memorystore | Managed in-memory store | Very low latency, rich structures, shared by many servers | Memory is costly; data can be lost; extra network hop |
| In-process application cache | A cache inside each app instance | Fastest possible, no network | Not shared, duplicated per instance, lost on restart |
| Self-managed Redis or Memcached on VMs or Kubernetes | You run the engine yourself | Full control and custom tuning | You carry patching, failover and monitoring work |
| Database read replicas | Copies of a database for reads | Familiar, strongly consistent in some cases | Higher latency than memory, scales with database cost |
| Content delivery network cache | Edge cache for web content | Serves users from nearby locations, offloads origin | Suited to web responses, not arbitrary application data |
| Wide-column or document databases | Durable, scalable databases | Durable, large scale with low latency | Not as fast as memory for the hottest paths |
How to choose
Start with the question: what is slow, and why? If a database is overloaded by repeated identical reads, a cache helps. If web pages are slow because users are far away, a content delivery network helps. If a very small set of values is read constantly inside one process, an in-process cache is enough. If many servers need to share fast state, such as sessions and counters, a shared in-memory store is the right tool. Often the best design combines two or three of these layers.
Your desk drawer, the shared office printer room and the company warehouse each hold things at different distances and sizes. A good office uses all three, placing each item where the speed and sharing needs match.
Measure before you cache. Profile the application to find the real bottleneck, because adding a cache in the wrong place adds cost and complexity without fixing the slow part.
19Best Practices and Common Mistakes
A short checklist makes the difference between a trusted cache and a source of incidents.
Best practices
Keep a source of truth
Hold authoritative data in a durable database and treat the cache as rebuildable.
Always set TTLs
Add random variation to avoid synchronized expiry and stampedes.
Choose the eviction policy deliberately
Match the policy to whether keys are all disposable or mixed.
Use a replicated or clustered setup in production
Reserve the single-node tier for disposable development use.
Pool connections and pipeline
Reuse connections and batch commands to cut round trips.
Enable authentication and encryption
Do not rely on network privacy alone.
Colocate with applications
Same region, and ideally the same zone, to keep latency low.
Monitor and rehearse
Track memory, hit ratio and evictions, and drill failover and cold-cache scenarios.
Common mistakes
Sizing to the exact data size. Overhead, replication and growth need headroom, and a full instance behaves badly. Leave a comfortable margin.
Letting the application crash when the cache is unreachable. Always include timeouts and a fallback to the source of truth.
Ignoring stale data. If correctness matters, define how fresh each cached item must be, and design invalidation to meet it.
Running whole-keyspace commands in production. They block the engine. Use incremental scanning and keep operations bounded.
Mixing environments carelessly. Using one instance for development, testing and production risks accidental deletion of live data. Separate them.
Write a short cache design note for each use: what is cached, who owns it, how it expires, how it is invalidated, and what happens if it vanishes. Future team members will thank you.
20Real-World and Industry Scenarios
Concrete stories show how the ideas fit together under real traffic.
E-commerce product catalog
An online store’s catalog pages are requested far more often than they change. Product details are cached with TTLs and explicit invalidation when prices change. During a sale, the cache absorbs the traffic surge, and the database sees only a fraction of the requests. Random TTL variation prevents stampedes when popular items expire.
Online gaming leaderboard
A game ranks millions of players by score. Sorted sets in a clustered Memorystore instance keep scores ordered, so showing the top players and a player’s own rank takes a single quick command. Scores are periodically saved to a durable database for history.
Banking and fintech session management
A mobile banking back end keeps authenticated sessions in a replicated instance with authentication and encryption in transit enabled. Sessions have short expiry and sensitive values are deliberately kept out of the cache. Any application server can serve any customer.
API platform rate limiting
A public API enforces per-customer limits using atomic counters with a time window. Because the counters are shared, limits apply no matter which server receives the request, and abusive clients are rejected before reaching expensive back ends.
Media streaming personalization
A streaming service precomputes recommendation lists in the background and stores them in Memorystore. When a user opens the app, the home screen reads the finished list immediately instead of computing it on demand.
Ad bidding and real-time decisioning
A bidding platform must decide in milliseconds. User attributes and campaign limits live in a large clustered in-memory store close to the bidding servers, with budgets tracked using atomic counters. The master data lives in durable databases and is loaded continuously.
In every story, the cache accelerates something that exists durably elsewhere, and the design assumes the cache may occasionally be empty, slow or briefly unavailable.
21Frequently Asked Questions
Short answers to the questions engineers ask most when adopting Memorystore.
Choose Memcached for simple, disposable string caching. Choose a Redis or Valkey offering when you need rich data structures, persistence options, or replication. Choose a clustered offering when you expect large scale or high throughput. Confirm current feature support in the documentation.
It is generally not recommended, because memory is volatile and costly. If you do store important state, use a replicated tier with persistence and regular exports, and test restoring. For most designs, keep the system of record in a durable database.
No. Instances have private addresses and are reachable only through connected private networks. Use a VM in the network, a VPN, or another private path for access.
In replicated tiers, the replica is promoted automatically, and clients reconnect to the same endpoint after a brief interruption. A tiny amount of the latest writes may be lost because replication is asynchronous. A single-node tier loses its data and is unavailable until it recovers.
Add random variation to TTLs, let only one request rebuild an expired entry while others wait or use the old value, and refresh very popular entries before they expire.
Common causes are TTLs that are too short, keys that include changing values so entries are never reused, an instance too small so entries are evicted, or caching data that is rarely requested twice. Examine key design and eviction metrics.
Yes, provided they have a private network path into the instance’s network, using direct VPC egress or a connector. Keep them in the same region to avoid extra latency.
No. Replication is typically asynchronous, so reads from replicas can be slightly stale. Use replica reads only where small staleness is acceptable.
Leave meaningful headroom, since replication buffers, snapshots and memory overhead need space. Do not size an instance to exactly match your data, and set alerts well before the limit.
Ask what happens if the cache is empty right now. If the answer is a short period of slower responses, the design is sound. If the answer is a crisis, add a fallback, protect the database, or reconsider what you are storing.
22Summary and Key Takeaways
Memorystore gives you managed, very fast in-memory data on open source engines. It shields databases from repeated reads, shares fast state such as sessions and counters across many servers, and supports real-time features like leaderboards and rate limiting. Google handles provisioning, patching and failover, while you decide the engine, tier, size, eviction behavior and the caching pattern.
The craft lies in respecting what memory is: fast, limited and forgetful. Keep a durable source of truth, set expiry on cached data, choose an eviction policy deliberately, run replicated or clustered setups in production, and avoid hot keys, big keys and heavy commands. Watch hit ratio, evictions and memory, rehearse failure, and keep applications close to the instance. Done well, Memorystore turns slow, expensive requests into instant answers.
Key Takeaways
- A speed layer, not a source of truth — keep authoritative data in a durable database, and design so the cache can be empty or lost without disaster.
- Pick the right family member — Memcached for simple disposable caching, Redis or Valkey for rich data structures, and clustered offerings for large scale and high throughput.
- Use patterns that fail gracefully — cache-aside with TTLs and invalidation is the safe default, and stampedes are prevented with jittered expiry and single-flight rebuilds.
- Manage memory on purpose — size from the working set with headroom, choose an eviction policy to match your data, and treat rising evictions as a resize signal.
- Buy availability where it matters — use replicated or clustered setups for production, remember replication is asynchronous, and make clients retry and reconnect during failover.
- Avoid the classic performance traps — spread hot keys, split big keys, pool connections, pipeline commands and never run whole-keyspace commands on a busy instance.
- Secure and observe it like a database — private networking, authentication, encryption in transit, careful choices about what to cache, and dashboards for memory, hit ratio, evictions and failovers.