SkillSprout
Chapter 3 · Lesson 4
Intermediate
6 min read

RDS, Aurora, ElastiCache and Caching Strategies

Overview

Not every workload fits a key-value store. When you need joins, transactions and a relational schema, Amazon RDS and Amazon Aurora run managed relational engines. To make any data store faster and cheaper to run, Amazon ElastiCache keeps frequently used data in memory.

Think of a library. The database is the stacks: complete but slow to walk. The cache is the reading table by the front desk where popular books are kept. A caching strategy decides when books go on the table (lazy loading or write-through) and when they are taken away (TTL).

As a developer you must know how applications connect to relational databases (especially from Lambda), how read replicas scale reads, and the trade-offs between caching patterns.

Key Concepts

  • RDS manages MySQL, PostgreSQL, MariaDB, Oracle, SQL Server and Db2; Multi-AZ gives synchronous standby failover for availability, read replicas are asynchronous and scale reads.
  • Aurora is a cloud-native MySQL/PostgreSQL-compatible engine with a shared storage volume replicated six ways across 3 AZs, up to 15 replicas and fast failover.
  • Aurora Serverless v2 scales capacity (ACUs) automatically in fine increments; Aurora Global Database supports cross-Region reads.
  • RDS Proxy pools and shares connections, reducing failover time and protecting databases from Lambda connection storms; it supports IAM authentication and Secrets Manager.
  • IAM database authentication uses short-lived tokens in place of passwords.
  • ElastiCache offers Redis OSS/Valkey (persistence, replication, data structures, pub/sub, Multi-AZ) and Memcached (simple, multi-threaded, no persistence).
  • Lazy loading (cache-aside) loads on miss; write-through updates the cache on every write; both use TTL to limit staleness.
  • Encrypt with KMS at rest and TLS in transit; use security groups to restrict access.

Detailed Notes

Multi-AZ vs read replicas

FeatureMulti-AZRead replica
PurposeHigh availability, failoverRead scaling, cross-Region reads
ReplicationSynchronousAsynchronous (lag possible)
ReadableNo (classic instance deployment)Yes
FailoverAutomatic, DNS endpoint flipsManual promotion

Always connect through the DNS endpoint, never an IP, because failover changes the underlying instance.

Aurora features

  • Cluster endpoint (writer), reader endpoint (load-balances replicas), custom endpoints.
  • Backtrack (MySQL) rewinds in place; cloning is a fast copy-on-write copy.
  • Failover typically completes in about 30 seconds or less.

Lambda and databases

Each Lambda environment opens its own connection, so a spike of 1,000 concurrent invocations can exhaust connections. Use RDS Proxy, create connections outside the handler and keep them small.

python
import os, boto3, pymysql

rds = boto3.client("rds")
token = rds.generate_db_auth_token(
    DBHostname=os.environ["PROXY_HOST"], Port=3306, DBUsername="app_user")

conn = pymysql.connect(
    host=os.environ["PROXY_HOST"], user="app_user", password=token,
    database="shop", ssl={"ca": "/opt/rds-ca.pem"})   # IAM auth requires TLS

Caching strategies

StrategyHowProsCons
Lazy loadingRead cache; on miss read DB and populateOnly requested data cached; node failure tolerableMiss penalty; stale data
Write-throughWrite to DB and cache togetherCache always freshWrite penalty; unused data cached
TTLExpire entries after N secondsBounds stalenessNeeds tuning
Write-behindWrite to cache, flush to DB laterFast writesRisk of data loss
python
import json, redis

cache = redis.Redis(host=CACHE_HOST, ssl=True)

def get_product(pid):
    key = f"product:{pid}"
    hit = cache.get(key)
    if hit:
        return json.loads(hit)                       # cache hit
    row = db_query("SELECT * FROM products WHERE id=%s", pid)   # cache miss
    cache.setex(key, 300, json.dumps(row))            # TTL 5 minutes (lazy loading)
    return row

def update_product(pid, data):
    db_update(pid, data)
    cache.setex(f"product:{pid}", 300, json.dumps(data))   # write-through

Redis vs Memcached

Redis / ValkeyMemcached
Data typesStrings, hashes, lists, sets, sorted setsStrings
Persistence / backupYesNo
Replication / failoverYes (Multi-AZ)No
Multi-threadedMostly single-threaded per shardYes
Use casesSessions, leaderboards, pub/sub, locksSimple scale-out cache

Sessions

Store session state in ElastiCache or DynamoDB so any server can handle any request, avoiding sticky sessions.

Other considerations

