AWS Builder Center
When a flood alert is issued, serve one small emergency page on every URL: CloudFront KeyValueStore, a template, and an AI agent kept off the critical path

When a flood alert is issued, serve one small emergency page on every URL: CloudFront KeyValueStore, a template, and an AI agent kept off the critical path

When a flood alert is issued, the city website is needed most and loads worst. This tutorial builds a disaster mode on AWS: every URL switches to one small emergency page at the edge with a CloudFront Function and KeyValueStore. A page built by code from the city's data goes live first; a Strands agent on Bedrock AgentCore can only replace it with a page that passes the same checks. Covers late and retried alerts, measured switch times, cost, and a full deploy, verify and teardown path.

Platform Engineering Head | Startup CTO | Founder
It is 2 a.m. and the river through your city is rising. The city raises the flood alert to level 4: everyone in the flood zone must evacuate now. Within minutes, thousands of people open the city website on their phones to find out one thing: where do I go? The site was built for normal days, with a video header, photo carousels and web fonts, and on a congested mobile network it does not finish loading.
This is not hypothetical. Japan's five-level alert system for heavy rain and floods ( nippon.com ) tells people exactly when to evacuate, and that is exactly when they rush to the city website. Some cities prepare a "disaster mode" for this: Chiba City's site, for example, has an emergency mode that  switches the whole page to a simple display with only the important information , so that it keeps serving under heavy access. The switch is the easy part. Keeping that simple page filled is the hard part: during a 2019 typhoon, Tokyo school websites  switched to their lightweight versions automatically, but many schools had not put any information on them , so the information did not reach parents.
In this tutorial you build a disaster mode that does both, for a fictional city:
  • When an alert comes in, every URL on the site returns one small emergency page. The switch happens at the edge, with one key.
  • The page fills itself from the city's own data, so nobody has to remember to update it in the middle of the night.
  • Nothing goes live without passing checks: the right shelters for this hazard, the right phone numbers, nothing invented.
  • An old or retried alert can never roll the site back to a lower level.
  • The whole system can be deployed, tested and removed from your AWS account with a few commands.
There is also an AI agent in it, and the way it is used is the main design lesson of this article: the agent is never on the critical path. A page built by ordinary code goes live first. The agent can only replace it with a better page that passes the same checks, and if it fails, nobody notices.
The code is in  ikenyal/brownout  (Apache 2.0). The city, its shelters and its data are fictional.

What you will build

Architecture: the template page goes live first, the agent may replace it, and the edge reads one key on every request


Alert levels

The fictional city uses five levels modeled on Japan's system. A higher level is more urgent, so the page gets smaller and carries only what matters now. The city has two hazards, flood and earthquake, and which shelters are safe depends on the hazard. This tutorial follows a flood.
Level
Meaning
What the site shows
Page budget (gzip)
1
Stay informed
Full site
none
2
Check your evacuation route and shelter
Full site
none
3
Older people and others evacuate; everyone else gets ready
Light page
500 KB
4
Everyone in a hazard area evacuates now
Lighter page
50 KB
5
Disaster is happening; move to the safest place you can reach
Survival page
14 KB (fits in the first network round trip)
The budgets matter. In the project's load test (Chrome DevTools network emulation, cache disabled,  scripts/loadtest.py ), the 28 MB everyday site did not finish loading within 180 seconds on a congested 3G connection (400 kbit/s, 400 ms RTT) or on 2G (50 kbit/s, 500 ms RTT). The emergency pages finished in 0.5 s and 1.0 s.

How it works

  1. An alert is an EventBridge event:  {"hazard": "flood", "level": 4} .
  1. A small Lambda function passes it, with the event's timestamp, to a runtime on Amazon Bedrock AgentCore Runtime.
  1. The runtime builds the emergency page from the city data with ordinary code, checks it, publishes it to S3 and writes the new level to CloudFront KeyValueStore. The site has now switched.
  1. Then a Strands agent writes a more readable page from the same data. A hook called PublishGuard lets it publish only a page that passes the same checks. If it does, that page replaces the first one. If not, the first one stays.
  1. A CloudFront Function reads the level on every request and rewrites every URL to the page for that level.

