Lesson 2 of 4 Scaling Compute, Caching and Global Deployment

Choosing and Implementing Caching Solutions

Caching stores frequently used data closer to where it is needed so that it can be served faster and with less load on the source. Caches are among the most effective tools for scalability, but they introduce questions of freshness and failure behaviour. This lesson explains caching layers on AWS, cache strategies, invalidation and expiry, and how to choose the right cache for a bottleneck.

Learning outcomes

After completing this lesson, you will be able to:

  • Describe the caching layers available on AWS from the edge to the database.
  • Compare lazy loading and write-through cache strategies and the role of TTLs.
  • Distinguish between ElastiCache, DAX, API Gateway caching and CloudFront caching for a given bottleneck.
  • Distinguish between ElastiCache as a cache and Amazon MemoryDB as a durable in-memory database.
  • Explain failure modes of caches, such as stampedes and cold caches, and how to mitigate them.

Caching Layers

A request can be served from a cache at several points between the user and the data. Each layer removes load from everything behind it.

LayerAWS serviceCachesRemoves load from
EdgeAmazon CloudFrontStatic assets, cacheable API responsesOrigins, load balancers, application tier
APIAPI Gateway REST API stage cacheResponses per method and cache keyBackend integrations such as Lambda
ApplicationAmazon ElastiCache (Valkey, Redis OSS, Memcached)Query results, sessions, computed objectsDatabases and services
DatabaseDynamoDB Accelerator (DAX)DynamoDB item and query resultsDynamoDB read capacity
Database replicasRDS read replicas, Aurora replicasNot a cache, but offloads readsThe primary database

The best layer is usually the one closest to the user that can still serve correct data: a response cached at the edge never reaches the Region at all. Data that is personalised or changes per request cannot be cached at the edge, so it is cached nearer the data.

The following diagram shows the caching layers in the order a request meets them.

Caching layers between users and data. CloudFront caches static assets and cacheable responses at the edge. The API Gateway REST API stage cache stores responses per method and cache key. ElastiCache holds query results, sessions and computed objects for the application. DynamoDB Accelerator caches DynamoDB reads. Read replicas are not a cache but offload reads from the primary. Each layer removes load from everything behind it, and the best layer is usually the one closest to the user that can still serve correct data.
A response served at the edge never reaches the Region.
Sort into groups

Cache at the right layer

Exam skills 3.2.2

Choose the cache layer for each bottleneck.

Log in to try this activity Interactive activities are free with an account.

Cache Strategies

Two strategies determine how data enters an application cache.

Lazy loading (cache-aside)

The application reads from the cache; on a miss, it reads from the database and writes the result to the cache. Only requested data is cached, and a cache failure is not fatal because the application falls back to the database. The drawbacks are that each miss costs three trips, and cached data can become stale when the database changes.

Write-through

The application writes to the cache whenever it writes to the database, so the cache is always current for written data. Reads are fast and fresh, but every write costs more, and the cache fills with data that may never be read.

In practice, the two are combined with a time to live (TTL) on every cached item: write-through keeps hot data fresh, lazy loading fills gaps, and the TTL bounds staleness and evicts unused data. Eviction policies such as least recently used remove items when memory is full.

Lazy loading
Data in cacheOnly data that was requested
StalenessPossible until TTL expires
Cost of a miss or writeExtra latency on misses
Cache failure impactFalls back to the database
Choose when Read-heavy data where some staleness is acceptable.
Write-through
Data in cacheAll written data
StalenessMinimal for written data
Cost of a miss or writeExtra latency on writes
Cache failure impactWrites must handle cache errors
Choose when Data that must be fresh when read soon after writing.

Choosing a Cache for the Bottleneck

The cache should match the bottleneck. The common cases are described below.

  • Global users and static or semi-static content: CloudFront, with versioned objects and appropriate TTLs, as covered in the CloudFront lesson.
  • Repeated identical API requests: API Gateway caching on a REST API stage, with a cache capacity, TTL (default 300 seconds, maximum 3,600) and cache keys from parameters; clients can be allowed to invalidate with a header, controlled by IAM. HTTP APIs do not offer caching.
  • Relational database read load or expensive queries: ElastiCache with lazy loading, or read replicas for queries that must be current; RDS Proxy addresses connection exhaustion, not query load.
  • DynamoDB hot reads or microsecond latency: DAX, which is API-compatible with DynamoDB, so applications switch by changing the client. DAX caches eventually consistent reads only; strongly consistent reads pass through to DynamoDB.
  • Session state: ElastiCache or DynamoDB, so instances stay stateless.
  • Data that changes on every request: caching does not help; scale the source instead.