Cache invalidation is the hard part: choose TTL values based on how stale a value may be. Protect against cache stampede by using jittered TTLs or locks.

ElastiCache engines and strategies compared

AspectRedis (and Valkey)Memcached
Data typesStrings, hashes, lists, sets, sorted sets, streamsStrings only
Persistence and replicationSnapshots, Multi-AZ replicas, automatic failoverNone
Multi-threadedMostly single-threaded per shard (I/O threads)Yes
Typical useSessions, leaderboards, pub/sub, rate limitingSimple, horizontally partitioned cache
StrategyHow it worksTrade-off
Lazy loading (cache-aside)Read cache; on a miss read the database and fill the cacheOnly needed data cached; first read slower; may be stale
Write-throughWrite to cache and database togetherAlways fresh; cache holds data that may never be read
TTLExpire entries after a timeBounds staleness
python
import json, random, redis

r = redis.Redis(host=ENDPOINT, port=6379, ssl=True)

def get_product(pid):
    cached = r.get(f"product:{pid}")
    if cached:
        return json.loads(cached)
    row = db_query(pid)                                   # database on a miss
    r.setex(f"product:{pid}", 300 + random.randint(0, 60), json.dumps(row))   # jittered TTL
    return row

Aurora and RDS details for developers

Aurora exposes a cluster (writer) endpoint, a reader endpoint that load-balances replicas, and instance endpoints. RDS Multi-AZ gives synchronous standby failover (not read scaling); read replicas scale reads asynchronously and can be cross-Region. Use IAM database authentication (15-minute tokens) or Secrets Manager rotation, enforce TLS, and use Aurora Serverless v2 for variable load. Apply schema changes with migration tools in the pipeline, and size connection pools for how many Lambda or container instances can run concurrently.

Real World Example

An e-commerce site moved from self-managed MySQL to Aurora MySQL with two readers. Product pages were read-heavy, so the app sent reads to the reader endpoint and added ElastiCache for Redis with lazy loading and a five-minute TTL. Their Lambda order functions connected via RDS Proxy with IAM auth. Database CPU fell from 80% to 25% and checkout survived a failover with only a brief retry.

Architecture Diagram

Cache-aside with Aurora and RDS Proxy
Architecture
VPC
Lambda
ElastiCache
RDS Proxy
Aurora cluster
Writer
Reader

Reads check the cache first; Lambda connects to the database through a proxy.

  1. 1The function looks up the key in ElastiCache.
  2. 2On a miss it queries the database through RDS Proxy.
  3. 3The result is stored in the cache with a TTL.
  4. 4Subsequent requests are served from memory.

Best Practices

  • ✓Use RDS Proxy for Lambda and other bursty clients.
  • ✓Send reads to replicas or reader endpoints; use Multi-AZ for availability.
  • ✓Combine lazy loading with TTL, and write-through where freshness matters.
  • ✓Use IAM auth or Secrets Manager rotation for DB credentials.
  • ✓Keep databases in private subnets with tight security groups.

Common Interview Questions

Exam Tips

DVA-C02 focus

  • Lambda + relational DB connection exhaustion -> RDS Proxy.
  • Read-heavy scaling -> read replicas / Aurora readers / cache.
  • Data must survive node failure in cache -> Redis, not Memcached.
  • Failover handling: connect via DNS endpoint.

Chapter quiz

Data Stores for Developers · 10 questions

  1. 1.A DynamoDB table has plenty of provisioned capacity, but requests for one popular partition key are throttled. What is the best fix?

  2. 2.An application must transfer a balance between two DynamoDB items so that either both updates succeed or neither does. Which API should it use?

  3. 3.Browsers must upload large files directly to a private S3 bucket without receiving AWS credentials. What should the backend provide?

  4. 4.A Lambda function connecting directly to an RDS MySQL database causes "too many connections" during traffic spikes. Which solution is MOST appropriate?

  5. 5.A product page is read thousands of times per second but updated rarely. The team wants to reduce database load and accepts data being up to five minutes stale. Which strategy fits?

  6. 6.A DynamoDB table keyed by date has one hot partition during the current day. What is the best fix?

  7. 7.A read must always reflect the latest successful write to a DynamoDB table. Which setting should be used?

  8. 8.Session records must disappear automatically 24 hours after creation without paying for delete requests. Which feature fits?

  9. 9.Full-text search with relevance scoring over product descriptions is required alongside a DynamoDB catalogue. What is a suitable pattern?

  10. 10.Objects in S3 should move to Standard-IA after 30 days and be deleted after one year. How do you implement this?

0 of 10 answered

Finished this lesson?

0 of 46 lessons done · 0% of the course