Ravindra BagaleCourses & study guides मराठी Track your progress

AWS Cloud

Chapter 16: Amazon RDS

Let's go. In Chapter 10 we installed MySQL or MariaDB on the same EC2 instance. That is one useful way to practise SQL; the overview below also includes local in-memory exercises. In a real project the database should not live and die with that one server. Today we learn Amazon RDS: AWS provides managed maintenance, backup and availability facilities according to the selected configuration. You still design the data, write the SQL and test recovery. Don't worry, you will get it.

In this chapter

  • Why RDS instead of MySQL on EC2
  • Engines and the DB subnet group
  • Create a private MySQL database
  • Connect from EC2 with the client
  • Point PHP, Python, Node, WordPress
  • Backups, snapshots and Multi-AZ
  • Stop, delete and a full lab

This chapter uses the EC2 instance from Chapter 5, the MySQL application from Chapter 10, and the VPC and security groups from Chapter 15. The expanded overview uses offline learning exercises. Before any separate authorised AWS lab, review the account, Region, resource configuration, charges and cleanup plan.

  Browser --> EC2 (Nginx / PHP / Flask / Node) --3306--> RDS MySQL
              private IP 10.0.1.25                      endpoint (DNS name)
              security group: web-sg                    security group: rds-sg
                                                        allows 3306 ONLY from web-sg

  The database is not a folder on the EC2 disk.
  Its placement uses a DB subnet group, normally spanning two or more AZs.
  Special Local Zone placement has different requirements.

Concepts in this chapter

  1. 16.1Why RDS instead of MySQL on EC2
  2. 16.2Engines and where the database lives
  3. 16.3Create a MySQL database
  4. 16.4Connect from EC2
  5. 16.5Point your app at the endpoint
  6. 16.6Backups and snapshots
  7. 16.7Multi-AZ and read replicas
  8. 16.8Stop and delete
  9. 16.9Production cautions

Review and practice

  1. ★Common Mistakes I See Students Make
  2. ★Interview Questions
  3. ★Practice Questions and Lab Exercises

Trace a reservation through commit and readback

Trace a reservation through commit and readbackRequest identityOne operation, recognisable retriesDatabase transactionRelated changes succeed togetherCommitted resultA response can still be lostVerified readbackUse the required freshness
Read all steps
  1. Request identity

    The application gives the reservation a stable operation identity and validates its details. Reusing that identity for a different student must not silently create or claim another result.

  2. Database transaction

    The application reserves capacity and stores the reservation within its chosen transaction design. In the local sequential exercise, a deliberate pre-commit failure rolls both changes back.

  3. Committed result

    The database can commit before a connection failure prevents the caller receiving confirmation. An unclear response therefore requires investigation or a safe retry design, not an assumption that nothing was stored.

  4. Verified readback

    Confirm the operation against the appropriate authoritative result. An asynchronous report copy may still show an older count. The teaching diagram does not measure replication delay or guarantee recovery timing.

1. Keep the registration record separate from the website process

Imagine that your college is running a robotics workshop. A student opens the registration page, selects a session and presses Reserve. The page must do more than display a cheerful message. It must remember who reserved a place, which session they selected and whether a seat remains. That information must still be present after the application restarts. It must also be available when a second application server receives the student's next request.

A variable inside one running application cannot provide all of that. The variable belongs to that process and disappears when the process ends. A local text file lasts longer, but multiple writers, searches, permissions and related updates soon become difficult to manage correctly. A database provides a structured system for storing and retrieving records and coordinating changes. You still design the records and operations; the database gives you tools for enforcing that design.

For this workshop, think of three tables: students, sessions and reservations. A row describes one student, one workshop session or one reservation. Columns describe attributes such as a student identifier, session title and booking status. A reservation refers to the identifiers of its student and session. These relationships let the application answer questions such as which students registered for the afternoon session without storing a separate, inconsistent copy of every student's details in every booking.

A primary key identifies a row. A foreign key can enforce a valid relationship between rows, when configured and supported by the chosen engine and table design. A unique constraint can prevent two records from claiming the same business identifier. These are practical protections, not vocabulary for an examination. If the reservation must refer to an existing session, encoding that rule in the database helps catch mistakes from different application paths.

Amazon Relational Database Service, usually called Amazon RDS, manages common work involved in operating supported relational database engines. The application uses a database driver and the selected engine's protocol to send SQL and receive results. RDS is not a replacement for SQL, a website builder or a place to upload your HTML files. It changes how the database service is operated while leaving application behaviour and data design as important responsibilities.

By the end of this overview, you should be able to trace one reservation from application to committed record, distinguish availability from recovery, and explain the evidence needed before switching an application to a restored database. The local activities use fictional data in memory. They teach decisions and SQL behaviour without creating an AWS database or requiring payment details.

2. Understand the work that RDS takes over

