devHọc Dev

Week 3 - Day 3: Database & Analytics (choosing a database, RDS/Aurora, DynamoDB, Analytics)

Week 3 – Day 3

This lesson combines 4 topics: Database Options, RDS & Aurora Deep Dive, DynamoDB Deep Dive, Data Analytics Services.

Learning Objectives

  • Compare the database services
  • Understand when to use which database
  • Master database scaling patterns
  • Distinguish RDS Multi-AZ (HA) from Read Replicas (scale/DR) and know the limits of each engine
  • Understand when you need RDS Proxy (connection pooling for Lambda/serverless)
  • Know Aurora Serverless v2, Aurora Cloning and the 2024–2025 updated figures
  • Choose the right capacity mode (Provisioned vs On-Demand) based on traffic pattern and cost
  • Distinguish GSI vs LSI and understand the throttling impact
  • Know DAX, Transactions, TTL and the single-table design pattern at Professional level
  • Know the standard analytics pipeline (Collect → Store → Process → Analyze → Visualize) and the matching services
  • Distinguish Kinesis Data Streams vs Data Firehose vs Managed Service for Apache Flink
  • Understand Redshift, Glue, Athena, Lake Formation well enough to pick the right service for a scenario

Part 1: Database Options

1. Database Decision Tree

┌─────────────────────────────────────────────────────────┐│DATABASESELECTION││││Relational+ACID?││├──Yes→RDS,Aurora,AuroraDSQL│││├──MySQL/PostgreSQLcompatible→Aurora│││├──Oracle/SQLServer→RDS│││├──Multi-regionwrites(single-region││││primary,asyncreplica)→AuroraGlobal│││└──DistributedSQLmulti-regionACIDwrites│││(active-active,99.999%multi-region)│││→AuroraDSQL│││││Key-Value+Extremescale?││└──Yes→DynamoDB││├──Needstrongconsistency→DynamoDB││└──Needcaching→DAX││││Document?││└──Yes→DocumentDB(MongoDBcompatible)││││Graph?││└──Yes→Neptune││││In-memory?││└──Yes→ElastiCache(Redis/Memcached)││││Time-series?││└──Yes→TimestreamforInfluxDB││(LiveAnalyticsclosedtonewcustomers06/2025)││││Ledger/Immutable?││└──Yes→AuroraPostgreSQL(ledgerpattern)││(QLDBreachedEOL31/07/2025—innewexam││optionsitonlyappearsasadistractor)││││Datawarehouse?││└──Yes→Redshift│└─────────────────────────────────────────────────────────┘

2. Aurora Advanced

Aurora Global Database

┌─────────────────────────────────────────────────────────┐│AURORAGLOBALDATABASE││││PrimaryRegion(us-east-1):││┌─────────────────────────────────────────────────┐│││PrimaryCluster││││├──WriterInstance││││└──ReaderInstances│││└─────────────────────────────────────────────────┘│││││AsyncReplication││(<1secondlag)│││││SecondaryRegion(eu-west-1):││┌─────────────────────────────────────────────────┐│││SecondaryCluster(Read-only)││││└──ReaderInstances││││││││Failover:<1minute(promotedtoprimary)│││└─────────────────────────────────────────────────┘││││WriteForwarding:Enablewritesinsecondary│└─────────────────────────────────────────────────────────┘

Aurora Serverless v2

Scaling: 0 ACU to 256 ACU
- Max 256 ACU (since 10/2024; previously 128)
- Min 0 ACU with auto-pause (since 11/2024;
  previously min 0.5 ACU)
- Auto-scales in seconds
- Pay per ACU-hour used

Use cases:
- Variable workloads
- Development/Test
- Multi-tenant applications

Note: Aurora Serverless v1 reached EOL 31/12/2024
— every serverless Aurora scenario is now v2.

Aurora DSQL (GA May 2025)

Aurora DSQL is a PostgreSQL-compatible distributed SQL serverless database. It differs fundamentally from a regular Aurora Global Database because it supports active-active multi-region writes with guaranteed ACID.

┌──────────────────────────────────────────────────────────────┐│AURORADSQL││││Architecture:││-Serverless,noinstancetomanage││-Storageandcomputefullydecoupled││-PostgreSQLwire-protocolcompatible││││Multi-region:││-Active-activewrites(everyregionacceptswrites)││-Strongconsistency(ACIDtransactionscross-region)││-99.999%availabilitymulti-regionSLA││-Automaticconflictresolution(snapshotisolation)││││Pricing:││-Perrequest+perstorageGB││-Noinstancecost,noidlecost│└──────────────────────────────────────────────────────────────┘