ElastiCache compared with Amazon MemoryDB

Amazon MemoryDB uses the same Valkey and Redis OSS data structures and API as ElastiCache, but it is a durable primary database, not a cache. Every write is committed to a Multi-AZ transaction log before it is acknowledged, so no acknowledged data is lost when a node or an AZ fails. ElastiCache replicates asynchronously and assumes that the data can be rebuilt from another source, so a failover can lose the most recent writes. MemoryDB writes therefore take single-digit milliseconds, while reads stay at microseconds.

Amazon ElastiCache
RoleCache in front of a database
DurabilityAsynchronous replication; recent writes can be lost
Source of truthAnother database
Typical useQuery results, sessions, rate limiting
Choose when Data can be rebuilt from a database and speed is the goal.
Amazon MemoryDB
RolePrimary in-memory database
DurabilityMulti-AZ transaction log; acknowledged writes survive
Source of truthMemoryDB itself
Typical useLeaderboards, session stores or inventories that must not lose data
Choose when Data must be stored durably at in-memory speed without a separate database.

ElastiCache Serverless removes capacity planning for caches: it scales memory and compute automatically, replicates across AZs and charges for data stored and processing units used. It suits spiky or unpredictable workloads, whereas node-based clusters suit steady loads where node types and counts can be tuned for cost.

Cache Failure Modes

Caches can cause problems of their own. A cold cache after a restart or failover sends all requests to the database at once, which may not be provisioned for that load; Multi-AZ replication keeps a warm replica, and gradual traffic ramp-up helps after deployments. A cache stampede happens when a popular item expires and many requests miss simultaneously and all query the database; adding random jitter to TTLs, refreshing hot items before they expire and allowing only one request to rebuild an item prevent it. Stale data is controlled by TTLs and explicit invalidation on writes. Monitoring cache hit ratio, evictions and memory in CloudWatch, for example the ElastiCache CacheHitRate, Evictions and DatabaseMemoryUsagePercentage metrics, shows whether the cache is sized correctly.

Scenario questions

Avoid cache problems

Exam skills 3.2.2 · 3.2.1

Practise avoiding cache failure modes.

Log in to try this activity Interactive activities are free with an account.
Worked example

Relieving a Database Bottleneck

A product catalogue on Aurora MySQL reaches 90% CPU during sales. Ninety per cent of queries read product details that change a few times a day, the same pages are requested by users worldwide, and the cart service writes stock levels that must be current.

  1. Edge

    Cache product pages and images in CloudFront with a five-minute TTL for pages and versioned names for images.

  2. Application cache

    Cache product detail queries in ElastiCache for Valkey with lazy loading, a one-hour TTL with jitter, and invalidation when the catalogue is updated.

  3. Fresh data

    Read stock levels from the Aurora writer or a replica, not from the cache.

  4. Measure

    Track CacheHitRate and Aurora CPU; add Aurora Auto Scaling for replicas as a fallback.

Check yourself

A team adds DAX in front of a DynamoDB table, but read capacity consumption does not fall. The application uses strongly consistent reads. Why?

Show answer

DAX serves only eventually consistent reads from its cache. Strongly consistent reads are passed through to DynamoDB, so they still consume table capacity.

Exam Tips

Remember for the exam

  • Cache as close to the user as correctness allows: CloudFront at the edge, API Gateway REST API caching, ElastiCache in the application tier, DAX for DynamoDB.
  • Lazy loading caches only requested data and tolerates cache failure; write-through keeps data fresh; combine both with TTLs.
  • DAX caches eventually consistent reads only; API Gateway caching is for REST APIs (TTL default 300 s, max 3,600 s).
  • Mitigate cache stampedes with TTL jitter and early refresh; watch hit rate and evictions.
  • MemoryDB is a durable, Multi-AZ primary database with the Valkey or Redis OSS API; ElastiCache is a cache whose data can be rebuilt.