# Managed databases: RDS, DynamoDB, ElastiCache

Choose relational, key-value or cache storage, then verify backups, capacity and deletion settings.

Course: [AWS for DevOps](https://devops.rajeev.pro/courses/aws), lesson 10. About 30 minutes, intermediate. Source: https://devops.rajeev.pro/courses/aws/10-databases

## What you will learn

- Choose between RDS, DynamoDB and ElastiCache for a workload.
- Explain RDS storage, Multi-AZ, replicas, backups and parameter groups.
- Model a DynamoDB table with a useful primary key.
- Compare on-demand and provisioned capacity.
- Delete temporary databases without retaining a final snapshot.

## RDS: managed relational databases

Before a managed database, a team installed PostgreSQL on a server, patched its operating system, watched its disks and maintained backup scripts. One missed patch or an untested restore could turn routine work into an outage. Amazon RDS takes over much of that host work, but it does not design the database for you.

RDS runs a relational engine while AWS manages much of the host, patching and infrastructure. Your application still connects to an endpoint, sends SQL and depends on the schema, indexes and connection limits you choose. You also own migrations and recovery decisions. In this lesson, you'll compare RDS with DynamoDB and caching, then inspect the settings on a small temporary database.

The lesson used PostgreSQL on a `db.t4g.micro`, 20 GiB gp3 storage, encryption, one Availability Zone and zero retained automated backups. It was deliberately small and temporary.

> **Figure.** Amazon RDS console showing a small private PostgreSQL database instance
>
> (1) The instance class and engine are visible. (2) The endpoint is private and the instance is single-AZ for this temporary exercise.

## RDS storage

gp3 is a general-purpose SSD option. Provisioned IOPS storage is for workloads that need a more controlled I/O profile and can justify the cost. Allocated storage is not the same as free space inside the database; monitor both the RDS volume and the engine.

The storage choice answers two separate questions: how much disk AWS allocates, and how consistently the workload needs to read and write. The engine also uses space for indexes, temporary work and transaction logs. So allocated storage does not tell you how much room remains for the application. Watch the database's free-storage metric as well as engine-level space. Start with gp3 for ordinary workloads unless measurements show a specific I/O need. Provisioned IOPS makes sense when predictable I/O performance is required and the budget supports it. Don't select a more expensive tier because one synthetic benchmark looked impressive; first measure latency and queueing under representative traffic.

## High availability and read scaling

Multi-AZ keeps a standby for failover. It is a high-availability design, not a read-scaling design. Read replicas are separate readable instances that use replication and can serve read traffic. Both features add cost and operational decisions.

With Multi-AZ, the standby exists to take over after a qualifying failure. Your application still uses the database endpoint, but existing connections can break during failover and must reconnect. A read replica has a different job: it receives changes from the source and can answer read queries. Replication does not guarantee every replica read is current, so the application must tolerate lag. Use Multi-AZ when recovery time matters. Add replicas when read demand is the bottleneck and slightly stale reads are acceptable. If the workload needs both properties, plan for both and test a failover; the architecture diagram alone cannot prove recovery works.

> **Video.** [Multi-AZ and Read Replicas (Deployment Options for RDS)](https://www.youtube.com/watch?v=-BP1VJWnCxA) (CloudWolf AWS)

## Backups and snapshots

Automated backups support point-in-time recovery within the retention window. A manual snapshot is a longer-lived recovery artifact. A final snapshot at deletion can be valuable in production but would leave storage behind in this exercise, so the mission explicitly skips it.

An automated backup is managed on a schedule and supports restore to a point inside its configured retention period. A manual snapshot is a named copy you keep until you remove it. These are recovery inputs, not proof that recovery works: a restore creates a separate database that still needs network access, credentials and an application check. Choose retention based on the recovery requirement, then rehearse a restore and record the time. This lesson's instance is temporary, so deletion skips its final snapshot. In production, keep a final snapshot only when its retention and owner are clear; it remains stored after the database is gone.

> **Video.** [RDS Backups: Automated Backups & Manual Snapshots Explained | AWS Database Tutorial](https://www.youtube.com/watch?v=Nax2zbYakf4) (CodeLucky)

## Parameter groups

Parameter groups hold engine settings. Change them deliberately, check whether a parameter is dynamic or requires a reboot, and test changes against the workload. A parameter group is not a replacement for migrations or query tuning.

The engine reads settings such as connection limits from this configuration. RDS groups those values so you can apply a known set to database instances or clusters. Some changes take effect immediately; others wait for a reboot. Check the parameter's apply type before planning the change. A setting can affect every connection or query, so roll it out carefully: compare the old value, try the change in a lower environment, then observe it before promotion. Use schema migrations for table changes and query plans for slow SQL. A parameter change will not fix a missing index or an inefficient query.

> **Video.** [04 Modifying parameters in a DB parameter group](https://www.youtube.com/watch?v=OlsTvGwrBLw) (AWSDBA)

## Aurora

Aurora is an AWS relational engine compatible with MySQL and PostgreSQL APIs. Its distributed storage and cluster model can suit workloads that need those characteristics, but it is not a default upgrade for every RDS database. Start with availability, latency and recovery requirements.

Compatibility helps when an application already speaks a supported MySQL or PostgreSQL protocol and the team wants Aurora's managed cluster design. It does not guarantee every extension, setting or behavior is identical, so test the application and migration path before switching. Compare standard RDS first: measure read and write latency, required recovery time, expected connections and total cost. Aurora is a candidate when its cluster and storage behavior solves a measured constraint. A small or steady database may be simpler on RDS. Don't choose it only because a general benchmark claims it is faster; a different workload cannot predict yours.

> **Video.** [Amazon Aurora Introduction](https://www.youtube.com/watch?v=ZCt3ctVfGIk) (Stephane Maarek)

## DynamoDB

DynamoDB is a managed key-value and document database. Model access patterns first. The partition key distributes data; an optional sort key orders related items within a partition. A table does not provide arbitrary SQL joins, so design queries around the keys and indexes you will actually use.

The temporary table used on-demand capacity and one string partition key:

```text
{
    "Name": "temporary-items",
    "Status": "ACTIVE",
    "ItemCount": 0,
    "Key": [{"AttributeName": "pk", "KeyType": "HASH"}]
}
```

> **Figure.** Amazon DynamoDB console showing an active on-demand table with a string partition key
>
> (1) The table is active. (2) Its partition key is the string attribute pk.

> **Video.** [Data Modeling with Amazon DynamoDB- AWS Database in 15](https://www.youtube.com/watch?v=kQ-DSjtCb90) (AWS Developers)

## DynamoDB capacity

On-demand capacity is useful for unpredictable traffic or early workloads where capacity planning is not settled. Provisioned capacity is useful when traffic is predictable and you can manage read and write capacity units. Review throttling, adaptive capacity and indexes before changing modes.

Streams record item changes for consumers. Point-in-time recovery and backups protect table data, but they do not fix a poor key design. DynamoDB Local is useful for development without making network calls to AWS.

Capacity mode controls how the table handles request volume; it does not change the data model. On-demand is a practical start when request rates are uncertain because you do not set a read/write allowance in advance. Provisioned mode lets you set capacity for a steady pattern and monitor whether it fits. If requests are throttled, inspect the operation, key distribution and any secondary index before raising capacity. One heavily used key range can become a hot partition even when the table-wide number looks healthy. Streams are for reacting to item changes; backups are for recovery. Neither removes the need to choose keys around the queries the application actually makes.

> **Video.** [DynamoDB Throughput Explained | On-Demand vs Provisioned Mode](https://www.youtube.com/watch?v=CQPpE5I4QeY) (CloudWolf AWS)

## ElastiCache

ElastiCache provides managed Redis/Valkey or Memcached deployments. A cache should be disposable: define misses, expiry and recovery. Never make the cache the only copy of important data. Redis/Valkey offers richer data structures and persistence choices; Memcached is a simpler distributed cache.

An application cache keeps a temporary copy near the code that needs it. On a hit, the application can avoid a slower database read. On a miss, it reads the source and may cache the result for later. The app must still work when the cache is empty or unavailable. Set expiry so old values do not live forever, and decide how writes update or invalidate cached entries. Redis/Valkey fits workloads that use richer structures or need its available persistence choices. Memcached fits simpler key-value caching. Choose based on tested behavior, and keep the database or another durable store as the source of truth.

> **Video.** [Introduction to Amazon ElastiCache for Redis](https://www.youtube.com/watch?v=GoNsuTqeMto) (Amazon Web Services)

> **A managed database is still your responsibility.** AWS manages infrastructure for the service, not your schema, credentials, queries, connection pool or recovery test. Keep credentials out of source control and use least privilege.

> **In production.** Use private subnets, security groups that allow only required clients, encryption, monitoring, tested backups and a documented deletion policy. Treat every snapshot and backup as a retained resource with an owner and expiry.

## Availability, replicas and recovery

Multi-AZ and read replicas solve different problems. Multi-AZ synchronously maintains a standby for instance failover;
the standby is not a read endpoint. A read replica is asynchronously replicated and can serve read traffic or be
promoted. Use Multi-AZ for availability, replicas for read scale, and both when the workload needs both properties.

<img src="./images/rds-ha-read-replica.svg" alt="Diagram comparing Multi-AZ standby failover with an asynchronous read replica" width="1440" height="420" />

Automated backups support point-in-time restore within the retention window. A manual snapshot is an explicit recovery
artifact. In production, set retention and test a restore; in this exercise, deletion uses `--skip-final-snapshot`
because leaving a snapshot behind would leave a billable resource.

> **Figure.** RDS Create database wizard showing engine choices and full configuration
>
> PostgreSQL is one of the available engines. Full configuration exposes availability, backups and security settings. The production template is not a reason to keep production defaults in a temporary exercise.

> **Figure.** RDS create wizard options area showing availability and backup configuration choices
>
> Compare Multi-AZ availability before creating. Review backup retention and the maintenance window before accepting defaults.

## Maintenance, upgrades and connection management

Maintenance windows make patch and engine-upgrade work predictable. Test a major engine upgrade separately, check
extension compatibility, and keep a rollback or restore plan. Parameter groups hold engine settings; a parameter can
be dynamic or require a reboot.

RDS Proxy pools and reuses database connections. It is useful when many short-lived functions would otherwise exhaust
the database connection limit. It does not replace query tuning or a sensible pool size.

IAM database authentication replaces a long-lived password with a short-lived authentication token for supported
engines. Secrets Manager is a better fit for a credential that must be rotated and retrieved by an application. Use
the smallest role and database grants possible.

> **Figure.** RDS database list with the temporary PostgreSQL instance and its creating state
>
> The temporary instance is visible in the database list. The engine and Availability Zone are visible before opening its configuration.

> **Figure.** Available private PostgreSQL RDS instance showing db.t4g.micro and its Availability Zone
>
> The instance is Available. The class is db.t4g.micro. PostgreSQL and the single Availability Zone are visible.

> **Video.** [Introduction to RDS Proxy](https://www.youtube.com/watch?v=ULRnn6tIYu8) (Amazon Web Services)

## Aurora and caching

Aurora uses a cluster with a writer endpoint and reader endpoint rather than treating every database as one isolated
instance. Aurora Serverless v2 scales capacity in fine-grained increments while the cluster remains available to the
application. Choose it when the workload needs Aurora's storage and cluster behavior; it is not automatically cheaper.

ElastiCache Redis or Valkey is for data that can be rebuilt or has an explicit source of truth. Cache-aside is the
usual pattern: read the cache, load from the database on a miss, then set an expiry. Define invalidation and stale-data
behavior before adding a cache. DAX is a DynamoDB-specific in-memory cache for read-heavy workloads; it changes the
client path and should be justified with measured latency and cost.

## DynamoDB keys, indexes and correctness

The partition key distributes items. A composite primary key adds a sort key, which lets one partition contain an
ordered collection of related items. A GSI can use a different partition and sort-key design and is eventually
consistent by default. An LSI shares the table partition key and must be declared when the table is created.

Use `Query` when the access pattern supplies a partition key; use `Scan` only for bounded maintenance or discovery
work. Conditional writes prevent lost updates. TTL removes expired items asynchronously. Streams publish item changes
for downstream consumers, and transactions make a small set of writes commit together.

> **Figure.** DynamoDB tables page showing an active on-demand table with one index
>
> The table is Active. Its string partition key is visible. The Indexes column shows the GSI.

On-demand capacity is a good default while traffic is uncertain. Provisioned capacity is useful when request rates
are predictable and you can manage capacity units. Both modes still need throttling metrics and a key design that
avoids hot partitions.

> **Video.** [Master DynamoDB Architecture | Partition Key, Sort Key, GSI, LSI, Streams, Global Tables](https://www.youtube.com/watch?v=Q1t84B7gdkQ) (Cloud Journey)

## Mission: One relational database and one key-value table

Create a small encrypted private PostgreSQL RDS instance and an on-demand DynamoDB table, inspect their settings, then delete both without retaining a final RDS snapshot.

- You need: AWS CLI credentials allowed to create and delete temporary RDS and DynamoDB resources
- You'll have: Verified RDS and DynamoDB settings followed by a clean account

```sh
$ export AWS_REGION=ap-south-1
$ export DB_ID="academy-postgres-$RANDOM"
$ export TABLE="academy-items-$RANDOM"
$ export DB_PASSWORD="Use-a-temporary-secret-here"
$ aws rds create-db-instance --region "$AWS_REGION" --db-instance-identifier "$DB_ID" \
    --db-instance-class db.t4g.micro --engine postgres --allocated-storage 20 \
    --storage-type gp3 --master-username academy --master-user-password "$DB_PASSWORD" \
    --db-subnet-group-name default --backup-retention-period 0 --no-multi-az \
    --no-publicly-accessible --storage-encrypted --no-deletion-protection
$ aws dynamodb create-table --region "$AWS_REGION" --table-name "$TABLE" \
    --attribute-definitions AttributeName=pk,AttributeType=S AttributeName=gsi,AttributeType=S \
    --key-schema AttributeName=pk,KeyType=HASH \
    --global-secondary-indexes 'IndexName=GSI1,KeySchema=[{AttributeName=gsi,KeyType=HASH}],Projection={ProjectionType=ALL}' \
    --billing-mode PAY_PER_REQUEST
$ aws dynamodb wait table-exists --region "$AWS_REGION" --table-name "$TABLE"
$ aws dynamodb put-item --region "$AWS_REGION" --table-name "$TABLE" --item '{"pk":{"S":"lesson-10"},"gsi":{"S":"database"},"value":{"N":"10"}}'
$ aws dynamodb query --region "$AWS_REGION" --table-name "$TABLE" --index-name GSI1 \
    --key-condition-expression 'gsi = :g' --expression-attribute-values '{":g":{"S":"database"}}' \
    --query 'Items' --output json
[
    {"pk":{"S":"lesson-10"},"gsi":{"S":"database"},"value":{"N":"10"}}
]
$ aws dynamodb scan --region "$AWS_REGION" --table-name "$TABLE" --query 'Items' --output json
[
    {"pk":{"S":"lesson-10"},"gsi":{"S":"database"},"value":{"N":"10"}}
]
$ aws dynamodb describe-table --region "$AWS_REGION" --table-name "$TABLE" \
    --query 'Table.{Name:TableName,Status:TableStatus,Keys:KeySchema}' --output table
---------------------------------------------
|              DescribeTable                 |
+---------+--------+-------------------------+
| Name    | Status | Keys                    |
+---------+--------+-------------------------+
| TABLE   | ACTIVE | pk / HASH               |
+---------+--------+-------------------------+
$ aws rds describe-db-instances --region "$AWS_REGION" --db-instance-identifier "$DB_ID" \
    --query 'DBInstances[0].{Status:DBInstanceStatus,Class:DBInstanceClass,Storage:AllocatedStorage,MultiAZ:MultiAZ,Backups:BackupRetentionPeriod,Encrypted:StorageEncrypted,Public:PubliclyAccessible}' --output table
$ aws rds delete-db-instance --region "$AWS_REGION" --db-instance-identifier "$DB_ID" \
    --skip-final-snapshot --delete-automated-backups
$ aws dynamodb delete-table --region "$AWS_REGION" --table-name "$TABLE"
$ aws dynamodb describe-table --region "$AWS_REGION" --table-name "$TABLE"
An error occurred (ResourceNotFoundException) when calling the DescribeTable operation
$ aws rds wait db-instance-deleted --region "$AWS_REGION" --db-instance-identifier "$DB_ID"
$ aws rds describe-db-instances --region "$AWS_REGION" --db-instance-identifier "$DB_ID"
An error occurred (DBInstanceNotFound) when calling the DescribeDBInstances operation
```

Use a secret manager or an interactive secret prompt for a real password. The placeholder above is only a shape; never paste a production password into shell history.

## Try it

- Create a small private PostgreSQL RDS instance.
- Create an on-demand DynamoDB table with a string partition key.
- Inspect encryption, backup retention and endpoint state.
- Compare a table item with a relational row.
- Delete both temporary databases and verify they are gone.

## Quiz

1. When is RDS a good fit?
   - **A workload needing SQL joins and transactions** (answer)
   - A cache that can be rebuilt
   - A document with no access pattern
   Why: RDS provides managed relational engines with SQL, transactions and familiar schemas.

2. What does Multi-AZ primarily provide for an RDS instance?
   - A read-only cache
   - **High availability with a standby** (answer)
   - A DynamoDB partition key
   Why: Multi-AZ maintains a synchronously replicated standby for failover. Read replicas serve read scaling instead.

3. What is the partition key used for in DynamoDB?
   - **To distribute items and locate them** (answer)
   - To encrypt the table
   - To choose an RDS engine
   Why: DynamoDB hashes the partition key to distribute data and locate items efficiently.

4. Which DynamoDB capacity mode suits unpredictable traffic with little capacity planning?
   - Provisioned only
   - **On-demand** (answer)
   - Multi-AZ RDS
   Why: On-demand capacity charges for requests and automatically handles changing traffic without capacity units.

5. What should you specify when deleting a temporary RDS instance?
   - **Skip the final snapshot** (answer)
   - Enable a public endpoint
   - Add a read replica
   Why: A temporary exercise should not retain a final snapshot. Production deletion needs an explicit, reviewed retention decision.

6. What is the difference between an RDS read replica and Multi-AZ?
   - **A read replica serves read scaling; Multi-AZ provides synchronous standby failover** (answer)
   - They are two names for the same feature
   - Multi-AZ is a DynamoDB index
   Why: Multi-AZ is primarily availability. Read replicas are readable copies used for scale and some reporting patterns.

7. Which DynamoDB operation should you prefer when you know the key condition?
   - **Query** (answer)
   - Scan
   - DescribeTable only
   Why: Query uses the partition key and optional sort-key condition. Scan reads every item and is usually more expensive and slower.

## Resources

- [Amazon RDS User Guide](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Welcome.html) (AWS Docs)
- [RDS Multi-AZ deployments](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Concepts.MultiAZ.html) (AWS Docs)
- [Amazon DynamoDB Developer Guide](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Introduction.html) (AWS Docs)
- [DynamoDB capacity modes](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/capacity-mode.html) (AWS Docs)
- [Amazon ElastiCache documentation](https://docs.aws.amazon.com/elasticache/) (AWS Docs)