Aurora DSQL vs Aurora Global Database:

CriteriaAurora DSQLAurora Global Database
Write topologyActive-active multi-regionSingle primary, async replicas (or write forwarding)
Consistency cross-regionStrong (ACID)Eventual (~< 1s lag)
Failover RTONear-zero (already active)< 1 minute
SLA99.999% multi-region99.99% region, 99.95% with failover
Schema/featurePostgreSQL subset (no triggers, limited FKs)Aurora full PostgreSQL/MySQL
PricingServerless per-requestPer instance + I/O
Use caseMulti-region financial / inventory / global SaaS that needs ACIDMulti-region read-heavy + DR

Exam keyword:

  • "Multi-region SQL with active-active writes, strong consistency" → Aurora DSQL
  • "Global app needs ACID transactions cross-region, no downtime failover" → Aurora DSQL
  • "Existing Aurora workload, needs multi-region read replica + failover < 1 min" → Aurora Global Database (write forwarding if you need writes from the secondary region)
  • "Needs full PostgreSQL features (triggers, extensions, complex foreign keys)" → Aurora Global Database, NOT DSQL (DSQL still has feature limitations)

3. DynamoDB Advanced

Global Tables

┌─────────────────────────────────────────────────────────┐│DYNAMODBGLOBALTABLES││││Multi-master,multi-region:││││┌──────────┐Active-Active┌──────────┐│││us-east-1│◄─────────────────►│eu-west-1││││(Write)││(Write)│││└──────────┘└──────────┘││▲▲││││││▼▼││┌──────────┐┌──────────┐│││ap-se-1││ap-ne-1││││(Write)││(Write)│││└──────────┘└──────────┘││││-Automaticconflictresolution(last-writer-wins)││-<1secondreplication│└─────────────────────────────────────────────────────────┘

DynamoDB Streams + Lambda

┌─────────────────────────────────────────────────────────┐│DYNAMODBSTREAMS││││DynamoDBTable│││││▼Changes(Insert,Update,Delete)││DynamoDBStream│││││▼EventSourceMapping││LambdaFunction│││││▼Reacttochanges││-UpdateElasticsearch││-Sendnotifications││-Aggregatedata│└─────────────────────────────────────────────────────────┘

4. ElastiCache Strategies

Caching Patterns

1. LAZY LOADING (Cache-Aside):
   - Read: Cache miss → Read DB → Write cache
   - Stale data possible

2. WRITE-THROUGH:
   - Write: Write DB + Write cache
   - Always consistent
   - Higher write latency

3. TTL:
   - Set expiration on cached data
   - Balance freshness vs performance

Valkey vs Redis OSS vs Memcached

FeatureValkeyRedis OSSMemcached
Data structuresYes (lists, sets...)Yes (lists, sets...)No
PersistenceYesYesNo
ReplicationYesYesNo
Multi-AZYesYesNo
Pub/SubYesYesNo
Price vs Redis OSS20% lower (node-based), 33% lower (Serverless)BaselineDifferent model
Use caseDefault for Redis-compatible cache, cost-effectiveWorkloads already running Redis OSSSimple caching, multi-threaded

ElastiCache for Valkey (GA 10/2024) is an open-source fork of Redis, API-compatible with Redis OSS. It is 20% cheaper for node-based and 33% cheaper for ElastiCache Serverless (minimum storage 100 MB). Redis OSS reserved nodes still apply when you upgrade to Valkey within the same instance family. Exam keyword: "most cost-effective Redis-compatible cache" → ElastiCache for Valkey; upgrading from Redis OSS to Valkey is in-place, with no client code changes.

Part 2: RDS & Aurora Deep Dive

1. RDS Multi-AZ

┌─────────────────────────────────────────────────────────┐│RDSMULTI-AZ││││┌─────────────────┐┌─────────────────┐│││AZ-a││AZ-b││││┌─────────┐││┌─────────┐│││││Primary│───┼────┼──►│Standby││││││(Active)││Sync││(Passive)│││││└─────────┘│Repl│└─────────┘│││└─────────────────┘└─────────────────┘││││Failovertriggers:││-Primaryinstancefailure││-AZfailure││-Instancetypechange││-Manualfailover(forpatching)││││Failovertime:60-120seconds│└─────────────────────────────────────────────────────────┘

2. RDS Read Replicas

Maximum number of read replicas:
- Aurora: 15
- RDS MySQL/MariaDB/PostgreSQL: 15 (raised from 5 to 15 in 2022)
- RDS Oracle/SQL Server: 5

