TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

All concepts ยท aws ยท databases ยท high availability ยท spring

Amazon RDS and Aurora

Relational databases that AWS runs for you. RDS handles patching, backups and failover to a synchronous standby; Aurora adds storage shared by all instances and spread across three Availability Zones. You still own the schema, the queries and how your app connects.

15 min6 animations

๐Ÿ“š Builds on๐Ÿ“š Replication and read replicas๐Ÿ›’ Transactions and isolation

๐Ÿ–จ๏ธ Cheat sheet

A records office the council runs

Bea runs a bakery, and she keeps all her records (orders, customers, prices) in filing cabinets. She could buy cabinets, rent a room, fit locks and hire a guard. Instead she keeps them at the town's records office, which the council runs. A service like that is called a managed database.

The council does the building work: it fixes the locks when a weakness is found, photographs every cabinet each night and writes down every single filing in a logbook. So if Bea asks the clerk to throw away the wrong drawer at 3:15 on Tuesday, the council can set up a fresh office with the cabinets exactly as they were at 3:14.

Bea still does her own part. She decides which drawers exist and what goes in them, she writes the index cards that help the clerk find things fast, and she decides what to ask for. If she asks for "every order ever, sorted by colour", the clerk will be slow, and that is not the council's fault.

What a managed database is

Amazon RDS (Relational Database Service) runs a database engine for you: PostgreSQL, MySQL, MariaDB, Oracle, SQL Server, Db2, or Aurora, AWS's own MySQL- and PostgreSQL-compatible engine. You pick an instance class and storage; AWS runs the host. You get an endpoint (a DNS name) and connect with the normal driver for the engine.

AWS doesYou still do
Hardware, OS and engine installationSchema design and migrations
OS and engine patching, in a maintenance window you chooseIndexes and query tuning
Automated backups and point-in-time restoreChoosing the retention period, testing restores
Replication and failover, when you enable themUsers, grants, network rules (security groups)
Monitoring metricsConnection management in your app

Automated backups are daily storage snapshots plus the engine's transaction logs, kept for a retention period you set (up to 35 days; on an RDS instance 0 turns them off, while Aurora keeps at least 1 day). Together they allow point-in-time restore to any second inside the window, up to the latest restorable time, which is usually a few minutes behind now. A restore always creates a new DB instance with a new endpoint; it never rewinds the existing one, so your app must be pointed at the restored copy.

There is no shell on the host. Engine settings live in parameter groups, and a slow query is still yours to fix with EXPLAIN and an index.

What AWS runs, what you own4 steps
Photos and logbook0123๐ŸฅBea's bakery๐Ÿ›๏ธThe council๐ŸขRecords office
Press play and watch it happen!

A twin office across town

What if the records office floods? The council can keep a standby: a twin office in another district, with its own copy of every cabinet.

Whenever Bea hands in a form, the clerk files it in both offices before saying "done". The twin keeps its doors shut; it's only there to take over.

Bea never writes the office's street address on her letters. She follows the signpost on the high street that says "Bea's records, this way". If the main office floods, the council turns the signpost to point at the twin. Bea's next trip ends at the twin, with nothing missing.

Multi-AZ: a synchronous standby

A Multi-AZ DB instance deployment keeps a standby in a second Availability Zone (a separate data centre in the same Region). Writes are replicated to it synchronously: a commit isn't acknowledged until the standby has it, so a failover loses no committed transactions. The cost is a little extra write latency.

In this classic setup the standby serves no traffic. It isn't a read replica; it exists for availability.

On failure (the primary host or its AZ fails, the instance is rebooted with failover, or during some maintenance) RDS promotes the standby and updates the instance's DNS endpoint to point at it. The endpoint name doesn't change, so apps only have to reconnect. Failover typically takes 60 to 120 seconds; long-running transactions can make recovery slower. Open connections are broken, and in-flight transactions roll back.

๐Ÿ”ง Going deeper

Multi-AZ DB clusters are a newer option for MySQL and PostgreSQL: one writer and two readable standbys in three AZs. A write commits once at least one standby has it, so failover is usually faster, and the standbys can serve reads through a reader endpoint.

Clients must re-resolve DNS. The JVM caches DNS lookups; most JVMs keep them for 30 seconds, but some configurations cache them until restart. AWS recommends a TTL of no more than 60 seconds (networkaddress.cache.ttl), or the app can keep dialling the old primary's IP after the endpoint has moved.