Prerequisites

  • An AWS account where you can create CloudFront, S3, Lambda, EventBridge, IAM and AgentCore resources. Everything runs in  us-east-1 .
  • Amazon Nova 2 Lite in Amazon Bedrock. Since October 2025, Bedrock  enables serverless models by default , so there is nothing to request. Make sure no IAM policy or SCP in your account denies it.
  • Python 3.13 and  uv , Node.js (for  npx ), and the AWS CLI v2.
  • About 30 to 40 minutes: in my runs the distribution took about 3 minutes to deploy, the runtime 2 to 6, and the teardown 4 to 7.
git clone https://github.com/ikenyal/brownout.git && cd brownout
uv sync
export AWS_PROFILE=your-profile

Choosing where the switch lives

The requirements above decide the switch. It has to change every URL at once, work while the origin is under load, need no deployment at 2 a.m., and cost almost nothing on the 364 days a year when nothing happens. Here are the usual options against those requirements:
Option
Changes every URL at once
No deploy to switch
Notes
CloudFront invalidation
No
No
Clears cached objects, but the origin still has to serve different content
Route 53 failover to a second site
Yes
Yes
Depends on DNS TTLs and how long resolvers and phones keep the old answer
Lambda@Edge
Yes
Yes
Works, but it is a full Lambda runtime for what is one lookup and one path change
CloudFront Function + KeyValueStore
Yes
Yes
A small function on every request reads one key; changing the key changes the site
The last option fits best. A viewer-request CloudFront Function runs before CloudFront checks its cache, so changing the URI also changes the cache key ( CloudFront docs ), and KeyValueStore is built for exactly this kind of edge configuration ( launch post ). The trade-off is that the function can do nothing clever: it reads a key and picks a path. Everything else has to happen before the key is written.

Step 1: Deploy the edge

uv run python infra/deploy_infra.py
This idempotent script creates a private S3 bucket behind an Origin Access Control, a KeyValueStore, the CloudFront Function, and the distribution. It writes their IDs to  infra/outputs.json , and a least-privilege policy for the runtime to  infra/runtime-policy.json .
The function is the entire switch, so it is worth reading once. The part that matters most is what happens when the key cannot be read:
// infra/router.js, shortened (cloudfront-js-2.0, viewer request)
import cf from 'cloudfront';
const kvs = cf.kvs();

async function handler(event) {
const req = event.request;
let level = 1;
try {
level = parseInt(await kvs.get('level'), 10) || 1;
} catch (e) {
level = 1; // key missing or unreadable: normal mode
}
if (req.uri.startsWith('/level-') || req.uri.startsWith('/full/')) {
return req; // direct links, for testing
}
if (level >= 3) {
req.uri = '/level-' + level + '/index.html'; // every URL collapses to one page
} else {
req.uri = '/full' + (req.uri === '/' ? '/index.html' : req.uri);
}
return req;
}
If anything goes wrong with the key, the site falls back to the normal site, not to an error page.
Upload the normal site, set level 1, and wait for the distribution:
uv run python scripts/build_full_site.py # generates the heavy "normal" site (about 28 MB)
PYTHONPATH=. uv run python -c "from pathlib import Path; from brownout.edge import upload_dir, set_level; upload_dir(Path('site/full'), 'full'); set_level(1)"
aws cloudfront wait distribution-deployed --id <distribution_id from infra/outputs.json>
curl -sI https://<domain from infra/outputs.json>/ | head -1

Step 2: Build the emergency page from data

The emergency page is not written by hand during the emergency. It is built from two files that the city maintains in calm times:
  •  content/town.json : the facts. Shelters with their addresses and the hazards they are safe for, hotlines, water points, and the meaning of each alert level.
  •  content/must_have.json : the rules. For each hazard and level, which facts must be on the page, which must not, and the size budget. For a level 4 flood, for example, the four flood-safe shelters are required, and the two shelters that are only safe in an earthquake are forbidden.
 brownout/template.py  turns those two files into a page with ordinary code, and  brownout/facts.py  checks any page against the rules:
# brownout/template.py (shortened)
def template_page(hazard: str, level: int) -> str:
required = MUST[hazard][str(level)]["required"] # e.g. ["shelter:S1", "hotline:H1", ...]
alert = TOWN["alert_levels"][str(level)]
parts = [f"<h1>{escape(alert['label'])}</h1>", f"<p><strong>Action:</strong> {escape(alert['action'])}</p>"]
# ...one list each for the required hotlines, shelters (with their notes) and water points
return "\n".join(parts)
The checks in  check()  are deterministic: the gzipped size fits the level's budget, every required fact is present, no forbidden shelter appears, and no phone number, address or place name appears that is not in the city data. The template passes them by construction, and a test proves it for every hazard and level:
uv run python tests/test_template.py
flood level 3: ok, 632 bytes gzipped (budget 500000)
flood level 4: ok, 603 bytes gzipped (budget 50000)
flood level 5: ok, 497 bytes gzipped (budget 14000)
earthquake level 3: ok, 755 bytes gzipped (budget 500000)
earthquake level 4: ok, 725 bytes gzipped (budget 50000)
earthquake level 5: ok, 545 bytes gzipped (budget 14000)
all template pages pass
This page is what goes live first, on every alert, before any model is called. With only Steps 1, 2, 4 and 5 (and  BROWNOUT_AGENT=off ), you already have a working disaster mode.

Step 3: Add an agent, behind a guard, after the switch

If the template already passes every check, why add an agent at all?
Because a page that passes the checks is not yet a page that reads well under stress. The template lists facts in a fixed order. A person reading it on a phone at 2 a.m. needs the action first, then the most useful options, and nothing that makes them scroll. With clean data like this demo's, the gain is modest. With the data a real city has (bulletins typed in a hurry, notes added by the shelter staff, updates that contradict yesterday's page), deciding what to say and in what order is real work, and that is the work a language model is good at.
It is also the work a language model can get wrong in ways that matter: a confident safety tip nobody approved, a phone number from memory, a shelter that is unsafe for this hazard. So the agent gets three constraints:
  1. It runs after the switch. The template is already live, so the agent adds no latency and is not needed for the site to work.
  1. It can only publish through a gate. A Strands hook checks every  publish_page  call before it runs.
  1. If it cannot pass the gate, nothing happens. The template stays.
The agent is a Strands agent on Amazon Nova 2 Lite with three tools:  read_town_facts  returns the city data,  curate  asks a second agent which facts matter most for this hazard and level, and  publish_page  writes the page. The gate is a hook on  BeforeToolCallEvent :
# brownout/agent.py (shortened)
from strands.hooks import BeforeToolCallEvent, HookProvider, HookRegistry

class PublishGuard(HookProvider):
def register_hooks(self, registry: HookRegistry) -> None:
registry.add_callback(BeforeToolCallEvent, self.guard)

def guard(self, event: BeforeToolCallEvent) -> None:
if event.tool_use["name"] != "publish_page":
return
self.log.attempts += 1
if self.log.attempts > MAX_PUBLISH_ATTEMPTS: # 6
event.cancel_tool = "Publish attempt limit reached. Stop and report the problem."
return
html = event.tool_use["input"].get("html", "")
result = check(html, self.hazard, self.level) # the same checks as the template
if result.passed and self.verifier is not None:
result.unsupported = unsupported_sentences(self.verifier, html) # second agent
if not result.passed:
event.cancel_tool = f"Refused, page not published. {describe(result)}"
Setting  event.cancel_tool  stops the tool call, and the string becomes the tool result the agent sees, so every refusal is concrete feedback the agent can act on, for example:
Remove shelter:S3 ('Riverside Community Hall'): it is NOT safe for this hazard and must not appear anywhere on the page.
On top of the deterministic checks, a Verifier agent lists any sentence the city data does not support, and a word-overlap check drops flags that are only paraphrases of the data. The runtime wires it together like this:
# runtime/main.py (shortened)
html = template_page(hazard, level)
if not check(html, hazard, level).passed: # never publish unchecked, not even the template
return {"ok": False, ...}
publish(level, html)
if not set_level(level, issued_at): # the site switches here (Step 7 explains issued_at)
return {"ok": False, "stale": True, ...}
log = brownout(hazard, level, publish) # the agent; PublishGuard decides what it may publish
mode = "agent-level-4" if log.published else "template-level-4"
You can try the agent on your laptop before deploying anything. It writes to a local folder instead of S3:
PYTHONPATH=. uv run python -c "
from pathlib import Path
from brownout.agent import brownout, local_publisher
log = brownout('flood', 4, local_publisher(Path('out')))
print('attempts:', log.attempts, '| published:', log.published is not None)
print(*log.feedback, sep='\n')"