Cross-Region Read Replica:
- Async replication
- Different region for DR
- Can be promoted to standalone

Read Replica Use Cases:
1. Read scaling
2. Reporting/Analytics
3. DR (promote if needed)

3. RDS Proxy

┌─────────────────────────────────────────────────────────┐│RDSPROXY││││Problem:ManyLambdafunctions=Manyconnections││││┌──────────┐┌──────────┐┌──────────┐│││Lambda1││Lambda2││LambdaN│││└────┬─────┘└────┬─────┘└────┬─────┘│││││││└─────────────┼─────────────┘││▼││┌─────────────────┐│││RDSProxy│Connectionpooling│││(Managed)│Autofailover││└────────┬────────┘│││Limitedconnections││▼││┌─────────────────┐│││RDS/Aurora│││└─────────────────┘│└─────────────────────────────────────────────────────────┘

4. Aurora Features

Aurora Serverless v2

Scaling:
- Min: 0 ACU (auto-pause, since 11/2024;
  previously min 0.5 ACU)
- Max: 256 ACU (since 10/2024; previously 128)
- Scale in seconds

Pricing:
- Per ACU-hour
- Storage separate

Use cases:
- Variable workloads
- Dev/Test
- Multi-tenant SaaS

Aurora Machine Learning

Integrate with ML services from SQL:
- SageMaker (custom models)
- Comprehend (sentiment)

SELECT
  review,
  aws_comprehend.detect_sentiment(review) as sentiment
FROM reviews;

5. Database Cloning

Aurora Cloning:
- Copy-on-write (instant)
- No storage copied initially
- Independent after creation

Use cases:
- Testing with production data
- Analytics without impacting prod
- Debugging

6. RDS/Aurora IAM Database Authentication

Instead of storing a password in the application, use IAM credentials to connect to the database: every connection generates a short-lived auth token from IAM.

┌─────────────────────────────────────────────────────────┐│IAMDATABASEAUTHENTICATIONFLOW││││┌──────────────┐1.generate-db-auth-token│││App(EC2/│─────────────────────────►IAM│││Lambdarole)│◄─────────────────────────││└──────┬───────┘2.Authtoken(TTL15minutes,│││signedwithSigV4)│││3.Connect:user+tokeninsteadofpassword│││(TLS/SSLREQUIRED)││▼││┌──────────────┐4.RDSverifiestokenwithIAM│││RDS/Aurora│→connectionallowed││└──────────────┘│└─────────────────────────────────────────────────────────┘

Key points:

AspectDetails
Supported enginesMySQL, PostgreSQL, MariaDB (both RDS and Aurora). Oracle/SQL Server are NOT supported
TokenGenerated via SDK/CLI: aws rds generate-db-auth-token, expires after 15 minutes, only used to open a connection (an open connection is not dropped when the token expires)
TransportTLS/SSL required in transit
IAM policyAction rds-db:connect, resource is the db-user ARN: arn:aws:rds-db:region:account:dbuser:DbiResourceId/db_username
DB userYou still have to create a user in the database mapped to IAM: MySQL/MariaDB CREATE USER ... IDENTIFIED WITH AWSAuthenticationPlugin AS 'RDS'; PostgreSQL GRANT rds_iam TO user

Example IAM policy:

{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Action": "rds-db:connect",
    "Resource": "arn:aws:rds-db:ap-northeast-1:123456789012:dbuser:db-ABCDEFGHIJKL/app_user"
  }]
}

Benefits (Professional angle):

  • No credentials stored in code/config, no manual password rotation
  • Leverages IAM: automatic rotation via roles, MFA, centralized access control for many databases through IAM policies
  • Auditing via CloudTrail

Exam keywords: "avoid storing database passwords", "use IAM credentials to connect to the database" → IAM Database Authentication. Distinguish: if the question says "rotate credentials automatically" for an engine that does not support IAM auth (Oracle/SQL Server), or the app needs a real password → Secrets Manager rotation.

7. Aurora Custom Endpoints

Aurora has 4 endpoint types:

EndpointPoints toUse case
Cluster (writer)The current primary instanceWrite traffic; switches automatically on failover
ReaderLoad-balances across ALL replicasGeneral read traffic
Instance1 specific instanceDebugging, rarely used by apps
CustomA chosen SUBSET of instancesSeparating workloads by replica group

A custom endpoint lets you specify a subset of instances. For example, 2 large replicas (r6g.8xlarge) dedicated to analytics and the small replicas for regular app reads, so the two workloads do not affect each other:

┌─────────────────────────────────────────────────────────┐│AURORACUSTOMENDPOINTS││││┌──────────┐││Cluster─────►│Writer│││endpoint└──────────┘││││CustomendpointCustomendpoint││"app-read""analytics"││┌─────────────────────┐┌───────────────────┐│││┌─────┐┌─────┐┌────┐││┌───────┐┌───────┐│││││Repl1││Repl2││Rep3││││Repl4││Repl5││││││small││small││smll││││r6g.8xl││r6g.8xl│││││└─────┘└─────┘└────┘││└───────┘└───────┘│││└─────────▲───────────┘└─────────▲─────────┘││││││AppqueriesAnalytics/Reporting││(OLTPreads)(heavyqueries)│└─────────────────────────────────────────────────────────┘

Notes:

  • Once you create custom endpoints, you usually stop using the reader endpoint for that workload (the reader endpoint still load-balances across ALL replicas, including the analytics group)
  • Membership is defined by a static list (list of instances) or an exclusion list; new instances added to the cluster can join automatically depending on configuration
  • Maximum 5 custom endpoints per cluster

Exam keyword: "run analytics/reporting queries on a dedicated subset of replicas without affecting the app's read traffic" → Aurora custom endpoint (not the reader endpoint, no need to create a new cluster).

Part 3: DynamoDB Deep Dive

1. DynamoDB Capacity Modes

┌─────────────────────────────────────────────────────────┐│CAPACITYMODES││││PROVISIONED:││-DefineRCU/WCUupfront││-AutoScalingavailable││-Reservedcapacitydiscount││-Bestfor:Predictableworkloads││││ON-DEMAND:││-Payperrequest││-Nocapacityplanning││-~3.5xcostofprovisionedatsteadystate││(afterthe50%on-demandpricecutin11/2024)││-Bestfor:Unpredictable,newworkloads││││RCU:1RCU=1stronglyconsistentreadof4KB/sec││or2eventuallyconsistentreads││WCU:1WCU=1writeof1KB/sec│└─────────────────────────────────────────────────────────┘

2. Secondary Indexes

┌─────────────────────────────────────────────────────────┐│GLOBALVSLOCALSECONDARYINDEX││││LOCALSECONDARYINDEX(LSI):││-Samepartitionkey,differentsortkey││-Mustcreateattablecreation││-Max5pertable││-SharesRCU/WCUwithtable││││GLOBALSECONDARYINDEX(GSI):││-Differentpartitionkey(andsortkey)││-Cancreateanytime││-Max20pertable││-SeparateRCU/WCU(canthrottlebasetable!)│└─────────────────────────────────────────────────────────┘

3. DynamoDB Accelerator (DAX)

┌─────────────────────────────────────────────────────────┐│DAX││││Application│││││▼SDKcalls││┌─────────────┐│││DAXCluster│←Microsecondlatency│││(Cache)│││└──────┬──────┘│││Cachemiss││▼││┌─────────────┐│││DynamoDB│←Millisecondlatency││└─────────────┘││││Twocaches:││-Itemcache(GetItem,BatchGetItem)││-Querycache(Query,Scanresults)│└─────────────────────────────────────────────────────────┘

4. DynamoDB Transactions

TransactWriteItems:
- Up to 100 items
- Atomic (all or nothing)
- Consumes 2x WCU

TransactGetItems:
- Up to 100 items
- Consumes 2x RCU

Use cases:
- Financial transactions
- Gaming leaderboards
- Multi-item updates

5. Time To Live (TTL)

Auto-delete expired items:
- No extra cost
- Eventually deleted (within 48 hours)
- Define TTL attribute (epoch timestamp)

Use cases:
- Session data
- Temporary tokens
- Log cleanup

6. Patterns

Single Table Design

PK          | SK              | Data
------------+-----------------+--------
USER#123    | METADATA        | {name, email}
USER#123    | ORDER#001       | {order details}
USER#123    | ORDER#002       | {order details}
PRODUCT#A   | METADATA        | {product info}
ORDER#001   | PRODUCT#A       | {line item}

Benefits:
- Single query for all user data
- Reduced latency
- Cost optimization

Part 4: Data Analytics Services

1. Analytics Services Overview

┌─────────────────────────────────────────────────────────┐│ANALYTICSPIPELINE││││Collect→Store→Process→Analyze→Visualize││││KinesisS3/EMR/Athena/QuickSight││DataRedshiftGlueRedshift││Firehose│└─────────────────────────────────────────────────────────┘

2. Amazon Kinesis

Kinesis Services

KINESIS DATA STREAMS:
- Real-time data streaming
- 1-365 days retention
- Replay capability
- Consumers: Lambda, Managed Flink, KCL apps