When you install a database on an EC2 instance, your team normally operates the guest operating system and database installation as well as the application. Someone plans patching, configures backups, checks storage, monitors failures and rehearses recovery. Running that database separately from the web server is already useful, but the operational work still needs an owner. RDS provides managed mechanisms for many of these common database administration tasks.

Managed does not mean that every useful feature is enabled with the correct settings for your project. The team chooses an engine and deployment, configures access, decides backup retention and tests application compatibility with maintenance. It also chooses recovery objectives and checks that the selected arrangement can meet them. A setting that is reasonable for a disposable learning environment may be inadequate for a service accepting real registrations.

Think of two responsibility lists. AWS operates the service infrastructure and the supported managed database facilities. Your team owns the meaning of the records, the correctness of the application, the SQL workload and the choices exposed through the service configuration. If an authorised application sends the wrong deletion query, a healthy managed database can execute that incorrect instruction perfectly. Good infrastructure does not recognise your intention.

A regular RDS database is also different from a general-purpose server you administer through SSH. Do not plan to install a web server alongside the database or change arbitrary operating-system files. The available privileges and extension choices follow the selected service and engine. Products such as RDS Custom have their own operating model; they do not make assumptions about a standard RDS instance universally true.

A useful planning conversation begins with the existing application. Which engine and version does its driver support? Which SQL features, extensions or collations does it use? How large is the data? How much interruption can the workshop tolerate? Who can restore it? Choosing a database by the smallest advertised instance class before answering these questions can produce a cheap resource that does not run the required application.

For a student project, write a short ownership note: the application owner handles schema and query changes; the service owner handles configuration, monitoring and maintenance planning; the recovery owner rehearses restoration and cutover. One student can hold all three roles. The value is making each job visible instead of assuming that the word managed has removed it.

3. Separate the engine, instance, database and endpoint

The engine is the database software family, such as PostgreSQL or MySQL. Its version determines supported behaviour and compatibility. RDS also supports other engine families, including MariaDB, Oracle Database, Microsoft SQL Server and IBM Db2. Aurora is related to the RDS family but has its own architecture and documentation. Do not transfer every instance-based RDS rule to an Aurora cluster merely because both appear in a database console.

A DB instance is a managed database environment with selected compute and storage characteristics. Inside that environment, the engine organises logical databases and schemas according to its own terminology and rules. The AWS identifier used to manage the instance is not automatically the database name that an application must select during login. Confusing these two names can make a reachable server seem broken when the requested logical database simply does not exist.

The instance class describes compute capabilities such as processor and memory resources. Storage configuration describes capacity and performance choices. Increasing storage capacity is not the same decision as increasing memory. Likewise, a larger machine does not automatically fix a query that examines an enormous table unnecessarily. Record which constraint you are trying to address before changing either setting.

The endpoint supplies a DNS name and associated connection information. Use the appropriate endpoint in the application configuration instead of saving a resolved IP address permanently. Service operations can change the underlying destination. A DNS name allows the service to direct new connections appropriately, but existing connections and application DNS caching still need to be handled correctly.

A parameter group supplies engine configuration settings; an option group applies to engines and features that use that mechanism. Some changes can take effect dynamically, while others require a restart or another controlled operation. An application configuration file is a different object again: it tells your code which endpoint, database and authentication method to use. Drawing these objects separately prevents a common beginner mistake of expecting one setting to configure every layer.

Names to record before connecting the workshop application
ItemQuestion it answersCommon confusion
DB instance identifierWhich AWS resource are we managing?Using it as the SQL database name without checking.
Engine and versionWhich database behaviour and client compatibility apply?Assuming every SQL dialect and extension behaves alike.
Endpoint and portWhere should this database connection go?Hard-coding a temporary resolved address.
Database and database userWhich records and privileges does the session use?Treating AWS console access as permission to read tables.

4. Follow the application's private database connection

The workshop website has more than one network conversation. The student's browser talks to the website. The application then makes a separate connection to the database. The browser should not receive the database password or open a direct SQL connection as part of ordinary website use. Keeping this separation clear makes both architecture diagrams and troubleshooting much easier.

In a typical private design, the RDS database is placed using a DB subnet group in the intended VPC. This group supplies candidate subnets for the database deployment; it is not a list of students allowed to connect. Ordinary regional DB subnet groups cover at least two Availability Zones. Special placements such as a Local Zone have different rules. Having multiple subnets available does not itself mean that you selected a Multi-AZ deployment.

Subnets also need sufficient free address space for the intended service operations. A design that barely accommodates today's resources can cause difficulty during maintenance or changes. Plan the application and database placement together, and record the actual VPC and subnet identifiers. Similar names in different Regions do not establish that two resources share a network.

The database security group should permit the intended client path and database port. For an application in a suitable same-VPC design, a rule can identify the application's security group as the allowed source. That reference does not copy the source group's rules, and it does not grant SQL privileges. It describes a network permission for traffic from the relevant associated interfaces.

