Skip to content

Lesson 6 of 30Core services

Databases on AWS

Choose between RDS, Aurora, DynamoDB and ElastiCache, and design keys and replicas that fit your access patterns.

16 min read0/4 questions

Picking the database is the decision that is hardest to undo. Compute you can swap in an afternoon; moving 400 GB of production data between engines is a quarter-long project. AWS offers a dozen database services, but four of them cover almost every web app, and interviewers expect you to explain why you would pick one over another.

RDS: managed Postgres and MySQL

Amazon RDS (Relational Database Service) runs a normal database engine (PostgreSQL, MySQL, MariaDB, SQL Server, Oracle) on instances AWS manages. You still pick an instance class (like db.t4g.medium or db.r7g.large) and storage size, but AWS handles:

  • installing and patching the engine (in a maintenance window you choose),
  • automated daily backups with point-in-time restore (to any second within your retention, up to 35 days),
  • failover, if you turn on Multi-AZ.

Your app connects with the same driver as always (psycopg, asyncpg, SQLAlchemy, Prisma). It is just Postgres with a hostname like app-db.c9xyz.us-east-1.rds.amazonaws.com.

create a small Postgres (dev settings)
aws rds create-db-instance \  --db-instance-identifier app-db \  --engine postgres --engine-version 17 \  --db-instance-class db.t4g.micro \  --allocated-storage 20 \  --master-username app_admin --manage-master-user-password \  --db-subnet-group-name app-db-subnets \  --vpc-security-group-ids sg-0db \  --no-publicly-accessible

--manage-master-user-password stores the password in Secrets Manager and rotates it, so it never appears in your shell history. --no-publicly-accessible plus private DB subnets (from VPC Networking) means the database has no path from the internet.

Multi-AZ vs read replicas

These two features sound similar and do different jobs.

Multi-AZ standby vs read replicas
AZ aAZ bAZ cAPI: writes + readsAPIwrites + readsReports job: heavy readsReports jobheavy readsPrimary: read/writePrimaryread/writeStandby: no trafficStandbyno trafficRead replica: read-onlyRead replicaread-onlySQLsyncasyncSELECT

The API sends all writes (and normal reads) to the primary.

1/4
  • Multi-AZ is for availability. Turn it on for production.
  • Read replicas are for read scaling. Add them when reads outgrow one instance. Because they lag, do not read your own just-written data from a replica.
Quick check
A user updates their profile, the page reloads, and shows the old name for a second. Reads go to a read replica. What is happening?
Need a nudge? A hint rules out a wrong answer.

Aurora: AWS's cloud-native relational engine

Amazon Aurora is MySQL- and PostgreSQL-compatible, but AWS rebuilt the storage layer. Data is stored 6 times across 3 AZs on a shared distributed volume, so replicas do not need their own copy of the data.

What that buys you:

  • up to 15 low-lag read replicas sharing one storage volume, and failover often under 30 seconds,
  • storage that grows automatically (no picking a disk size),
  • Aurora Serverless v2, which scales capacity up and down in small steps (ACUs) with load, and can scale to zero when idle for dev databases,
  • Global Database for cross-Region replicas.

The trade-off: it costs more than plain RDS for small, steady workloads, and I/O-heavy workloads should look at the I/O-Optimized configuration. Start on RDS Postgres; move to Aurora when you need its scaling or failover speed.

DynamoDB: key-value at any scale

Amazon DynamoDB is a fully managed NoSQL database. No instances, no connections to pool, single-digit millisecond reads at any size. In exchange, you must design around your access patterns up front, because you can only query efficiently by key.

Every item has a primary key:

  • Partition key (pk): DynamoDB hashes it to decide which partition stores the item. Every query must name one partition key.
  • Sort key (sk, optional): items with the same partition key are stored together, sorted by sort key. You can query ranges and prefixes on it.

Single-table design puts several entity types in one table, shaping keys so one query returns everything a page needs:

pkskother attributes
USER#42PROFILEname: Ada, plan: pro
USER#42ORDER#2026-09-30#A17total: 49.00
USER#42ORDER#2026-10-12#B02total: 12.50
USER#7PROFILEname: Sam

"Get user 42's orders, newest first" is one Query: pk = USER#42 AND begins_with(sk, "ORDER#"), scanning backwards. Putting ISO dates in the sort key is what makes them come back in order.