AMAZON DATA FIREHOSE (formerly: Kinesis Data Firehose):
- Load data to destinations
- Near real-time (buffer 0–900 seconds; zero buffering supported since Dec 2023)
- Destinations: S3, Redshift, OpenSearch, Splunk
- No data retention (pass-through)
- Note: AWS renamed "Kinesis Data Firehose" → "Amazon Data Firehose" (2024). The exam may use either name; the knowledge is the same.

AMAZON MANAGED SERVICE FOR APACHE FLINK
(old name: Kinesis Data Analytics, renamed 08/2023):
- Apache Flink on streaming data
- Real-time analytics
- Note: the old SQL application type is discontinued
  (no new ones since 10/2023; EOL early 2026) —
  the current answer for stream processing is Flink

KINESIS VIDEO STREAMS:
- Stream video from devices
- ML integration

Kinesis Shards

1 Shard capacity:
- Read: 2 MB/s, 5 transactions/s
- Write: 1 MB/s, 1000 records/s

Scaling:
- Shard splitting (scale up)
- Shard merging (scale down)

3. Amazon Redshift

┌─────────────────────────────────────────────────────────┐│REDSHIFT││││ClusterTypes:││├──Provisioned:RA3,DC2nodes││└──Serverless:Auto-scaling││││Features:││-Columnarstorage││-MPP(MassivelyParallelProcessing)││-Upto16PB││-RedshiftSpectrum(queryS3directly)││-FederatedQuery(RDS,Aurora)││-MLwithCREATEMODEL││││DistributionStyles:││-AUTO(recommended)││-EVEN(round-robin)││-KEY(bycolumnvalue)││-ALL(fullcopyoneachnode)│└─────────────────────────────────────────────────────────┘

4. AWS Glue

┌─────────────────────────────────────────────────────────┐│AWSGLUE││││Components:││├──GlueDataCatalog│││└──Metadatarepository│││││├──GlueCrawlers│││└──Auto-discoverschema│││││├──GlueETLJobs│││├──Spark(Python/Scala)│││└──PythonShell│││││├──GlueDataBrew│││└──Visualdatapreparation│││││└──GlueStudio││└──VisualETL│└─────────────────────────────────────────────────────────┘

5. Amazon Athena

Serverless SQL on S3:
- Pay per query ($5/TB scanned)
- Standard SQL (Presto)
- Integrates with Glue Data Catalog

Cost Optimization:
- Use columnar formats (Parquet, ORC)
- Partition data
- Compress data

Federated Query:
- Query across data sources
- RDS, DynamoDB, Redshift, on-prem

6. Lake Formation

┌─────────────────────────────────────────────────────────┐│LAKEFORMATION││││Centralizeddatalakemanagement:││││1.Ingestdatafromsources││2.StoreinS3(withformatting)││3.CatalogwithGlue││4.Securewithfine-grainedpermissions││5.Discoverandanalyze││││Security:││-Column-levelsecurity││-Row-levelsecurity││-Cell-levelsecurity││-Tag-basedaccesscontrol│└─────────────────────────────────────────────────────────┘

7. AWS Batch

Managed batch computing: you submit container jobs and Batch handles provisioning, scheduling and scaling, with no cluster to manage by hand.

Main components

┌─────────────────────────────────────────────────────────┐│AWSBATCH││││├──JobDefinition│││└──Containerimage,vCPU/memory,IAMrole,│││retrystrategy(upto10attempts)│││││├──JobQueue│││└──Priority—higher-priorityqueuesare│││scheduledfirst;1queuemapstomanyCEs│││││└──ComputeEnvironment(CE)││├──Managed:Batchpickstheinstancetype+│││scaleswithqueuedepth││├──Unmanaged:youmanagetheECScluster││└──Capacitytype:EC2On-Demand/EC2Spot/││Fargate/FargateSpot│└─────────────────────────────────────────────────────────┘

Professional-level features

- Array jobs: fan out 1 job definition into thousands of
  child jobs (up to 10,000) — each child gets its own index
  (AWS_BATCH_JOB_ARRAY_INDEX), good for per-file/per-shard work
- Job dependencies: job B runs after job A SUCCEEDED
  (build a simple DAG without Step Functions)
- Multi-node parallel jobs: 1 job spans multiple EC2 instances
  (HPC, distributed ML training) — Fargate/Spot not supported
- Spot integration: CE uses Spot (allocation strategy
  SPOT_CAPACITY_OPTIMIZED) + retry strategy auto-resubmits
  on reclaim → ~70-90% lower batch cost
- Fargate: small jobs, fast startup, no AMI/EC2 to manage