A database login needs several layers to work: name resolution, a valid network path, applicable security rules, a listening service, a compatible client and accepted authentication. A public-access setting is not a general solution to every connection failure. Private access can also reach a database from connected networks using an approved design. Diagnose the actual source and destination before changing exposure.

Suppose the timetable page loads but Reserve reports a database timeout. The first observation proves that a web response was delivered. It does not prove the separate application-to-database path. Capture the database endpoint actually used by the application, its port and the error timestamp. Test from the application's environment or an authorised equivalent; a successful connection from your laptop may use a completely different path.

5. Keep network access, login and encryption distinct

AWS permissions control management operations such as describing or changing an RDS resource. Database privileges control operations inside the engine, such as selecting rows or changing a table. A person may be allowed to view an instance in the AWS console without being a database user. Conversely, an application database account can have useful SQL privileges without permission to resize or delete the AWS resource.

Create application privileges around the operations actually required. The reservation application might read sessions and create reservations, while a reporting identity only reads selected data. Routine application requests should not depend on a broadly privileged administrator account. When a feature requires a schema migration, run it through a reviewed maintenance process rather than giving every web request unrestricted schema-changing rights.

Store and retrieve credentials through the project's approved secret mechanism. Do not paste passwords into a public repository, web page, screenshot or command example. Rotation also has an application side: the application must obtain and use the new credential without continuing indefinitely with an old cached value. The secret changing successfully is only one part of a working rotation.

Supported MariaDB, MySQL and PostgreSQL configurations can use IAM database authentication. A signed token is used when establishing the connection, with a fifteen-minute token lifetime. That lifetime is not a fifteen-minute forced expiry of an already authenticated database session. Engine, version and Region support still matter, and the database account and IAM permissions must be configured correctly. Token authentication does not remove the need for a working network path.

TLS protects a connection in transit. Server certificate verification additionally helps the client establish that it reached the intended server. Use the selected engine's documented client settings and the appropriate trusted RDS certificate bundle. Disabling verification because a certificate error appeared removes evidence about server identity; investigate the hostname, trust bundle and certificate validity instead.

Storage encryption is a separate control. It protects stored database material using the configured encryption mechanism and keys; it does not replace TLS or database authorisation. Recovery also depends on continued access to the necessary keys. An encrypted backup that the recovery team cannot decrypt is not useful recovery evidence. Record key dependencies alongside the backup plan, without copying secret material into the plan itself.

6. Save a complete reservation, then handle an uncertain response

A workshop booking changes related facts. The application reserves a seat and creates a reservation record. If it reduces the seat count but fails to create the record, one place disappears without an identifiable student. If it creates the record without enforcing capacity, too many students may receive confirmations. A transaction groups the relevant database changes into a unit whose successful outcome is committed together.

Atomicity describes the all-or-nothing boundary of that transaction. Consistency depends on the constraints and logic you actually define. Isolation describes how concurrent transactions interact, with details depending on the engine and chosen isolation level. Durability concerns retaining committed results under the guarantees of the selected system. These ideas are useful because they force you to identify the exact record and failure you are protecting.

Putting two statements inside a transaction is not sufficient proof that every concurrent booking algorithm is correct. Consider two applications both reading one remaining seat and independently deciding to accept a booking. The design needs suitable concurrency control, such as an appropriate conditional update and constraints, with correct handling of its result. Test competing requests using the chosen engine; a single-user exercise cannot prove concurrent behaviour.

Another problem appears after the database has done its work. The transaction commits, but the connection breaks before the application receives confirmation. The student sees an error and presses Reserve again. The first result is now uncertain from the client's point of view. Treating every communication error as proof that nothing was saved can create duplicate reservations.

A carefully designed request identifier helps the application recognise repeated attempts at the same operation. The identifier and the result must be stored with appropriate uniqueness and transaction handling. A naive separate check followed by an insert can still race with another request. When an identifier already exists, compare the original operation details instead of accepting an unrelated request that accidentally or maliciously reused it.

Retries therefore need a policy, not an unconditional loop. Establish whether the operation is safe to repeat, limit attempts, wait appropriately between attempts and preserve an identifier that lets you investigate the outcome. A payment or email sent to another service is outside an ordinary local database transaction. More elaborate application patterns are needed to coordinate such side effects; a database rollback cannot unsend an email.

7. Choose separately for availability, read traffic and recovery

These three needs sound similar because each involves additional copies of data, but the copies have different purposes. Availability concerns keeping or restoring service after infrastructure trouble. Read scaling concerns handling suitable query work elsewhere. Recovery concerns obtaining usable records after a problem such as accidental deletion. Begin with the failure or workload, then choose the mechanism.

A Multi-AZ DB instance deployment has a primary and a synchronously maintained standby in another Availability Zone. Its standby is for failover and does not serve ordinary application reads. A Multi-AZ DB cluster is a different arrangement: it has a writer and two readable standby instances across three Availability Zones. Always include the deployment type when explaining the word Multi-AZ.

