Using Memcache Stay organized with collections Save and categorize content based on your preferences.
This page describes how to configure and monitor the memcache service for yourapplication using the Google Cloud console. It also describes how to use the App Engine memcache PythonAPI to set and retrieve cached values and use the compare-and-set feature tohandle concurrent write requests to the same memcachekey. To learn more about memcache,read theMemcache Overview.
This API is supported for first-generation runtimes and can be used whenupgrading to corresponding second-generation runtimes. If you are updating to the App Engine Python 3 runtime, refer to themigration guide to learn about your migration options for legacy bundled services.Configuring memcache
- Go to the Memcache page in the Google Cloud console.
Go to the Memcache page Select the memcache service level you want to use:
- Shared (default) - free and provides cache capacity on a best-effort basis.
- Dedicated - billed by the GB-hour of cache size and provides a fixed cache capacity assigned exclusively to your application.
Learn more about available service classes inMemcache Overview.
Caching and retrieving values
Caching a value
Useadd() to add a key's value if and only if it doesn't already exist, withan optional expiration time:
memcache.add(key="[KEY]",value="[VALUE]",time=[EXPIRATION_TIME])For example, to add the valueraining to the keyweather_USA_98105 with anexpiration time of one hour from when the value is written:
memcache.add(key="weather_USA_98105",value="raining",time=3600)Learn more aboutadd() and other methods for setting values in thememcachePython APIdocumentation.
See other examples of caching values inMemcache Examples.
Looking up cached values
Useget() to look up the value of a single key:
memcache.get(key="[KEY]")For example, to get the value of the keyweather_USA_98105:
memcache.get(key="weather_USA_98105")Learn more aboutget() and other methods for looking up values in thememcache Python APIdocumentation.
Monitoring memcache in the Google Cloud console
- Go to the Memcache page in the Google Cloud console.
Go to the Memcache page - Look at the following reports:
- Memcache service level: Shows if your application is using the Sharedor Dedicated service level.If you are an owner of the project, you can switch between the two. Learnmore about theservice levels.
- Hit ratio: Shows the percentage of data requests that were served fromthe cache, as well as the raw number of data requests that were servedfrom the cache.
- Items in the cache.
- Oldest item age: The age of the oldest cached item. Note that the ageof an item is reset every time it is used, either read or written.
- Total cache size.
You can take any of the following actions:
- New key: Add a new key to the cache.
- Find a key: Retrieve an existing key.
- Flush cache: Remove all the key-value pairs from the cache.
(Dedicated memcache only) Look through the list ofHot keys.
- "Hot keys" are keys that receive more than 100 queries per second (QPS) inthe memcache.
- This list includes up to 100 hot keys, sorted by highest QPS.
Handling concurrent writes
To use the compare and set feature to handle writes from multiple requests tothe same memcache key:
- Instantiate a memcache
Clientobject. - Use a retry loop (preferably with a limit on the number of retries and usingexponential backoff)
- Within the retry loop, get the key using
gets()orget_multi()withthefor_casparameter set toTrue. - Within the retry loop, update the key value using
cas()orcas_multi().
- Within the retry loop, get the key using
The following snippet shows one way to use the compare and set feature:
defbump_counter(key):client=memcache.Client()whileTrue:# Retry loopcounter=client.gets(key)ifcounterisNone:raiseKeyError('Uninitialized counter')ifclient.cas(key,counter+1):breakThe retry loop is necessary because without the loop this code doesn't actuallyavoid race conditions, it just detects them! The memcache service guaranteesthat when used in the pattern shown here (that is, usinggets() andcas()),if two (or more) different client instances happen to be involved in a racecondition, only the first one to execute thecas() operation succeeds (returnTrue), while the second one (and subsequent ones) fails (returnFalse).
Another refinement you should add to this sample code is to set a limit on thenumber of retries, to avoid an infinite loop in worst-case scenarios where thereis a lot of contention for the same counter. An example of when such contentioncould occur is if there are more requests trying to update the counter than thememcache service can process in real time.
Learn more about compare and set in theMemcacheOverview.
What's next
- Learn more about memcache in theMemcache Overview.
- See code examples of using memcache in Python inMemcacheExamples.
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-12-15 UTC.