Batch vs Lambda (vs EMR)

CriteriaLambdaAWS Batch
Run timeUp to 15 minutesUnlimited
MemoryUp to 10 GBDepends on instance (hundreds of GB+)
RuntimeLimited runtimes (or container ≤10GB)Any container
GPU / EBSNoYes (GPU instances, EBS volumes)
ModelFully serverless, event-drivenManaged infra, runs on EC2/Fargate
CostPer-invocationEC2/Fargate (Spot is very cheap)
  • Compared with EMR: EMR = managed big data framework (Spark/Hadoop/Hive) for distributed data processing; Batch = runs arbitrary container batch jobs not tied to any framework.

Exam keywords

  • "long-running batch jobs", "jobs > 15 minutes" (Lambda is not enough) → AWS Batch
  • "GPU batch processing" (rendering, genomics, bulk ML inference) → AWS Batch with GPU instances
  • "cost-effective" for interruption-tolerant batch → Batch + Spot + retry

Typical pattern

S3event/EventBridgeschedule│(submitjob)▼┌──────────────┐┌─────────────────────────┐│JobQueue│───▶│ComputeEnvironment││(priority)││Managed—Spotfleet│└──────────────┘│scalesbyqueuedepth│└───────────┬─────────────┘│containerprocesses▼S3(outputresults)

Review Questions

  1. When do you choose DynamoDB vs RDS?

    Show answer

    DynamoDB when: (1) you need millisecond latency at any scale (10M+ req/s), (2) the data model is key-value or document, (3) the schema is not fixed or changes often, (4) serverless/global scale, (5) no complex SQL joins are needed. RDS when: (1) you need complex ACID transactions, (2) complex JOINs across many tables, (3) reporting/analytics with SQL, (4) existing apps with a relational schema, (5) the team is familiar with SQL. Aurora = enhanced RDS for higher scale and availability.

  2. What is the Aurora Global Database replication lag?

    Show answer

    Typically under 1 second. Aurora Global Database uses storage-level replication (not binlog) with dedicated replication infrastructure. In practice it is usually < 1 second, and AWS documentation states typically < 1 second for "typical workloads". Failover (promoting the secondary): < 1 minute (managed failover). This is why Aurora Global Database fits DR with RPO near 0 and RTO < 1 minute.

  3. Are DynamoDB Global Tables active-active or active-passive?

    Show answer

    Active-active: all Regions can read and write at the same time. This differs from many DB replication setups that are active-passive (only the primary writes). Global Tables use last-writer-wins to resolve conflicts. Good for: global applications that need low-latency writes from multiple continents, gaming leaderboards, user profiles. Design pattern: partition users by Region (users from Asia → write to the Asia table) to avoid conflicts.

  4. How do Redis and Memcached differ?

    Show answer

    Redis: persistence (RDB + AOF), replication, pub/sub, Sorted Sets, Streams, scripting, Multi-AZ failover; feature-rich. Memcached: simple, multi-threaded (scales with CPU cores), horizontal sharding, no persistence; a pure cache. Choose Redis when you need persistence, replication, pub/sub, complex data types, HA. Choose Memcached for simple pure caching, when you need multi-threading for CPU-intensive cache operations and no persistence.

  5. How does Multi-AZ differ from a Read Replica?

    Show answer

    Multi-AZ: the goal is HA. The standby uses sync replication, does not serve read traffic (except Multi-AZ DB Cluster with 2 readable standbys), fails over automatically in 60–120s, same endpoint. Read Replica: the goal is read scaling / DR. It uses async replication, serves read traffic, can be cross-region, and is promoted manually to standalone. Common exam trap: "increase availability" → Multi-AZ; "offload reporting queries" → Read Replica; "DR to another region with low RPO" → cross-region read replica (or Aurora Global Database).

  6. What is the maximum number of read replicas for each engine?

    Show answer

    Aurora: 15 replicas (shared storage volume, ~ms lag, can be failover targets by priority tier). RDS MySQL/MariaDB/PostgreSQL: 15 (raised from 5 to 15 in 2022; older material saying 5 is outdated). RDS Oracle/SQL Server: 5. RDS read replicas use engine-level async replication, so lag is higher than Aurora.

  7. When do you need RDS Proxy?

    Show answer

    When many short-lived connections exhaust max_connections, typically Lambda scaling to thousands of concurrent executions that each open a connection. RDS Proxy provides managed connection pooling and multiplexing, reduces failover time by up to ~66% (keeps connections during failover), and supports IAM auth + Secrets Manager. Keyword: "Lambda + RDS + too many connections" or "reduce database failover time" → RDS Proxy.

  8. How does Aurora Cloning work and how is it different from restoring a snapshot?

    Show answer

    Cloning uses copy-on-write on the shared storage layer: the clone is created almost instantly, no data is copied up front, and new pages are only written when the clone or the source changes. Restoring from a snapshot has to copy all the data, so it is slower and uses more storage. Use clones for testing on production data, ad-hoc analytics, debugging. Limitation: clones stay in the same region (cross-account is possible via RAM sharing).

  9. An application on EC2 needs to connect to Aurora MySQL "without storing the database password". What is the solution and how do you configure it?

    Show answer

    IAM Database Authentication. Steps: (1) enable IAM DB auth on the cluster; (2) create a DB user mapped to IAM: CREATE USER 'app_user' IDENTIFIED WITH AWSAuthenticationPlugin AS 'RDS' (PostgreSQL: GRANT rds_iam); (3) attach an IAM policy to the EC2 instance role with action rds-db:connect on the db-user ARN; (4) the app calls generate-db-auth-token to get a 15-minute token and connects over TLS using the token instead of a password. Only MySQL/PostgreSQL/MariaDB are supported. Keyword: "avoid storing database passwords", "use IAM credentials to connect" → IAM DB auth.

  10. The analytics team runs heavy queries on Aurora that slow down the app's read traffic. How do you separate the two workloads without creating a new cluster?