Failover does not mean that every client connection continues uninterrupted. Applications need appropriate timeouts, connection recovery and useful user-facing behaviour. The effective interruption includes database recovery, destination discovery, connection establishment and application handling. A diagram showing a second box cannot tell you how long your particular booking operation will take to recover.

A DB instance read replica receives changes asynchronously from its source. It can handle suitable read work, with engine-specific exceptions and restrictions. Because it can lag, an immediately repeated read may not see a just-committed reservation. A registration confirmation must use a design that provides the required freshness. A report that tolerates a little delay is a different workload from deciding whether the last seat is still available.

Merely creating a replica does not automatically send the application's reporting queries there. The application or its approved connection arrangement must route the appropriate reads. Track both the source workload and replica lag, and consider what the application should do when the replica is unavailable. Moving all reads blindly can change correctness even if response times improve.

A replicated mistake is still a mistake. If a valid account deletes the workshop reservations, another continuously updated copy can receive that deletion. Historical recovery points address a different need. A replica may contribute to a recovery architecture, but it is not a substitute for independent retention and tested recovery appropriate to the failure scenario.

Match the workshop problem to the intended capability
Observed needRelevant mechanismEvidence still required
Recover service after a supported infrastructure failureSuitable Multi-AZ deploymentApplication reconnect behaviour and measured interruption.
Reduce suitable report work on the writerReadable replica or supported cluster readersRead routing, acceptable freshness and actual workload results.
Find records from before an accidental deletionUsable backup and restore historyCorrect recovery point, restored content and reconciliation.
Avoid a duplicate reservation after an unclear responseApplication request identity and transaction designRepeated and competing request tests in the chosen engine.

8. Recover records into a checked destination

A backup plan starts with the loss you must recover from. Suppose an organiser deletes the afternoon reservations at 11:20, and the team notices at 11:35. The latest data is not necessarily the desired recovery point, because it may already contain the deletion. Investigate the event time and available recovery history before choosing a restore target.

RDS provides automated backups and manual snapshots for supported deployments. Retention and actual backup availability matter. Do not infer that every desired time is recoverable just because someone enabled backups months ago. Inspect the available recovery window and backup state, then rehearse the operation. A snapshot of an RDS DB instance covers that instance's storage rather than exporting only one selected application table.

Point-in-time recovery for an RDS DB instance creates a new DB instance; it does not rewind the source in place. That separation gives the team an opportunity to inspect recovered data before using it. The restored destination has configuration and connection details that must be checked. Restoration is not automatically an application cutover.

In the workshop example, a pre-deletion copy may contain the missing afternoon bookings but lack legitimate new morning bookings accepted after that time. Replacing all current data with the older copy would solve one problem while introducing another. Decide whether the recovery should supply selected missing records, replace a service after controlled reconciliation, or support another reviewed procedure.

Recovery Point Objective, or RPO, expresses the target amount of recent data loss in time. Recovery Time Objective, or RTO, expresses the target duration before service is restored. They are objectives to test, not promises created by writing two numbers in a document. Measure from clearly defined starting and ending events, including the application validation required for a useful service.

A restoration check should include known records, row relationships, application queries, authentication and network configuration. Check the selected parameter and option groups rather than assuming every setting was reproduced. A resource marked available can still need data initialization that affects performance. Evaluate the expected workload before declaring that recovery meets its time and capacity objectives.

Keep the original source and recovery evidence until the approved process says they can be retired. Record the selected time with its timezone, the source and destination identities, the checks performed and the unresolved data gap. This record lets another engineer understand what was recovered without depending on your memory of a console session.

9. Investigate slow requests without guessing

The registration page taking eight seconds does not automatically mean the database needs more CPU. Break the request into stages: time waiting for an application worker, time waiting for a database connection, query execution, and any external work. A connection pool can become the waiting point even when the database query itself is quick.

A pool maintains reusable connections and provides a controlled limit for borrowing them. Each application process may have its own pool. Four servers with three worker processes and a maximum of ten connections per worker can potentially request one hundred and twenty connections. The arithmetic matters because a setting that looks small in one configuration file can become large across the deployment.

That multiplication is a planning bound, not proof of the exact number that will be open at every moment. Account for administration, background jobs and failover behaviour too. Return connections reliably, close or replace broken ones, and avoid holding a transaction open while waiting for unrelated user activity. Raising every limit can move the queue into the database and make the incident harder to control.

For a slow query, inspect its shape and execution evidence. Does it fetch every reservation when it needs one session? Does it repeatedly make small queries that could be organised better? Does an appropriate index exist for the access pattern? An index can reduce searching work, but it consumes storage and adds maintenance work to writes. Create it for an observed query need and measure the result.