Multi-AZ failover5 steps
๐Ÿ˜๏ธ District A๐Ÿ˜๏ธ District B๐ŸฅBea's bakery๐ŸชงSignpost๐ŸขMain office๐ŸคTwin office
Press play and watch it happen!

Reading rooms

Lots of people only want to look at Bea's files, never change them: her accountant, her delivery driver, her own website. They all queue at one office.

So the council opens reading rooms, called read replicas. A courier carries a copy of each new filing to every reading room, but only after the main office has said "done" to Bea. That means a reading room can be a moment behind.

Anyone can look things up in a reading room. Changes still go to the main office; a reading room won't accept a form. If the main office is lost for good, Bea can ask the council to turn a reading room into a new main office, but the signpost doesn't move by itself, and anything the courier hadn't delivered yet is missing.

Read replicas

A read replica is a separate instance with its own endpoint, fed by the engine's asynchronous replication (see Replication). RDS for MySQL, MariaDB and PostgreSQL support up to 15 per source, including replicas in other Regions.

  • Replicas are read-only. Your app must send reads to them on purpose, by using their endpoints.
  • Replication is asynchronous, so replicas lag: read-your-writes needs the primary.
  • A replica can be promoted to a standalone instance, manually. Unreplicated changes are lost, and promotion breaks replication; it's a disaster-recovery tool, not automatic failover.
Multi-AZ standbyRead replica
ReplicationSynchronousAsynchronous
Serves readsNo (classic Multi-AZ)Yes
FailoverAutomatic, same endpointManual promotion, new endpoint
PurposeAvailabilityRead scaling, reporting, DR
Read replicas4 steps
๐ŸฅBea's bakery๐ŸขMain office๐Ÿ“–Reading room 1๐Ÿ“–Reading room 2
Press play and watch it happen!

One vault, many counters

The council's newest offices, called Aurora, work differently. The files aren't kept inside any one office. They sit in one big shared vault spread across three districts, with six copies of every page, two in each district. A form counts as filed once four of the six copies have it, so a whole district can flood and nothing is lost.

The offices are just counters on top of the vault. One main counter takes forms. Several reading counters look things up in the very same vault, so they're barely behind at all.

There are two signposts: the main signpost leads to the main counter, and the reading signpost sends each visitor to one of the reading counters. If the main counter closes, a reading counter simply starts taking forms. No files need to move, because they were in the shared vault all along.

Aurora: shared storage and endpoints

An Aurora DB cluster separates compute from storage. Every instance reads from one cluster volume that stores six copies of the data across three AZs. A write is durable once 4 of 6 copies acknowledge it, so the volume keeps accepting writes after losing two copies (a whole AZ) and keeps serving reads after losing three, and storage repairs itself in the background. The writer ships only log records to storage, not whole pages.

  • One writer (primary) instance and up to 15 Aurora Replicas. Replicas read the same volume, so they don't copy data; their lag is usually under 100 ms.
  • The cluster endpoint always points at the current writer. Use it for writes.
  • The reader endpoint spreads connections (not individual queries) across the replicas. A pooled connection stays on one replica.
  • Failover promotes a replica to writer and moves the cluster endpoint to it. With no data to catch up on, this is much faster than rebuilding an instance. Each replica has a priority tier (0 is highest) that picks the winner. With no replicas at all, the cluster is unavailable until the writer is recreated.
Aurora's shared storage5 steps
๐Ÿฆ Shared vaultDistrict A shelves012District B shelves012District C shelves012๐ŸฅBea's bakery๐ŸชงMain signpost๐ŸชงReading signpost๐Ÿง‘โ€๐Ÿ’ผMain counter๐Ÿง‘โ€๐ŸซReading counter 1๐Ÿง‘โ€๐ŸซReading counter 2
Press play and watch it happen!

Not enough windows

The office has only so many service windows, and each visitor keeps theirs until they leave. Bea's website sends a few helpers, and each one grabs a whole row of windows just in case, then mostly stands there. Soon every window is taken, and the next helper is turned away at the door, even though the clerks are mostly idle.

So the council puts a doorman at the entrance, called a proxy. Helpers talk to the doorman instead. The doorman keeps a few windows open and passes each helper's form through whichever one is free. Many helpers now share a few windows. And if the main counter has to move, the doorman knows where it went, so the helpers just wait a moment at the door.

Connection limits and RDS Proxy

Each database connection costs the server memory (a whole backend process in PostgreSQL), so max_connections is capped; by default the parameter group derives it from the instance's memory. Many app instances, each with its own pool, or a burst of AWS Lambda invocations, can exhaust it, and new connections fail with "too many connections".

