The 3 AM Extinction Event. Designing AWS for the Bump in the Night. Is it a bug, a bill, or a breach? A glowing blueprint of stacked cloud layers labeled storage, load balancing, gateway, database and security, with arrows looping between them.

12 Things You Should (and Shouldn't) Do in AWS, a Visual Guide

TL;DR: Most AWS disasters aren't exotic. They're a leaked access key, a wildcard permission, a public S3 bucket or a database the internet can reach, each one a convenient choice somebody made on a quiet afternoon. The fixes are mostly boring: Docker images instead of hand-tuned servers, infrastructure as code, IAM roles instead of keys, private subnets and tight security groups, CloudFront in front of S3, and an eye on the bill. The last piece you can't configure at all: practicing the incident before it happens.

Your site is down. It's 3 a.m. Is it a bug, a bill, or a breach? You can't tell yet, and everyone is watching you find out. Michael Kennedy, host of Talk Python, has woken up to outages more than once. He thinks his deployments and applications got better because of them, but in the moment he also "aged faster than normal."

The uncomfortable part is that nearly everything you wish you had in that moment gets decided months earlier, on ordinary afternoons, when someone chose the convenient thing. Widen a permission to unblock a deploy. SSH into a server and tweak it by hand. Leave a database reachable from the internet because it makes local debugging easier. None of those feels dangerous when you do it.

Matt Lea has spent about 15 years as the person companies call when it goes wrong, and runs Schematical, a small consulting agency that specializes in AWS. Its tagline sums up the job: "we help CTOs running on AWS sleep at night."

So which afternoons matter most? This guide works through the list. It starts with servers you can throw away and rebuild, and with infrastructure as code. Identity comes next (IAM roles, and why the asterisk is your enemy), then the network - subnets, security groups and getting in without a bastion. After that it's S3, CloudFront and WAF at the edge, AI agents and your data, and finally logs and the bill.

It ends with Cloud War Games, where outages are staged on purpose so a team's first real incident isn't their first incident.

Listen to the full episode

Why AWS outages are decided months before 3am

The War Room Blueprint. Tuesday, 2:00 PM: a developer adds an asterisk to a permissions block to unblock a deploy. Sunday, 3:00 AM: a server rack explodes and the entire production environment is deleted. Incident response is not a skill deployed in the moment; it is a bill that comes due for decisions made when nothing was on fire.

Picture two moments. On a Tuesday afternoon, a developer has been fighting a permissions error for an hour and widens a policy so the deploy goes through. On a Sunday at 3 a.m., production is in trouble and nobody can say why. They look like two separate events, but they're the same decision, just with a few months in between.

That's the thread through nearly every AWS do and don't. Incident response isn't a skill you summon in the moment, because what you can do at 3 a.m. is limited by what you set up earlier. A wildcard permission gets its own section. So do the other usual suspects: a server nobody can rebuild, a key sitting in a repo, a database the internet can reach, a bill nobody is watching. Each one is a convenient choice with a delayed invoice.

Why does the bad night always come as a surprise? Because the weak link is often not the one you were watching. Black Friday is the classic case. It's a huge retail day, and for an e-commerce site the first big year can look a lot like "we'll be fine." The unglamorous answer is a routine: check in ahead of the day, make sure everything is provisioned, and have a plan for what happens if you suddenly need to double in scale.

Even that doesn't cover everything. Michael Kennedy has never had a site go down on Black Friday, but he has come close, and not for the reason he expected. One time an extra large JavaScript file, served and gzipped by Nginx, almost took the site down. He hadn't expected a big JavaScript file to be the weak link, and that's how it caught him off guard.

Is there a way to learn this without the outages? Simulation is one. Cloud War Games runs simulated outages, and it gets its own section at the end of this guide. Everything in between is the other half: the choices you can make on a calm Tuesday so the Sunday never comes, or at least goes better when it does.

“everything you want in that moment gets decided months earlier, on ordinary afternoons, when someone chose the convenient thing.”

Michael Kennedy

Cattle, not puppies: replacing hand-tuned EC2 servers with Docker images

Stop nursing EC2 instances. Build cattle, not puppies. A developer's tangled SSH lines reach three cracked, bandaged servers: hand-tuned, irreplaceable. Below, a Docker press stamps identical containers onto a conveyor: defined by Dockerfile, instantly replaceable. Setup commands cannot live in one person's head. Use ECS or Lambda.

Servers should be interchangeable cattle, not puppies you nurse. A puppy is the EC2 instance (a plain virtual server) that someone booted, SSHed into and tuned until it was absolutely perfect. Then it gets sick or dies, and the team is left asking how it was set up and which scripts ran. On EC2, SSHing in and customizing things is just way too easy at first, which is exactly why it's tempting.

Cattle are built from an image. A Docker image works like building your OS and saving it to a disk you can pop in any time to boot the exact same machine. The recipe is a Dockerfile, which Docker's docs describe as a text document of all the commands you could call on the command line to assemble an image. If you had to delete your servers 10 times a day, you could bring them back exactly as they were when they first started taking traffic, in a split second.

FROM python:3-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["python", "app.py"]

Add a .dockerignore file that lists .env, so COPY . . never copies keys into the image. Read the file as the commands you would have typed into the server anyway. RUN is the install step, COPY puts your code in, and CMD is what starts when a container boots. The difference is that the commands live in a file you can read, review and rebuild from.

On AWS, images run on ECS, the Elastic Container Service, which AWS describes as a fully managed container orchestration service for deploying, managing and scaling containerized applications. Lambda is the other cattle option. It feels a lot like Docker but isn't actually Docker underneath. Both make autoscaling work: two containers in the middle of the night, 100 the day after Thanksgiving, without anyone logging in.

Is it always worth it? Not necessarily. A startup moving fast, where uptime and reliability aren't the issue, can skip it. The case for images gets stronger once downtime costs real money, because the setup can't live in one person's head.

What about Kubernetes? One developer's rule of thumb, relayed secondhand, is that Kubernetes on anything but GCP is a poor fit. AWS has EKS, the Elastic Kubernetes Service, and some teams do well with it. Matt Lea has been asked more than once to move clients from EKS to ECS, which is more AWS native, though he's clear Kubernetes isn't his expertise.

You can also run containers yourself, on EC2 or any Linux server, with Docker Compose. Tools like Coolify sit on top: point them at a server, they install a small agent, and they manage the Docker side of self-hosted apps. The business questions still decide it. What if someone kicks the power plug, and how many engineering hours will it take versus a managed service? Even a setup that manages itself is still a bit of a puppy, because backups are yours, and so is a bad upgrade that corrupts the database.

“If you're a company that goes down and loses a hundred thousand dollars an hour and you don't have the setup commands documented or your lead tech gets hit by a bus, quote unquote, you want that Docker file to be clear as day.”

Matt Lea

Infrastructure as code on AWS: Terraform, OpenTofu and reading the plan

Layer 1: Foundation. Never click, only code. Clicking in the AWS console ends in: who changed this setting? A .tf file flows through CodePipeline, CodeBuild and ECR to a checkmark. Infrastructure as code (Terraform, CloudFormation). Always read the plan before you apply: an AI-coded database rename makes Terraform delete the production DB.

You already keep application code in version control instead of FTPing it to a server and hoping it doesn't disappear. Servers, databases, roles and firewall rules deserve the same treatment. Infrastructure as code (IaC) is the category, and the tools are Terraform, OpenTofu and CloudFormation, which is AWS's own proprietary one. OpenTofu's docs describe it as a tool that lets you define cloud and on-prem resources in human-readable configuration files. CloudFormation's docs describe a template that lists the AWS resources you want, from which CloudFormation provisions and configures them.

The idea is the same across all three. You describe what you want in code, say an EC2 instance and a MySQL database at a specific version, commit it, and apply. It's almost crazy what can be defined: every user role, every access key, every firewall rule, the way a VPC (a virtual private cloud) lays out its subnets. If someone accidentally deletes the application layer, re-running apply provisions the missing pieces. What it can't define as easily is what's inside the box.

Start early, because it's very difficult to get into later. Once everything is hand-spun, the questions become: how did I do that again, and what did the person who left the company set up? Moving from one setup to another turns into a research project.

The catch is that Terraform does exactly what you tell it. Plenty of teams auto-apply changes without reading them, and a slight rename of a database can turn into a delete and replace. So the rule is to always know what you're about to send, and make sure it's an update, not a delete and replace. Terraform's plan step is where you check:

terraform plan -out=tfplan
terraform apply tfplan

terraform plan previews the changes without making them. -out saves the plan to a file, and passing that file to terraform apply runs exactly what you reviewed. Terraform's docs also describe prevent_destroy, a lifecycle setting that makes Terraform reject any plan that would destroy that resource. The docs suggest using it sparingly, for costly resources such as databases.

resource "aws_db_instance" "example" {
  # ...

  lifecycle {
    prevent_destroy = true
  }
}

The same hazard shows up with AI agents, in a case Matt Lea wrote up but didn't live through. Someone had an AI vibe code a change that renamed a production database, and Terraform deleted it and spun up a new one. A common agent failure looks like this: an insert fails because the structure is wrong, so the agent decides to just recreate the database. That technically solves the problem, and it's also not acceptable.

Does the application code go through Terraform too? Not in this approach. Terraform spins up a separate build pipeline instead. AWS CodePipeline is the orchestration layer that listens for a commit and sequences the steps. CodeBuild runs your Docker build in the cloud and pushes the image to ECR, the Elastic Container Registry, where images are stored, and then CodePipeline handles the deploy. Database migrations and automated tests can run there too, though it's fine to be looser about that when you're just starting. Why AWS's own tools instead of something else? The same granular IAM roles secure the whole thing, without two different things in the mix.

“Somebody had their AI vibe code this thing, and it wanted to rename the database. Well, then what happens is Terraform deleted the database and then spun up another database right there. That was their production database.”

Matt Lea

IAM roles vs access keys: assume a leaked AWS key is gone immediately

Layer 2: Identity. The death of the access key. A .env commit to GitHub, the shhgit scanner, then 16,000,000: a junior's email access key in a public repo becomes 16 million knockoff Viagra emails before AWS shuts the account down. Uncommitting is not a remediation. Assign granular IAM roles to the service (EC2, Lambda) instead.

IAM is Identity and Access Management, how you define the way your users, and the services you run, interact with AWS. Most people start the same way: download their first access keys, put them in a nice .env file and hope for the best. Beginners pushing to production sometimes ship that .env file right along with the code. A key is a long-lived secret, and anything that can read it can act as you.

Here's how that can go. A junior developer pushed access keys for sending email to a public repo on GitHub, and some bad guys got them. Luckily, the keys were only for sending and receiving email. Even so, as it was recalled, roughly 16 million emails for some type of knockoff Viagra went out in about eight minutes before AWS shut down the account.

How fast does somebody find a key like that? shhgit, a site that is no longer running, watched the real-time firehose of changes on GitHub, pulled out anything that looked cryptographic, AWS keys and email keys included, and streamed the finds live, updating roughly once a second. It's a good thing to show anyone who says "I can just uncommit it" because it's not a very popular repo anyway.

The fix is roles. AWS's docs describe an IAM role as an identity with permissions that, unlike a user, has no standard long-term credentials such as a password or access keys. Whoever assumes the role receives temporary security credentials for the session. IAM has users and groups too, but roles are what you assign to the services you boot up: a role for an EC2 instance, a role for a Lambda.

A Lambda function's role is called its execution role, and Lambda assumes it automatically when the function runs. The role carries a trust policy naming who may assume it. For Lambda, the service principal is lambda.amazonaws.com:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "lambda.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}

That policy only says who can use the role. What the role can do comes from separate permission policies, so you can say this Lambda may reach one specific S3 bucket, and nothing in the code needs a key. AWS's docs do note that some workloads can't use roles, such as third-party clients running outside AWS, and long-term keys remain the fallback there.

IAM stops at a boundary. It's service level, not network level (that's security groups, in the network section). It answers questions like: can this instance boot up other instances? Can this Lambda trigger other Lambdas? It doesn't decide which rows in your database a query can see.

