Database / Google Memorystore Interview questions
Last updated
1. What is Google Cloud Memorystore?
Teams typically put it in front of a slower database such as Cloud SQL or Spanner, or use it directly for sessions, counters, queues and leaderboards.
Google handles VM provisioning, OS and engine patching, replication, monitoring hooks and automatic failover (on tiers that support it). You still own key design, TTLs, eviction policy and client behaviour.
Take quiz
a managed object storage service
a managed in-memory data store service
a serverless SQL warehouse
a managed message-queue service
Google Cloud
the customer's on-call team
the application's client library
Cloud Build at deploy time
2. What are the engines supported by Memorystore?
Memorystore currently offers four products: Memorystore for Redis (single-node or primary/replica), Memorystore for Redis Cluster (sharded), Memorystore for Memcached and Memorystore for Valkey.
Redis and Redis Cluster are based on open-source Redis 7.2 and earlier. Valkey is the Linux Foundation fork of Redis and Memorystore supports versions 7.2, 8.0 and 9.0, with 9.1 in preview at the time of writing.
Pick by workload: simple cache with HA means Redis Standard tier, horizontal scale means Redis Cluster or Valkey, and pure multi-threaded key-value caching means Memcached.
Take quiz
Memcached
Valkey
Redis Cluster
MongoDB
a proprietary Google key-value format
Apache Cassandra
the open-source Valkey project
a fork of Memcached 1.4
3. What is Memorystore for Redis?
Memorystore for Redis is the original managed Redis offering. One instance is a single logical Redis deployment, either a lone node (Basic tier) or a primary with a replica in another zone (Standard tier).
Capacity runs from 1 GB up to 300 GB per instance, and supported versions run from Redis 3.2 through 7.2. Clients connect to a private IP address inside your VPC using private services access.
Because there is only one primary, write throughput is bounded by a single node. When you outgrow that, the usual next step is Memorystore for Redis Cluster.
Take quiz
one per zone
one
three, fixed
as many as there are shards
in a different zone from the primary
on the same VM as the primary
in another cloud region
in Cloud Storage
4. What is Memorystore for Redis Cluster?
Memorystore for Redis Cluster is a managed, sharded Redis deployment. Data is spread over many primaries (shards) using Redis Cluster hash slots, so both memory and throughput scale horizontally instead of being capped by one node.
You choose a node type and a shard count, plus zero to five replicas per shard. Replicas are spread across zones and failover is automatic, which is how the service reaches a 99.99% SLA on supported node types.
Shards can be added or removed while the cluster serves traffic. Clients must be Redis Cluster-aware, and the service also offers RDB/AOF persistence, TLS and cross-region replication.
Take quiz
adding read replicas only
increasing the TTL
enabling AOF
adding shards that own different hash slots
Basic tier Redis only
redis-shared-core-nano nodes
supported node types of Memorystore for Redis Cluster
any self-managed Redis on GCE
5. What is Memorystore for Memcached?
Memorystore for Memcached is a managed cluster of Memcached nodes. You pick the node count, the vCPU and memory per node, and Google runs it inside your VPC.
It is a pure cache: strings only, no persistence, no replication, no built-in data structures. Keys are spread across nodes by the client using consistent hashing, and an auto-discovery endpoint tells the client which nodes currently exist.
If a node is lost, the keys that lived there are simply gone and the application falls back to the database. That makes it a good fit for read-through caching of rebuildable data, but not for sessions or counters you cannot lose.
Take quiz
the Memorystore control plane
Cloud DNS
the client library, via hashing
the primary node
sorted sets and streams
simple key-value caching without persistence
AOF persistence
Lua scripting
6. What is Memorystore for Valkey?
Memorystore for Valkey is Google's managed service for Valkey, the open-source, Redis-compatible store maintained under the Linux Foundation. It uses a sharded cluster design like Redis Cluster.
Supported versions are 7.2, 8.0 and 9.0 (the default), with 9.1 in preview as of this writing. You can upgrade an instance in place to any newer version, for example 7.2 straight to 9.0.
Each primary can have up to five replicas, instances can be created in the remaining zones if one zone is unavailable, and multiple VPCs can reach one instance through Private Service Connect endpoints. Valkey 9.0 adds hash field expiration.
Take quiz
five
one
two
ten
no, you must recreate it
only to 8.0
only after exporting to Cloud Storage
yes, in place to any newer supported version
7. What are the service tiers in Memorystore for Redis?
Memorystore for Redis has two tiers. Basic is a single node with no replica and no SLA. Standard adds a replica in a second zone with automatic failover and a 99.9% availability SLA.
With Basic, any maintenance, scaling operation or node failure flushes the cache, so it suits development or caches that are cheap to rebuild. Standard keeps data through failover because the replica is continuously synced.
| Feature | Basic | Standard |
| Replica | None | One, in another zone |
| Failover | Not available | Automatic |
| SLA | None | 99.9% |
| Data on failure | Lost | Kept on replica |
| Read replicas | No | Optional, up to 5 |
Take quiz
Standard
Both tiers
Basic
Neither tier
nothing, the cache is flushed
the data synced to the replica
only keys with a TTL
only keys written in the last second
8. What is the purpose of a replica in Memorystore Standard tier?
The replica exists mainly for high availability. Writes land on the primary and are streamed asynchronously to the replica, which sits in a different zone.
If the primary or its zone fails, Memorystore promotes the replica and the instance keeps serving, normally with the same endpoint IP. The old primary is rebuilt as the new replica.
Because replication is asynchronous, a few of the most recent writes may be lost in an unplanned failover. If you enable read replicas on a Standard instance, the extra replicas can also serve read traffic.
Take quiz
take over when the primary fails
compress keys at rest
run Lua scripts faster
store the RDB file only
synchronous with a quorum
disabled until failover
manual, via gcloud
asynchronous
9. What are the common use cases of Memorystore?
The most common use is a read-through or cache-aside layer in front of Cloud SQL, Spanner or Firestore to cut read latency and database load.
Other frequent uses: session and token storage, rate limiting with atomic counters, leaderboards with sorted sets, job queues with lists or streams, pub/sub fan-out, and real-time feature lookups for ML serving. Redis Cluster also supports vector search for similarity workloads.
It is a poor fit as a system of record unless you accept the durability limits of persistence and asynchronous replication.
Take quiz
plain string
bitmap only
sorted set
HyperLogLog
it cannot store strings
in-memory data with async replication has limited durability
it has no private networking
it only runs one command per second
10. How do you create a Memorystore for Redis instance?
You can use the Cloud Console, Terraform or the gcloud CLI. The key choices are name, region, tier, capacity in GB, Redis version and the VPC network the instance attaches to.
gcloud redis instances create session-cache \ --region=us-east1 \ --tier=standard \ --size=5 \ --redis-version=redis_7_2 \ --network=default
Make sure the Memorystore for Redis API is enabled and private services access is configured on the VPC. Once the command finishes, gcloud redis instances describe shows the host IP and port (6379 by default) to hand to your application.
Pick the region close to your clients, since cross-region calls add tens of milliseconds. Terraform's google_redis_instance resource expresses the same settings, which keeps instance sizing reviewable in code.
Take quiz
gcloud memcache nodes launch
gcloud redis instances create
gcloud sql redis create
gcloud compute redis add
--tier
--size
--region
--redis-version
11. How do you connect to a Memorystore instance?
Memorystore for Redis exposes a private IP in your VPC, so clients must run in that network or a connected one: Compute Engine, GKE, Cloud Run or Cloud Functions via Serverless VPC Access or Direct VPC egress, or on-premises over VPN/Interconnect.
From a Compute Engine VM in the same VPC you can test with:
redis-cli -h 10.0.0.3 -p 6379 ping
If AUTH or TLS is enabled, supply the password and CA certificate. There is no public IP, so connecting from a laptop requires a bastion host, VPN or an SSH tunnel through a VM.
Take quiz
port 6379 is blocked by Redis itself
it requires a Google account cookie
it only accepts HTTPS
it only has a private IP in your VPC
Cloud CDN
Pub/Sub push
VPC connectivity such as Serverless VPC Access or Direct VPC egress
Cloud Armor
12. What is private services access in Memorystore for Redis?
Private services access is the VPC peering-based mechanism that lets Google-managed services such as Memorystore for Redis live in a Google-owned VPC yet be reachable from your VPC using internal IP addresses.
You reserve an IP range (for example a /16) in your VPC, then create a private connection to servicenetworking.googleapis.com. Instances are allocated addresses from that range.
Plan the range carefully. If it overlaps with other subnets or is too small, instance creation fails. Peering is non-transitive, so on-premises access needs custom route advertisement.
Take quiz
opening a public IP with a firewall rule
reserving an IP range and peering with Google's service network
tunnelling over SSH
exposing a Cloud Load Balancer
an overlapping or exhausted reserved IP range
using lowercase instance names
setting a TTL
enabling Cloud Logging
13. What is Private Service Connect in Memorystore?
Each instance gets a discovery endpoint and a data endpoint per node. The cluster client talks to the discovery address first to learn the topology, then connects to node endpoints directly.
One benefit is that several VPCs, even in different projects, can create PSC endpoints to the same instance, and no IP range overlap with Google's network has to be negotiated.
Take quiz
a public HTTPS URL
a Cloud NAT gateway
a Pub/Sub topic
Private Service Connect endpoints
it removes the need for a client library
it adds a public IP
multiple VPCs can have endpoints to the same instance
it disables TLS
14. What are the eviction policies in Memorystore for Redis?
When memory reaches maxmemory, Redis follows the configured maxmemory-policy. Memorystore for Redis lets you set it to one of these:
| Policy | Behaviour |
| noeviction | Reject writes with an error |
| allkeys-lru / allkeys-lfu | Evict least recently / frequently used key from all keys |
| volatile-lru / volatile-lfu | Same, but only among keys with a TTL |
| allkeys-random / volatile-random | Evict random keys |
| volatile-ttl | Evict keys with the shortest remaining TTL |
The default is volatile-lru. For a pure cache, allkeys-lru is usually safer because keys without a TTL can still be evicted. For data you cannot lose, use noeviction and alert on memory usage.
Take quiz
noeviction
volatile-lru
allkeys-random
volatile-ttl
have an expiry set
are larger than 1 MB
were created today
are hashes
15. What is the maximum capacity of a Memorystore for Redis instance?
A single Memorystore for Redis instance can be sized from 1 GB up to 300 GB. Bandwidth and throughput scale with the capacity you pick, because network egress limits are tied to instance size.
Redis itself runs commands on one main thread, so even a big instance is limited by single-node CPU. If you need more than 300 GB, or more throughput than one node gives, move to Memorystore for Redis Cluster or Valkey, which shard data across many nodes.
Take quiz
300 GB
16 GB
1 TB
5 TB
a larger Basic tier
more Cloud Storage buckets
Cloud SQL read replicas
a sharded product such as Redis Cluster
16. What is AUTH in Memorystore for Redis?
AUTH is Redis's password mechanism. When you enable it on a Memorystore for Redis instance, Memorystore generates an AUTH string and every client must send it, for example with AUTH <string> or in the connection URL.
It protects against other workloads in the same VPC that can reach the IP but should not read the data. It does not encrypt traffic. Pair it with in-transit encryption (TLS) if the connection crosses untrusted segments.
Rotating the string is possible but requires coordinating client updates, so keep it in Secret Manager rather than in code.
Take quiz
encryption of data in transit
automatic backups
a shared password clients must present
IAM role binding to each key
a public Git repository
Secret Manager
the instance name
a Cloud Storage object with public read
17. What is in-transit encryption in Memorystore?
In-transit encryption wraps client-to-Redis traffic in TLS. You turn it on when you create the instance, since for Memorystore for Redis it generally cannot be switched on later.
After creation you download the server CA certificate and configure your client with it. Clients then connect with TLS (often on the same port) and verify the server certificate.
Expect a small CPU cost for the handshake and encryption, so use connection pooling to avoid re-handshaking on every request.
Verify it end to end with redis-cli --tls --cacert server-ca.pem. A certificate or hostname mismatch is the most common cause of handshake errors.
Take quiz
TLS
base64 encoding
RDB compression
DNS over HTTPS
the project billing ID
a Cloud KMS key ring
the replica's MAC address
the server CA certificate
18. What are RDB and AOF persistence in Memorystore?
Memorystore for Redis Cluster and Valkey support both modes as managed features. Persistence helps recover after node loss or restart, but it is not a replacement for backups to Cloud Storage when you need long retention.
Take quiz
RDB
neither
AOF
Cloud Logging
no snapshots at all
faster restarts but more potential data loss
slower writes on every command
no compression
19. Describe the cache-aside pattern with Memorystore?
In cache-aside (lazy loading) the application owns the cache logic. It checks Memorystore first, falls back to the database on a miss, then writes the result back with a TTL.
def get_product(pid): key = f"product:{pid}" cached = r.get(key) if cached: return json.loads(cached) # cache hit row = db.fetch_product(pid) # cache miss r.setex(key, 300, json.dumps(row)) # populate, 5 min TTL return row
On updates, either delete the key (simplest and safest) or rewrite it. The pattern tolerates cache loss, since the database stays the source of truth, but stale reads are possible until the TTL expires or the key is invalidated.
Wrap the database call in a lock or request coalescing for hot keys, otherwise many parallel misses can all hit the database together.
Take quiz
reads the database and then populates the cache
returns an error to the user
waits for Memorystore to fetch it
flushes the whole instance
disabling replication
using Basic tier
larger instance size
a TTL or explicit invalidation on update
20. What is a maintenance window in Memorystore?
A maintenance window is the day and hour you tell Memorystore it may apply updates, such as engine patches or infrastructure upgrades, to your instance.
Pick a quiet period for your traffic. If you set none, Google chooses the time. On Basic tier maintenance flushes the cache, while on Standard tier the replica is updated first and then a failover happens, causing a short disconnect.
Maintenance changelogs and Cloud Logging entries tell you what was applied, and Memorystore can notify you ahead of time so you can plan client retries.
Take quiz
which keys are evicted
the Redis port
the cache hit ratio
when updates may be applied
it stays fully available
it moves to Standard tier
its data is lost because there is no replica
it changes region
21. How do you monitor Memorystore?
Memorystore publishes metrics to Cloud Monitoring automatically, and logs go to Cloud Logging. You build dashboards and alerting policies on top of them.
Metrics worth alerting on:
| Metric | Why it matters |
| Memory usage ratio | Close to 100% means evictions or write errors |
| Cache hit ratio | Falling ratio signals bad keys or TTLs |
| Evicted keys | Cache is too small or policy is aggressive |
| Connected clients | Spikes point to connection leaks |
| CPU utilization | Single-thread saturation hurts latency |
| Replication offset lag | Replica may lose data on failover |
Database Center also surfaces recommendations across instances. Use INFO and SLOWLOG from redis-cli for per-command detail.
Take quiz
BigQuery only
Cloud Monitoring
Cloud Build
Firebase Console
the cache is too small for the working set
the TLS certificate expired
the VPC has too many subnets
the replica is healthy
22. How do you control access to Memorystore with IAM?
IAM governs the control plane: who can create, update, delete, import or export instances. Predefined roles include Redis Admin, Redis Editor and Redis Viewer, and Memcached has similar ones.
IAM does not, by itself, decide who can run GET or SET on keys. Data access is controlled by network reachability and by AUTH. For Redis Cluster and Valkey you can additionally use IAM-based authentication for clients, so no static password has to be shared.
Follow least privilege: give application service accounts only the access they need and keep admin roles for the platform team.
Take quiz
each individual GET and SET
key-level ACLs only
the VPC's MTU
management actions on instances
Owner on the project
Redis Admin for everyone
Redis Viewer or a narrow custom role
Editor on the organization
23. What are the node types in Memorystore for Redis Cluster?
Every shard in a cluster uses the same node type, which fixes the memory and vCPUs per node. The main types are redis-shared-core-nano, redis-standard-small, redis-highmem-medium, redis-highmem-xlarge and redis-highcpu-medium.
The nano type targets tiny workloads and has no SLA, so keep it out of production. Standard-small allows small clusters and small growth steps. Highmem types give more RAM per core for large datasets, while highcpu gives more compute per GB.
You can change the node type after creation, which lets you right-size as the workload grows.
Take quiz
redis-highmem-xlarge
redis-shared-core-nano
redis-highcpu-medium
redis-highmem-medium
redis-highcpu-medium
redis-shared-core-nano
redis-highmem-xlarge
a Memcached node
24. What are shards in Memorystore for Redis Cluster?
A shard is one primary node plus its replicas. Each shard owns a slice of the 16,384 hash slots, and each key belongs to exactly one slot, so it lives on exactly one shard.
More shards mean more total memory, more CPU and more connections. Replica count is configured per cluster, from zero to five replicas per shard, and each shard's nodes are spread across zones.
Adding or removing shards triggers slot migration in the background while the cluster keeps serving requests.
Take quiz
a Cloud Storage bucket
a single read-only replica
one hash slot
a primary and its replicas
1,024
65,536
16,384
256
25. What is the difference between Memorystore for Redis and Redis Cluster?
Both run Redis-compatible engines, but they scale differently. The classic product is one primary with an optional replica, while the cluster product shards data across many primaries.
| Aspect | Memorystore for Redis | Redis Cluster |
| Data layout | Single primary, whole keyspace | Sharded over 16,384 slots |
| Max capacity | Up to 300 GB | Terabytes across shards |
| Write scaling | Vertical only | Add shards |
| Connectivity | Private services access | Private Service Connect |
| Client | Standard client | Cluster-aware client |
| SLA | 99.9% (Standard) | 99.99% |
| Multi-key ops | Any keys | Same slot only |
Choose the classic product for simple caches that fit on one node. Choose the cluster product when you need more memory, more throughput or a higher availability target.
Take quiz
Basic tier Redis
Memcached
Memorystore for Redis Cluster
none of them
Redis Cluster without hash tags
non-cluster Memorystore for Redis
Valkey with any key set
no product at all
26. What is the difference between Redis and Memcached in Memorystore?
| Aspect | Redis | Memcached |
| Data types | Strings, hashes, lists, sets, sorted sets, streams | Strings only |
| Persistence | RDB/AOF on cluster products | None |
| Replication | Replica in Standard tier | None |
| Threading | Main thread (I/O threads in newer versions) | Multi-threaded |
| Sharding | Server-side (cluster) or none | Client-side hashing |
| Scripting and pub/sub | Yes | No |
Redis does more and offers failover, so it is the default choice. Memcached is simpler and uses every core on a node, which suits large volumes of small, disposable cache entries.
Memcached loses a node's data on failure, so only store things the database can rebuild.
A practical rule: if you ever think "I wish I could increment this atomically" or "I need this to survive a restart", you already need Redis, not Memcached.
Take quiz
Redis
Memcached
both equally
neither
on the Memorystore primary
in Cloud Load Balancing
in IAM
on the client
27. How does failover work in Memorystore Standard tier?
A health monitor watches the primary. If it stops responding, or its zone fails, Memorystore promotes the replica to primary, then creates a new replica in the freed zone.
sequenceDiagram
participant C as Client
participant P as Primary (zone A)
participant R as Replica (zone B)
participant M as Memorystore monitor
C->>P: writes
P-->>R: async replication
M->>P: health check fails
M->>R: promote to primary
C->>R: reconnect, same endpoint IP
M->>P: rebuild as new replica
The primary endpoint IP stays the same, so clients just reconnect. Writes accepted by the old primary but not yet replicated can be lost. You can also trigger a manual failover to test your clients, with a limited-data-loss or force-data-loss mode.
Clients should use short connect timeouts, retry with backoff, and reopen pooled connections after a failover, otherwise they keep writing to sockets that point at the dead node. Failover typically completes within about a minute, but test your own app rather than assuming.
Take quiz
a new public IP
a Cloud Storage URL
the same primary endpoint IP
a brand new project
all writes older than a day
writes not yet replicated to the replica
only reads
none, replication is synchronous
28. How does Memorystore for Redis Cluster achieve high availability?
Availability comes from three things: replicas, zone spreading and automatic failover. Each shard can have replicas placed in different zones, so one zone outage doesn't take out a whole shard.
When a primary fails, the cluster promotes one of its replicas and updates the topology that clients see. No manual action is needed, and clients with proper cluster logic refresh their slot map after a redirect.
Replicas, AOF/RDB persistence and cross-region replication stack on top for recovery and disaster recovery. The 99.99% SLA assumes at least one replica per shard on supported node types.
Also check that your client sends reads only where you intend. A replica read right after a failover can briefly see older data, so keep read-your-own-write paths on the primary.
Take quiz
replicas of each shard placed in other zones
a larger TTL
Cloud CDN
running fewer shards
zero replicas
the nano node type
disabling persistence
at least one replica per shard
29. How does scaling work in Memorystore for Redis?
You can resize an instance (up or down) with gcloud redis instances update --size. The capacity change is applied by Memorystore, not by you.
On Basic tier, scaling flushes all data and the instance is unavailable for a short time. On Standard tier, the replica is scaled first and a failover follows, so there is only a brief interruption and data is preserved.
Even on Standard tier, run scaling during low traffic and make sure clients retry on connection errors. Shrinking requires that the new size can hold the current dataset.
Scaling also changes bandwidth and throughput limits, since both depend on instance size, so a resize can fix network-bound latency even when memory is not the bottleneck.
Take quiz
it is migrated live
it is exported automatically
it is flushed
nothing, scaling is invisible
pausing all clients for an hour
resizing the replica first and then failing over
deleting the replica
switching to Memcached
30. How does Memorystore for Redis Cluster scale shards without downtime?
When you change the shard count, Memorystore moves hash slots between shards in the background. The keys in each moving slot are migrated while the cluster keeps answering requests.
flowchart LR
A["Add shard"] --> B["New shard joins, owns no slots"]
B --> C["Pick slots to move"]
C --> D["Migrate keys slot by slot"]
D --> E["Update slot map"]
E --> F["Clients get redirected"]
During migration a client may get a MOVED or ASK redirect, which cluster-aware clients handle on their own. Expect a little extra latency for keys in transit. Scale out ahead of load, not in the middle of a spike.
Track progress in the operation status shown by gcloud or the Console. If a cluster is already close to its memory limit, scale earlier, because the migrating keys briefly exist on both sides.
Take quiz
rewriting the AOF
migrating hash slots to the new shard
changing every key name
restarting all clients
a redirect such as MOVED or ASK
a 404 page
a Cloud Storage signed URL
nothing, the key is deleted
31. When should you choose Redis Cluster over Standard tier?
Choose Redis Cluster when your dataset or throughput will not fit comfortably on a single node, or when you need the 99.99% SLA, zero-downtime scaling and zone-distributed replicas.
Stay on Standard tier when the data is under a few tens of GB, the workload is mostly simple, and your code uses multi-key commands or Lua scripts across arbitrary keys that would be awkward on a sharded layout.
Migrating later means changing the client to a cluster-aware one and reviewing key design, so decide early if growth is likely.
A simple test: estimate peak ops per second and dataset size for the next year. If either approaches the capacity of one node, begin with Cluster and avoid a later migration.
Take quiz
you need only 2 GB cache
you don't want TLS
you use only SET/GET on a tiny dataset
the dataset or write rate exceeds one node
rename the VPC
switch to SQL
use a cluster-aware client and review multi-key commands
remove all TTLs
32. When would you choose Memcached over Redis?
Pick Memcached when the job is purely to cache rebuildable values as plain strings and you want simple horizontal scaling with all cores of each node in use.
Typical fits are HTML fragments, query results and API responses where a lost node just means a temporary drop in hit ratio. If you need persistence, replication, atomic counters, sorted sets, streams or pub/sub, choose a Redis-compatible product instead.
Remember that Memcached sharding happens in the client, so every service must use the same hashing configuration and the auto-discovery endpoint.
Memcached also tolerates adding nodes easily, though consistent hashing means only a fraction of keys move and the rest stay put. Test the hit-ratio dip when you resize.
Take quiz
need AOF durability
only cache rebuildable string values
need sorted sets
need pub/sub
the same hashing scheme and node list
a single TTL
the same Redis password
the same Linux kernel
33. How do read replicas work in Memorystore for Redis?
On Standard tier you can enable read replicas, which adds up to five replicas in total and a separate read endpoint. The read endpoint spreads connections across the replicas.
Writes still go to the primary endpoint. Replication is asynchronous, so a read replica may return slightly old data. Treat it as eventually consistent: good for product catalogs, not for balance checks.
The point is to offload read-heavy traffic from the primary and to have more failover candidates. Remember that enabling read replicas is an instance-level setting that affects pricing and can't simply be toggled off at will.
Use the read endpoint only for paths where staleness is acceptable, and monitor replication lag so a lagging replica doesn't serve very old values.
Take quiz
always strongly consistent
encrypted with a different cipher
blocked by IAM
slightly stale
to the read endpoint
to any replica at random
to the primary endpoint
to Cloud Storage
34. How does a cluster client discover nodes in Memorystore?
The client starts from the instance's discovery endpoint, a PSC address that returns the current cluster topology. It asks for the slot-to-node mapping (for example with CLUSTER SLOTS) and keeps it in memory.
From then on, it hashes each key, looks up the owner node endpoint and sends the command there directly. If the topology changes, a MOVED reply makes the client refresh its map.
from redis.cluster import RedisCluster rc = RedisCluster(host="10.1.0.5", port=6379) # discovery endpoint rc.set("user:42:name", "Asha") print(rc.get("user:42:name"))
Don't hard-code individual node IPs, since replicas and primaries swap roles during failover.
Most cluster clients also re-run discovery periodically and on connection failures, so a node replaced by Memorystore is picked up without an application restart.
Take quiz
each node IP hard-coded
the discovery endpoint
Cloud DNS TXT records
the control plane API
a MOVED redirect
a successful GET
a Cloud Billing alert
a change in TTL
35. What happens when Memorystore reaches maxmemory?
Redis applies the configured maxmemory-policy. With an eviction policy such as allkeys-lru, it removes keys to make room for each new write, so the evicted-keys metric climbs and hit ratio drops.
With noeviction, writes that need more memory fail with an OOM error while reads keep working. Applications that don't handle that error can start failing in odd ways.
Memory fragmentation and replication buffers also consume RAM beyond the dataset, so alert well before 100% usage. The fix is a bigger instance or more shards, shorter TTLs, smaller values or a more selective eviction policy.
Check that the application handles the OOM error and does not retry in a tight loop, since that adds load to an already full instance.
Take quiz
fails with an OOM error
silently deletes the oldest key
is queued forever
is redirected to Cloud Storage
replica count
disk IOPS
number of subnets
evicted keys
36. How do you troubleshoot high latency in Memorystore?
Start by separating server time from network and client time. Run redis-cli --latency from a VM in the same zone and compare it with what the app sees.
Then check the usual suspects in order:
- CPU near 100% on the primary, since Redis is mostly single-threaded.
SLOWLOG GETfor O(N) commands such as KEYS, SMEMBERS on huge sets or large LRANGE calls.- Big keys that block the thread while being read or deleted (use UNLINK instead of DEL).
- Memory at the limit, causing constant eviction work.
- Connection storms or missing pooling that add handshake overhead.
- Cross-zone or cross-region client placement.
Fix the cause: replace KEYS with SCAN, split big keys, add shards or replicas for reads, and keep clients in the same region.
Take quiz
PING
GET on a small key
KEYS *
SETEX with a short TTL
INFO clients only
SLOWLOG GET
DBSIZE
FLUSHALL
37. Why do you need a cluster-aware client for Memorystore Redis Cluster?
Because the keyspace is split across shards, a node only answers for the slots it owns. For any other key it replies with a MOVED redirect. A plain client doesn't follow redirects and would just see errors.
A cluster-aware client loads the slot map, computes CRC16(key) mod 16384 locally and sends each command to the right node. It also refreshes the map after failover or resharding and splits pipelines per node.
Examples include redis-py's RedisCluster, Jedis/Lettuce cluster mode and ioredis Cluster. Multi-key commands only work when every key maps to the same slot, which you can force with hash tags.
Take quiz
MOVED redirect errors
faster responses
automatic sharding
a Cloud Storage fallback
MD5(key) mod 100
key length mod 3
SHA-1 of the project ID
CRC16(key) mod 16384
38. How do you import and export data in Memorystore for Redis?
Memorystore for Redis can export an RDB snapshot of an instance to a Cloud Storage bucket and import an RDB file from a bucket into an instance.
gcloud redis instances export gs://my-bucket/cache.rdb my-cache --region=us-east1 gcloud redis instances import gs://my-bucket/cache.rdb my-cache --region=us-east1
The instance's service account needs access to the bucket. An import replaces what is in the target instance, and during an import the instance is not available for normal use, so schedule it. On Standard tier, export is taken from the replica path to limit impact on the primary, but plan for a short latency bump anyway.
This is also the simplest backup method: export on a schedule with Cloud Scheduler and keep files under a bucket lifecycle rule.
Take quiz
Cloud SQL
Persistent Disk attached to your VM
a Cloud Storage bucket
Pub/Sub
merges it with the file
replaces it with the imported dataset
ignores the file
doubles the TTLs
39. How do you migrate an existing Redis deployment to Memorystore?
The right method depends on how much downtime and data loss you can tolerate.
| Method | Downtime | Notes |
| RDB snapshot to Cloud Storage, then import | Window needed | Simple, data after the snapshot is missed |
| Live replication tools such as RIOT | Minimal | Keeps target in sync until cutover |
| Dual writes from the app | None if done carefully | Needs app changes, then cut reads over |
| Warm-up only (cold start) | None | Fine for pure caches, expect a miss spike |
For a pure cache, many teams skip data copy altogether and just let the new instance warm up. For a store with real data, use RDB import plus a live sync, check key counts and sample values, switch clients, then retire the old deployment.
Check version compatibility first: Memorystore supports Redis 7.2 and earlier, so a newer source may use features or RDB formats it cannot load.
Take quiz
start empty and let it warm up
freeze all traffic for a week
export the database to BigQuery
hand-copy keys one by one
RDB files are always text
Cloud Storage rejects RDB
TTL values change
the source may be newer than what Memorystore supports
40. What is cross-region replication in Memorystore for Redis Cluster?
Cross-region replication links a primary cluster in one region to one or more secondary clusters in other regions. Writes go to the primary and are copied asynchronously to the secondaries, which are read-only.
flowchart LR
App1["App in region A"] -->|reads and writes| P["Primary cluster, region A"]
P -->|async replication| S["Secondary cluster, region B"]
App2["App in region B"] -->|reads| S
It serves two purposes: regional disaster recovery and low-latency reads close to users in other regions. In a regional outage you can switch the roles so a secondary becomes the primary.
Because the link is asynchronous and crosses regions, expect some replication lag and possible loss of the latest writes on an unplanned failover.
Test the switchover regularly. A DR plan that was never exercised often fails on DNS, client config or capacity in the secondary region, not on Redis itself.
Take quiz
independent writable shards
Memcached nodes
backups in Cloud Storage
read-only copies
compressing keys
lowering TLS cost
regional disaster recovery and nearer reads
removing AUTH
41. How does CMEK work with Memorystore?
By default Memorystore encrypts data at rest with Google-managed keys. With CMEK (customer-managed encryption keys) you instead point the instance at a key you control in Cloud KMS.
You create the key and key ring, grant the Memorystore service agent the cloudkms.cryptoKeyEncrypterDecrypter role on it, then reference the key when creating the instance. The key location must match the instance region.
If you disable or destroy the key, the service can no longer decrypt the persisted data, so treat key lifecycle as part of your operations. CMEK helps meet compliance rules but doesn't replace TLS or AUTH.
Audit access with Cloud Audit Logs on the key, and use separate keys per environment so that disabling a test key never touches production data.
Take quiz
Secret Manager only
Cloud KMS
Cloud DNS
Cloud Run
the encrypted data can no longer be decrypted
data is moved to Standard tier
the instance doubles in size
clients get a new password
42. How do you secure a Memorystore deployment?
Think in layers, since no single feature covers everything:
- Network: keep the instance on private IPs only, restrict who can reach the VPC or PSC endpoint with firewall rules, and consider VPC Service Controls.
- Authentication: enable AUTH (or IAM auth on cluster products) and store secrets in Secret Manager.
- Encryption: turn on TLS for in-transit traffic and use CMEK where policy requires.
- Access control: use least-privilege IAM roles for managing instances.
- Visibility: enable audit logs and alert on unusual client counts.
Some options, such as in-transit encryption, are chosen at creation time, so decide before launch, not after.
Also run Redis commands with least privilege: on cluster products with ACL or IAM auth, avoid giving application users administrative commands like FLUSHALL and CONFIG.
Take quiz
exposing a public IP
disabling VPC
opening 0.0.0.0/0 to port 6379
private IP only plus firewall rules
it can only be enabled by Google support
it is free only on Fridays
it is typically chosen when the instance is created
it requires Memcached
43. How can you optimize Memorystore cost?
Cost is driven by provisioned capacity, node count and tier, not by how much of it you use, so right-sizing is the main lever.
- Use Basic tier or a smaller node type in dev and test.
- Size from the working set plus headroom, using memory usage and hit ratio metrics, then shrink if you are far below.
- Use shorter TTLs and compression so fewer GB are needed.
- Pick replicas by need: zero replicas for rebuildable caches in Cluster, one or more for critical data.
- Buy committed use discounts for steady production usage.
- Delete idle instances and use deletion protection only where required.
Always compare saved cost against the extra database load a smaller cache will cause.
Review the bill monthly alongside the hit-ratio chart. A cache with a 20% hit ratio is usually costing money without saving much database load.
Take quiz
number of GET calls
provisioned capacity and node configuration
number of TTLs
size of your VPC
committed use discounts
spot instances
free-tier credits
sustained downtime
44. How can you optimize memory usage in Memorystore?
Redis stores every key plus overhead, so small design choices add up at millions of keys.
- Use short, consistent key names.
- Pack small related fields into hashes, which use compact encodings below size thresholds.
- Set TTLs so stale data leaves on its own.
- Compress large values (for example gzip or snappy) on the client.
- Avoid huge keys; split them into buckets.
- Pick integer IDs over long UUID strings where possible.
- Check usage with
MEMORY USAGE keyand--bigkeys.
Also leave headroom for fragmentation and replication buffers by not running memory at 100%.
For example, storing 1 million small user records as 1 million separate keys costs far more RAM than bucketing them into hashes of a few hundred fields, because each top-level key carries its own overhead.
Take quiz
one string key per field with long names
unbounded lists
uncompressed JSON blobs
hashes with compact encoding
PING
TTL
MEMORY USAGE
DBSIZE
45. Why is setting a TTL important when caching in Memorystore?
A TTL gives every cached value a lifetime, so stale entries expire by themselves and memory is reclaimed without any cleanup job.
It also bounds how stale a read can be, which is your effective consistency window in cache-aside. Without TTLs, a missed invalidation can serve wrong data forever, and the instance slowly fills until eviction or OOM errors start.
Pick TTLs from how often data changes and how bad staleness is, and add a little random jitter so many keys don't expire at the same instant. Note that volatile-* eviction policies can only evict keys that have a TTL.
For data like feature flags, a short TTL of a few seconds still gives most of the benefit while keeping changes visible quickly.
Take quiz
encrypts the value
moves keys to another shard
limits how long an entry can stay and go stale
disables replication
it evicts everything at once
only keys with an expiry are eligible to be evicted
it ignores memory
it requires Memcached
46. What happens when many cached keys expire at the same time?
All the requests for those keys miss at once and hit the database together. This is a cache stampede (thundering herd), and it can overload the backend exactly when it is least ready.
Ways to reduce it:
- Add random jitter to TTLs so expiries spread out.
- Use a short lock (
SET lock:key 1 NX EX 10) so one request rebuilds the value while others wait or serve stale data. - Refresh hot keys early in the background.
- Keep a stale copy with a longer TTL as fallback.
- Rate-limit or queue database access.
Warm the cache after a restart or failover on Basic tier too, since it comes back empty.
Log the miss rate per key prefix. A sudden synchronized spike after a deploy or a restart is the signature of a stampede, not of a general traffic increase.
Take quiz
spreading expirations over time
encrypting entries
increasing the TTL to infinity
disabling eviction
FLUSHALL
KEYS *
a larger maxmemory
SET with NX and an expiry as a lock
47. Which is better and why: Memorystore or self-managed Redis on Compute Engine?
For most teams Memorystore wins, because patching, failover, monitoring hooks, backups and networking are handled for you, and the SLA comes with the service.
| Aspect | Memorystore | Self-managed Redis |
| Operations | Managed by Google | You patch, monitor, fail over |
| Version freedom | Supported versions only | Any version or module |
| Config control | A curated set of settings | Full redis.conf |
| Failover | Built in (Standard, Cluster) | Sentinel or Cluster you run |
| SLA | 99.9% to 99.99% | Yours to build |
| Cost | Service premium | VM cost plus ops time |
Self-managed makes sense if you need a newer Redis version, custom modules or kernel-level tuning that Memorystore doesn't allow. Count engineer time and on-call risk before deciding it is cheaper.
A hybrid is also common: Memorystore in production for reliability, and a containerized Redis on a developer laptop or CI for fast local tests.
Take quiz
you want Google to patch it
you want a managed SLA
you need a custom module or unsupported version
you want built-in failover with no effort
your Terraform loop
Memorystore itself
each client at runtime
Cloud Build
48. How do you choose between Memorystore for Valkey and Redis Cluster?
Both are sharded, PSC-connected and highly available, so the choice is mostly about engine and roadmap. Redis Cluster follows open-source Redis 7.2 and earlier, while Valkey is the community-governed fork with active releases (9.0 as default, 9.1 in preview).
| Consideration | Valkey | Redis Cluster |
| Engine line | Valkey 7.2, 8.0, 9.0 | Redis 7.2 and earlier |
| Newer features | Yes, such as hash field expiration in 9.0 | Frozen at 7.2 level |
| Replicas per primary | Up to 5 | Up to 5 |
| Upgrade path | In-place to newer Valkey | Within supported versions |
| Existing clients | Redis-compatible | Redis-compatible |
For new projects Valkey is the forward-looking choice. Stay on Redis Cluster if you depend on a feature only offered there, such as a specific module or API, and check the current docs for gaps before committing.
Take quiz
Valkey
Memcached
Redis 3.2
Redis 6.0
Valkey has no replicas
Valkey cannot be sharded
Redis Cluster is free
it relies on a feature available only there
49. Explain the internal working of hash slots in Redis Cluster?
Redis Cluster divides the keyspace into 16,384 hash slots. For every key the slot is CRC16(key) mod 16384. Each primary owns a range of slots, for example 0-5460, 5461-10922 and 10923-16383 in a three-shard cluster.
flowchart TD
K["key: user:42"] --> H["CRC16 mod 16384 = slot 8123"]
H --> L{Which shard owns slot 8123?}
L --> S2["Shard 2 primary"]
S2 --> RR["Replicas of shard 2"]
If the key contains hash tags in braces, only the part inside the first braces is hashed. That lets related keys share a slot so multi-key commands, transactions and Lua scripts work.
SET {cart:42}:items 3 SET {cart:42}:total 59.90 MGET {cart:42}:items {cart:42}:total # same slot, allowed
Moving a slot means copying its keys to another primary and then updating ownership. Don't overuse one tag for huge groups, or you create a hot shard.
This design is why a cluster has a hard upper limit of 16,384 primaries in theory. Real clusters are far smaller, and Memorystore sets its own shard limits per node type.
Take quiz
the whole string including braces
only items
cart:42
only the final character
to encrypt keys
to put related keys in one slot for multi-key commands
to set TTLs faster
to add replicas
50. How do you design a session store using Memorystore?
Store each session under a key like sess:<id>, as a string with JSON or as a hash, and set a TTL equal to the session timeout. Refresh it with EXPIRE on activity for sliding expiry.
Because losing sessions logs users out, use Standard tier (or a cluster with replicas) rather than Basic, and enable persistence if you want to survive restarts. Make the session ID unguessable and keep values small.
Choose volatile-lru or volatile-ttl eviction so only expiring session keys are evicted. Stateless services can then share the same store, and a failover costs at most a few recent writes.
r.hset(f"sess:{sid}", mapping={"uid": 42, "role": "admin"}) r.expire(f"sess:{sid}", 1800) # 30 minutes
Never store raw passwords or secrets in the session; keep only a user ID and the minimum claims, and rotate the session ID after login to prevent fixation attacks.