The agent's level 4 flood page on a laptop (phone numbers and addresses hidden)


The order of these steps comes from a failure. In my first version the agent ran first, and the site switched only after the agent had published. In one rehearsal the agent tried seven times and never got past the gate. Every refusal was the same: it kept naming the two shelters that are unsafe in a flood. The logs showed why. The curating agent had ended its brief with a well-meant warning, "Do not go to Riverside Community Hall or East Park Field", and the writing agent kept it. A warning that names an unsafe shelter still puts that name on the page, and the gate does not read intent. The gate did its job, and nothing unchecked went live. But the site stayed on the 28 MB everyday version during a level 4 alert, which is exactly what this system exists to prevent. Moving the template in front of the agent turned that failure into one nobody would see.

Step 4: Deploy the runtime to AgentCore Runtime

scripts/deploy_runtime.sh
On the first run the script creates an AgentCore project with the AgentCore CLI ( agentcore create , then  agentcore add runtime ) without prompts, passing the bucket, the KeyValueStore ARN and  BROWNOUT_AGENT  as environment variables and the policy file from Step 1 as an additional policy. Then it copies the code into the project and runs  agentcore deploy , which deploys a CDK stack. To run without the agent,  export BROWNOUT_AGENT=off  before the first run.
The policy is small on purpose. The runtime can write only the emergency pages, switch the level, and call Nova. It cannot touch the normal site under  full/ :
{"Sid": "PublishLitePages", "Effect": "Allow", "Action": ["s3:PutObject"],
"Resource": "arn:aws:s3:::<bucket>/level-*"},
{"Sid": "FlipMode", "Effect": "Allow", "Resource": "<kvs-arn>",
"Action": ["cloudfront-keyvaluestore:DescribeKeyValueStore", "cloudfront-keyvaluestore:GetKey",
"cloudfront-keyvaluestore:PutKey", "cloudfront-keyvaluestore:UpdateKeys"]},
{"Sid": "NovaModels", "Effect": "Allow",
"Action": ["bedrock:InvokeModel", "bedrock:InvokeModelWithResponseStream"],
"Resource": ["arn:aws:bedrock:*::foundation-model/amazon.nova-*",
"arn:aws:bedrock:*:*:inference-profile/us.amazon.nova-*"]}
If you use the AgentCore CLI by hand instead of the script, four things will trip you up:
  • The deployment target is created in your profile's default region. Everything here is in  us-east-1 , including the Lambda that calls the runtime, so set  AWS_REGION=us-east-1  first.
  •  agentcore create --skip-install  skips the CDK app's  npm install , and the deploy then stops with "CDK dependencies are missing". Run  npm install  in  agentcore/cdk .
  • A new Python runtime starts as  PYTHON_3_14 . Pin  requires-python = ">=3.13,<3.14"  in the agent's  pyproject.toml , and the CLI switches it to  PYTHON_3_13  at deploy time.
  • The first deploy turns on CloudWatch Transaction Search for the account. Removing the stack does not turn it off. Span ingestion is  billed by volume , so it costs money in proportion to the traces you send rather than for being on.

Step 5: Wire the alert

RT_ARN=$(aws bedrock-agentcore-control list-agent-runtimes --region us-east-1 \
--query "agentRuntimes[?contains(agentRuntimeName,'brownout')].agentRuntimeArn | [0]" --output text)
uv run python infra/deploy_trigger.py "$RT_ARN"
This creates an EventBridge rule for  AlertLevelChanged  events from  examplecity.alerts , and a Lambda function that calls  InvokeAgentRuntime  with the hazard, the level and the event's timestamp.

Step 6: Verify the switch

