Understand the building blocks, design a small service, and reason about failure and cost.
A practical first pass through cloud infrastructure, identity, networking, compute, storage, databases, messaging, operations, and a local capstone.
14 chapters10 diagrams28 practice tasks
Clear explanations. Worked examples. Practice with reasoning. Original text · CC BY-SA 4.0 Code · MIT
Before you begin
How to use this guide
For learners who can follow a small program and want to understand what happens around it when it becomes an online service. No AWS account is required for the core exercises.
Helpful background
Basic files, folders, HTTP requests, and terminal familiarity
Python 3 for optional local simulations; standard-library examples use no cloud credentials
A willingness to draw the request path and state assumptions before choosing a service
What you will be able to do
Explain responsibility and failure boundaries instead of memorizing service names
Trace identity, network reachability, authorization, and data changes through a request
Choose compute, storage, databases, and queues from stated workload needs
Estimate capacity and cost with units and distinguish measured facts from assumptions
Investigate symptoms using useful signals and design a reversible change
Build and test a local idempotent event-processing prototype
A useful study rhythm
Read the explanation, close the book, and draw or explain the idea from memory. Predict each example before running or tracing it. Attempt the chapter exercises, compare your reasoning with the solution manual, and return to the source when an assumption changes.
For a first pass, follow the chapter order. For revision, use the contents and glossary. Assessment answers and exercise solutions are separated from the questions so you can retrieve an answer before seeing it. Internal links and bookmarks work in most PDF readers; the printed page number helps when reading on paper.
Scope and assumptions
Concept-first foundation, not certification exam preparation or an exhaustive catalog of AWS services.
AWS documentation evolves. Verify service-specific quotas, pricing, regional availability, runtimes, and account terms before deploying. No current price or free-tier entitlement is promised.
Core labs run locally and create no cloud resources. AWS CLI commands and infrastructure snippets are labeled illustrations; optional authenticated queries need an authorized account.
IAM examples simplify the full policy evaluation model. Organization policies, resource policies, boundaries, and service-specific conditions can change the effective result.
RDS discussions distinguish a classic Multi-AZ DB instance with one standby from a Multi-AZ DB cluster and from read replicas.
Core explanations and original diagrams are available offline. External books, videos, and documentation remain at their publishers’ sites and may require an internet connection or a separate account.
Chapter 01
What you are renting and what you still own
Start with a running application and divide the work between your team and the cloud provider.
By the end of this chapter
Separate a service from a machine
Allocate responsibilities for a concrete workload
Draw a useful first inventory
A service is a chain of responsibilities
Imagine a study website that accepts a quiz answer, stores progress, and sends a response. The code is only one part of the chain. Something supplies electricity and a network, starts the operating system, patches software, checks the caller, stores data, and notices when the service fails. Amazon Web Services (AWS) is one cloud provider. Cloud computing lets you obtain some of those capabilities through service interfaces instead of purchasing and operating every physical component yourself.
Start with the work you need done, not the provider’s product list. “Keep these files and retrieve them by key” is a storage requirement. “Run this handler when an event arrives” is a compute requirement. A managed service changes the division of operational work; it does not eliminate the need to understand data, access, and failure. You still decide whether the service meets the application’s contract.
For a virtual machine, the provider operates underlying facilities and hardware while your team manages the guest operating system and application configuration. A managed database takes on more platform maintenance, but your team still controls important choices such as users, accessible data, backup settings, and application queries. Writing “AWS handles security” in a design document hides these distinctions.
Create a responsibility inventory before any deployment. For each component, name its purpose, owner, sensitive data, failure symptom, and recovery action. This turns vague confidence into questions you can test. If a developer accidentally exposes a document through an overly broad permission, the location of the physical disk does not solve the application mistake.
Worked example · Inventory a lesson download
Asset: a PDF intended for public reading. Owner: the content team. Integrity matters because a wrong file misleads learners.
Asset: a learner email address. Owner: the account service. Confidentiality matters, so public content hosting must not expose account records.
Recovery: retain a known-good content revision and test restoring account data separately. Publishing a new PDF is not an account backup.
Result: Two assets on one platform need different access and recovery rules.
Begin with a user operation and its responsibilities.
Managed services change operational boundaries, not ownership of application decisions.
Practise before moving on
Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.
1.1 · Practice task
Your quiz API runs on a virtual machine and stores results in a managed database. Who should validate input, patch the guest OS, and control database access?
Hint: Separate application correctness from provider infrastructure.
Place components with failure boundaries and user needs in mind.
By the end of this chapter
Distinguish a Region from an Availability Zone
Calculate a simple availability budget
Identify correlated failures
Location is a design decision
A Region is a geographic grouping containing multiple Availability Zones. A zone is an infrastructure isolation boundary rather than a guarantee that everything inside it can never fail. A subnet belongs to one zone, while some higher-level services offer configurations spanning zones. Check what a particular configuration actually deploys; a diagram containing two rectangles does not create redundancy.
Choose a Region using data-location requirements, users, service availability, dependencies, and measured latency. Then ask which failures the application should survive: a process crash, a machine failure, a zone disruption, or a Region outage. Surviving a wider failure usually requires more copies, more coordination, and a more demanding operational plan. Building across Regions is not the automatic next step for a small learning project.
Nested failure boundaries. An account contains resources in a chosen Region. Within that Region, separate zones reduce exposure to one facility-level failure, while the application still depends on shared identity, software, and data decisions.Scroll horizontally to read the full diagram on a small screen.
Availability should describe something observable: for example, the fraction of valid progress-save requests that succeed within a stated time. A process that stays alive while every database call fails is not delivering that operation. Define the numerator, denominator, measurement window, and treatment of client errors before discussing a percentage.
A second instance helps only when traffic can reach it and its dependencies remain usable. A bad software release, expired shared credential, or exhausted database connection pool can affect both instances together. Practise a failure story: one instance disappears, the remaining instance receives traffic, and the database is reachable. Then ask a different question: the database is reachable but returns incorrect data. The second story needs integrity and recovery controls, not merely another web server.
Worked example · A hypothetical monthly error budget
Assume a 30-day month and a time-based target of 99.9% availability. This is a teaching assumption, not an AWS service promise.
There are 30 × 24 × 60 = 43,200 minutes. The unavailable fraction is 0.001.
43,200 × 0.001 = 43.2 minutes. A request-based target can allocate errors differently and must be defined separately.
Result: The percentage becomes useful only after the measurement and window are explicit.
Determine who is asking, what they may do, and how long their credentials should remain useful.
By the end of this chapter
Separate authentication from authorization
Read a narrow policy statement
Reason about temporary credentials and explicit deny
Give every caller a job
Authentication establishes the caller’s identity; authorization decides whether the requested action is permitted. An application may correctly identify a learner and still wrongly let that learner read someone else’s progress. AWS Identity and Access Management (IAM) controls access to AWS resource operations, while your application still needs its own per-user authorization checks.
For people, prefer an organization-supported sign-in and temporary credentials where available. For workloads, associate an appropriate role rather than copying a human’s long-lived access key into source code. Temporary credentials expire, which reduces the lifetime of a leaked credential, but a stolen session can still be harmful before it expires. Grant the role a small, understandable responsibility and arrange renewal through supported tooling.
An allow statement should identify an action and the resources on which that action is allowed. The illustrative policy below permits reading objects under one prefix. It does not list a bucket’s contents, grant writes, or make every public request succeed. The bucket name is an example placeholder, not a resource this book creates.
A useful first approximation is “start denied, look for an applicable allow, and check for an explicit deny.” The complete evaluation includes the kinds of identity, resource, organization, session, and boundary policies that apply. An explicit deny can defeat an allow. Debug authorization with the actual principal, resource, action, and context; repeatedly widening a wildcard until a request works removes the evidence you need to understand it.
Illustrative object-read policy; not deployed JSON
Trace an actual packet path rather than guessing from a resource label.
By the end of this chapter
Read CIDR sizes and subnet boundaries
Distinguish routing from access filtering
Explain public and private paths
Reachability needs a complete path
A virtual private cloud (VPC) gives resources a logically isolated network with address ranges and routing choices. A subnet is a range within that network and belongs to one Availability Zone. A route table answers where matching traffic should go next. Security groups answer a different question: which traffic is allowed to reach or leave an associated resource.
A route to an internet gateway alone does not make every machine reachable from the internet. The addressing, resource configuration, routes in both directions, access controls, and listening application must work together. Likewise, placing a database in a subnet called “private” does not prove that the application authorization is correct. Names are documentation; behaviour follows configuration.
Trace the request in layers. Check name resolution and destination first, then routes, traffic rules, and the listening process. A failure at any required stage can make the same user operation fail.Scroll horizontally to read the full diagram on a small screen.
IPv4 CIDR notation combines an address with a prefix length. In a /24, eight bits remain for addresses, so the range contains 256 addresses. That is address arithmetic, not a promise that all 256 are assignable to workloads: AWS reserves certain subnet addresses. Keep total-address calculations separate from usable-address planning.
Security groups are stateful controls. For common supported traffic, response traffic for an allowed connection is tracked rather than requiring a mirrored rule for each reply packet. Network ACLs have different behaviour and are subnet-level controls; do not transfer security-group assumptions to every firewall. For an initial design, keep the path simple and document why each permitted source needs each port. Debug from a known source with a known destination instead of opening all inbound traffic.
Inspect a private address range locally Python
from ipaddress import ip_network
network = ip_network("10.20.4.0/24")
print(network.num_addresses)
print("10.20.4.19" in [str(ip) for ip in network])
print(network.subnet_of(ip_network("10.20.0.0/16")))
Expected result
256
True
True
Worked example · Application-to-database access
The web service needs the database port, while the public browser does not.
Where supported, express the database rule in terms of the application security group rather than every internet address.
Check that the application can resolve and route to the private database endpoint. A correct rule cannot repair a missing route or wrong hostname.
Result: Expose only the entry point that serves the user operation; keep internal access tied to a documented caller.
Compare servers, containers, and functions by operational needs instead of fashion.
By the end of this chapter
Separate a process from a packaging format
Estimate concurrency from arrival rate and duration
Identify state that must outlive a process
Control and operational work move together
Amazon Elastic Compute Cloud (EC2) gives you a virtual machine on which to run software. You choose the operating-system image, software, and instance configuration and take on the corresponding operational work. A container packages an application and dependencies as an isolated process environment; it is not itself a complete answer to scheduling, networking, storage, or updating. A managed container platform can take on some of those tasks.
A function service runs a handler in response to an invocation. This suits bounded event-driven work, but “no server management” does not mean no execution limits, startup effects, concurrency planning, or state design. Choose from the workload: duration, traffic pattern, runtime needs, deployment skill, and failure behaviour. A long-running interactive worker and a short thumbnail-generation handler need different conversations.
Three compute responsibilities. Each option runs code, but the operational interface differs. Compare the work your team must own rather than assuming one option is universally faster or cheaper.Scroll horizontally to read the full diagram on a small screen.
Keep durable learner progress outside a replaceable process. Memory can be reused, and a temporary file may remain available in some execution environments, but neither is an appropriate sole system of record for account progress. If two requests land on different workers, each must be able to find the same authoritative state.
Estimate resource pressure using a clearly stated model. If requests arrive at a steady 40 per second and each spends an average of 0.2 seconds in a service, the average number in that service is about eight under stable conditions. This arithmetic is an average, not a concurrency limit or a guarantee about bursts. A slow database increases in-flight work even when arrival rate does not change. Observe duration and queueing together before adding workers.
A local concurrency estimate with explicit units Python
Understand a bucket-and-key model and practise recovery reasoning.
By the end of this chapter
Distinguish object storage from a filesystem
Explain overwrite, version, and delete marker
Separate public content from private account data
A key identifies an object
Amazon Simple Storage Service (S3) is an object-storage service. Object storage keeps data associated with keys and metadata. A key that contains slashes may look like a directory path, but that appearance does not make the service a normal mounted filesystem with every local filesystem operation. Design around the operations and guarantees the object service actually provides. A stable key such as guides/python.pdf can identify a public course artifact; a content hash or versioned name can identify a specific immutable revision.
Separate the bytes from the records that describe them. An application database might record a guide title, language, and object key while the PDF bytes live in object storage. Decide what happens when one is updated without the other. A release manifest pointing to tested, immutable files is easier to inspect than an ambiguous collection of overwritten files.
Publishing an immutable guide revision. Build and verify the PDF, store it under a versioned key, then update the manifest that readers use. Keep the prior tested revision available for rollback.Scroll horizontally to read the full diagram on a small screen.
Versioning can retain multiple versions of an object and make accidental overwrite or deletion easier to recover from. In a versioned bucket, an ordinary delete can create a delete marker rather than permanently remove every stored version. Permanent deletion of particular versions and retention policies are different operations. Treat recovery as a procedure you rehearse with noncritical test data.
Retaining versions also retains data and associated storage cost. A lifecycle policy should follow the required recovery window, privacy obligations, and access pattern, not a desire to make a chart look small. Public-access protection should reflect the asset: a public guide may need a public delivery path, while a private submission must not inherit that path simply because it is also a file. Check both intended readers and unintended readers.
Worked example · Recover the wrong PDF
Revision A is the approved guide. Revision B accidentally omits the exercise solutions. Record which revision the catalog references.
Verify that A remains intact, then restore the catalog pointer or the intended object version using the documented process.
Check a fresh reader request, not only the publishing computer’s cache, and retain evidence of what was repaired.
Result: Recovery includes validation of the learner-visible result, not just a successful storage API call.
Translate progress tracking into keys, queries, and consistency needs.
By the end of this chapter
Write access patterns before choosing storage
Separate relational transactions from key-based access
Distinguish replicas from recovery copies
Begin with the operation
A data model should make the required reads and writes understandable. For progress tracking, write the operations first: read one learner’s course progress, mark a lesson complete, list the next incomplete lesson, and preserve correctness if a request is repeated. Then identify uniqueness rules and the data that must change together.
A relational model can express related entities, constraints, and transactions. A key-value or document-oriented model may organize data around a partition key and particular access patterns. These are not moral categories. The right choice depends on queries, update relationships, scale, operations, and team knowledge. Adding a secondary index helps particular queries but introduces storage and write work; it is not free acceleration for every possible question.
Illustrative relational key for completion; SQLite-compatible SQL
CREATE TABLE completion (
learner_id TEXT NOT NULL,
lesson_id TEXT NOT NULL,
completed_at TEXT NOT NULL,
PRIMARY KEY (learner_id, lesson_id)
);
A read replica can serve read traffic but may lag behind its source. Immediately after marking a lesson complete, a learner expects the next screen to reflect that action. Decide whether to read that result from the authoritative write path or otherwise provide a clear read-after-write contract. “There is a replica” is not a sufficient consistency design.
In Amazon Relational Database Service (RDS), a classic Multi-AZ DB instance has one standby for failover that does not serve read traffic; a Multi-AZ DB cluster has a different arrangement that can serve reads from standbys. Read replicas, standby failover, and backups solve different needs. A replicated accidental delete can appear in several live copies. A backup and a tested restore procedure address recovery from earlier points in time, with explicit data-loss and time targets.
Set recovery objectives before choosing a backup plan. A recovery point objective (RPO) states the maximum time interval of data updates the organization is prepared to lose after a disruption. An RPO of fifteen minutes requires a recoverable point no more than fifteen minutes before the interruption; it does not promise that recovery finishes in fifteen minutes. A recovery time objective (RTO) instead sets the target duration for restoring the required service. Test both targets with the actual backup, restore, and validation procedure rather than treating the configured backup schedule as proof.
Worked example · Read-after-write in the learning app
The write endpoint reports that lesson 7 is complete. A replica has not yet applied the update.
Reading immediately from that replica can show an incomplete lesson even though the write succeeded.
For the immediate response, return authoritative state or route the dependent read through a path that meets the required consistency.
Result: Define user-visible semantics first, then choose read routing and replica behaviour.
Three data-copy roles. A live replica supports specified read or failover needs, while a retained backup supports historical restoration. None of these replaces checking application-level data correctness.Scroll horizontally to read the full diagram on a small screen.
Follow an HTTP request through delivery and caching
Connect a browser request to edge delivery and application processing.
By the end of this chapter
Separate name resolution, TLS, caching, and application work
Choose cache keys and freshness deliberately
Keep personalized responses private
One URL can involve several systems
A learner enters a course URL. Name resolution helps locate an endpoint, the client establishes the required transport security, and an HTTP request reaches a delivery or application component. A content-delivery network (CDN) can serve a cached artifact close to the user or fetch it from an origin. A load balancer can distribute requests to healthy application targets. Each component has a responsibility; none makes the others unnecessary.
Separate static content from personalized state in the design. A versioned public PDF is a good candidate for shared caching. A response containing one learner’s account details requires careful authorization and cache behaviour. Adding a CDN without reviewing cache keys, headers, and identity-sensitive paths can amplify a data-exposure mistake because a cached response may be reused.
Public document request. The browser requests a known versioned PDF. The edge can serve a valid cached copy or ask the origin for it. Account-progress requests take a separately authorized application path.Scroll horizontally to read the full diagram on a small screen.
A cache key determines which requests may reuse the same stored response. Freshness rules determine for how long that reuse is acceptable. If a response varies by language, format, or a relevant query parameter, the key and origin behaviour must agree. If every irrelevant parameter creates a new key, the cache fragments and does less useful work.
For course releases, immutable revision-specific URLs make a simple promise: this URL keeps meaning this revision. A small catalog can point to the chosen revision and use a shorter freshness policy. Replacing the bytes at a long-cached URL creates a harder rollout story because different readers can see different versions until caches refresh. Understand invalidation and client caching before relying on an emergency fix.
Worked example · A cache-key mistake
A shared cache stores /account without distinguishing authenticated users. The first response contains one learner’s details.
A second learner requests the same cache key. If the response is reused, application authorization at the origin may never run for that response.
Exclude personalized data from shared caching unless a carefully designed private or identity-aware policy explicitly meets the contract.
Result: The cache is part of the authorization and privacy review.
Illustrative response headers for an immutable public revision text
Content-Type: application/pdf
Cache-Control: public, max-age=31536000, immutable
Only use this policy when the URL truly identifies an immutable public revision.
Move background work out of the request path without losing correctness.
By the end of this chapter
Explain at-least-once processing
Choose acknowledgement timing
Design an idempotent effect
A queue changes timing, not responsibility
A queue lets a producer hand work to a consumer without requiring the consumer to finish during the user’s original request. This can smooth a temporary burst and isolate processing speed. It does not make an overloaded system infinitely fast. If work arrives faster than consumers can complete it for long enough, the backlog grows and users wait longer.
For an Amazon Simple Queue Service (SQS) standard queue, design for possible duplicate and out-of-order delivery. A message becoming visible again is not necessarily evidence of a defective provider. A consumer might perform the work and then crash before acknowledging it. The next consumer must decide whether repeating the business effect is safe. Use the message’s business meaning, not only its transport delivery count.
The acknowledgement gap. A worker can commit the result and lose its acknowledgement. Redelivery then repeats the message, so the durable effect needs a repeat-safe design.Scroll horizontally to read the full diagram on a small screen.
An idempotent operation has the same intended effect when repeated as when applied once. Setting a lesson’s completion flag can be repeat-safe; incrementing a counter on every delivery is not automatically repeat-safe. A deduplication key identifies a logical operation, and the record of that key must be coordinated with the business update. Marking a key as “done” before the update can lose work if the process crashes between those writes.
Timeouts make the outcome uncertain: the caller stopped waiting, but the server may already have committed. Retry only under an appropriate contract, with bounded attempts, a deadline, and backoff with jitter where suitable. A dead-letter path should preserve enough context for diagnosis and controlled replay. It is a review queue, not permission to ignore failed learner work indefinitely.
A queue receives 80 tasks per second and workers finish 60. Starting empty, what is the approximate backlog after five minutes under these assumptions?
Hint: Use the difference in rates over the interval.
Combine authorization, encryption, secrets handling, and a concrete threat model.
By the end of this chapter
Distinguish encryption from permission
Keep secrets out of source and logs
Test a cross-user access boundary
Follow a sensitive value
Choose one sensitive value, such as a password-reset token, and follow it from creation to expiry. Which component generates it, where is it stored, which service can read it, how does the browser receive it, and what appears in logs? This small exercise often reveals a leak that a large architecture poster hides.
Encryption protects data under particular threat assumptions. Transport encryption protects a connection; encryption at rest protects stored data under its key and access model. Neither establishes that a logged-in learner is allowed to read another learner’s record. An overly broad application query can return private plaintext through a perfectly encrypted connection. Review identity and object-level authorization alongside encryption settings.
Use two test identities with deliberately different records. Authenticate as one and attempt the permitted operation on its own record, then attempt the same operation on the other identity’s record. Expect a controlled denial without revealing unnecessary details. Repeat for listing, updating, exporting, and direct file retrieval; hiding a UI button does not protect an API endpoint.
Treat configuration and observability as part of the boundary. Avoid printing secrets in debugging output or embedding them in public static JavaScript. Give workloads only the access needed for their job, and keep operational access auditable. A secret-management service can help distribute and rotate secrets, but the application must still avoid copying them into errors, support screenshots, or analytics events.
A local object-ownership check Python
records = {"r1": {"owner": "alice", "lesson": "python"}}
def can_read(user_id, record_id):
row = records.get(record_id)
return row is not None and row["owner"] == user_id
assert can_read("alice", "r1")
assert not can_read("bob", "r1")
assert not can_read("alice", "missing")
print("ownership checks passed")
Expected result
ownership checks passed
Worked example · Threat-model a download link
Public learning guides can use stable public URLs. Private assignments require an authorized delivery path.
List who can create a link, who can use it, how long it should work, and where the URL is recorded.
Test expired, altered, and cross-user access without sending real personal data.
Result: The appropriate link design follows the audience and failure model, not simply the fact that both assets are PDFs.
Use a small set of signals to connect a learner complaint to the failing component.
By the end of this chapter
Distinguish metrics, logs, traces, and audit events
Choose actionable user-centered alerts
Investigate a slow request with a hypothesis
Signals answer different questions
A metric summarizes measurements over time, such as successful saves per minute or a latency distribution. A log records a selected event with context. A trace connects spans of work across a request path. An audit event helps answer who performed a relevant administrative or API action. These overlap in useful ways but are not interchangeable copies of the same record.
CloudWatch supplies operational monitoring capabilities, while CloudTrail records supported account and API activity according to its configuration. Check which event types are enabled and retained; an absent record does not prove an operation never happened. Start with a practical question: when a learner says progress vanished, what evidence connects the browser request, authorization result, database commit, and later read?
A useful investigation path. Begin with a user operation and request identifier, narrow the time window with metrics, follow relevant events, and test a focused hypothesis before changing configuration.Scroll horizontally to read the full diagram on a small screen.
An alert should lead to a useful action. “CPU rose briefly” may be interesting, but “valid save requests are failing above the agreed budget” connects more directly to the learner experience. Keep diagnostic dashboards available for causes without turning every fluctuating measurement into a page to an operator.
Avoid averages that hide a slow group. If most reads are fast but a small set repeatedly takes several seconds, the mean may look comfortable. Record a latency distribution and relevant bounded dimensions such as endpoint or outcome. Do not use unique user identifiers as unlimited metric dimensions; that can create an unmanageable and costly cardinality problem. Keep high-detail investigation in an appropriate controlled record store.
Treat infrastructure and application changes as testable revisions.
By the end of this chapter
Explain declarative infrastructure and drift
Design a safe rollout and rollback boundary
Separate backup creation from successful recovery
A declared design can be reviewed
Infrastructure as code records intended resources and configuration in reviewable source. CloudFormation manages related resources through a stack and a template. The benefit is a versioned description and a repeatable management interface, not a guarantee that every proposed change is safe. A small diff can still replace a resource or change access in an important way.
Review the plan against current state before applying it. Record ownership, environment, and dependencies, and understand which changes are replacements, modifications, or removals. A console-only emergency edit may be necessary during an incident, but reconcile it with the declared source afterward. Otherwise the next routine deployment may undo an important repair or reproduce the incident.
Illustrative template fragment; do not deploy without cost and access review YAML
AWSTemplateFormatVersion: '2010-09-09'
Description: Example only; a resource declaration is an operational change
Resources:
CourseFiles:
Type: AWS::S3::Bucket
DeletionPolicy: Retain
Properties:
VersioningConfiguration:
Status: Enabled
A new application version may write data the old version cannot read. Rolling back only the executable then fails even if the deployment tool reports success. Prefer changes that permit a period of mixed versions, and separate data expansion, migration, and removal when the system requires it. Test both old and new readers against the intended transition state.
A release should state what success looks like, which evidence will stop the rollout, and how to return to a known-good state. A backup is part of that story only when you know its recovery point, restore time, and validation procedure. Practise recovery on disposable local fixtures or a separate approved environment, never by improvising a destructive experiment on live learner data.
Worked example · Expand before removing a field
Version A reads display_name. Version B introduces preferred_name.
First add support for the new representation while preserving the old reader’s needs. Migrate with checks and observe the transition.
Remove the old field only after no required reader depends on it and the recovery plan is explicit.
Result: The rollout separates compatibility from cleanup instead of assuming one instantaneous switch.
A deliberate change loop. Review intent, test a bounded change, observe the user outcome, and either expand the rollout or restore the compatible prior state.Scroll horizontally to read the full diagram on a small screen.
Estimate cost without pretending to know the future
Build a transparent model and check the assumptions that dominate it.
By the end of this chapter
Keep units consistent in capacity and cost estimates
Separate budgets from instantaneous spending stops
Plan cleanup and verify what remains
A useful estimate is a model you can change
A cloud bill can combine time, storage, request counts, data transfer, retained versions, logs, and other service-specific dimensions. Start by listing the resources and operations your design creates. Then attach the current price dimension and Region from the provider calculator or pricing page. This guide uses invented rates only to teach arithmetic; it does not quote a real service price or promise a free allowance.
Treat the workload estimate as uncertain. Write a normal case, a burst case, and a mistake case such as a retry loop or a retained large artifact. A design that looks affordable only when every estimate is exactly right is fragile. Explain which assumptions dominate the result so that a reviewer knows where better measurements are worth the effort.
A hypothetical cost worksheet, not AWS pricing Python
Assume one version of a PDF is 20 MB and 100 versions are retained. That is about 2,000 MB before accounting for the chosen unit convention and related storage.
A display that shows only the latest 20 MB object hides retained history. Inventory all retained versions before estimating storage.
Next add download volume, request activity, and the selected delivery path rather than assuming storage is the entire cost.
Result: The estimate follows the resources that actually remain, not only the objects visible in the application UI.
A budget can track costs and notify or trigger configured actions. Cost information and alerts have update delays, so a budget is not a universal instantaneous spending cap. Permissions and resource limits can reduce some risks, but no single checkbox replaces understanding the resources a lab creates. Use current terms for the account and chosen services; old tutorials may describe offers that no longer apply.
For an optional real deployment, prepare the cleanup inventory before starting. Name resources, Regions, object versions, volumes, snapshots, logs, network devices, and retained items that may survive a simple deletion. Export required learning results, remove only the intended resources with authorization, then inspect inventory and later billing evidence. For this book, the capstone runs locally so the core learning does not depend on a paid cloud experiment.
Budget alerts and stopping a machine are not universal cost guarantees.
Practise before moving on
Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.
13.1 · Practice task
Using invented rates of 2 units per worker-hour and 0.5 units per GB-month, estimate 3 workers running 10 hours and 8 GB stored for a month. What is omitted?
Capstone Build a repeat-safe learning-progress worker
Combine identity boundaries, durable effects, duplicate handling, tests, and an operational plan.
By the end of this chapter
Trace a complete event-processing operation
Test duplicate and conflicting intent
Map a local prototype to a reviewed cloud design
Define success before choosing services
The capstone accepts a logical completion event containing an event ID, a learner ID, and a lesson ID. Applying the same event twice must not create two completion rows. Reusing the same event ID with a different meaning must be rejected. The local exercise assumes a trusted caller supplies the verified learner identity; a real API must derive that identity from its authentication context rather than trusting arbitrary input.
The program uses an in-memory SQLite database so every run starts clean and creates no cloud resource. The transaction coordinates the processed-event record with the completion row. This models a correctness boundary; it does not reproduce the throughput, concurrency, replication, or operational behaviour of an AWS database or queue. Keep those assumptions visible when transferring the idea.
From local model to cloud responsibilities. The model separates request identity, event delivery, the transactional effect, and feedback. Each cloud implementation must preserve the same business contract while adding its own operational controls.Scroll horizontally to read the full diagram on a small screen.
Save the code as progress_worker.py and run it with Python 3. It uses only the standard library. Read the uniqueness constraints before tracing the function. The processed table remembers both the event ID and its intended effect, so a reused key is not silently treated as equivalent when it refers to another learner.
The first call creates the effect; the second finds the same intent. The conflicting third call raises an error while the existing progress remains intact. The database context manager commits successful work and rolls back an exception. In a persistent or concurrent system, test the actual transaction and isolation semantics under contention; this single-connection teaching example is not a substitute for that work.
Complete local capstone; save as progress_worker.py Python
import sqlite3
# Local in-memory database: no AWS account or network calls.
db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE progress (
learner TEXT NOT NULL,
lesson TEXT NOT NULL,
PRIMARY KEY (learner, lesson)
);
CREATE TABLE processed (
event_id TEXT PRIMARY KEY,
learner TEXT NOT NULL,
lesson TEXT NOT NULL
);
""")
def apply(event):
required = ("id", "learner", "lesson")
if not all(isinstance(event.get(k), str) and event[k] for k in required):
raise ValueError("nonempty id, learner, and lesson required")
with db:
previous = db.execute(
"SELECT learner, lesson FROM processed WHERE event_id = ?",
(event["id"],)
).fetchone()
effect = (event["learner"], event["lesson"])
if previous is not None:
if previous != effect:
raise ValueError("event ID reused with different intent")
return "existing"
db.execute("INSERT INTO processed VALUES (?, ?, ?)",
(event["id"], *effect))
db.execute("INSERT OR IGNORE INTO progress VALUES (?, ?)", effect)
return "created"
event = {"id": "e1", "learner": "alice", "lesson": "python-1"}
print(apply(event))
print(apply(event))
print(db.execute("SELECT COUNT(*) FROM progress").fetchone()[0])
try:
apply({"id": "e1", "learner": "bob", "lesson": "python-1"})
except ValueError as error:
print(error)
assert db.execute("SELECT COUNT(*) FROM progress").fetchone()[0] == 1
Expected result
created
existing
1
event ID reused with different intent
Write a deployment proposal, not a deployment command. Pick an authorized request entry point, a delivery mechanism if background work is required, a compute model, and a durable store that can express the integrity rules. For each choice, explain the expected traffic, security boundary, failure path, cost dimensions, and recovery procedure. A small synchronous database operation may not need a queue at all; introduce one only when its timing and isolation benefits justify the new states.
Test missing fields, duplicate events, conflicting intent, a crash before commit, and a crash after commit but before acknowledgement. Add a privacy check showing that one learner cannot choose another learner’s identity. Define the signals needed to diagnose a stuck backlog or repeated conflict. The final artifact is a coherent argument about behaviour, backed by local tests and verified service documentation, rather than a collection of service logos.
Worked example · A capstone review checklist
Data: one completion for each learner/lesson pair, and stable event intent.
Failure: replay after an uncertain acknowledgement without repeating the effect.
Operations: useful metrics, protected logs, a cost model, and a recovery exercise.
Result: A successful first pass explains both what the system does and the assumptions under which the explanation holds.
These solutions show a valid line of reasoning. Compare assumptions and intermediate steps, rather than only the final number or output. Other implementations can be equally good when they preserve the stated contract.
Chapter 1 · What you are renting and what you still own
Solution 1.1
The application team validates input because the provider cannot know the quiz rules. For the virtual machine, the team manages the guest OS patching process. Database access remains a customer configuration responsibility even when the provider operates the database engine infrastructure. Name a person or team for each task and verify the actual service contract; “managed” does not supply a universal answer.
A public course file can be copied intentionally, but an unauthorized replacement damages integrity; restore a known-good revision and review publishing permissions. A reset token must remain confidential and short-lived; invalidate a disclosed token and examine how it leaked. Separate the storage and logging paths so that diagnostic records do not casually expose account-recovery secrets.
Chapter 2 · Regions, zones, and the meaning of available
Solution 2.1
The instances had different infrastructure locations but shared the same defective code or configuration. Zone separation addresses some correlated infrastructure failures, not every common cause. A safer release process gradually changes traffic, monitors user outcomes, and can restore a compatible previous version. Test dependency and configuration failures as well as machine loss.
Seven days contain 7 × 24 × 60 = 10,080 minutes. One percent is 0.01, so the allowance is 100.8 minutes. State whether planned maintenance counts, and do not confuse this arithmetic with a provider guarantee or a prediction. A service-level agreement and your own service-level objective can use different definitions.
Chapter 3 · Identity, roles, and permissions you can explain
Solution 3.1
Replacing an object needs a write action such as PutObject; the sample grants only GetObject. The private key is outside the public prefix, so this statement does not allow reading it. Another applicable policy might alter the full authorization result, which is why an isolated statement is not a complete account audit. Do not infer unrelated permissions from a familiar resource name.
The script would share a human identity, inherit unnecessary permissions, and expose a reusable secret to repository readers and artifacts. A workload role can express the script’s job and obtain temporary credentials through the platform. The application still must avoid logging credentials and must handle renewal or expiry correctly. Restrict the role to required actions and resources, and rotate any credential already disclosed.
Chapter 4 · Networks, subnets, routes, and security groups
Solution 4.1
A /26 leaves six address bits and therefore 2^6 = 64 total addresses. Workload capacity is lower because provider reservations and the architecture consume addresses. Also account for scaling, replacements, endpoints, and other interfaces rather than planning only the current machine count. Use the service’s current subnet-address documentation for a deployment calculation.
Confirm the application log and timeout stage, resolve the database endpoint from the workload environment, check target port and routes, inspect the relevant security-group rules, and verify the database is listening and healthy. Then check authentication, connection-pool limits, and query duration. A network timeout and a database permission error suggest different layers, so capture the actual error before changing rules.
Chapter 5 · Choose compute from the work it must do
Solution 5.1
The job may not fit the selected function service configuration or lifecycle. Check execution duration, supported environment, storage, connection behaviour, and interruption handling. A long-running container or virtual machine may express the workload more naturally. The useful conclusion is not “functions are bad”; it is that a service must fit the actual contract and operational constraints.
The estimate is 100 × 0.15 = 15 requests in flight on average. At 0.30 seconds it becomes 30. This is a stable-system average, so leave room for burstiness and tail latency. Increasing client concurrency without addressing a slow dependency can make the dependency less healthy, so measure the bottleneck and set sensible bounds.
Chapter 6 · Object storage, versions, and recovering a file
Solution 6.1
Inspect the key’s version history and current delete-marker state through authorized tooling. If an earlier version exists, verify its content and restore the intended reference according to your process. Check caching and manifest state too. Do not assume recovery is possible if versions were permanently removed or retention was not configured; the actual stored history determines the options.
The guide is intended for public reading, while the assignment may contain personal work or identifying information. Give the assignment its own authorization path and least-privilege permissions, and test that another learner cannot fetch it. A difficult-to-guess key is not a substitute for authorization. Also consider logs, caches, and generated links when reviewing who can see the contents.
Chapter 7 · Choose a database by the questions and guarantees
Solution 7.1
The compound key prevents two current completion rows for the same learner and lesson. It does not establish the caller’s identity, authorize access, validate that the lesson exists, or atomically coordinate unrelated external effects such as sending email. State each additional rule explicitly and test repeated and concurrent requests against the database constraint.
Live replicas may receive the same delete, so they are not automatically historical backups. Recovery depends on retained backups or logs, the available restore point, and the time needed to validate and restore. Practise restoring into a separate environment and checking the affected records before replacing production data. A successful backup job alone is not evidence that the intended recovery can be completed.
Chapter 8 · Follow an HTTP request through delivery and caching
Solution 8.1
With immutable revision URLs, each cached object remains internally consistent and the catalog chooses which one new readers discover. Overwriting a long-cached URL leaves some clients with old bytes and others with new bytes under the same identifier. The catalog still needs its own freshness and rollout policy, but separating the small mutable pointer from the large immutable artifact makes the state easier to inspect and restore.
The public file may be served from a nearby cache, while the progress request must reach authenticated application code and durable storage. Measure each stage of the save request, including connection time, authorization, database wait, and response generation. A CDN can help delivery in appropriate cases, but it does not automatically remove application bottlenecks or permit unsafe caching of private responses.
Chapter 9 · Events, queues, and safe repeated work
Solution 9.1
A later worker sees the event marked processed and skips it even though the business update never happened. Coordinate the deduplication record and update in one transactional boundary, or use a design whose recovery protocol explicitly handles the intermediate state. A temporary process-local set also disappears on restart and is not sufficient for durable correctness.
The backlog grows by 20 tasks per second. Five minutes is 300 seconds, giving about 6,000 waiting tasks, ignoring startup, variability, and retries. Add workers only if downstream capacity and per-task resource use permit it. Monitor oldest-message age as well as queue depth, because users experience waiting time rather than the visual height of a queue chart.
Chapter 10 · Protect data across the complete application path
Solution 10.1
Object-level or collection-level authorization is broken. HTTPS protects the connection but does not decide which records the authenticated caller may receive. Bind the query and update operation to a verified account identity, limit returned fields, and test cross-account access for each endpoint. Review caches and logs as additional places where the same records could be exposed.
Log a request identifier, a coarse outcome, timing, and carefully selected nonsecret context such as an approved error category. Exclude passwords, tokens, and unnecessary personal data. Apply retention and access rules to logs, and test the failure path to confirm redaction actually happens. A general instruction to developers is weaker than a narrow structured logging interface and a verified example.
Chapter 11 · Observe outcomes and investigate failures
Solution 11.1
Record the database operation’s error category, connection or pool wait, execution duration where available, and request identifier. A denied connection should lead to identity or access investigation; a slow successful query suggests a different path such as locks, indexes, or load. Preserve useful context without recording database credentials or the full contents of sensitive records.
For a teaching service, define a target for valid progress saves and alert when sustained failures or slow requests consume the agreed error budget quickly enough to require action. Choose windows and thresholds from actual workload needs, not this book’s arbitrary numbers. Include a runbook, a way to identify recent changes, and a verification step for learner-visible recovery.
Chapter 12 · Make changes repeatable and reversible
Solution 12.1
Retention can preserve important data when a stack resource is removed, but it also means the resource and associated charges may continue to exist. Document its owner, location, recovery use, and later authorized disposal procedure. Do not assume deleting the stack eliminates every object, version, snapshot, log, or related resource. Verify actual inventory and billing after cleanup.
Check whether the previous application can read data written by the new application, whether clients still send the old format, and whether any background job depends on it. Use representative fixtures and a mixed-version scenario. If compatibility fails, redesign the migration or define a deliberate data-recovery procedure rather than treating a code-version switch as a complete rollback.
Chapter 13 · Estimate cost without pretending to know the future
Solution 13.1
Compute is 3 × 10 × 2 = 60 units. Storage is 8 × 0.5 = 4 units, so the simplified total is 64 units. It omits requests, data transfer, logs, backups, taxes, discounts, partial-month rules, and any other service-specific dimensions. State those omissions and replace invented rates with verified current rates only when planning an actual deployment.
Stopping one compute resource may leave storage, addresses, snapshots, load balancers, logs, object versions, or unrelated resources. Inspect the full lab inventory and service-specific behaviour. Some charges can appear after usage because billing data is delayed. Cleanup should be an explicit, authorized procedure with verification, rather than an assumption based on one resource’s visible state.
Chapter 14 · Capstone Build a repeat-safe learning-progress worker
Solution 14.1
A new ID for Alice’s already completed python-1 event can be recorded as a distinct processed event, but INSERT OR IGNORE preserves one completion row for the same learner/lesson pair. A new lesson creates a second completion row. Test both outcomes and inspect both tables: a count in the processed table measures logical events seen, while a count in progress measures the current completed relationships.
It needs real authentication and per-account authorization, persistent storage with tested transactions and concurrency behaviour, input and lesson validation with bounded resource use, and operational monitoring plus recovery procedures. A deployment also needs reviewed access policies, secrets handling, encryption choices, cost controls, and cleanup ownership. These are concrete additions to the contract, not reasons to discard the useful local model.
A delivery-protocol confirmation that a consumer has completed work according to that protocol. Chapter
Authorization
Deciding whether an identified caller may perform an operation on particular data or resources. Chapter
Availability Zone
An infrastructure isolation grouping within a Region, comprising one or more data centers. Chapter
AWS
Amazon Web Services, a cloud provider offering infrastructure and managed services. Chapter
Backoff
Increasing or otherwise controlling the delay before another attempt. Chapter
Backup
A retained recovery copy or history intended to restore earlier data according to a tested recovery procedure. Chapter
Budget alert
A notification based on configured cost or usage measurements, subject to update timing. Chapter
Cache key
The request-derived identity used to decide whether a stored response can be reused. Chapter
CDN
Content-delivery network, a delivery layer that can cache eligible responses near readers and fetch misses from an origin. Chapter
CIDR
Notation expressing an IP address prefix and the number of fixed network bits. Chapter
Concurrency
Work in flight at the same time, distinct from arrival rate and completion throughput. Chapter
Container
A packaged process environment; its surrounding scheduling and storage still need a design. Chapter
Delete marker
A versioned-storage marker that can make a key appear deleted without removing every prior version. Chapter
Drift
A difference between declared infrastructure intent and actual managed configuration. Chapter
Durable state
State designed to survive the failures and process replacement named in its contract. Chapter
EC2
Elastic Compute Cloud, the AWS virtual-machine service. Chapter
Explicit deny
A policy decision that can override an applicable allow according to the evaluation model. Chapter
IAM
Identity and Access Management, the AWS service for controlling access to AWS resource operations. Chapter
Idempotency
Repeat-safe intended effect under a defined operation contract. Chapter
Infrastructure as code
A versioned machine-readable declaration or program for managing intended infrastructure. Chapter
Jitter
A deliberate random variation in retry timing to avoid synchronized bursts. Chapter
Least privilege
Granting the actions and resources required for a responsibility, with no unjustified extra access. Chapter
Managed service
A service that takes on specified operational tasks while exposing an interface and customer controls. Chapter
Object key
The identifier used to address an object within an object-storage bucket. Chapter
Origin
The source from which a delivery layer fetches an object or response on a miss. Chapter
Primary key
A key used to identify a row or item under the database’s uniqueness rules. Chapter
Principal
An identity that makes a request evaluated by the authorization system. Chapter
RDS
Relational Database Service, a managed relational-database service with configuration-specific availability and replication options. Chapter
Read replica
A copy that can serve reads according to configured replication and consistency behaviour. Chapter
Region
A geographic AWS infrastructure grouping with multiple Availability Zones. Chapter
Role
An assumable identity with permissions, used to represent a workload or delegated responsibility. Chapter
Route table
Rules selecting the next destination for traffic matching network prefixes. Chapter
RPO
Recovery point objective: the maximum acceptable time interval of potential data loss between the last recoverable data point and a disruption. Chapter
RTO
Recovery time objective: the duration within which a recovery plan aims to restore the required service. Chapter
S3
Simple Storage Service, the AWS service for storing and retrieving objects by key. Chapter
Security group
A stateful resource-associated traffic control with inbound and outbound rules. Chapter
Shared responsibility
The division of operational and security duties between a provider and customer for a particular service. Chapter
SLA
Service-level agreement, a provider or contractual commitment with its own measurement rules and remedies; distinct from an internal SLO. Chapter
SLO
A stated objective for an explicitly measured service outcome over a defined window. Chapter
SQS
Simple Queue Service, an AWS message-queue service whose selected queue type determines delivery guarantees. Chapter
Subnet
An address range within a VPC, placed in one Availability Zone. Chapter
Trace
A connected representation of stages of work for a request or operation. Chapter
Transactional boundary
The set of changes committed or rolled back together under a database contract. Chapter
Versioning
Keeping multiple object revisions according to the storage service’s version model. Chapter
VPC
A logically isolated virtual network with configured address ranges and routing. Chapter
Read and watch with a purpose
Reading and video library
Use the chapter source links to choose a relevant next explanation. Each entry below states what it adds. Documentation links may evolve; edition 2026.12 records the assumptions used here.
Optional provider-led video and course paths after a first read. Some learning options require an account or subscription; verify the selected course access before starting.
A short official AWS whiteboard explanation of recovery-point and recovery-time objectives. Published in 2018; use it for stable concepts rather than current service details.
If a paragraph needs a clearer example, a command changes, or a diagram hides an important assumption, propose a correction in the open-source repository. Explain the issue and add a source or a reproducible example.
Original OpenLearning instructional text and diagrams: CC BY-SA 4.0. Original code: MIT. External material retains its own copyright and license. This book links to authorized resources; it does not relicense them.