RDS Proxy is a managed connection pooler in front of an RDS instance or Aurora cluster:

  • Clients connect to the proxy's endpoint. The proxy keeps a smaller pool of connections to the database and multiplexes: after each transaction, the database connection can serve another client.
  • Some session state (temporary tables, session variables, certain SET statements) forces pinning, which ties the client to one database connection and removes the benefit. Watch for it.
  • During a failover the proxy keeps idle client connections open and sends them to the new writer itself, without waiting for DNS to change, which shortens the outage apps see. A transaction in flight still fails and must be retried.
  • Credentials come from AWS Secrets Manager, or clients use IAM authentication.

Without a proxy, keep maximumPoolSize times the number of app instances safely under max_connections. With one, size the proxy's share of the database's connections (MaxConnectionsPercent) instead, and still keep app pools modest.

Connection limits and RDS Proxy4 steps
๐Ÿง‘Helper 1๐Ÿ‘ฉHelper 2๐Ÿง”Helper 3๐ŸขRecords office
Press play and watch it happen!

Bea's address card

Bea's bakery keeps an address card that says where to send forms. It must name the signpost, never the office's street address, because the office behind the signpost can change.

When a door shuts in the middle of an errand, Bea's helper doesn't give up. They let go of the old window, look at the signpost again and try the whole errand once more, from the start. A half-finished errand never counts, so trying again is safe, as long as doing the errand twice wouldn't cause harm (like paying a bill twice).

Connecting from Spring

Point the JDBC URL at the cluster endpoint (Aurora) or the DB instance endpoint (RDS), never at an Aurora instance endpoint or an IP address, which stay put when the writer moves:

1spring:2  datasource:3    url: jdbc:postgresql://orders.cluster-abc123xyz.eu-west-1.rds.amazonaws.com:5432/orders4    username: app5    password: ${DB_PASSWORD}6    hikari:7      maximum-pool-size: 108      max-lifetime: 300000     # recycle connections so they re-resolve DNS9      connection-timeout: 5000

When the writer fails, open connections break and in-flight transactions roll back. HikariCP evicts the broken connections and opens new ones, which resolve the endpoint again, so pin the JVM's DNS cache to a short TTL instead of relying on the JVM's default:

1public static void main(String[] args) {2    java.security.Security.setProperty("networkaddress.cache.ttl", "30");3    SpringApplication.run(OrdersApplication.class, args);4}

A transaction that failed during failover rolled back as a whole (see Transactions), so the app can retry it once, from the start, as long as the work is idempotent. Put the retry around the @Transactional method, not inside it.

For faster failover on Aurora and Multi-AZ DB clusters, the AWS Advanced JDBC Wrapper wraps the normal driver (jdbc:aws-wrapper:postgresql://..., driver class software.amazon.jdbc.Driver) and tracks the cluster's topology itself, reconnecting to the new writer without waiting for DNS. It still throws an SQLException after failing over (SQLState 08S02, or 08007 if a transaction was open), so the retry above is still needed.

Send read-only work to the reader endpoint with a second data source, for example an AbstractRoutingDataSource wrapped in a LazyConnectionDataSourceProxy that routes @Transactional(readOnly = true) methods to the reader, and keep reads that must see the latest write on the writer.

A Spring app rides out a failover4 steps
๐Ÿง‘Bea's helper๐ŸชงSignpost๐Ÿง‘โ€๐Ÿ’ผCounter A๐Ÿง‘โ€๐ŸซCounter B
Press play and watch it happen!

๐Ÿงฉ Quick quiz

Quick quiz! 5 questions about Amazon RDS and Aurora, told the same way as the story.
  1. Bea asks the clerk for every order ever, sorted by colour, and it takes ages. Whose job is it to fix?
  2. The main office floods. Why doesn't Bea lose any form she was told was done?
  3. In the newest offices, why can a reading counter take over from the main counter so quickly?
  4. Bea's helpers keep getting turned away at the door, although the clerks are mostly idle. What helps?
  5. Counter A shuts in the middle of the helper's errand. What should the helper do?
Answer every question to check.Passing marks Amazon RDS and Aurora as done.
Got the hang of Amazon RDS and Aurora? Mark it as done, and your paths show how far youโ€™ve got.

Saved in this browser.

โ˜๏ธ AWS from zeroStep 9 of 12

โ† Previous on the path๐Ÿ“Œ Amazon DynamoDBNext on the path โ†’๐Ÿ—ž๏ธ Amazon CloudFront