Chapter 37 — Cloud & AWS for Backend Engineers
Part VII · Delivery | Prerequisites: Ch 36, Ch 24 | Builds: Pulsely deployed to AWS (ECS Fargate, Aurora, ElastiCache, MSK, S3, SQS) in a VPC
Earlier you turned Pulsely into an immutable, stateless, config-from-env container — an artifact that any orchestrator can run N copies of without surprise. That artifact is now homeless. It needs somewhere to run that survives a datacenter losing power, scales when Monday-morning intake triples traffic at 8 a.m., holds the durable state your container deliberately doesn't — patient charts, encounters, claims — and does all of it without one engineer being the only person who knows the firewall rules. And because this is a HIPAA platform, "somewhere to run" carries a second clause: the protected health information (PHI) it touches must never sit on a public network, and every service that handles PHI must be one AWS will cover under a signed agreement. This chapter is about that somewhere.
The trap to avoid first: treating AWS as a console full of magic buttons you click until the green checkmark appears. That path produces snowflake infrastructure nobody can rebuild and a bill nobody can explain. We're going to do the opposite — derive each service from the problem it solves, place every primitive on three axes you already understand (failure domains, security boundaries, cost centers), and reason about the cloud the same way you reason about the request spine. By the end you'll deploy Pulsely to a production-shaped AWS topology and be able to defend every box in the diagram. The how do I express this as code part — Terraform, CDK, pipelines — is deliberately the next chapter's job; here we learn what we're building and why.
1. The problem: why rent computers as APIs
Let me start where most teams start, because the pain is what makes the cloud make sense.
Pulsely's first production deploy was one EC2 instance — a virtual machine in a single Availability Zone in us-east-1. The app ran, Postgres ran on the same box, life was good. Then on a Tuesday afternoon that AZ had a power event. Not a hack, not a bug — a physical datacenter problem. Pulsely was down for four hours, and in a clinic that is not a cosmetic outage: providers couldn't open a chart, couldn't e-prescribe, couldn't see the critical potassium result a lab had just posted. The team could do nothing but wait, because capacity, networking, and data all lived on that one physical machine. There was no second copy to fail over to, because there was no second anything.
That's failure mode one: everything coupled to a single physical box. Failure mode two is quieter and arrives without an outage. The EC2 box accumulated history — a manual hotfix here, a firewall rule someone added over SSH at 2 a.m., a half-applied migration, a Node minor version that drifted from staging. It became a snowflake: unique, irreproducible, and understood by exactly one person. When that person was on holiday, nobody dared touch it. Failure mode three is the bill you pay to avoid failure mode one the naive way: to survive the 8 a.m. peak you provision for the peak and run that capacity 24 hours a day, paying for idle metal at 4 a.m. when the clinic is closed.
The cloud's answer to all three is a single reframe: stop buying computers and start renting primitives that are themselves API calls. A server, a network, a disk, a queue, a load balancer — each is created, scaled, and destroyed by an API request, not a purchase order and a trip to a rack. That one property cascades into everything good about the cloud: because resources are API calls, you can ask for capacity in seconds and give it back when the surge ends (elasticity); you can run identical copies in two physically separate datacenters and let one take over when the other dies (managed failover); and you turn a large up-front hardware purchase (capex) into a metered monthly bill (opex).
But notice what the reframe costs you, because senior engineering is naming the cost. When infrastructure becomes API calls, the bill becomes a runtime concern — a slow query or a misrouted gigabyte now shows up on an invoice, not just a latency graph. And it introduces a failure mode the locked server room never had: a leaked credential or an over-broad permission is now an internet-facing blast radius. On a healthcare platform that blast radius has a name — a leaked credential that reaches a bucket of patient records is a reportable HIPAA breach, with legal notification obligations attached. The server room had a physical door. The cloud's door is an IAM policy, and we get that wrong constantly.
🧭 A useful distinction. "The cloud" is not a place; it is someone else's computers exposed as APIs you compose. You are not renting a building you walk into — you are renting the ability to summon and destroy buildings, networks, and machines with code. This is why "infrastructure as code" isn't a fashion: when the infrastructure is already an API, not scripting it is the anomaly. We summon by hand in this chapter only to learn; the next chapter scripts it for real.
🔑 PHI narrows the menu: the BAA line. Before any service touches patient data, AWS must sign a Business Associate Agreement (BAA) — a legal contract that makes AWS jointly responsible for safeguarding PHI. Only the subset of services AWS marks HIPAA-eligible may sit in the PHI path (Fargate, Aurora, S3, KMS, SQS, and MSK all qualify). A service that isn't covered — or one you use in a non-conformant way, like an unencrypted bucket — is off-limits for anything with a patient in it. This isn't a footnote; it's a hard filter on the architecture you're allowed to draw.
2. The mental model: three axes, a moving line, and nested domains
Hold four pictures. The first three place services; the fourth places responsibility.
Three axes for any service
Every AWS service — and there are hundreds, which is what makes the console terrifying — sits on one of three axes. Sort by axis and the menu shrinks to something you can reason about:
- Compute — runs your code. EC2, ECS/Fargate, Lambda. This is where your Pulsely container or function actually executes.
- State — stores your data. Aurora/RDS, DynamoDB, S3, ElastiCache. This is the durable truth your stateless compute deliberately externalized — the charts, the claims, the vitals history.
- Glue — connects them. The VPC and its networking, messaging (SQS/SNS, MSK), and identity (IAM). Glue is the membrane and the wiring; it's also where most outages and most breaches actually live.
When someone names a service you've never heard of, your first move is to place it on an axis. A new database service is state and inherits state's questions (durability, consistency, failover). A new function runtime is compute and inherits compute's questions (cold start, scaling, who runs the OS).
The shared-responsibility line
AWS secures OF the cloud │ YOU secure IN the cloud
│
EC2 │ hardware, hypervisor │ guest OS patching, your runtime, your code,
│ │ IAM, network rules, data, encryption keys
─────── │ ─────────────────────── │ ──────── line moves LEFT as you go down ────────
ECS │ + container host │ your image, IAM, network rules, data
─────── │ ─────────────────────── │
Fargate │ + the host entirely │ your image, IAM, network rules, data
─────── │ ─────────────────────── │
Lambda │ + the runtime lifecycle │ your function, IAM, data
🧭 Mental model. AWS secures of the cloud — the physical hardware, the hypervisor, the internals of managed services. You secure in the cloud — your data, your identities, your network rules, and the OS where you still own it. The line is not fixed: it slides left (AWS takes more) as you move EC2 → ECS → Fargate → Lambda. On EC2 you patch the kernel; on Fargate you don't own a host to patch; on Lambda you don't own a runtime to patch. What never moves across the line, no matter how managed the service, is the trust boundary: authorization is always yours. AWS will keep the disk encrypted and the host patched, but whether this biller may open this patient's chart is your code's decision, every time. Outsourcing the machine never outsources the role — and in healthcare, a broken access check is not a bug ticket, it's a breach.
Failure domains nest
The third picture connects directly to the independent failure domains you've already met. AWS gives you a hierarchy of failure domains, and your job is to design so that losing an inner domain is survived by redundancy in the outer one:
┌─────────────────────── REGION (us-east-1) ───────────────────────┐
│ independent geography · DR boundary · data stays here │
│ ┌──────── AZ-a ────────┐ ┌──────── AZ-b ────────┐ ┌─ AZ-c ─┐ │
│ │ independent power, │ │ independent power, │ │ ... │ │
│ │ cooling, network │ │ cooling, network │ │ │ │
│ │ ┌────┐ ┌────┐ │ │ ┌────┐ ┌────┐ │ │ │ │
│ │ │task│ │task│ ... │ │ │task│ │task│ ... │ │ │ │
│ │ └────┘ └────┘ │ │ └────┘ └────┘ │ │ │ │
│ └──────────────────────┘ └──────────────────────┘ └────────┘ │
└──────────────────────────────────────────────────────────────────┘
Region ⊃ Availability Zone ⊃ instance / task
The four-hour outage was a single AZ failure with no second AZ to absorb it. The cloud doesn't make AZs stop failing; it makes their failures independent and survivable — but only if you spread across them, which costs more and which most single-AZ tutorials quietly skip. For a clinical system that spread is not gold-plating: an EHR that goes dark mid-visit is a patient-safety event, and "we were on AWS" is not a defense if you ran everything in one AZ.
Identity is the perimeter
The fourth idea is the one that reorients backend engineers most. In a traditional datacenter the wall is the network — inside is trusted, outside is not. In the cloud that intuition gets you breached, because the network has no edges you fully control and an attacker who lands inside can call AWS APIs freely. The real perimeter is identity: which principal is allowed to call which action on which resource. Network controls (security groups, subnets) are real and useful, but they are defense in depth layered behind the identity boundary, not the boundary itself. Internalize this now: in the cloud, who can call what API is the membrane, and IAM is how you draw it.
🔑 Cost is a non-functional requirement. Like latency, every architectural choice has a dollar shape, and at a senior level you are expected to know it before you commit. A NAT gateway, a cross-AZ replication link, an idle Fargate task — each is a line item you chose, often without realizing you chose it. We treat cost as first-class throughout, the same way we treat latency.
3. Theory & invariants
A mental model places things; invariants tell you what must stay true or you don't have what you think you have. These are the load-bearing rules for everything that follows.
Region — the boundary AWS will not silently cross. A Region is an independent geographic deployment with its own copy of services and its own data sovereignty. Its defining invariant: your data does not leave a Region unless you explicitly move it. That makes the Region the unit of disaster recovery (a true region-down event is rare and survived only by multi-region, which we defer) and the unit of compliance — for PHI, keeping records inside the US regions your BAA and contracts require.
Availability Zone — the unit of high availability. An AZ is one or more discrete datacenters inside a Region with independent power, cooling, and network, linked to its sibling AZs by low-latency private fiber.
🔑 The HA invariant. Replicate state and spread compute across ≥2 AZs, or you do not have high availability — you have a single point of failure wearing a cloud logo. Aurora Multi-AZ, an ALB with targets in two AZs, ECS tasks placed across AZs: each exists to make one AZ's death a degraded moment, not an outage. This is independent failure domains made concrete and billable.
IAM — the grammar of the perimeter. Every authorization decision is a sentence with four parts: principal (who is asking), action (which API call), resource (on which ARN), and condition (under what circumstances — source IP, MFA present, time). Two policy attachment styles exist: identity-based (attached to the principal: "this role may do X") and resource-based (attached to the thing: "this bucket may be read by Y"). And the piece engineers misuse most:
🔑 Roles are assumed, not logged into. A role is a set of permissions with no long-lived credentials — a workload (or a human, briefly) assumes it and receives temporary keys that expire in minutes to hours. A role has two policies: a trust policy (who is allowed to assume it) and a permission policy (what the assumer may then do). This is the mechanism that lets a Fargate task get AWS permissions with zero static secrets baked into the image — the thing static-key leaks are the leading cause of cloud breaches for. If you remember one IAM fact, remember this one.
Least privilege is derivable, not aspirational. A correct policy is one you could reconstruct from the actual list of API calls the workload makes — every permission beyond that list is latent blast radius waiting for a compromise to spend it. "We'll tighten it later" is how Action: * reaches production. This is the cloud face of a rule you carry through the whole platform — minimum necessary: a task, like a user, gets exactly the access its job requires and not one permission more.
VPC invariants. A subnet lives in exactly one AZ (so spreading across AZs means spreading across subnets). Think of a subnet as a room and its route table as the list of doors out of that room. A subnet is "public" not because of what's inside it but because its door-list contains a door to the open internet — an Internet Gateway. So "public" is not a property of a subnet's contents; it means a route to an Internet Gateway exists. A private subnet has no such inbound door: the only way out is a one-way service exit — a NAT — that lets traffic leave but never lets strangers walk in. That distinction is the whole reason PHI can live in a private data subnet safely: nothing on the public internet has a door to it. Security groups are stateful allow-lists attached to resources: allow the inbound, and the return traffic is automatically permitted; there is no implicit allow, only what you add. (NACLs are stateless subnet-level filters you will rarely need — mentioned so you can ignore them with confidence.)
Durability ≠ availability. S3's famous eleven nines is a durability claim — the probability your bytes still exist — not a promise the service is reachable this second. Keep them separate; they have different failure modes and different mitigations.
Delivery is at-least-once by default. SQS, SNS, and Kafka/MSK all guarantee a message arrives at least once, which means possibly more than once. Exactly-once and strict ordering are opt-in, costly, and constrained.
📎 Borrowed on credit: idempotent consumers. Because the messaging substrate redelivers, every consumer that changes state must produce the same result whether it sees a message once or five times — an idempotency key plus a dedup store, exactly as developed in Ch 25. Why it matters here: it's the difference between SQS smoothing your traffic and SQS quietly filing a duplicate medication order — or a duplicate insurance claim — because a redelivered job ran twice. We lean on the contract; we don't re-derive it.
4. Under the hood: compute, the request's path, and how trust is vended
Now we open the boxes — just enough mechanics to kill the magic, so the production beat has somewhere to land.
The compute spectrum
The single most consequential cloud decision is which compute primitive runs your code, because it sets the shared-responsibility line, the scaling model, and a large slice of the bill. Three options, increasing in how much AWS does for you:
- EC2 — a virtual machine. You get an OS you own: you patch the kernel, run the process supervisor, configure an Auto Scaling Group, and wire health checks. Maximum control, maximum operational surface, longest-lived. You reach for it when you need a specific instance type (GPU, huge memory), or when steady scale makes its economics (reserved/spot pricing) decisively cheaper.
- ECS on Fargate — a container, no host. You hand AWS a task definition — your image, a CPU/memory size, environment, an IAM task role, a log driver — and Fargate runs the container with no EC2 host for you to manage or patch. The ECS scheduler places tasks across AZs; an ALB load-balances across them. This is the container story you built earlier with the host erased, and it's our default for the Pulsely API and workers.
- Lambda — a function. You ship a handler; AWS owns the entire runtime lifecycle, scales it per concurrent request, and bills per millisecond and per invocation. The catch is the freeze/thaw model: between invocations the execution environment is frozen and may be torn down, so a first call after idle pays a cold start, and anything you cached (a DB connection) may not survive.
The Node specifics matter here. On Fargate your container's signal handling is load-bearing exactly as you saw earlier: when ECS stops a task it sends SIGTERM, and only an exec-form entrypoint with a handler drains in-flight requests gracefully — otherwise every deploy drops live requests, and "live request" here can mean a provider mid-save on a clinical note. On Lambda the dangerous Node pattern is the database connection pool (a fixed, shared set of reusable DB connections a long-lived process borrows from). A pool assumes a long-lived process, but Lambda gives you N short-lived ones scaling per request, so a burst opens hundreds of connections and Aurora returns too many connections. The fixes are real and named: RDS Proxy to multiplex connections, or a data store with an HTTP API (DynamoDB) that has no pool to exhaust.
Cold start is worth understanding precisely, because it's the single property that decides whether Lambda belongs on a given request path. An invocation runs in two phases: an init phase — AWS provisions a micro-VM, downloads your package, and runs your handler module's top-level code (imports, SDK-client construction, config load) — and an invoke phase, where your handler body runs. A warm call skips init and is fast; a cold call pays the whole init, and three things inflate it:
- a large deployment package — more to fetch and parse;
- heavy top-level work — constructing clients, opening connections;
- and the brutal one, attaching the function to a VPC.
That last one deserves plain terms. To talk to your private Aurora database, a Lambda needs its own virtual network card inside your VPC — an elastic network interface (ENI). Historically AWS created that card during the very first call, on the cold path, and that setup could add hundreds of milliseconds. AWS has since mostly fixed it by pre-creating and sharing those cards, but a VPC-attached function is still the worst-case cold start you'll see.
What you control: keep the package small; hoist expensive client construction to module scope so it's reused across warm invocations on the same environment; and reach for provisioned concurrency (pre-warmed environments you pay to keep hot) only when a user-facing path genuinely can't tolerate the occasional cold tail. The senior framing is that cold start is a p99-tail problem, not an average one — irrelevant for the spiky PDF-summary job nobody is waiting on, disqualifying for a synchronous provider-login endpoint with a tight latency budget. Match the runtime to the latency contract, not to the marketing.
📎 Borrowed on credit: graceful shutdown & 12-factor disposability. The SIGTERM-drain mechanics and the stateless-process discipline that make Fargate task replacement safe are Ch 36's territory. Here we only note where they bite (task stops, rolling deploys) and move on.
How a Pulsely request actually flows through the VPC
This is the cloud version of the request spine. Trace it once and the VPC stops being abstract:
client ─▶ Route 53 (DNS) ─▶ ALB ──────────────┐ PUBLIC subnets (AZ-a, AZ-b)
│ route to Internet Gateway
───────────────────────────────────────────── │ ─────────────────────────────
▼
Fargate task (Pulsely API) PRIVATE app subnets
│ no inbound from internet
┌────────────┼─────────────┐
▼ ▼ ▼
Aurora ElastiCache S3 / external
(private data (private) via VPC endpoint
subnets) or NAT (egress only)
Read it as membrane crossings. The ALB lives in public subnets — it is the only thing with an internet route — and terminates TLS. It forwards to a target group of Fargate tasks in private app subnets, which have no inbound internet path at all; the only way in is through the ALB. Those tasks talk to Aurora and ElastiCache in private data subnets that have no internet route whatsoever, in or out. This is where the room-and-doors picture pays off directly: the charts, encounters, and claims live in the room with no door to the outside world. There is no public IP on PHI anywhere in this topology. When a task needs S3 or an external API — a lab interface, a clearinghouse — it egresses through a VPC endpoint (a private door straight to the AWS service, no internet) or through a NAT gateway (egress-only, for general internet). The data tier is the most-guarded room precisely because it holds the durable truth about real patients.
How trust gets vended (no static keys, ever)
Here's the mechanism behind "roles are assumed," and it's worth slowing down because it has no frontend analog you've had to think about. On the frontend, auth is a token you attach to fetch. A backend process, by contrast, has to discover its own credentials — and here's how it does that without a single secret in the image.
A Fargate task starts with an attached task role. When your Node code makes its first AWS API call, the SDK needs credentials but you gave it none. So it looks through a fixed list of places, in order — the default credential chain — and, running on Fargate, it finds a special internal URL reachable only from inside the task: the container/instance metadata service. That URL hands back temporary keys tied to the task role.
In plain terms: the task asks the platform "who am I allowed to be?" and gets back a short-lived badge — the same way a browser silently swaps a refresh token for a fresh access token at a refresh endpoint instead of storing your password. Those badge credentials are derived under the hood from sts:AssumeRole, they expire, and the SDK auto-refreshes them. IMDSv2 is just the hardened version of that internal URL: it requires a session token first, so an app-layer bug can't trivially trick the service into reading out the credentials. At no point is a long-lived access key in your image, your env, or your Git history. The SDK call s3.getObject(...) simply works, authorized by the role, with nothing to leak.
KMS rides the same "permission is the real gate" logic via envelope encryption. Start with the intuition: encrypting everything with one master key is like using one house key for a whole city — if it leaks, everything opens at once, and you can never cheaply change the locks. So AWS uses two levels of key. It generates a throwaway data key per object, encrypts your data with that, then asks KMS to wrap (encrypt) the little data key with a long-lived customer master key (CMK). The data key locks the data; the master key only ever locks the little keys. To read the data later, a principal needs both the ciphertext and kms:Decrypt permission on the CMK to unwrap the data key.
task ─assume role─▶ STS ─temp creds─▶ s3.GetObject(bucket, key)
│ returns ciphertext + wrapped data key
▼
KMS.Decrypt(wrapped key) ← needs kms:Decrypt on the CMK
│ returns plaintext data key
▼
decrypt object → plaintext
🔑 Whoever holds
kms:Decryptcan read the data — regardless of bucket policy. Encryption-at-rest moves the access question from "who can reach the bucket" to "who can use the key." A perfectly locked-down bucket of patient documents whose CMK grantskms:Decrypt: *is not protected. This is the lens Ch 31 gives you, applied to AWS's at-rest story — and for PHI it's why every S3 bucket and Aurora volume in the design is server-side encrypted (SSE-KMS) with a scoped key, not just "encrypted."
🛑 What we deliberately did not explain. How Terraform or CDK expresses this VPC, these roles, and these services as reviewable, rebuildable code — and how a pipeline ships it — is the entire subject of Ch 38. We also don't open the internals of how Aurora replicates storage, how DynamoDB partitions, or how MSK's log is laid on disk — Ch 19, Ch 21, and Ch 27 own those engines. Here we choose and operate them; we don't rebuild them.
5. In production: deploying Pulsely to AWS
Here is the topology we build — the Pulsely increment — and the production practices that separate a deploy that survives Tuesday from one that demos and dies.
Route 53 ─▶ ALB (public, AZ-a + AZ-b, TLS terminate)
│
┌───────┴────────┐ target groups
▼ ▼
Fargate API Fargate worker (private app subnets, ≥2 AZs)
(autoscale on (autoscale on
CPU + req) SQS queue depth)
│ │ │ │
▼ ▼ ▼ ▼
Aurora Redis S3 SQS ──DLQ MSK (event log)
(PG, (Elasti (scanned (reminders, (patient-timeline
Multi- Cache) docs, visit-summary fan-out,
AZ: SSE-KMS) PDFs) clinical search index)
writer+reader)
▲
Secrets Manager (DB creds, rotated) · KMS (at-rest) · CloudWatch (logs/metrics/alarms)
Account & identity hygiene — the part tutorials skip. The root account is locked away behind MFA and never used day-to-day. Humans authenticate through SSO / IAM Identity Center into roles, not IAM users with static keys. Workloads use task roles. The principle: no long-lived human or machine credentials exist anywhere if a short-lived assumed role can do the job. In a HIPAA account this also means human access is itself minimum-necessary and logged — CloudTrail records every console action, so "who touched what" is answerable after the fact.
Networking the way it's really built. Three subnet tiers per AZ: public (ALB only), private-app (Fargate), private-data (Aurora/Redis — the PHI tier). Run one NAT gateway per AZ so a single AZ's NAT failure doesn't drag the others, and so egress traffic stays AZ-local rather than paying cross-AZ transfer to reach a NAT elsewhere. Add gateway VPC endpoints for S3 and DynamoDB (free, and they keep that traffic off NAT entirely) and interface endpoints for Secrets Manager and friends — this is both a security win (PHI-adjacent traffic never touches the public internet) and a direct cost win on the NAT data-transfer line.
Aurora in production. Aurora PostgreSQL gives you a writer endpoint and a reader endpoint over storage replicated across AZs; on writer failure it promotes a replica and the writer endpoint re-points, usually in under a minute. Route Pulsely's read-heavy queries — the chart timeline, the RPM vitals history a clinician scrolls — to the reader endpoint to spare the writer.
📎 Borrowed on credit: read replicas & chart-read load. Why the chart timeline and RPM history are read-dominant and how splitting reads from writes scales it is Ch 29's scalability material and Ch 19's Postgres depth; Aurora is the managed expression of it.
Store the DB password in Secrets Manager with automatic rotation and inject it at task start — never as ENV DB_PASSWORD= in the image (which would persist in image history — the same secret-leak pitfall you saw earlier).
ECS service config that matters. Health checks so the ALB only routes to ready tasks; task autoscaling driven by CPU and by SQS queue depth for the worker tier (scale on the actual backlog, not a proxy for it); a rolling or blue/green deployment so in-flight requests drain rather than drop. The deployment strategies themselves — canary, blue/green, health-gated rollback — are the next chapter's to own.
Messaging split: MSK vs SQS, used for what each is good at. Pulsely uses MSK (Kafka) as the durable, replayable, multi-consumer event log — "encounter signed," "vitals reading ingested" — that the patient-timeline fan-out and the clinical search indexer both consume independently, each at its own offset, and can replay from history when you rebuild an index. It uses SQS as point-to-point job queues — send-appointment-reminder, render-visit-summary-PDF — where a job is done once and forgotten, with a dead-letter queue (DLQ) catching messages that fail repeatedly and a visibility timeout tuned to the handler's P99 so a slow-but-fine job isn't redelivered as a duplicate.
📎 Borrowed on credit: log-vs-queue semantics. The deep "why a replayable log differs from a consume-once queue" distinction is Ch 26 and Ch 27; MSK and SQS are the managed instances of those two shapes.
Observability — the build-vs-buy question deferred to here. Earlier you learned logs, metrics, traces, and what good observability is; that left the question of whose tooling open, and the cloud is where you answer it. The managed default on AWS is CloudWatch: your container's stdout JSON logs (factor XI) flow to CloudWatch Logs via the task's log driver; metrics and custom dimensions go to CloudWatch Metrics; and alarms page someone when SQS queue depth, Aurora connection count, or task health crosses a threshold. The senior framing is build-vs-buy: CloudWatch is zero-integration and AWS-native but weaker at high-cardinality tracing and cross-service correlation, where teams add a third-party (Datadog, Honeycomb, an OpenTelemetry pipeline). The decision rule is the same as every build-vs-buy: buy the managed default until a specific limitation it has costs you more than the alternative's integration burden.
🔑 The audit log is not the observability log — and in healthcare it's the bigger obligation. CloudWatch answers "is the system healthy?" The HIPAA audit log answers a legally-mandated question: who viewed or changed this patient's record, and when. It must capture every chart view, not just writes — a clinician merely opening a chart is a PHI access event that has to be recorded. And it must be append-only and tamper-evident: no operator, not even an admin, may edit or delete an entry. Practically, that means a separate sink from your app logs — an append-only store such as an S3 bucket with Object Lock (WORM) or a dedicated audit table you never grant
UPDATE/DELETEon — with a long retention (six years is the common HIPAA floor) and its own access controls. Ordinary CloudWatch logs can rotate and expire; the audit trail cannot. When compliance asks "prove no one outside the care team read this chart," this is the artifact that answers, so it is designed first-class, not scraped out of application logs after the fact.
A task-definition.json makes the whole shared-responsibility, identity, and config story concrete in one artifact:
{
"family": "pulsely-api",
"requiresCompatibilities": ["FARGATE"],
"networkMode": "awsvpc",
"cpu": "512", "memory": "1024",
"executionRoleArn": "arn:aws:iam::123:role/pulsely-task-execution",
"taskRoleArn": "arn:aws:iam::123:role/pulsely-api-task",
"containerDefinitions": [{
"name": "api",
"image": "123.dkr.ecr.us-east-1.amazonaws.com/pulsely-api@sha256:abc...",
"portMappings": [{ "containerPort": 3000 }],
"environment": [{ "name": "NODE_ENV", "value": "production" }],
"secrets": [{
"name": "DATABASE_URL",
"valueFrom": "arn:aws:secretsmanager:us-east-1:123:secret:pulsely/db-url"
}],
"logConfiguration": {
"logDriver": "awslogs",
"options": { "awslogs-group": "/pulsely/api", "awslogs-region": "us-east-1" }
}
}]
}
Two roles, not one (executionRole lets ECS pull the image and fetch the secret; taskRole is what your code gets at runtime — the least-privilege boundary); the image pinned by digest (@sha256:...), so the bytes deployed equal the bytes CI tested; the secret referenced by ARN and injected at start, never baked in; logs to stdout → CloudWatch. Everything we've said, in twenty lines.
6. Common pitfalls
Each is signature → fix: the symptom, then the principle that dissolves it.
Wide-open IAM (Action: *, Resource: *). Signature: one compromised task can read every bucket and every secret in the account; a small bug becomes a total breach — and if any of those buckets hold PHI, a reportable one. Fix: scope every policy to specific actions on specific ARNs, derived from the API calls the service actually makes; tighten using CloudTrail history and IAM Access Analyzer.
Single-AZ everything. Signature: "we're on AWS" yet one AZ event is a full outage — a clinic dark mid-visit. Fix: the HA invariant — subnets, Aurora, ElastiCache, and ECS tasks all spread across ≥2 AZs, so one AZ's loss is degradation, not downtime.
Security group 0.0.0.0/0 on the database port. Signature: the PHI-holding DB is reachable from the internet and is being port-scanned within minutes of launch. Fix: the data-tier SG allows only the app tier's SG as a source; nothing public ever touches the data tier.
Static access keys in the image, env, or Git. Signature: a key in a commit becomes a crypto-miner on your bill — or a data-exfil path — within hours of being pushed. Fix: roles + short-lived STS credentials (§4); secret-scanning in CI; if a key ever existed, rotate and revoke — it is already compromised.
Public S3 bucket holding PHI. Signature: a bucket set public "just to test" exposes scanned documents or exports to the open internet — the most common cloud data-leak headline, and here a HIPAA breach with notification duties. Fix: account-level Block Public Access on, SSE-KMS enforced, bucket policy scoped to the exact task roles that need it.
NAT/egress surprise bill. Signature: an unexplained data-transfer charge from S3 traffic that's being routed out through NAT. Fix: gateway VPC endpoints for S3/DynamoDB (free, off-NAT) and interface endpoints for other services.
Non-idempotent SQS consumers. Signature: duplicate medication-order jobs or duplicate reminders because at-least-once redelivery fired after a slow handler exceeded the visibility timeout. Fix: idempotency keys + a dedup store (the borrowed-on-credit contract above); set visibility timeout above the handler's P99.
Lambda + connection-pool exhaustion. Signature: Aurora throws too many connections under a burst. Fix: RDS Proxy, much smaller pools, or move that workload to Fargate where a long-lived pool fits the runtime.
No DLQ. Signature: a single poison message is retried forever, backing up the queue and starving good work — the appointment-reminder queue stalls and no one gets reminded. Fix: a DLQ with an alarm and a deliberate redrive path.
7. Tradeoffs
Senior engineering is naming the spectrum and saying why you stand where you stand — and crucially, what would make you move. These are the chapter's two ADRs.
ECS/Fargate vs Lambda (ADR decision 1 — Pulsely compute). Fargate suits steady-state, long-running, connection-heavy services — exactly the Pulsely API and its workers, which hold DB pools and run continuously. Lambda suits spiky, event-driven, short tasks — a thumbnail or PDF render triggered by an S3 upload (a scanned insurance card, a signed visit summary), idle most of the day. Reverse toward Lambda when traffic becomes bursty and sparse enough that paying for idle Fargate dominates the bill. Reverse toward Fargate the moment cold starts, long job durations, or persistent connections start hurting. Decision for Pulsely: Fargate for the API and the reminder/summary workers (steady, connection-heavy, latency-sensitive); Lambda only for the S3-triggered document-thumbnail/PDF job (spiky, stateless, short).
Fargate vs EC2. Fargate removes host ops at a per-vCPU premium; EC2 with reserved or spot instances wins at large steady scale or when you need special hardware. Reverse to EC2 when bin-packing savings at scale exceed the operational cost you'd take back on.
Aurora vs DynamoDB (ADR decision 2 — Pulsely core data). Aurora (relational) fits Pulsely's core: patients, encounters, appointment slots, claims — entities with joins, transactions, referential integrity, and ad-hoc queries you can't predict at design time (every new clinical report is an unplanned query). DynamoDB fits known-access-pattern, hyper-scale, key-value workloads — a session store, or alert/notification fan-out state — where you trade query flexibility for predictable single-digit-millisecond latency at any scale. Reverse toward relational when access patterns are still evolving (you can't design Dynamo keys for queries you haven't invented). Reverse toward DynamoDB only when you've genuinely outgrown a single writer. Decision for Pulsely: Aurora PostgreSQL for the relational clinical and billing core; DynamoDB held in reserve for a session/alert-state store if and when scale demands it — not adopted speculatively.
MSK vs SQS/SNS. MSK (Kafka) when you need a durable, replayable, multi-consumer log — and accept the operational weight (or pay for serverless MSK). SQS/SNS when you want managed, near-zero-ops point-to-point or fan-out and don't need replay or ordering. Reverse toward SQS/SNS whenever "replay" and "strict ordering" aren't actual requirements — most job queues aren't, and the ops savings are large. Decision for Pulsely: MSK for the replayable event log (patient-timeline fan-out, clinical search indexing); SQS for fire-and-forget jobs.
Managed vs self-run. RDS and MSK cost more than rolling Postgres or Kafka yourself on EC2 — but the premium buys back failover, patching, and backups. The senior call is recognizing when not paying it is a false economy: a two-person team self-operating a Kafka cluster is usually spending engineer-weeks to save dollars — weeks better spent on the clinical product.
🚫 A framing this book rejects. "We're cloud-native because we use Lambda and DynamoDB for everything." Picking the most-managed, most-serverless option reflexively is not architecture — it's cargo-culting the marketing. Lambda for a connection-heavy steady API invites cold starts and pool exhaustion; DynamoDB for an evolving clinical model forces you to know your queries before you've written the product. Fit the primitive to the workload's shape — traffic profile, connection model, query predictability, replay needs — not to which service sounds most modern.
8. Security & scale notes
The threat surface the cloud introduces. The IAM control plane is now the crown jewel: a compromised privileged role is worse than any single host compromise, because it can rewrite the perimeter itself. Watch three classic holes. Public S3 buckets and over-broad bucket policies leak data wholesale — the most common cloud headline, and with PHI inside, a reportable breach. SSRF reaching the metadata service lets an app-layer bug coax IMDS into handing over the task role's credentials; IMDSv2's session requirement and a hop-limit of 1 are the defenses. And secrets in env or logs — a DATABASE_URL printed into a CloudWatch log is a credential leak with a retention policy. A related healthcare-specific sin: PHI in logs. A patient name or MRN dumped into an application log has just widened the PHI boundary to your whole logging pipeline; scrub at the source.
Defense in depth, layered behind identity. Org-level Service Control Policies and permission boundaries cap what any role can be granted; per-service scoped roles enforce least privilege; security groups are the network allow-list; KMS encrypts at rest; TLS encrypts in transit; VPC isolation keeps the PHI tier off the internet entirely. No single layer is trusted alone — which is exactly the posture a HIPAA audit expects you to be able to describe.
📎 Borrowed on credit: the crypto & authz foundations. Why envelope encryption and key-access control work, and the authorization model behind least-privilege roles and minimum-necessary access, are Ch 31 and Ch 32. AWS is where you apply them: KMS is envelope encryption, IAM is policy-based authorization, both as managed services.
Behavior under load — where the real ceiling hides. ALB + Fargate target-tracking scales the compute tier smoothly, which is exactly how teams get surprised: the bottleneck migrates to Aurora's connection ceiling. The arithmetic is worth doing concretely, because it's the surprise that pages you. Say each Fargate task runs a pool of 20 connections, and target-tracking scales you to 60 tasks under an intake spike: that's 60 × 20 = 1,200 connections demanded — but an Aurora db.r6g.large caps max_connections near ~1,000, so autoscaling the compute tier walks the system straight into FATAL: too many connections and every new task fails to connect at the worst possible moment. The compute tier scaled; the data tier couldn't, and the two weren't coordinated. The fixes are stacked, not either/or: RDS Proxy sits between tasks and Aurora and multiplexes hundreds of client connections onto a small set of real backend connections (so 1,200 app-side becomes ~100 DB-side); read replicas move read traffic off the writer entirely; and ElastiCache sheds the read load before it ever reaches the database. Meanwhile SQS acts as a shock absorber: a traffic spike piles into the queue and workers drain it at their sustainable rate instead of toppling, turning a spike into a backlog. And MSK's partition count caps consumer parallelism — you cannot have more active consumers in a group than partitions, so partition count is a scaling decision you make up front. The pattern across all three: in the cloud you scale one tier with a slider, and the ceiling silently relocates to the tier you didn't scale.
🔑 Cost is a senior responsibility you operate, not a finance problem you ignore. Read the bill by tag and by service (Cost Explorer). The usual offenders are predictable: NAT data transfer, idle Fargate, over-provisioned Aurora, cross-AZ traffic, and orphaned EBS volumes and snapshots. The levers are equally concrete: Savings Plans for steady compute, Spot for stateless workers, S3 lifecycle / Intelligent-Tiering for cold media (old scanned documents), right-sizing tasks. The discipline that ties it together: set budgets and alarms so a cost regression pages someone the same way a latency regression does. A bill that doubles silently is an incident you didn't instrument.
This is one face of the Well-Architected lens — AWS's framework of six pillars (operational excellence, security, reliability, performance efficiency, cost optimization, sustainability). You don't need to recite it; you need to use it as a review checklist before you call a design done: Is it secure (least privilege, encrypted, PHI off the public net)? Reliable (multi-AZ)? Performant (right primitives)? Cost-optimal (no idle, no NAT waste)? If a pillar's question makes you wince, you've found your next ticket.
9. Interview lens & exercises
Interview questions
Cloud interviews separate "I clicked through a tutorial" from "I reason about failure domains, identity, and cost." The same question reveals the level.
"EC2, ECS/Fargate, or Lambda for this service — how do you decide?"
- Junior answer: names features — "Lambda is serverless, Fargate runs containers." Correct and useless.
- Senior answer: narrates the axes — traffic shape (steady vs spiky), connection model (persistent pool vs none), cold-start tolerance, job duration, and ops cost — places the service, and crucially states when they'd reverse it. "Fargate for the steady connection-heavy API; Lambda for the spiky S3-triggered document render; I'd move the API to Lambda only if it went mostly-idle, and I'd never put the connection pool on Lambda without RDS Proxy."
"Walk me through what happens when a request hits your app in a VPC."
- Junior: "the ALB sends it to the app."
- Senior: traces it — Route 53, ALB in a public subnet terminating TLS, target group to Fargate in a private app subnet, security groups gating each hop, the PHI data tier in a private subnet with no internet route, and egress via VPC endpoint vs NAT. The same per-hop annotation discipline as the request spine, now in cloud topology.
"How do you give a Fargate task access to one S3 bucket and nothing else?"
- Junior: reaches for access keys in an env var.
- Senior: a scoped task role with a policy granting
s3:GetObject/PutObjecton that bucket's ARN only, vended as short-lived STS credentials with zero static secrets — and explains why the role, not the key, is the answer.
"SQS gives at-least-once delivery — what does that force in your consumer?"
- Junior: assumes exactly-once and is surprised by duplicates.
- Senior: idempotency keys, a dedup store, visibility timeout tuned above handler P99, and a DLQ for poison messages — the consumer is designed for redelivery, not hoping to avoid it. On a clinical queue that discipline is what stops a redelivered job from filing a second medication order.
"Your AWS bill doubled this month — how do you find out why?"
- Junior: shrugs, or "ask AWS."
- Senior: Cost Explorer grouped by tag and service, names the likely culprits (NAT transfer, cross-AZ, idle Fargate, orphaned snapshots), fixes the driver, and adds a budget alarm so the next regression pages instead of surprising.
Exercises & the Pulsely increment
Do these by hand in the console first (to learn the moving parts), knowing the next chapter will replace every click with code.
-
Build the Pulsely topology. A VPC with 3 subnet tiers across 2 AZs; the API and a worker as Fargate services behind an ALB; Aurora PostgreSQL Multi-AZ + ElastiCache; an S3 bucket for scanned documents with SSE-KMS and Block Public Access on; an SQS reminder/PDF queue with a DLQ; an MSK topic for the patient-timeline event log. Draw the security-group arrows (ALB→app→data) before you build, and verify the PHI data tier has no internet route.
-
IAM least-privilege drill. Start the API's task role at
Action: *, Resource: *. Run the app, capture the real API calls from CloudTrail, and iteratively tighten the policy until only the exact S3, Secrets Manager, SQS, and KMS actions Pulsely uses remain. Diff the before/after — that diff is your blast-radius reduction, and on a PHI account it's the difference between a scoped incident and a reportable breach. -
Write the ADR. Document both decisions — ECS-vs-Lambda (compute) and Aurora-vs-DynamoDB plus MSK-vs-SQS (data) — in the standard form: context, options considered, decision, consequences, and the explicit condition that would reverse each. The reversal condition is the part juniors omit and the part that proves you understood the tradeoff.
-
FinOps audit. Tag every Pulsely resource, generate a cost breakdown by tag, identify the top three drivers (bet on NAT, Aurora, and idle Fargate), and propose one concrete saving per driver with the tradeoff it carries (e.g. "Spot for stateless workers — saves ~60%, costs occasional interruption the SQS backlog absorbs").
Key takeaways
- The cloud is someone else's computers exposed as APIs you compose — which is why infrastructure becomes code and why the bill becomes a runtime concern. For PHI, a BAA and HIPAA-eligible services are a hard filter on which of those APIs you're allowed to compose.
- Place every service on three axes — compute, state, glue — and place responsibility on the shared-responsibility line that slides left as you go EC2 → Fargate → Lambda. Authorization never crosses it: it's always yours, and a broken check is a reportable breach.
- Failure domains nest (Region ⊃ AZ ⊃ task); the HA invariant is replicate state and spread compute across ≥2 AZs or you have no high availability.
- Identity is the perimeter. IAM is principal × action × resource × condition; roles are assumed for short-lived credentials, never logged into with static keys — the single biggest source of cloud breaches; least privilege is the cloud face of minimum-necessary access.
- The VPC isolates tiers: ALB in public subnets, app in private, PHI data tier with no internet route; security groups are stateful allow-lists; buckets are SSE-KMS with public access blocked.
- Delivery is at-least-once — consumers must be idempotent (a duplicate is a duplicate order, not a cosmetic bug); choose MSK for replayable logs, SQS for fire-and-forget jobs; Aurora for the relational core, DynamoDB for known-pattern hyper-scale; Fargate for steady services, Lambda for spiky events — and know what would reverse each.
- Cost, observability, and the immutable audit log are senior responsibilities you operate — CloudWatch as the managed default, a separate append-only trail that records every chart view, budgets and alarms that page like latency alarms, and a Well-Architected pass before you call a design done.
← Previous: Ch 36 — Containers & the 12-Factor App · Up: Part VII overview · Master TOC · Next: Ch 38 — CI/CD, IaC & Deployment Strategies →