PYTHONPATH=. uv run python scripts/alert.py flood 4 # raise the alert
PYTHONPATH=. uv run python scripts/alert.py flood 1 # all clear
 alert.py  sends the event and polls the site every 2 seconds. It prints two times: when the new page was first seen, and when it had been seen on five reads in a row with no old page in between. You need both, because "switched" is not one moment.
Three rounds of level 4 and back, after one warm-up alert. All times are seconds after the alert was sent; the first two columns come from the Lambda logs, the rest from  alert.py :
Switch
Level written to KeyValueStore
Agent's page replaced the template
New page first seen
Stable (5 reads in a row)
Old page seen in between
to level 4, round 1
4.1
20.0 (3 attempts)
31.0
57.7
4 times
to level 1, round 1
2.8
n/a
41.0
68.0
4 times
to level 4, round 2
2.9
10.1
12.1
40.8
5 times
to level 1, round 2
2.9
n/a
44.7
63.2
2 times
to level 4, round 3
2.9
10.7
18.0
42.6
6 times
to level 1, round 3
2.8
n/a
17.8
44.9
5 times
The pipeline from alert to KeyValueStore write is fast, about 3 to 4 seconds, because no model call stands in the way. The agent's page followed 10 to 20 seconds after the alert; in round 1 the agent was refused twice before its page passed, and visitors had the template during that time. All three agent runs ended with a published page.
The slow part is after the write. The first request saw the new page 9 to 42 seconds after the write, and every request saw it 38 to 65 seconds after the write. In between, requests returned a mix of the new and the old page. AWS describes KeyValueStore updates as reaching edge locations within seconds, and I cannot tell from one client which part of the extra time belongs to KeyValueStore, to the function, or to my measurement point. What a visitor near me would have seen is up to about a minute of a mixed site after each switch.
For this use case that is acceptable, since both pages are correct for one of the two moments. It does set the promise you can make: not "switches in seconds", but "the emergency page is live for everyone within a minute or two of the alert". That is what an operator should plan around.

Step 7: Handling out-of-order alerts

Alerts do not always finish in the order they were sent. A level 4 run can still be working when a level 5 alert arrives, and the level 5 run can finish first. And EventBridge invokes the Lambda asynchronously, so  Lambda retries a failed invocation up to two times , later. This happened in two of my rehearsals: the first alert, sent a few seconds after the trigger was created, failed with  AccessDeniedException  on  InvokeAgentRuntime , most likely because the new role's policy had not taken effect yet, and Lambda ran the same request again about a minute later, this time successfully. A retry like that can land after a newer alert. If the code simply writes the level its run was given, the last run to finish wins, and the site can step back from "evacuate now" to an earlier level.
The fix has two parts. First, the trigger passes the event's own timestamp. The  time  field is when the alert was issued (the sender can set it, and EventBridge uses the time of the  PutEvents  call if it does not), so it orders alerts no matter when their runs finish:
payload = {"hazard": d["hazard"], "level": int(d["level"]), "issued_at": event["time"]}
Second, the level and its timestamp are written together, with a compare-and-set:
# brownout/edge.py
def set_level(level: int, issued_at: str | None = None) -> bool:
kvs = boto3.client("cloudfront-keyvaluestore", region_name=REGION)
arn = config()["kvs_arn"]
for _ in range(5):
etag = kvs.describe_key_value_store(KvsARN=arn)["ETag"]
if issued_at is not None and (current := live_issued_at(kvs, arn)) and current > issued_at:
return False # a newer alert is already live
puts = [{"Key": "level", "Value": str(level)}]
if issued_at is not None:
puts.append({"Key": "issued_at", "Value": issued_at})
try:
kvs.update_keys(KvsARN=arn, IfMatch=etag, Puts=puts)
return True
except kvs.exceptions.ConflictException:
continue # someone wrote first; read again
raise RuntimeError("KeyValueStore kept changing; giving up")
 UpdateKeys  writes both keys in one call, and  IfMatch  makes it conditional on the store's ETag. If another run wrote anything between the read and the write, the ETag no longer matches, the write is rejected, and the loop reads again. The runtime also checks the timestamp before it does anything else, so a stale alert neither publishes a page nor calls the model. A Lambda retry of the same alert is now harmless: same timestamp, same level.