Pythondynamo_like.py
table = [ {"pk": "USER#42", "sk": "PROFILE", "name": "Ada"}, {"pk": "USER#42", "sk": "ORDER#2026-10-12#B02", "total": 12.50}, {"pk": "USER#7", "sk": "PROFILE", "name": "Sam"}, {"pk": "USER#42", "sk": "ORDER#2026-09-30#A17", "total": 49.00},] def query(pk, begins_with="", newest_first=False): rows = [r for r in table if r["pk"] == pk and r["sk"].startswith(begins_with)] return sorted(rows, key=lambda r: r["sk"], reverse=newest_first) for row in query("USER#42", "ORDER#", newest_first=True): print(row["sk"], row["total"])print(query("USER#42", "PROFILE")[0]["name"])
Output
Press Run (⌘ Enter) to see what happens.

And the same call with boto3:

orders.py
import boto3
from boto3.dynamodb.conditions import Key
 
table = boto3.resource("dynamodb").Table("app")
resp = table.query(
    KeyConditionExpression=Key("pk").eq("USER#42") & Key("sk").begins_with("ORDER#"),
    ScanIndexForward=False,  # newest first
    Limit=20,
)

For questions your primary key cannot answer ("all orders over $100 this week"), you add a global secondary index (GSI) with different keys, or you accept that DynamoDB is the wrong tool for ad-hoc analytics. A Scan reads the whole table and is almost never what you want in an API path.

Capacity modes:

  • On-demand: pay per read and write request. No planning. The right default for new or spiky apps.
  • Provisioned: you set read and write capacity units (optionally with auto scaling). Cheaper for steady, predictable traffic.
Quick check
You store page views with partition key date (like 2026-10-20). Writes are getting throttled at peak. Why?
Need a nudge? A hint rules out a wrong answer.

ElastiCache: Redis and Valkey

Amazon ElastiCache runs managed in-memory caches: Valkey (the open-source fork of Redis that AWS now leads with, and prices lower), Redis OSS, and Memcached. There is also a serverless option that scales without picking nodes.

Typical uses: caching expensive query results, session storage, rate-limit counters, leaderboards with sorted sets. The usual pattern is cache-aside: check the cache, on a miss read the database and write the result to the cache with a TTL.

Like RDS, it lives in private subnets, and your app's security group must be allowed on port 6379.

Choosing between them

RDS (Postgres/MySQL)AuroraDynamoDBElastiCache
ModelRelational, SQLRelational, SQLKey-value / documentIn-memory key-value
QueriesAny SQL, joins, ad hocAny SQL, joins, ad hocBy key and sort key (plus GSIs)By key
ScalingBigger instance, read replicasUp to 15 replicas, Serverless v2Practically unlimited, automaticAdd shards/nodes, or serverless
OpsLowLowerAlmost noneLow
Pick it whenDefault for most appsNeed fast failover or big read scaleKnown access patterns, huge or spiky scaleSpeed up reads, sessions, counters
Match the pairs0/4 matched

Match the workload to the service.

Choose an item, then its match on the other side.
Quick check
Your Lambda function needs to query a Postgres RDS instance that sits in private DB subnets. What do you configure?
Need a nudge? A hint rules out a wrong answer.
ChallengeMedium

A DynamoDB Query

In DynamoDB, a Query picks one partition key (pk) and optionally a sort key condition. Items inside a partition come back sorted by sort key (sk).

Write query(items, pk, sk_prefix) that returns the sk values of every item whose pk equals the given one and whose sk begins with sk_prefix, sorted ascending (plain string order). An empty prefix matches every item in the partition.

items = [{"pk": "USER#1", "sk": "PROFILE"},
         {"pk": "USER#1", "sk": "ORDER#2026-03-02"},
         {"pk": "USER#2", "sk": "ORDER#2026-01-15"},
         {"pk": "USER#1", "sk": "ORDER#2026-01-09"}]
query(items, "USER#1", "ORDER#")  →  ["ORDER#2026-01-09", "ORDER#2026-03-02"]
query(items, "USER#1", "")        →  ["ORDER#2026-01-09", "ORDER#2026-03-02", "PROFILE"]
def query(items: list[dict], pk: str, sk_prefix: str) -> list[str]: pass
Key terms
Multi-AZ
A synchronous standby in another AZ that RDS promotes on failure. For availability, not read scaling.
read replica
An asynchronous, read-only copy for scaling reads. Can lag behind the primary.
Aurora
AWS's MySQL/Postgres-compatible engine with storage replicated 6 ways across 3 AZs.
partition key
The DynamoDB key that is hashed to choose a partition. Every Query names exactly one.
sort key
Orders items within a partition, enabling range and begins_with queries.
cache-aside
Read from cache; on a miss, read the database and store the result with a TTL.