Look at database and application observations together: connection counts, waits, processor use, memory pressure, storage behaviour and the relevant query plan. A lock wait is different from a full scan, and both differ from a network timeout before login. Use the monitoring facilities supported by your engine and current RDS configuration rather than assuming every dashboard or metric has identical meaning.

Finally, repeat a representative workload after the change. A single fast query against an empty development table is weak evidence for a busy registration system. Keep the before-and-after inputs comparable, include error rates and state the limitations of the test. A useful performance explanation tells the next student what was measured, what changed and which conclusion the evidence supports.

10. Plan maintenance and the end of a cloud lab

Before a real deployment, write down the account, Region, engine, version, placement, access rules, backup choices, expected charges and owner. Use the current console and documentation to verify available combinations. A short create command shown in a browser exercise is not a complete design. It may omit settings that are essential for your actual network, security and recovery requirements.

Maintenance is an application event as well as a service event. Read the proposed change, determine whether it affects availability, test compatibility where possible and agree on a suitable window. Applying a change immediately can also apply other pending changes according to the service's rules. Inspect the full pending state instead of treating that option as a harmless way to make a tutorial finish sooner.

Eligible RDS DB instances can be stopped temporarily for up to seven consecutive days, after which RDS starts them automatically. While stopped, storage, provisioned IOPS, backups and applicable public IPv4 charges can remain. Instance stop support has restrictions, including DB instances that are replicas or have replicas and SQL Server Multi-AZ DB instances. Check the exact deployment; this paragraph is not a universal rule for every database cluster product.

Deletion is a separate decision. Review the final snapshot and retained automated-backup choices before deleting an instance, and account for retained resources afterwards. A manual snapshot can remain after its source instance is gone. The end of a lab is therefore an inventory check: identify what should remain, who owns it and how it will be recovered or retired later.

11. Practise transactions and recovery without a cloud account

These activities need Python 3 with its SQLite module. Run each complete block in a terminal that understands the shown heredoc syntax, such as Bash or Zsh. All databases exist only in process memory, and the programs close their connections. They do not connect to AWS, read your credentials or create a database file. SQLite is the teaching engine here; it is not an RDS engine or a simulation of RDS networking and failover.

Lab A: observe rollback and recognise a repeated request

Start with two seats. The first attempt deliberately fails after making the related changes but before committing. Predict the remaining seats and reservation count before running the block. Then the same fictional request succeeds, followed by a repeated attempt with the same identity. This is a sequential demonstration; production concurrency and uncertain network outcomes need separate tests.

python3 - <<'PY'
import sqlite3
db = sqlite3.connect(':memory:', isolation_level=None)
db.executescript('''
CREATE TABLE sessions(id INTEGER PRIMARY KEY, remaining INTEGER NOT NULL CHECK(remaining >= 0));
CREATE TABLE reservations(request_id TEXT PRIMARY KEY, student TEXT NOT NULL);
INSERT INTO sessions VALUES(1, 2);
''')
def reserve(request_id, student, fail=False):
    previous = db.execute('SELECT student FROM reservations WHERE request_id=?', (request_id,)).fetchone()
    if previous:
        if previous[0] != student:
            raise ValueError('Request identifier reused with different details')
        return 'existing reservation'
    db.execute('BEGIN')
    try:
        changed = db.execute('UPDATE sessions SET remaining=remaining-1 WHERE id=1 AND remaining>0')
        if changed.rowcount != 1:
            raise ValueError('No seat available')
        db.execute('INSERT INTO reservations VALUES(?, ?)', (request_id, student))
        if fail:
            raise RuntimeError('Teaching failure before commit')
        db.execute('COMMIT')
    except Exception:
        db.execute('ROLLBACK')
        raise
    return 'new reservation'
def state():
    return (db.execute('SELECT remaining FROM sessions').fetchone()[0],
            db.execute('SELECT COUNT(*) FROM reservations').fetchone()[0])
try:
    try:
        reserve('request-101', 'Mira', fail=True)
    except RuntimeError:
        pass
    print('After rollback:', state())
    assert state() == (2, 0)
    print(reserve('request-101', 'Mira'))
    print(reserve('request-101', 'Mira'))
    print('After repeat:', state())
    assert state() == (1, 1)
    try:
        reserve('request-101', 'Dev')
    except ValueError:
        print('Different details rejected')
    else:
        raise AssertionError('Mismatched request was accepted')
finally:
    db.close()
PY

The first tuple must be two seats and zero reservations. Rollback removes both related changes. After the successful and repeated calls, the tuple must be one seat and one reservation. The repeat reports an existing result rather than subtracting another seat. The mismatched student is rejected because the same identifier must not silently represent two different operations.

Notice the parameter placeholders used for supplied values. Binding data separately from SQL is different from pasting a student's name into SQL text. Also notice the limits: the function checks for a previous record before its transaction, uses one connection and stores only a minimal request shape. It is intentionally not a complete concurrent booking implementation. Explain those limits when presenting the exercise.

