Sub topic 3
Caching Values in Applications and Operating Them Safely
Assume you know AWS regions, IAM roles, the AWS CLI, and basic Python. This chapter focuses on reducing retrieval calls and choosing safe integration patterns.
Cache values after retrieval
Applications should not call Parameter Store or Secrets Manager for every request. Each call adds latency, cost, and a possible dependency failure. Load values at startup or cache them for a short time. Refresh secrets before their rotation window ends.
import time
import boto3
client = boto3.client("secretsmanager")
cached = None
expires = 0
def get_password():
global cached, expires
if cached is None or time.time() >= expires:
result = client.get_secret_value(SecretId="myapp/prod/db")
cached = result["SecretString"]
expires = time.time() + 300
return cachedA cache can briefly hold an old value after rotation. Choose the lifetime according to your rotation and availability requirements.
Connect infrastructure and compute
CloudFormation dynamic references resolve values during deployment:
Environment:
Variables:
DB_HOST: '{{resolve:ssm:/myapp/prod/db/host}}'
DB_SECRET_NAME: myapp/prod/dbPass a secret’s name, rather than its value, to Lambda, ECS, or EC2. The workload’s IAM role then retrieves the value at runtime. This avoids placing the secret in a template or environment variable.
Choose the storage service
Use Parameter Store for hierarchical configuration, simple values, and lower-cost standard parameters. Use Secrets Manager for credentials, JSON documents, rotation, and secret-specific lifecycle features. Parameter Store can read a Secrets Manager value through /aws/reference/secretsmanager/, but this does not add rotation or change the underlying permissions.
Plan around limits and cost. Parameter values are limited to 4 KB in the standard tier and 8 KB in the advanced tier. Secrets Manager secret values support up to 64 KB. Advanced parameters and Secrets Manager secrets incur charges, and API calls can also affect cost.
Share, replicate, and audit
Cross-account access requires explicit IAM permissions, resource policies where supported, and KMS permissions. Secrets Manager can replicate secrets to other Regions. Treat each replica as another sensitive copy and restrict its access.
CloudTrail records access activity such as parameter and secret retrieval. Send trail logs to protected storage, alert on unexpected principals or Regions, and review failed access attempts.
Exercise
Why should an application cache a secret instead of retrieving it for every request?
Show answer
Caching reduces latency, API calls, cost, and dependence on a network service while the cache remains valid.