To test it without waiting for a real race,  alert.py  can backdate an alert:
uv run python tests/test_edge_ordering.py # no AWS needed
PYTHONPATH=. uv run python scripts/alert.py flood 5
PYTHONPATH=. uv run python scripts/alert.py flood 4 --issued-ago 120 --timeout 90 # expect: no change
The Lambda log then shows the backdated alert refused before anything ran:
"payload": {"hazard": "flood", "level": 4, "issued_at": "2026-11-10T00:54:22Z"}, "result": "{\"ok\": false, \"stale\": true, \"level\": 4, \"previous\": 5}"

Step 8: Clean up

scripts/teardown.sh # type the name to confirm
The order matters, and each step waits for the one before it:
  1. The EventBridge rule, the Lambda function, its role and its log group, so no new alert reaches the runtime.
  1. The AgentCore Runtime:  agentcore remove all --yes , then  agentcore deploy --yes , which removes the stack because the project no longer declares anything.
  1. The CloudFront distribution is disabled, and the script waits until that change is deployed. Only then can it be deleted.
  1. The Origin Access Control, the CloudFront Function (it cannot be deleted while a distribution uses it), and the KeyValueStore (it cannot be deleted while a function is associated with it).
  1. The S3 bucket, after emptying it.
  1. The runtime's log groups. Removing the AgentCore stack does not remove them, so the script deletes the log groups whose names start with the project's prefix.
The whole teardown took 4 to 7 minutes in my runs. To check that nothing is left:
aws bedrock-agentcore-control list-agent-runtimes --region us-east-1 --query "agentRuntimes[].agentRuntimeName"
aws cloudformation describe-stacks --region us-east-1 --query "Stacks[?contains(StackName,'brownout')].StackName"
aws logs describe-log-groups --region us-east-1 --query "logGroups[?contains(logGroupName,'brownout')].logGroupName"
Two things stay on purpose: the CDK bootstrap stack ( CDKToolkit ), which other CDK apps in the account may use, and the Transaction Search setting from Step 4.

Production checklist

Already handled in the code:
  • Nothing unchecked goes live. The template and the agent's page pass the same checks, and the level changes only after a checked page is published.
  • The agent is optional. If it fails, or  BROWNOUT_AGENT=off , the template stays live.
  • Old and retried alerts cannot roll the site back (Step 7).
  • If the function cannot read the level, visitors get the normal site, not an error.
  • Least privilege: the runtime can write only  level-*  pages, and the bucket is readable only through CloudFront.
Not handled, and what to change:
  • Who can raise an alert. Today anyone in the account with  events:PutEvents  on the default event bus can. Create a dedicated event bus in  infra/deploy_trigger.py  (pass  EventBusName  to  put_rule  and  put_targets ) and give it a resource policy that allows only the real alert publisher.
  • Failed alerts are invisible. Add an on-failure destination to the Lambda ( put_function_event_invoke_config  with an SQS queue) so an alert that failed after its retries can be found and replayed.
  • Nobody is told when something goes wrong. Add a CloudWatch metric filter on the Lambda's log group for  "ok": false  and an alarm on it.
  • Your data is not this clean. The checks here match a small, structured data file. If your page is built from messier sources, grow  facts.py  with them, because the checks, not the agent, are what make the page safe.

What it costs

From Cost Explorer for my account, usage before credits, for the services this tutorial uses, on the day I ran two full rehearsals (each a deploy, about ten alerts and a teardown):
Service
USD
Amazon CloudFront
0.086
Amazon Bedrock (Nova 2 Lite)
0.078
Amazon Bedrock AgentCore
0.051
Amazon S3
0.0007
EventBridge
0.00002
Total
about 0.22
Lambda stayed within the free tier. On a day with no alerts, the same services came to less than one cent. Running this tutorial once should cost well under a dollar.

Wrap-up

You now have a disaster mode that switches every URL with one key at the edge, fills its page from data instead of from someone's memory, never publishes an unchecked page, cannot be rolled back by a late alert, and leaves nothing behind when you remove it. The agent makes the page better when it can and is never needed for the site to work. The full code, with the tests and the deploy and teardown scripts, is at  ikenyal/brownout .
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article