Lab B: preserve a later valid record during recovery

This model starts with reservations one and two, creates a separate checkpoint, deletes reservation two, and accepts a new reservation three. A recovered copy contains one and two. Before running it, decide which valid record would disappear if you replaced the current database wholesale with that older copy.

python3 - <<'PY'
import sqlite3
source, checkpoint, restored = [sqlite3.connect(':memory:', isolation_level=None) for _ in range(3)]
def rows(connection):
    return connection.execute('SELECT id, student FROM reservations ORDER BY id').fetchall()
try:
    source.execute('CREATE TABLE reservations(id INTEGER PRIMARY KEY, student TEXT NOT NULL)')
    source.executemany('INSERT INTO reservations VALUES(?, ?)', [(1, 'Mira'), (2, 'Dev')])
    source.backup(checkpoint)
    source.execute('DELETE FROM reservations WHERE id=2')
    source.execute('INSERT INTO reservations VALUES(3, ?)', ('Noor',))
    checkpoint.backup(restored)
    print('Current:', rows(source))
    print('Recovered:', rows(restored))
    assert rows(source) == [(1, 'Mira'), (3, 'Noor')]
    assert rows(restored) == [(1, 'Mira'), (2, 'Dev')]
    missing = restored.execute('SELECT id, student FROM reservations WHERE id=2').fetchone()
    source.execute('INSERT INTO reservations VALUES(?, ?)', missing)
    print('Reviewed merge:', rows(source))
    assert rows(source) == [(1, 'Mira'), (2, 'Dev'), (3, 'Noor')]
finally:
    for connection in (source, checkpoint, restored):
        connection.close()
PY

Noor's later reservation survives the illustrated merge. The program uses an explicit, known missing identifier because this small exercise already tells us what was deleted. A real incident needs investigation of relationships, conflicting edits, dependent records and business approval. Automatically inserting every difference between two arbitrary databases would not be a safe general recovery procedure.

The checkpoint and restored objects are separate SQLite databases. They demonstrate the reasoning behind recovering into a separate destination and checking data differences. They do not reproduce RDS snapshots, transaction-log replay, restore duration or configuration choices. Write that distinction in your lab report so that an observed local result is not mistaken for a measured AWS recovery guarantee.

Lab C: reason about a delayed report

On paper, draw writer and report columns. At the first moment both show forty reservations. Next, the writer commits reservation forty-one while the report remains at forty. Finally, the report catches up. Identify which moment could cause a recently registered student to believe their booking failed. Explain how reading the appropriate authoritative result changes the confirmation flow.

This exercise uses supplied states, not measured replication timings. Do not attach a promised delay to the diagram. Your answer should distinguish a successful write, delayed read visibility and a genuinely rejected booking. Then describe what evidence the application could retain to investigate a student's uncertain result without creating another reservation immediately.

12. Turn a symptom into the next useful check

A connection times out: record the source environment, endpoint, port and time. Establish whether name resolution and the intended network path work before changing database credentials. A timeout is an observation, not proof that one particular security rule is missing. Compare the actual resource configuration with the approved design.

The engine rejects the login: a database response provides different evidence from a silent timeout. Inspect the username, authentication method, requested database and reported error. Avoid repeatedly changing network exposure after the database has already answered an authentication request. Preserve useful error details while keeping passwords and tokens out of shared logs.

The login works but a query is denied: distinguish authentication from authorisation. Confirm which identity the session actually uses and which operation failed. Grant only the reviewed privilege needed for that operation. Giving the application administrative rights might hide the immediate symptom while creating a much larger access problem.

Reads disagree immediately after a booking: identify the endpoints used for the write and each read. Check whether a replica or cache is involved and whether freshness is required for this operation. Do not conclude that the committed booking disappeared just because a delayed report has not yet included it.

A restored database looks healthy but the application fails: inspect the new endpoint, configuration, credentials, schema expectations and representative records. Resource availability alone does not test the application's dependency contract. Keep the recovery destination isolated from ordinary writes until its purpose and validation state are clear.

13. Interview questions with explained answers

1. Explain RDS without saying that AWS does everything.

RDS operates supported relational database environments and supplies managed administration facilities. The team still chooses the deployment and access configuration, designs the schema, writes correct queries and rehearses recovery. For the workshop, AWS can operate the database service while the application team remains responsible for preventing duplicate reservations and enforcing seat capacity.

2. Does a subnet group across two zones prove that the database is highly available?

No. The subnet group defines placement options. The selected database deployment determines whether a standby or cluster arrangement exists. Inspect the actual deployment type and its status, then test application recovery behaviour. Two subnet names in a configuration are not evidence that a second database is ready to take over.

3. Can the Multi-AZ standby handle our reports?