Show answer

Create an Aurora custom endpoint: add 2 large replicas dedicated to analytics and group them into 1 custom endpoint; the app reads through another custom endpoint (or the reader endpoint if the analytics group has been excluded; but note the reader endpoint by default load-balances across ALL replicas, so you usually create 2 custom endpoints and stop using the reader endpoint for these workloads). Result: analytics queries run only on the designated subset of replicas and do not affect OLTP reads. Keyword: "reporting/analytics on a dedicated subset of replicas" → custom endpoint.

  1. When do you choose On-Demand instead of Provisioned?
Show answer

On-Demand when: traffic is unpredictable/spiky, the workload is new with no baseline yet, or you want zero capacity planning ("least operational overhead"). Provisioned when: traffic is steady/predictable. It is ~3.5× cheaper at steady state (after the 50% on-demand price cut in 11/2024; previously the gap was ~6–7×), and you can buy reserved capacity. Provisioned + Auto Scaling is the middle ground for traffic that fluctuates with a pattern.

  1. How does a GSI differ from an LSI, and when does a GSI throttle the base table?
Show answer

LSI: same partition key, different sort key; only created at table creation; max 5; shares RCU/WCU with the table; supports strongly consistent reads. GSI: can have a different partition key; created any time; max 20; its own RCU/WCU; eventually consistent only. Key trap: if a GSI lacks WCU, writes to the base table get throttled even though the table still has capacity, because every write must propagate to the GSI. Provision GSI WCU ≥ base table WCU for the indexed attributes.

  1. Which use cases suit DAX, and which do not?
Show answer

Good fit: read-heavy, read-mostly workloads that need microsecond latency (item cache for GetItem, query cache for Query/Scan), and reducing RCU cost when hot keys are read repeatedly. Poor fit: write-heavy workloads, workloads that need strongly consistent reads (DAX only serves eventually consistent), or apps that do not use a DAX-compatible SDK. If you need a shared cache for multiple data sources → ElastiCache instead of DAX.

  1. Is TTL charged, and how long is the deletion delay?
Show answer

TTL is free (deletes do not consume WCU). Expired items are deleted eventually, typically within a few days, not instantly (docs: typically within 48 hours), so filter out expired items in queries if the app is sensitive to them. Items deleted by TTL appear in DynamoDB Streams (as REMOVE with userIdentity set to dynamodb.amazonaws.com). A common pattern: TTL + Streams + Lambda to archive expired data to S3.

  1. How does Kinesis Data Streams differ from Amazon Data Firehose?
Show answer

Data Streams: real-time (~ms), retention 1–365 days, replayable, custom consumers (Lambda, Managed Flink, KCL), you manage shards (or use on-demand mode). Data Firehose: near real-time (buffer 0–900s), no retention (pass-through), fully managed loading into S3/Redshift/OpenSearch/Splunk, Lambda transforms, zero admin. Keyword: "replay/multiple consumers/custom processing" → Streams; "load streaming data into S3/Redshift with least operational overhead" → Firehose.

  1. Which service handles real-time stream processing today, and what was its old name?
Show answer

