Sub topic 10
Caching values in your application
This chapter assumes you can already read parameters and secrets from the CLI and SDK, as covered in the retrieval chapter. It also assumes you know how Secrets Manager versions and staging labels work, and that you have run Python with boto3. Here you will stop calling AWS on every read and keep values in memory for a short time.
Why cache
Each call to GetSecretValue or GetParameter is an HTTPS request. It adds latency, usually tens of milliseconds. It also counts against service quotas and shows up in CloudTrail. If the value is encrypted with a customer managed KMS key, each read also triggers a KMS Decrypt call. That call has its own quota and its own cost.
An application that reads its database password on every request pays these costs thousands of times for a value that changes rarely. A cache fixes this. The application loads the value once, keeps it in memory for a fixed time, and reloads it when that time expires.
Caching has three benefits:
- Lower latency. Cached reads happen in process memory.
- Fewer throttling errors. Many instances starting at once cannot overwhelm the API quota if each one reads only occasionally.
- Lower cost. Secrets Manager charges per 10,000 API calls, and KMS charges per request.
It also has a cost. The application can use a stale value until the cache expires. Most of this chapter is about managing that trade-off.
Choosing a time to live
The time to live (TTL) is how long an entry may be reused before it must be reloaded. It sets the worst-case delay before a change reaches your application.
| TTL | Effect | Typical use |
|---|---|---|
| 0 to 30 seconds | Changes appear almost at once, with little reduction in API calls | Feature flags that operators flip during incidents |
| 1 to 5 minutes | Good balance for most workloads | Database credentials, API keys, endpoints |
| 1 hour or more | Fewest calls, slowest to reflect changes | Values that effectively never change |
Match the TTL to your rotation design. If a secret rotates every 30 days and your TTL is one hour, the cache is not a problem. If you rotate with a mechanism that invalidates the old credential immediately, you need either a short TTL or retry logic, covered below.
Option 1: the Secrets Manager caching client
AWS publishes caching libraries for Secrets Manager in Python, Java, .NET, Go, and JavaScript. The Python one is aws-secretsmanager-caching. It keeps secrets in memory and refreshes them after a configurable interval. The default is one hour, so set it explicitly.
import json
import boto3
from aws_secretsmanager_caching import SecretCache, SecretCacheConfig
client = boto3.client("secretsmanager")
config = SecretCacheConfig(secret_refresh_interval=300) # seconds
cache = SecretCache(config=config, client=client)
creds = json.loads(cache.get_secret_string("myapp/prod/db"))
print(creds["username"])Install it with pip install aws-secretsmanager-caching. Create the SecretCache once, at module level or application startup. If you create a new one per request, every request misses and the cache does nothing.
By default the client caches the version with the AWSCURRENT staging label. When rotation moves that label to a new version, the client picks up the change on its next refresh.
Option 2: a small cache for Parameter Store
Parameter Store has no official caching client in boto3. Many applications write a small TTL cache. The following version works for both services and is safe to use from several threads.
import json
import threading
import time
import boto3
class TtlCache:
def __init__(self, ttl_seconds=300):
self._ttl = ttl_seconds
self._items = {}
self._lock = threading.Lock()
def get(self, key, loader, force=False):
now = time.monotonic()
with self._lock:
entry = self._items.get(key)
if entry and not force and now < entry[0]:
return entry[1]
value = loader() # network call happens outside the lock
with self._lock:
self._items[key] = (time.monotonic() + self._ttl, value)
return value
_cache = TtlCache(ttl_seconds=300)
_ssm = boto3.client("ssm")
_secrets = boto3.client("secretsmanager")
def get_parameter(name, force=False):
return _cache.get(
("ssm", name),
lambda: _ssm.get_parameter(Name=name, WithDecryption=True)["Parameter"]["Value"],
force,
)
def get_secret_json(secret_id, force=False):
return _cache.get(
("sm", secret_id),
lambda: json.loads(
_secrets.get_secret_value(SecretId=secret_id)["SecretString"]
),
force,
)
if __name__ == "__main__":
print(get_parameter("/myapp/prod/db/host"))
print(get_secret_json("myapp/prod/db")["username"])Some design points in this code:
time.monotonic()is used instead oftime.time(), so clock adjustments cannot expire or extend entries wrongly.- The loader runs outside the lock. If two threads miss at the same moment, both call AWS. That wastes one call but never blocks every thread behind a slow network request.
- The
forceargument bypasses the cache. You will use it for the retry pattern in the next section. - Failures are not cached. If the loader raises, nothing is stored and the next call tries again.
Handling rotation: refresh on failure
A TTL cache can hold a credential that rotation has already replaced. With the Secrets Manager rotation flow, the old version moves to AWSPREVIOUS and often keeps working for a while. Some databases or APIs reject it immediately, though. In that case your application sees authentication errors until the cache expires.
The standard defense is to treat an authentication failure as a signal that the cached value may be stale. Reload once with force=True and retry.
def connect_with_retry(connect):
"""connect(creds) opens a connection and raises PermissionError on bad credentials."""
creds = get_secret_json("myapp/prod/db")
try:
return connect(creds)
except PermissionError:
creds = get_secret_json("myapp/prod/db", force=True)
return connect(creds)Retry only once. If the fresh value also fails, the problem is not staleness, and looping would hammer both your database and the Secrets Manager API.
Option 3: the Lambda extension
In AWS Lambda, a new execution environment starts from scratch, and module-level caches last only as long as that environment does. The AWS Parameters and Secrets Lambda Extension is a layer that runs beside your function. It caches values and exposes them over a local HTTP endpoint. Its cache is shared by all invocations in the same environment, and you need no SDK calls in your own code.
The extension listens on port 2773 by default. Its default TTL is 300 seconds. You can change these with environment variables:
| Variable | Purpose | Default |
|---|---|---|
| `SECRETS_MANAGER_TTL` | Cache lifetime for secrets, in seconds | 300 |
| `SSM_PARAMETER_STORE_TTL` | Cache lifetime for parameters, in seconds | 300 |
| `PARAMETERS_SECRETS_EXTENSION_HTTP_PORT` | Local port | 2773 |
Requests must carry the function's session token in a header. The function's execution role still needs the usual IAM and KMS permissions, because the extension calls AWS with that role.
import json
import os
import urllib.parse
import urllib.request
def get_secret(secret_id):
url = "http://localhost:2773/secretsmanager/get?secretId=" + urllib.parse.quote(
secret_id, safe=""
)
request = urllib.request.Request(
url, headers={"X-Aws-Parameters-Secrets-Token": os.environ["AWS_SESSION_TOKEN"]}
)
with urllib.request.urlopen(request) as response:
return json.loads(json.loads(response.read())["SecretString"])For parameters, call /systemsmanager/parameters/get?name=...&withDecryption=true with the same header. Add the extension as a layer using the ARN that AWS publishes for your Region and architecture.
Pitfalls
- Logging cached secrets. A cache makes it easy to pass values around. Never log them, and never put them in exception messages.
- Caching per request. Create clients and caches once per process, not once per call.
- Cold starts. A cache is empty after startup, so the first read is always slow. If startup latency matters, load required values during initialization, not on the first user request.
- Many instances, one TTL. If a hundred instances start together and use the same TTL, they all expire together too. Adding a small random jitter to each TTL spreads the refresh load.
- Unbounded caches. A cache keyed by user-supplied names can grow without limit. Restrict keys to a known set of parameter and secret names.
Exercise
Your service caches a database secret for 15 minutes. Rotation replaces the password, and the database rejects the old one immediately. For up to 15 minutes afterward, requests fail with authentication errors. Name two changes that reduce this window without removing the cache.
Show answer
First, add refresh-on-failure logic: when a connection fails authentication, reload the secret once with the cache bypassed and retry the connection. Second, shorten the TTL, for example to 1 to 5 minutes. A third option is to use a rotation strategy that keeps the previous credential valid for a while, so the old value in the cache still works until it expires.