Short-lived credentials push the same idea further. The abstract of a PyCon talk, Zero Trust in 200 Milliseconds, describes a separate key of roughly 200 milliseconds for each API call or transaction, an idea used in parts of the US government's FedRAMP cloud program. The practical questions are how long it takes to provision that key and what it costs in latency. Government latency limits are probably a lot looser than those of an e-commerce site competing on speed.

“If it's up there, you should assume it's gone immediately.”

Michael Kennedy

Least privilege in AWS IAM: why the wildcard is your enemy

The wildcard is the enemy of Least Privilege. Fatigue + { Resource: * } = Extinction Event. The realistic path to a wildcard is fatigue: an hour fighting a permissions error, then an asterisk to unblock the deploy. Granular permissions separate a minor incident from a company-ending one. Scope down to the exact path inside an S3 bucket.

An IAM policy is a JSON document that says which actions a principal may take on which resources. The two fields that matter most are Action and Resource, and each one accepts an asterisk. That is where least privilege goes wrong. Go back to the leaked email key from the access keys section: if its policy had said "let it do anything on any service," the attacker could have deleted everything in a second.

Nobody adds a wildcard to be reckless. It's fatigue. An hour of banging your head against a permissions error ends with "we're just going to let them access all the S3 buckets," and a couple of months later someone has your internal reporting. Here is the mistake (do not use this) next to the fix:

{
  "Version": "2012-10-17",
  "Statement": [
    { "Effect": "Allow", "Action": "s3:*", "Resource": "*" }
  ]
}

s3:* is every S3 permission, including deleting the bucket, and a Resource of * is every bucket in the account. The scoped version names the one action and the one place:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "s3:PutObject",
      "Resource": "arn:aws:s3:::amzn-s3-demo-bucket1/uploads/*"
    }
  ]
}

Both halves matter. With 20 buckets, list only the ones you write to, and if you want you can go all the way down to a path inside the bucket, as the uploads/* prefix does here.

Need a wildcard for 10 seconds to find out whether permissions are even the problem? That is one thing, but don't commit it. If you poke a hole while experimenting, version control and Terraform should wipe it out the moment you're done, and keep it out of production.

Doesn't AI make this easier? Granular permissions used to mean a wall of allow and disallow boxes, and now you can describe what needs to talk to what. It depends. Tell an agent you just need this to talk to that, and it can get there by putting the asterisk in. It met the goal, just not the way you'd want. Telling it that least privilege is its primary goal is worth a try, and so is a second, more skeptical agent doing a peer review ("is there any possible way to break this?"), since a single agent will sometimes just say it did it. Either way you still have to know what good looks like: what a cross-site scripting or injection attack is, for a start, and whether the policy that came back is really scoped.

“The asterisk is your enemy. Basically S3 colon asterisk gives you all S3 permissions.”

Matt Lea

Public vs private subnets and security groups in an AWS VPC

Layer 3: Network. The myth of the flat subnet. An npm supply chain hack spreads to every server in a flat network, but is stopped by a firewall in nested public (load balancers), worker and private (production databases) subnets. One security group for everything is a flat network with extra steps. Private subnets leave no network path to your data.

Does your database need to be open on the internet? Probably not. It's convenient, because everyone wants to hit the database from a laptop, but you can still do that through a bastion or something better (see the next section).

Start with the layout. A virtual private cloud (VPC) is your own slice of network inside an AWS account, and you carve it into subnets. Each subnet lives entirely inside one availability zone, and each availability zone has its own independent power supply, so spreading subnets across several is what gives you redundancy. One big subnet in one zone in one region is not redundancy. Zones go down fairly frequently, and you only fail to notice when you use more than one. Whether a subnet is public or private comes down to routing: a public subnet has a direct route to an internet gateway, a private one doesn't. The AWS docs recommend private subnets for protecting resources.

The layout that works keeps only what must face the world in the public subnet, typically the load balancer, which passes traffic on to instances in each zone. Databases and anything secure go in a private subnet. Can't you just firewall a public database? You can, but it's easy to poke a hole in a firewall when it's convenient, and audits keep finding things like port 22 open to traffic from anywhere. Say someone installs the wrong game, it grabs their SSH keys, and the whole world was allowed in on that port. With the database in a private subnet there's still no network path from point A to point B.

Security groups are the firewall layer: each rule says which sources may reach a resource on which port, and they're stateful. Give the Lambda or app servers one group and the database another, then let the database accept traffic only from the app group:

aws ec2 authorize-security-group-ingress \
    --group-id sg-1234567890abcdef0 \
    --protocol tcp \
    --port 5432 \
    --source-group sg-1a2b3c4d

The anti-pattern is one big group where anything in it can talk to anything else on any port. That's a flat network with extra steps, and it enables lateral movement: once an attacker gets a foothold, where else can they go? If a malicious npm package lands in the application layer, it can reach the database anyway. But with groups and subnets set up right, a compromise in test can't reach production, and it can't crawl every IP in the subnet.

Outbound rules are the half most people skip. Limit where a box can talk out to, say only the IP of one third-party API vendor, and it can't reach somewhere overseas you don't know about. As a day-one beginner it may not be worth the bother. As a big company, it is.

“Well, now they still can't get to it because there's not actually a network path that would go from point A to point B.”

Matt Lea

SSM Session Manager vs a bastion host for private AWS access

Access Management: Kill the Bastion Host. Tuesday shortcut: a 24/7 bastion host with port 22 open and a clipboard of crossed-out IP addresses to keep allowlisted. 3 AM blueprint: AWS Systems Manager (SSM) Session Manager, with IAM authentication into a private shell. No SSH keys, no open doors, no 24/7 idle EC2 costs.

If your database lives in a private subnet, how do you get to it? The classic answer is a bastion: a small server in a public subnet, ideally locked down by a security group that accepts port 22 only from your own IP address. You SSH into it, and it becomes the door to everything else, including port forwarding so local development can reach the test database. The costs are an instance running 24/7 just to be a door, and an allowlist you have to update every time your IP changes.

AWS Systems Manager (SSM) Session Manager is the newer option. You get a shell on an instance by authenticating with IAM, which is much more secure, and you don't pay to run an EC2 instance 24/7 as a bastion. The alternative on EC2 is putting an SSH key on the box so you can get in and hand-tune it. The advice is short: use Session Manager instead of the bastion, if you can.

From the AWS CLI, a session is one command. You need the Session Manager plugin on your machine and SSM Agent on the instance, per the setup steps in the docs:

aws ssm start-session --target i-0123456789abcdef0

For local development against a private database, forward a port to a remote host through the instance. The remote host doesn't have to be managed by Systems Manager, and the docs require SSM Agent 3.1.1374.0 or later on the instance:

aws ssm start-session \
    --target i-0123456789abcdef0 \
    --document-name AWS-StartPortForwardingSessionToRemoteHost \
    --parameters '{"host":["mydb.example.us-east-2.rds.amazonaws.com"],"portNumber":["3306"],"localPortNumber":["3306"]}'

One trade-off from the docs: session logging isn't available for sessions that connect through port forwarding or SSH.

Two ideas from outside AWS cover the same problem. An overlay network like Tailscale is another option: it can put your people on a private network that reaches the database server and nothing else. KnocKnoc takes the opposite approach: management ports are blocked 100% for every IP, you authenticate somewhere else, and the port opens just for your IP address for the length of that session.

That second idea sparked a feature request: durations on security group rules. You'd open a port to debug something, and it would shut itself back off without anyone having to remember, which fails safe.

“That's actually a good feature request for AWS to have durations on their security group rules. So you say I only want to do this for an hour.”

Matt Lea

Private S3 buckets with CloudFront and signed URLs

Layer 4: Storage and Edge. S3 is storage, not a CDN. Path A: a user goes straight to a public-read S3 bucket: vulnerable, expensive, enumeratable. Path B: a user goes through CloudFront (CDN) and a 2-minute signed URL to a private S3 bucket. Never make S3 public; use short-lived signed URLs for exactly one file.

Audits of AWS accounts keep turning up something in S3 that's not supposed to be public. Often it's something like sales numbers you don't want a competitor to have.

Here's how it happens. During a short assessment of one system, a client said certain binary files absolutely couldn't be public, because it would be big trouble if anybody got them. Sure enough, the bucket was public to anybody on the planet. Listing was off, so crawling it would have been tough, but the file naming pattern wasn't random enough to stop someone brute forcing and enumerating the files.

Security is one reason to fix this, and cost is the other. S3 is storage, and it isn't a CDN. Serving lots of files fast straight from it isn't cost effective (the quote below says it plainly). CloudFront, AWS's CDN, is optimized for high volumes of binary files or assets like JavaScript, so the right shape is a private bucket with CloudFront in front of it.

When you need to lock access down, use signed URLs on the CloudFront side. A signed URL carries a policy, and the policy can say how long it's valid: you can set an expiration, down to a few minutes, and the signed URL then goes to exactly this one file. CloudFront verifies the signature against a public key in a trusted key group on your distribution, and your app holds the private key. A canned policy covers one resource with an expiry. A custom policy can add a start time or an allowed IP range.

Uploads follow the same idea, with a presigned URL straight to S3. You choose how long it lasts, five minutes, two minutes, 30 seconds, and the upload has to finish inside that window. With boto3:

import boto3
from botocore.config import Config

s3 = boto3.client('s3', config=Config(signature_version='s3v4'))

url = s3.generate_presigned_url(
    ClientMethod='put_object',
    Params={'Bucket': 'amzn-s3-demo-bucket1', 'Key': 'uploads/report.pdf'},
    ExpiresIn=120,  # seconds; the default is 3600
    HttpMethod='PUT',
)

The browser then sends an HTTP PUT of the file bytes to that URL, and your app never touches the upload. Signing with Signature Version 4 is what the boto3 docs recommend. If you sign with a role's temporary credentials, the URL stops working when those credentials expire, even if ExpiresIn is longer.

“S3 is a wonderful binary storage. It is not a CDN. It is not cost effective to serve up things at mass very fast through that.”

Matt Lea

Stopping DDoS attacks and bots with AWS WAF, cheap rules first

Edge Defense: Exhaust the blunt instruments first. A funnel: blunt instruments (instant, cheap) like banning /wp-admin requests on non-WordPress sites and geo-blocking; invisible challenges (cost-effective) like Cloudflare Turnstile or JavaScript challenges instead of CAPTCHAs; heavy ML models (expensive). Use AWS WAF to drop obvious bad traffic at the edge.

Once you get to the big league, attacks come from the front, with phishing from the side and the back. DDoS attacks are everywhere: a big one at a large customer recently drew almost three times normal traffic. On AWS, one tool for this is WAF, the web application firewall. It inspects HTTP(S) requests headed for a protected resource, such as a CloudFront distribution or an Application Load Balancer, and decides whether the request gets the content, a 403 or a custom response, based on rules you write. It works at the HTTP layer, so it is not a cure-all for volumetric network-level floods, which AWS handles with a separate service, Shield.

The cost point decides how to spend it. Tools that do fancy analytical work on every request can work, but at volume they aren't the most cost effective: running each request through a model adds up (see the quote below). So exhaust the cheap, obvious rules first:

  • Known-bad paths. A request looking for the WordPress admin when you don't run WordPress is an instant ban, not a judgment call.
  • Rate limiting. A rate-based rule counts requests grouped by criteria you choose and limits the groups that come in too fast. A scope-down statement narrows it to a particular route.
  • Packaged rules. A lot of this already comes packaged, so you don't always need the smartest model to decide. If the URL is something that shouldn't be there, you know it.

For bots, WAF offers two actions beyond block. A Challenge runs a JavaScript script in the browser, and the user won't really notice it. CAPTCHA puts a puzzle in front of the person and costs more, and per the AWS docs both actions carry additional fees. Both have a time and a place, so FinOps your way to how much you want to spend. Cloudflare's Turnstile is a non-AWS option, and Michael Kennedy has found it goes a long way toward keeping bots away without another round of find-the-fire-hydrants.

You can also block entire countries, though that's a blunt instrument. One client decided to block France, and the reaction was "I'm like, why? We can figure out this traffic."

“Every request that comes through, you're running through some AI model, it's going to add up real quick.”

Matt Lea

Keep AI agents out of your production database with a data lake

The Agentic Era: Keep AI out of the Production DB. The data lake stack: application events, Kinesis (Firehose), S3 (Parquet files), queried by Athena or Glue. An AI agent reads the data lake through a read-only tool call; its path to the production DB is walled off. An agent stuck in a loop can spam a complex query and slow production.

As executives get comfortable with AI agents, the requests start to sound alike: give me direct access to the database so I can pull the latest numbers myself. Handing an agent a production connection string is the wrong answer. Agents work in a narrow context and make mistakes now and then, and a mistake with write access hits the whole company.

A better shape is a tool call. Code up one that only reads, and route all AI access through it. You can observe everything that passes through, and through that tool the agent has no capability to destroy anything, as long as its credentials are read-only. If you also want writes, put them behind a second tool call that needs a human's approval, so the agent can suggest a change instead of making it.

There's a second layer worth adding: point that read tool at a data lake, not at the production database. Agents can spam like no tomorrow. A very complicated read query fired over and over could slow down a production database that isn't tuned for it. A data lake can be built without personally identifiable information, since the data is anonymized for big data analysis. Done right, even a leak of five years of sales data isn't a PII leak (quote below).

What does a data lake look like on AWS? Here's one stack:

  • Kinesis is a firehose-style queue, so many consumers can read the same stream. Whenever the application fires an event (a user was created, a sale was made), publish it there.
  • Firehose delivers those events to S3. It can convert JSON to Parquet, a columnar format commonly used to save space and speed up analytical queries, before it writes the files.
  • Athena queries the files in S3 with standard SQL, serverless, and you pay for the queries you run. Glue is another route and also involves Python. Firehose also uses a schema from the Glue Data Catalog to read your events.

S3 storage is extremely cheap, and there are good Python libraries that mount Parquet files on S3 and query them directly.

The same layout fixes an old habit: don't keep sales from 2003 in the production database. Move old data out and keep production lean and fast.

Two more picks for Python people. SageMaker is Python first and data science first, and it gives finer control over GPUs than basically any other service. For more generic AI work, Bedrock is a good fit, their Netflix for AI.

“Even if they leaked all your sales data for the last five years, at least you wouldn't have a PII leak, which would cost you even more.”

Matt Lea

CloudWatch, Cost Explorer and the real cost of AWS complexity

Layer 5: Telemetry. Managing complexity and runaway costs. A CloudWatch graph where autoscaling is triggered by queue message depth, not CPU, beside a Cost Explorer chart with a towering December spike. Insights queries over 5 years of logs run up a bill. Scale workers on queue depth, set budgets, tag QA vs. Prod, check Cost Explorer weekly.

The biggest surprise for teams moving to the cloud is probably the complexity. AWS has services for robotics, which won't matter if you run an e-commerce platform. The fix is to whittle AWS down to a few core services that meet your goals and get good with those. Just starting out, without a crazy amount of traffic? API Gateway plus Lambda is an extremely cheap serverless application layer. It's not a data layer, but it's a great start, and free Terraform scripts for it live at Schematical.

Once you leave the single server, your logs aren't one file on one machine. CloudWatch collects logs and metrics from your services in one place. ECS tasks and Lambdas send it everything you'd see from docker logs. The gap is a process that writes its own log file to disk, which you have to pipe out or ship with the AWS CLI or SDK.

CloudWatch Logs Insights queries all of it, and it's billed by how much log data a query scans. Point one at five years of logs and the bill will show it. So get the query right over a five minute range first, then widen it. Metrics cover CPU, memory and load balancer latency and volume. When latency spiked on some day, you zoom layer by layer down to a database short on swap or Redis evictions through the roof.

Alarms do more than page you. They can drive autoscaling. The default signal is CPU or memory, but a queue worker can scale on the count of messages in flight instead. That's often the better signal: an analytics job can pin the CPU without the service being busy, and more servers wouldn't help.

Then there's the bill. Among people griping about AWS, cost is pretty much the number one topic, and Cost Explorer is where you find out why a bill jumped. You switch between services, usage types and breakdowns until you land on the jump, then trace it to a specific resource. In March, a new past end of life fee for older database versions put some clients at about $4,000 a month with no idea why. Tags make the numbers readable: production, staging, microservice X, so you can say, for example, that QA is costing $20,000 a month. AWS Budgets lets you set a cost threshold and get an alert by email or SNS when actual or forecast spend crosses it, though notifications can lag the charges. A weekly look at the budget sheet is one way to spot a spike and ask what happened.

The cautionary tale comes from Vercel, not AWS: an artist's app for spotting AI-generated art hit something like number one on the App Store, and a $95,000 bill arrived in a couple of days. No upper bound was set, and the warning emails sat unanswered for something like three or four days. Sometimes spikes are amazing. Sometimes they're not.

“Get your queries figured out in the five minute range and then run them, you know, so you're not debugging query over and over again with a long date range.”

Matt Lea

Recap: the Tuesday shortcut and the safer default

The AWS Anti-Pattern Matrix. Tuesday shortcut (danger) vs 3 AM blueprint (secure standard): access keys in .env vs IAM roles; SSH via an always-on bastion vs SSM Session Manager; a public S3 bucket vs CloudFront plus signed URLs; one flat security group vs segmented VPCs with restricted outbound; click-ops in the console vs IaC (Terraform) plus PR review.

Every row in the table above is the same trade. The shortcut works today. The default takes a little more effort up front and saves you the bad night later.

  • Access keys in a .env file. Attach an IAM role to the service instead, so there's no long-term key to leak. See IAM roles vs access keys.
  • An always-on bastion. Session Manager gets you in with IAM authentication and no server idling around the clock. See Session Manager.
  • A public S3 bucket. Keep it private, put CloudFront in front and sign the URLs. See private S3 with CloudFront.
  • One flat security group. Separate groups and private subnets limit lateral movement, and outbound rules limit where a box can talk to. See subnets and security groups.
  • Clicking in the console. Keep infrastructure as code in version control, and read the plan before you apply. See infrastructure as code.

Nothing on this list is exotic. Every row is a choice somebody makes on an ordinary afternoon.

Recap: how the pieces fit into one AWS architecture

The Bulletproof Blueprint. Traffic flows through WAF and the CloudFront CDN to a load balancer in the public subnet, to ECS and Lambda workers (cattle) governed by IAM roles in a private compute subnet, then to secured RDS and an S3 Parquet data lake in a deep data subnet. A multi-AZ VPC, provisioned entirely via Terraform.

The table in the last section compared choices one at a time. The drawing above puts them together. Follow one request from the left, and most of this guide shows up along the way.

  • At the edge, WAF drops the obvious junk with cheap rules before anything expensive runs. See AWS WAF.
  • In the public subnet, only the load balancer. See subnets and security groups.
  • In private subnets, containers or Lambdas built from images, each acting with its own IAM role. See cattle, not puppies and least privilege.
  • Behind them, the database, with a separate data lake for analytics and AI agents. See the data lake.
  • Around all of it, multiple availability zones, defined in code. See infrastructure as code.

Is it bulletproof? No. Audits keep finding holes someone poked for convenience. What a layout like this does is make the easy path and the safer path line up, so nobody has to be disciplined at 3am.

Cloud War Games: practicing the 3am incident before it happens

You can configure everything in this guide and still lose the night. What you can't configure is how people react when the site is down. Nobody's calm at 3 a.m. The site is down, you scramble to find out why, and you wonder whether you did something wrong. In real incidents, junior engineers handed something to look at often freeze, even though they can explain the problem afterward.

That's the case for rehearsing. Cloud War Games runs simulated outages as a game of roughly 45 minutes, with the facilitator playing the junior who accidentally deletes something important. Most scenarios come from real incidents someone suffered through. Every game ends with a postmortem, and that habit carries over to real outages: run one every time, especially if people froze up. That's how a team learns.

Playing is simple. At the time of recording you could sign up for asynchronous challenges, one a week, completely free, though the format was still changing. Live games are being moved into the Schematical community and a Discord, with the aim that a game can start on the spot instead of waiting for a monthly schedule. Companies use it for training and for hiring. With AI-written resumes everywhere, putting a few candidates through a game shows who really knows their stuff, and who is a team player shouting out ideas instead of going heads down alone. The advanced scenario is a ransomware attack specific to AWS that can run from one command with the right privileges, and its details stay private.

The most common findings in audits are misconfigured IAM, misconfigured VPCs and public S3 buckets.

Not every scramble is an attack, though. An internal MongoDB TLS certificate set to expire after a year did exactly that for Michael Kennedy, and he couldn't remember the command he'd used or where anything was. A managed service of some kind would likely have handled it, probably for less than that night cost.

For the application half of security, Talk Python Training's Python Web Security: OWASP Top 10 with Agentic AI pairs well with this infrastructure advice. Python Web Apps that Fly with CDNs goes deeper on putting a CDN in front of your app, the same idea as CloudFront in the S3 section. And Agentic AI Programming for Python covers working with coding agents.

“You'd rather learn, you know, get the stress inoculation during a simulation, a 45-minute game, than at 3 a.m., you know, or when the entire board of directors is standing behind you because you're the guy that's supposed to fix it.”

Matt Lea

Talk Python's Mastodon Michael Kennedy's Mastodon