Amazon Managed Service for Apache Flink, formerly Kinesis Data Analytics (renamed 08/2023). It runs Apache Flink applications for windowed aggregation, anomaly detection, streaming ETL. The old SQL application type is discontinued (no new ones since 10/2023, EOL early 2026). If a question says "SQL on streaming data" with a KDA SQL option, that is an outdated distractor; the current answer is Flink.

  1. How do you reduce Athena costs?
Show answer

Athena charges $5/TB scanned, so reduce the data scanned: (1) columnar format (Parquet/ORC) reads only the needed columns, (2) partition by date/region + partition projection, (3) compress (Snappy/GZIP), (4) SELECT only the needed columns instead of SELECT *, (5) use CTAS to create optimized tables from raw data. Combined, these often cut cost by 90%+. This is the classic "most cost-effective" question.

  1. How does Redshift Spectrum differ from Athena?
Show answer

Both query S3 directly via the Glue Data Catalog. Spectrum runs from a Redshift cluster and can JOIN S3 data with local Redshift tables; it fits when you already have Redshift and want to extend the warehouse into the data lake. Athena is fully serverless with no cluster; it fits ad-hoc queries, "occasional queries, pay per query". If the scenario has no existing Redshift → Athena; existing Redshift + need to join local data → Spectrum.

  1. When do you choose AWS Batch instead of Lambda for batch processing?
Show answer

Choose AWS Batch when the job exceeds Lambda limits: runs > 15 minutes, needs > 10 GB RAM, needs a GPU or EBS volume, or needs an arbitrary container/runtime. Batch provisions and scales the Compute Environment by queue depth, supports array jobs (fan out thousands of jobs), job dependencies and Spot with automatic retry on reclaim, the "most cost-effective" option for interruption-tolerant batch. Lambda wins for short, event-driven jobs that need fully serverless with zero infra. If the scenario is big data with Spark/Hadoop → EMR, not Batch.

Hands-on Exercises

Part 1: Database Options

  1. Aurora Serverless v2 auto-pause: create an Aurora PostgreSQL Serverless v2 cluster with a capacity range of 0–4 ACU (min 0 to enable auto-pause). Leave it idle for ~10 minutes, watch the ServerlessDatabaseCapacity metric drop to 0, then measure the resume time when a new connection arrives. Note the trade-off between resume latency and idle cost.

  2. DynamoDB Global Tables: create a Global Table in 2 regions, write the same item from both regions almost simultaneously, and observe last-writer-wins conflict resolution through the final item. Conclude why you should partition users by region.

  3. Caching pattern with ElastiCache: set up Redis (Serverless or a small node), implement lazy loading + TTL in front of an RDS/DynamoDB table; measure cache hit vs miss latency and discuss when you need write-through.

Part 2: RDS & Aurora Deep Dive

  1. Multi-AZ failover: create an RDS MySQL Multi-AZ instance (db.t3.micro), run reboot with failover, measure how long the client loses its connection and verify the endpoint does not change.

  2. RDS Proxy + Lambda: create an RDS Proxy in front of that database, point Lambda at the proxy endpoint with IAM auth; run 200 concurrent invocations and compare the number of connections on the DB (SHOW PROCESSLIST) when going direct vs through the proxy.

  3. Aurora clone: create a small Aurora cluster, insert sample data, create a clone and measure the creation time; modify data on the clone and verify the source is unchanged.

Part 3: DynamoDB Deep Dive

  1. Compare capacity modes: create 2 identical tables (1 On-Demand, 1 Provisioned 5 RCU/5 WCU), run a small load test that exceeds the provisioned capacity and watch the ThrottledRequests metric; estimate the monthly cost for the same steady 50 req/s workload in both modes.

  2. GSI throttling: create a GSI with much lower WCU than the base table, write heavily and observe writes to the base table being throttled, confirming the "GSI can throttle the base table" trap.

  3. TTL + Streams archive: enable TTL on an epoch attribute, enable Streams, attach a Lambda that writes expired items to S3. Verify that REMOVE records caused by TTL carry the characteristic userIdentity.

Part 4: Data Analytics Services

  1. Firehose → S3 pipeline: create a Firehose delivery stream with an S3 destination and dynamic partitioning by date, send sample records via the CLI (put-record), and watch files land in S3 according to the buffer interval.

  2. Athena cost optimization: upload a CSV dataset (~100MB) to S3, query it with Athena and record "data scanned"; use CTAS to convert to Parquet + partitions, rerun the same query and compare the amount scanned/cost.

  3. Glue Crawler + Catalog: run a Glue Crawler on the dataset bucket from exercise 2, see the schema land automatically in the Data Catalog, and query it via Athena without writing DDL by hand.

References


Next lesson →