Specify the deployment first. The standby in a Multi-AZ DB instance deployment does not serve normal application reads. A Multi-AZ DB cluster has two readable standby instances as well as its writer. A strong answer states the resource type instead of applying one rule to every feature with Multi-AZ in its name.

4. A booking committed, but its confirmation was lost. Should the application repeat it?

It must first follow an operation-specific retry design. The outcome may already exist, so a blind repeat can create a duplicate. A stable request identity, uniqueness enforcement and transactional result handling help recognise prior work. Also compare request details and test concurrent retries; checking once before inserting is not sufficient proof of correctness.

5. Would a read replica recover an accidentally deleted table?

A continuously updated replica can receive the same deletion. Investigate usable historical backups or recovery points and restore into a separate destination for validation. A replica and a backup have different purposes. Explain which failure you are addressing and how the proposed copy preserves the records needed for that failure.

6. Does point-in-time recovery automatically put the website back online?

No. For an RDS DB instance it creates a new instance at the selected recoverable time. The team still verifies configuration and records, handles data written after that point and decides how the application should use the recovered destination. Measured service recovery includes these steps, not only the database reaching an available state.

7. A database is slow. Would you increase its instance class first?

I would identify the slow operation and inspect evidence before choosing a change. Waiting for a pool connection, waiting for a lock and scanning too many rows have different remedies. I would compare representative results after a targeted change. More capacity can help an actual resource constraint, but it does not establish that the query or application design is correct.

8. Can a stopped training database be forgotten safely?

No. Eligible instances restart automatically after the permitted stop period, and some charges remain while stopped. The owner should record whether the resource will be reused or retired, inspect retained backups and confirm the final inventory. Temporary stopping and permanent cleanup are different lifecycle decisions.

14. Check your reasoning before opening each answer

1. The security group allows the app, but SELECT is denied. Which layer should you investigate?

Investigate the authenticated database identity and its SQL privileges. The network rule allows the connection path; it does not grant permission to read tables. The engine's explicit denial gives more focused evidence than a connection timeout would.

2. The writer has 41 bookings and the reporting replica has 40. Has the last booking definitely failed?

No. The observations are consistent with replication delay. Verify the authoritative transaction result and the endpoints involved. Repeating a successful operation because of an older report can introduce a duplicate that did not exist before the retry.

3. A recovered copy has bookings 1 and 2; current data has 1 and 3. Is replacement automatically correct?

No. Booking three may be a valid later record. Compare the missing and newer information, investigate relationships and choose an approved reconciliation procedure. The recovery copy supplies evidence; it does not decide the business meaning of the differences.

4. Twelve application processes allow ten connections each. Is a total budget of 100 sufficient?

The possible application allocation is 120, before administration and background work. That exceeds the supplied budget. Revisit process and pool sizing together. This arithmetic checks a planning bound; actual demand and database behaviour still require observation.

5. A TLS connection encrypts traffic. Does that prove the server identity was verified?

No. Inspect the driver's certificate and hostname verification settings and trusted CA configuration. Encryption and identity verification are related but distinct checks. A client configured to ignore identity errors provides weaker assurance about which server received the connection.

15. Revision cards for the chapter

Managed responsibility

Identify the service work AWS operates and the application decisions your team owns. Managed infrastructure does not design constraints, correct SQL or decide an acceptable recovery gap.

Connection layers

Trace endpoint resolution, route, permission, listener, authentication and SQL privilege separately. Evidence from one layer narrows the investigation but does not prove every later layer works.

Transaction boundary

Group related database changes and handle their results. A lost response after commit creates uncertainty for the caller; it is not proof that the database rolled back.

Copy purpose

Name the purpose of each copy: failover, suitable read work or historical recovery. Then state its freshness and failure limitations before using it in a solution.

Recovery evidence

Record the selected time, recovered records, configuration and application checks. A successful restore operation is one step toward a verified service, not the entire recovery.

Lab ownership

Track retained instances, snapshots and dependencies until the exercise is properly closed. A stop button does not establish that every related charge or resource has disappeared.

16. Build your own evidence sheet

  1. Draw the service path. Show browser, application and database with separate connection arrows. Label the application identity, endpoint and permission checks. Explain which arrow a successful timetable request has actually tested.
  2. Present the transaction lab. Predict each printed state, run the block and explain the rollback. Describe one concurrent scenario the sequential program does not test. A complete answer includes both observed results and remaining limitations.
  3. Choose a recovery plan. Use a fictional deletion at 11:20 and discovery at 11:35. State the evidence needed to select a recovery point and preserve later valid records. Include timezone and validation steps.
  4. Review a proposed database change. List compatibility, pending changes, availability impact, backup evidence, rollback limitations and the useful application test. Keep this as a paper review; do not modify an unrelated account to complete the task.
  5. Explain one tradeoff aloud. Compare a writer read with a report replica read for booking confirmation. Your explanation should connect freshness to the student's experience rather than simply repeating that replicas are faster.

Primary references for the service details and local exercises

The scenarios and exercises above are original teaching material. Service capabilities depend on the selected engine, version, Region and deployment. These official references support the distinctions used in this overview.

Practice Tasks

Practice checks run in your browser. They check the answer for this exercise; they do not create resources or connect to your AWS account.

About this scenario

Vidarbha Cotton Mills is a textiles business in Nagpur. Ganesh Wankhede looks after its IT and cloud work. They count money in INR and run their AWS resources in the ap-south-1 Region. The tasks below are browser-only answer exercises for this fictional scenario. All names, account IDs, IP addresses and numbers are made up for practice.

0 / 12

Easy Find the database endpoint

Your app connects using the endpoint name, not an IP.

Describe DB instance vidarbhacotton-db.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Easy Biggest orders first

Querying the database is daily work after you set up RDS.

Show order id and amount, biggest amount first.

Tables: customers(id, name, city) and orders(id, customer_id, amount, odate).

  1. Find the table the task is about (see the table list above the box).
  2. Write the SQL statement step by step: what, from where, which rows.
  3. End the statement with ;
  4. Click Check answer. Your query runs on a practice copy of the table.

Easy Filter customers by city

Querying the database is daily work after you set up RDS.

List the names of customers in Pune.

Tables: customers(id, name, city) and orders(id, customer_id, amount, odate).

  1. Find the table the task is about (see the table list above the box).
  2. Write the SQL statement step by step: what, from where, which rows.
  3. End the statement with ;
  4. Click Check answer. Your query runs on a practice copy of the table.

Medium Remove small orders

Querying the database is daily work after you set up RDS.

Delete orders with amount below 200.

Tables: customers(id, name, city) and orders(id, customer_id, amount, odate).

  1. Find the table the task is about (see the table list above the box).
  2. Write the SQL statement step by step: what, from where, which rows.
  3. End the statement with ;
  4. Click Check answer. Your query runs on a practice copy of the table.

Medium Orders with customer names

Querying the database is daily work after you set up RDS.

Show each customer name with each order amount.

Tables: customers(id, name, city) and orders(id, customer_id, amount, odate).

  1. Find the table the task is about (see the table list above the box).
  2. Write the SQL statement step by step: what, from where, which rows.
  3. End the statement with ;
  4. Click Check answer. Your query runs on a practice copy of the table.

Medium Total sales

Querying the database is daily work after you set up RDS.

Show the total of all order amounts as one number.

Tables: customers(id, name, city) and orders(id, customer_id, amount, odate).

  1. Find the table the task is about (see the table list above the box).
  2. Write the SQL statement step by step: what, from where, which rows.
  3. End the statement with ;
  4. Click Check answer. Your query runs on a practice copy of the table.

Medium Fix a city

Querying the database is daily work after you set up RDS.

Customer 5 moved to Rome. Update the record.

Tables: customers(id, name, city) and orders(id, customer_id, amount, odate).

  1. Find the table the task is about (see the table list above the box).
  2. Write the SQL statement step by step: what, from where, which rows.
  3. End the statement with ;
  4. Click Check answer. Your query runs on a practice copy of the table.

Medium Turn on Multi-AZ

A Multi-AZ DB instance has a failover standby in another AZ. A Multi-AZ DB cluster uses three AZs and can serve reads from its two secondary instances.

For this browser-only syntax exercise, express a Multi-AZ change to vidarbhacotton-db with immediate application. Real changes require reviewing pending modifications, availability impact and the maintenance plan.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Hard Sales per customer

Querying the database is daily work after you set up RDS.

Show customer_id and total amount per customer, only where total is above 1000.

Tables: customers(id, name, city) and orders(id, customer_id, amount, odate).

  1. Find the table the task is about (see the table list above the box).
  2. Write the SQL statement step by step: what, from where, which rows.
  3. End the statement with ;
  4. Click Check answer. Your query runs on a practice copy of the table.

Hard Customers with no orders

Querying the database is daily work after you set up RDS.

List names of customers who have never ordered.

Tables: customers(id, name, city) and orders(id, customer_id, amount, odate).

  1. Find the table the task is about (see the table list above the box).
  2. Write the SQL statement step by step: what, from where, which rows.
  3. End the statement with ;
  4. Click Check answer. Your query runs on a practice copy of the table.

Hard Create a MySQL database

RDS supplies managed database facilities; backup retention, deployment availability and maintenance choices must still be configured and verified.

In this browser-only syntax exercise, describe creation of vidarbhacotton-db: engine mysql, class db.t3.micro, 20 GiB storage, master user admin, password placeholder $DB_PASS. This incomplete example is not a reviewed deployment recipe; do not enter a real password here.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Hard Create a read replica

Applications can route suitable reads to a supported read replica. Asynchronous replication can delay visibility of recent writes.

Create read replica vidarbhacotton-db-ro from source vidarbhacotton-db.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.