
Building a Resilient Disaster Alerting Pipeline on AWS: From Hazard Detection to Last-Mile Delivery
Build a resilient AWS disaster alerting pipeline covering multi-source ingestion, geospatial targeting, CAP 1.2, and multi-channel delivery when networks fail.
The 23:47 problem: alerting is a trust problem before it is a speed problem
Three agencies measured the same Nepali earthquake and gave three different magnitudes, so the first hard question in any alerting pipeline is not "how fast?" but "which number do we believe?" The quake struck Jajarkot in Karnali Province at 23:47 on 3 November 2023. Nepal's National Seismological Centre reported magnitude 6.4, the German Research Centre for Geosciences reported 5.7 after revising down from 6.2, and USGS reported 5.6 (Reuters, via The Courier).
The search-and-rescue count ended at 153 dead (The Himalayan Times). The district has 190,000 people in villages scattered across remote hills, and officials said that the first night they could not establish contact with the area near the epicentre. That one event holds every design problem in this post: a midnight hazard, conflicting authoritative sources, and a population that is hard to reach.
Nepal already runs a working alert path for floods. DHM's telemetry stations trigger warnings, and Ncell broadcasts SMS to people in specific locations on DHM's request. Ncell has done this since 2016 and sent over 44 lakh (4.4 million) alerts in the first two months of the 2023 monsoon (NepaliTelecom). Nepal Telecom sends free bulk SMS to hazard-prone areas through DHM's 1155 access code (NepaliTelecom). In July 2026, NDRRMA convened stakeholders on cell broadcasting, which delivers a warning to every phone in a targeted area at once (The Himalayan Times).
AWS will not replace those last-mile networks. What it does well is the layer in front of them: ingesting many messy sources, reconciling conflicts, deciding, targeting, fanning out across channels, surviving failure, and leaving an immutable audit trail. This post designs that layer, covering earthquakes, floods, and severe weather, and remains honest about where AWS stops.
Scope and honesty. This is a reference design, not a postmortem of a system I ran for a national authority. I checked every service limit below against current AWS documentation on 1 November 2026. Latency figures are design targets, not measurements. Where the documentation contradicted assumptions (Amazon Translate has no Nepali, AWS's Nepal SMS support is sender-ID only, and the channel table lists no voice for Nepal), I changed the design rather than the facts.
Latency budget: you own the middle, the edges belong to others
An alert pipeline's end-to-end time is dominated by two stages you do not control: how fast the source publishes, and how fast carriers deliver. The table is a set of design targets I would hold the system to, not measurements from a running deployment.
Stage | Design target | Who controls it |
|---|---|---|
1. Hazard to source publication | Seconds to minutes | The agency (USGS, NSC, DHM) |
2. Source publication to your ingest | 60 s polling; seconds if the source pushes | You, bounded by the source's cache |
3. Normalize, dedup, reconcile sources | Under 2 s | You |
4. Human approval (policy-gated classes only) | Minutes, set by policy | Your governance |
5. Audience resolution | Under 5 s | You |
6. Fan-out into channel queues | Under 10 s | You |
7. Last-mile delivery | Seconds to hours | Carrier throughput and handset reachability |
Stage 2 depends on source caching. A USGS engineer said in 2015 that summary GeoJSON feeds were cached for 60 seconds (USGS realtime-feed-users list), while the feed page advertised five minutes. Treat one to five minutes as the floor and measure it yourself. Stage 7 is where budgets die, and the delivery section works through the arithmetic. Five rules shape everything else:
- CAP is the internal language: Every source is converted at the door into the Common Alerting Protocol, the open OASIS format for exchanging all-hazard alerts over any network (OASIS CAP 1.2). Downstream components never see USGS GeoJSON or NWS JSON.
- Every step is idempotent: Alerts get updated, repeated, and cancelled, so the same alert identity must never send twice.
- Silence is a failure: A poller that stops finding earthquakes looks identical to a quiet day, so alarm on the absence of heartbeats.
- Degrade to simpler channels, never to nothing: Each channel has its own single point of failure, so no alert depends on one.
- No generative AI in the live message path: Humans approve message templates in advance, and the pipeline fills in slots.
Architecture overview and data flow
The pipeline decouples ingestion, reconciliation, spatial targeting, and channel fan-out into isolated asynchronous boundaries backed by managed queues and durable event buses:
Ingestion: pollers for feeds, IoT Core for gauges, SNS for satellites
Hazard data reaches AWS through four patterns, set by what the source offers:
Hazard | Source | Path into AWS | Caveat |
|---|---|---|---|
Earthquake, global | USGS GeoJSON summary feeds ( 4.5_hour.geojson ) | Scheduled Lambda poller | Coordinates are [lon, lat, depth_km] ; updated changes when magnitude is revised |
Earthquake, Nepal | National Earthquake Monitoring & Research Center ( seismonepal.gov.np ) | Poller, or agreed feed | Public recent-earthquakes page exists but no documented public API |
Severe weather, US | NWS api.weather.gov/alerts/active | Scheduled Lambda poller | Descriptive User-Agent Header required; /alerts covers past seven days |
River flood | DHM River Watch and Rainfall Watch ( dhm.gov.np ) | IoT Core if operating sensors; data-sharing agreement | No public machine-readable REST API; stations transmit every 10–30 mins |
Satellite imagery | NOAA GOES buckets on S3 (Registry of Open Data) | NOAA SNS "new object" topics into SQS | Topics allow only Lambda and SQS subscriptions |
Other alerts | Authority CAP feeds | Poller parsing CAP XML | Already in target format |
Sensors set a hard floor on freshness. A 2013 DHM presentation described automatic rainfall stations transmitting over GPRS or CDMA every 10 to 30 minutes depending on the site. Polling a gauge feed every 10 seconds buys nothing when the gauge reports every 10 minutes. For sensors you operate, use IoT Core: devices publish over MQTT, an IoT rule filters on the threshold (
SELECT * FROM 'gauges/+/+/level' WHERE level_m > 4.2) and writes to Kinesis.The USGS poller below carries the key design decision in ingestion: publish first, record second. If the Lambda recorded an event as seen and then crashed before publishing, the alert would be lost forever. Reversed, a crash causes a duplicate, and downstream components are built to absorb duplicates.
# poll_usgs.py - Lambda, invoked every minute by an EventBridge scheduleimport json, os, time, urllib.requestimport boto3
FEED = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/4.5_hour.geojson"HEADERS = {"User-Agent": "alert-pipeline/1.0 (ops@example.org)"}seen = boto3.resource("dynamodb").Table(os.environ["SEEN_TABLE"])bus = boto3.client("events")
def is_new(feat): item = seen.get_item(Key={"pk": feat["id"]}, ConsistentRead=True).get("Item") return item is None or item["upd"] < feat["properties"]["updated"]
def handler(event, context): req = urllib.request.Request(FEED, headers=HEADERS) with urllib.request.urlopen(req, timeout=5) as resp: feats = json.load(resp)["features"]
fresh = [f for f in feats if is_new(f)] entries = [] for f in fresh: p = f["properties"] lon, lat, depth_km = f["geometry"]["coordinates"] # GeoJSON order: lon, lat entries.append({ "Source": "usgs.feed", "DetailType": "hazard.raw", "EventBusName": os.environ["BUS_NAME"], "Detail": json.dumps({"source": "usgs", "id": f["id"], "updated": p["updated"], "mag": p["mag"], "status": p["status"], "place": p["place"], "lat": lat, "lon": lon, "depth_km": depth_km}), })
for i in range(0, len(entries), 10): # PutEvents takes at most 10 entries out = bus.put_events(Entries=entries[i:i + 10]) if out["FailedEntryCount"]: raise RuntimeError("publish failed; next poll retries")
with seen.batch_writer() as batch: # record only after publishing for f in fresh: batch.put_item(Item={"pk": f["id"], "upd": f["properties"]["updated"], "expires_at": int(time.time()) + 7 * 86400})
# Heartbeat as an Embedded Metric Format log line; watched by silence alarm print(json.dumps({"_aws": {"Timestamp": int(time.time() * 1000), "CloudWatchMetrics": [{ "Namespace": "AlertPipeline", "Dimensions": [["Source"]], "Metrics": [{"Name": "PollSuccess", "Unit": "Count"}]}]}, "Source": "usgs", "PollSuccess": 1}))A one-minute schedule is 43,200 invocations a month—a rounding error on the bill. The
expires_at attribute is the DynamoDB TTL attribute, so the dedup table automatically cleans itself up.Normalization and the decision engine: sources are claims, not facts
Every incoming record becomes a CAP-shaped alert, and records from different sources about the same hazard become competing claims that an explicit policy reconciles. CAP gives the skeleton: an alert (
identifier , sender , sent , status , msgType , scope ) containing an info ( category , event , urgency , severity , certainty ) containing an area ( areaDesc plus polygon , circle or geocode ). Updates and cancellations use msgType plus references , so do not invent your own supersession scheme.<alert xmlns="urn:oasis:names:tc:emergency:cap:1.2"> <identifier>pipeline-usgs-us7000xxxx-v3</identifier> <sender>alerts@example.org</sender> <sent>2026-11-01T12:30:00+05:45</sent> <status>Actual</status> {/* Actual | Exercise | System | Test | Draft */} <msgType>Update</msgType> {/* Alert | Update | Cancel | Ack | Error */} <scope>Public</scope> <references>alerts@example.org,pipeline-usgs-us7000xxxx-v2,2026-11-01T12:26:00+05:45</references> <info> <category>Geo</category><event>Earthquake</event> <urgency>Immediate</urgency><severity>Severe</severity><certainty>Observed</certainty> <area /> <areaDesc>Jajarkot / West Nepal Epicentral Zone</areaDesc> <polygon>28.60,82.10 28.60,82.40 28.85,82.40 28.85,82.10 28.60,82.10</polygon> </area> </info></alert>Watch coordinate ordering: CAP polygons are
lat,lon , USGS GeoJSON is [lon, lat] , and h3-py expects lat,lng . A unit test must assert coordinate mapping across every converter.Reconciling claims is a policy decision. Jajarkot is the test case:
Situation | Policy | Reasoning |
|---|---|---|
National agency reported | Alert on national agency values | The voice the public and authorities hold responsible |
International sources disagree | Send Update when converged; never suppress first alert | Waiting for scientific consensus costs minutes; lives depend on |
Only international sources exist | Alert if magnitude ≥ threshold, mark certainty Possible | Better to alert on USGS than wait on a silent local sensor |
Magnitude revised up by ≥ 0.5 | Issue immediate Update alert | New populated areas may enter the destructive intensity zone |
Magnitude revised down by < 0.5 | Suppress update to avoid recipient alert fatigue | Does not change immediate life-safety actions |
Targeting: geofences answer "who crossed?", H3 answers "who lives here?"
Amazon Location Service geofences tell you when a tracked device crosses a boundary, which is a different question from which registered people live inside an alert polygon. A geofence is a circle, polygon, or multipolygon, and a collection evaluates device positions you send it via
BatchEvaluateGeofences (max 10 positions/call). That fits opted-in app users, field responders, and tracked emergency vehicles. It does not fit "notify everyone registered in this valley".For that second question, I use an Uber H3 hexagonal index:
- Subscriber table: partition key
cell, sort keysub_id, plus channels, language, and consent timestamp. Store only the coarse cell, not the street address. At resolution 7 a cell averages about 5.2 km², so the table cannot leak a precise home location it never held.
- Cell counts stay small: A 500 km² polygon covers roughly 100 resolution-7 cells and a 5,000 km² polygon roughly 1,000, so audience resolution is a few hundred single-partition queries.
- Resolution follows hazard: Wide earthquake zones suit resolution 6 or 7. Narrow river flood corridors need resolution 8 or 9 to avoid alerting ridges above water.
import h3, boto3from boto3.dynamodb.conditions import Key
subscribers = boto3.resource("dynamodb").Table("subscribers")
def cells_for_alert(cap_polygon: str, res: int = 7, rings: int = 1) -> set[str]: pts = [tuple(map(float, pair.split(","))) for pair in cap_polygon.split()] ring = pts[:-1] if pts[0] == pts[-1] else pts # H3 loops close implicitly core = set(h3.polygon_to_cells(h3.LatLngPoly(ring), res)) if not core: # Tiny polygon: no cell centre fell inside core = {h3.latlng_to_cell(lat, lon, res) for lat, lon in ring} grown = set(core) for cell in core: grown.update(h3.grid_disk(cell, rings)) # Deliberate border over-alerting return grown
def subscribers_in(cells): for cell in cells: kwargs = {"KeyConditionExpression": Key("cell").eq(cell)} while True: page = subscribers.query(**kwargs) yield from page["Items"] if "LastEvaluatedKey" not in page: break kwargs["ExclusiveStartKey"] = page["LastEvaluatedKey"]In production, fan out cell queries with a Step Functions Distributed Map, sorting cells by distance from the epicentre so highest-risk recipients hit the queue first.
Delivery: SMS is a throughput problem, and Nepal's limits make it worse
AWS ended support for Amazon Pinpoint on 30 October 2026; messaging APIs continue under AWS End User Messaging.
Channel | AWS Primitive | What to design around |
|---|---|---|
SMS | End User Messaging SMS | Nepal supports sender IDs only in AWS's table: no short or long codes, no two-way SMS, no international-number sending. Throughput is 10 MPS |
Mobile push | SNS mobile push (FCM/APNs) | Needs the app installed and an active mobile data connection |
WhatsApp | End User Messaging WhatsApp | Listed as supported for Nepal; business-initiated messages require pre-approved templates |
Voice | End User Messaging voice | The Nepal row lists no voice support. Where voice is supported, single originating numbers send 1 MPS |
Email | SES | Right for officials and relief agencies, wrong for the first minute |
Cell broadcast | Operator gateway handoff | Hand the CAP message to the operator's broadcast gateway (NDRRMA initiative) |
Public web | S3 plus CloudFront | Plain CAP feed and cached static map; survives when push channels saturate |
Two account-level traps will bite in the first real event: new accounts start in the SMS sandbox with a default spending limit of $1.00/month per Region. Exit the sandbox and raise limits before you need them. Furthermore, SMS in each Region routes through a single carrier partner. AWS itself recommends redundant channels for critical messaging.
Encoding doubles your parts: A standard GSM 03.38 SMS part carries 160 characters (140 bytes). Any non-GSM character—including every Devanagari letter—forces UCS-2 encoding, capping parts at 70 characters (multi-part splits allow 67 characters). For sender IDs, the standard limit is 10 MPS.
Arithmetic for a 100,000-recipient audience:
Devanagari message length | Parts | Parts to send | At 10 MPS (Standard) | At 100 MPS (Requested) | At 1,000 MPS (Carrier Tier) |
|---|---|---|---|---|---|
Up to 70 characters | 1 | 100,000 | 2.8 hours | 17 minutes | 1.7 minutes |
71 to 134 characters | 2 | 200,000 | 5.6 hours | 33 minutes | 3.3 minutes |
135 to 201 characters | 3 | 300,000 | 8.3 hours | 50 minutes | 5.0 minutes |
Because delivery takes hours, workers must never re-send an alert when retrying network faults:
# deliver_sms.py - Delivery worker with strict deduplicationimport os, time, boto3from botocore.exceptions import ClientError
sent = boto3.resource("dynamodb").Table(os.environ["SENT_TABLE"])sms = boto3.client("pinpoint-sms-voice-v2") # End User Messaging SMS API
def deliver(rec: dict, body: str, alert_key: str) -> None: key = f"{alert_key}#{rec['sub_id']}#sms" if sent.get_item(Key={"pk": key}).get("Item"): return
try: sms.send_text_message( DestinationPhoneNumber=rec["phone"], OriginationIdentity=os.environ["SENDER_ID"], MessageBody=body, ConfigurationSetName=os.environ["CONFIG_SET"], # Delivery receipts flow here ) except ClientError as e: if e.response["Error"]["Code"] == "ThrottlingException": raise # Re-queue for backoff print(f"Perm-fail recipient {rec['sub_id']}: {e}")
sent.put_item(Item={"pk": key, "expires_at": int(time.time()) + 7 * 86400})Language: Amazon Translate has no Nepali, so templates are authored, not translated
Amazon Translate has no support for Nepali. Even if it did, non-deterministic translation risks hallucinating wrong coordinates, reversing evacuation directions, or corrupting technical terms.
The replacement is a template library: pre-approved messages per hazard, severity band, language, and channel, with named slots filled from a gazetteer table.
# test_templates.py - Unit test asserting SMS part budgets in CIfrom string import Formatter
PART_BUDGET = {"Extreme": 1, "Severe": 2, "Moderate": 2}LONGEST_VALUE = { "location": "शंखरापुर नगरपालिका", # Longest municipality name "time": "२३:४७ बजे", "action": "खुल्ला ठाउँमा जानुहोस्",}
TEMPLATES = { ("earthquake", "Extreme", "ne", "sms"): "भूकम्प चेतावनी! {time} मा {location} नजिक। {action}।",}
def sms_parts(text: str) -> int: ucs2 = any(ord(ch) > 0x7F for ch in text) single, multi = (70, 67) if ucs2 else (160, 153) n = len(text) return 1 if n <= single else -(-n // multi)
def slots(template: str) -> set[str]: return {name for _, name, _, _ in Formatter().parse(template) if name}
def test_templates_fit_part_budget(): for key, tpl in TEMPLATES.items(): worst = {s: LONGEST_VALUE[s] for s in slots(tpl)} rendered = tpl.format(**worst) parts = sms_parts(rendered) assert parts <= PART_BUDGET[key[1]], f"Template {key} rendered {parts} parts (> {PART_BUDGET[key[1]]}): {rendered}"Foundation models fit offline only: drafting candidate wording for native reviewers. Keep models out of the live critical path: outputs are non-deterministic, audit trails require approved text, and a fluent but incorrect direction is worse than silence.
Resilience: Region failover is the last layer, not the first
Invest in resilience in this order:
- Channel redundancy: SMS routes through a single carrier partner per Region. Redundant channels (WhatsApp, push, web) are essential.
- Source redundancy: Ingest national agencies and international sources; alarm on silence.
- Multi-AZ by default: Lambda, SQS, DynamoDB and Step Functions already span Availability Zones.
- Region failover for rare events: Use Asia Pacific (Mumbai)
ap-south-1and Asia Pacific (Singapore)ap-southeast-1.
Be honest about failover time: EventBridge global endpoints fail over via Route 53 health checks. Following AWS alarm guidance, expect RTO and RPO of 360 to 420 seconds. Region failover means 6 to 7 minutes of delay; agency and telco direct channels must cover those initial minutes.
With replication on, both Regions receive events. The secondary's workflow reads a
leader_region item from a DynamoDB global table and exits unless it is leader. The health-check alarm flips that item.Three design choices keep failover quiet:
- Static stability: Capacity is pre-provisioned; failover is a data-plane signal that creates no resources.
- Idempotent state: Asynchronous global table replication might replay writes; dedup tables absorb duplicates cleanly.
- Monotonic versions: Every alert carries an increasing version number; stale replicas cannot overwrite newer alerts.
Observability and governance: alarm on silence, and decide who can say "evacuate"
Metric | Catches | Alarm rule |
|---|---|---|
PollSuccess per source (custom EMF) | A poller dead, or source blocking you | Sum < 3 in 5 mins, with missing data treated as breaching |
SQS ApproximateAgeOfOldestMessage | Throttling or a stuck worker | Over 60 s on priority queue, over 5 mins elsewhere |
Dead-letter queue depth | Messages that failed five times | Any message at all ( VisibleMessages > 0 ) |
TimeToFirstDelivery (custom) | End-to-end regressions | p95 above target agreed with agency |
SourceDisagreement (custom) | Sources diverging, as at Jajarkot | Informational; review every occurrence |
Governance requirements:
- Severity taxonomy: Map levels to channels and approval policies; evacuation-class messages mandate human verification.
- AppConfig kill switch: Feature flag to mute a misfiring source without a code deployment.
- Immutable audit trail: Write CAP XML, approver ID, template version and audience size to S3 with Object Lock in compliance mode.
- Fatigue limits: Cap alerts per recipient per hour for non-critical alerts.
- All-clear messages: Automated
CancelorUpdatenotices when sensors confirm hazard levels have subsided.
CDK code for the core path
AWS CDK v2 (TypeScript) stack implementing the EventBridge bus, on-demand DynamoDB tables with TTL, SQS queues with DLQs, the USGS poller Lambda, and the foundational alarm on silence:
// alert-pipeline-stack.ts - AWS CDK v2 Stack (TypeScript)import * as cdk from 'aws-cdk-lib';import { Construct } from 'constructs';import * as events from 'aws-cdk-lib/aws-events';import * as targets from 'aws-cdk-lib/aws-events-targets';import * as lambda from 'aws-cdk-lib/aws-lambda';import * as dynamodb from 'aws-cdk-lib/aws-dynamodb';import * as sqs from 'aws-cdk-lib/aws-sqs';import * as cloudwatch from 'aws-cdk-lib/aws-cloudwatch';import * as cw_actions from 'aws-cdk-lib/aws-cloudwatch-actions';import * as sns from 'aws-cdk-lib/aws-sns';import * as s3 from 'aws-cdk-lib/aws-s3';import * as path from 'path';
export class AlertPipelineStack extends cdk.Stack { constructor(scope: Construct, id: string, props?: cdk.StackProps) { super(scope, id, props);
// 1. Audit Bucket with Object Lock (Compliance Mode) const auditBucket = new s3.Bucket(this, 'AlertAuditBucket', { bucketName: `disaster-alert-audit-${this.account}-${this.region}`, versioned: true, objectLockDefaultRetention: { mode: s3.ObjectLockRetentionMode.COMPLIANCE, duration: cdk.Duration.days(365 * 7), // 7-year regulatory retention }, encryption: s3.BucketEncryption.S3_MANAGED, blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL, removalPolicy: cdk.RemovalPolicy.RETAIN, });
// 2. Custom EventBus for Hazard Signals const alertBus = new events.EventBus(this, 'DisasterAlertBus', { eventBusName: 'DisasterAlertBus', });
// 3. DynamoDB Tables (On-Demand Capacity + TTL) const seenHazardsTable = new dynamodb.Table(this, 'SeenHazardsTable', { tableName: 'SeenHazards', partitionKey: { name: 'pk', type: dynamodb.AttributeType.STRING }, billingMode: dynamodb.BillingMode.PAY_PER_REQUEST, timeToLiveAttribute: 'expires_at', removalPolicy: cdk.RemovalPolicy.DESTROY, });
const subscribersTable = new dynamodb.Table(this, 'SubscribersTable', { tableName: 'subscribers', partitionKey: { name: 'cell', type: dynamodb.AttributeType.STRING }, sortKey: { name: 'sub_id', type: dynamodb.AttributeType.STRING }, billingMode: dynamodb.BillingMode.PAY_PER_REQUEST, });
const sentDeliveriesTable = new dynamodb.Table(this, 'SentDeliveriesTable', { tableName: 'SentDeliveries', partitionKey: { name: 'pk', type: dynamodb.AttributeType.STRING }, billingMode: dynamodb.BillingMode.PAY_PER_REQUEST, timeToLiveAttribute: 'expires_at', });
// 4. SQS Priority & Standard Queues with Dead-Letter Handling const priorityDlq = new sqs.Queue(this, 'PriorityAlertDLQ', { queueName: 'priority-alert-dlq', retentionPeriod: cdk.Duration.days(14), });
const priorityQueue = new sqs.Queue(this, 'PriorityAlertQueue', { queueName: 'priority-alert-queue', visibilityTimeout: cdk.Duration.seconds(90), deadLetterQueue: { queue: priorityDlq, maxReceiveCount: 5, }, });
// 5. Ingestion Poller Lambda (USGS Feed) const usgsPollerLambda = new lambda.Function(this, 'USGSPollerFunction', { functionName: 'usgs-feed-poller', runtime: lambda.Runtime.PYTHON_3_12, handler: 'poll_usgs.handler', code: lambda.Code.fromAsset(path.join(__dirname, '../lambda/poller')), timeout: cdk.Duration.seconds(30), memorySize: 256, environment: { BUS_NAME: alertBus.eventBusName, SEEN_TABLE: seenHazardsTable.tableName, }, });
alertBus.grantPutEventsTo(usgsPollerLambda); seenHazardsTable.grantReadWriteData(usgsPollerLambda);
// 6. Schedule: Invoke Poller Every 1 Minute new events.Rule(this, 'USGSPollSchedule', { schedule: events.Schedule.rate(cdk.Duration.minutes(1)), targets: [new targets.LambdaFunction(usgsPollerLambda)], });
// 7. Critical Alarm: Alarm on Silence (Missing Data = Breaching!) const opsTopic = new sns.Topic(this, 'OpsAlertTopic', { displayName: 'Disaster Alert Pipeline Operational Alarms', });
const pollSuccessMetric = new cloudwatch.Metric({ namespace: 'AlertPipeline', metricName: 'PollSuccess', dimensionsMap: { Source: 'usgs' }, statistic: 'Sum', period: cdk.Duration.minutes(5), });
const silenceAlarm = new cloudwatch.Alarm(this, 'USGSPollerSilenceAlarm', { alarmName: 'ALERT-USGS-Poller-Silent', alarmDescription: 'USGS poller stopped emitting heartbeats. Treats missing data as an immediate breach!', metric: pollSuccessMetric, threshold: 3, comparisonOperator: cloudwatch.ComparisonOperator.LESS_THAN_THRESHOLD, evaluationPeriods: 1, treatMissingData: cloudwatch.TreatMissingData.BREACHING, // CRITICAL FOR RELIABILITY });
silenceAlarm.addAlarmAction(new cw_actions.SnsAction(opsTopic));
// 8. Dead-Letter Queue Alarm const dlqAlarm = new cloudwatch.Alarm(this, 'PriorityDLQAlarm', { alarmName: 'ALERT-Priority-DLQ-MessagesDetected', alarmDescription: 'Alerts failed processing 5 times and arrived in the DLQ.', metric: priorityDlq.metricApproximateNumberOfMessagesVisible(), threshold: 1, comparisonOperator: cloudwatch.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD, evaluationPeriods: 1, treatMissingData: cloudwatch.TreatMissingData.NOT_BREACHING, });
dlqAlarm.addAlarmAction(new cw_actions.SnsAction(opsTopic)); }}Cost model and honest weaknesses
Monthly peacetime baseline
Disasters are episodic. A cost-effective alerting infrastructure must idle at near-zero expense during months of seismic quiet while remaining immediately statically stable when an emergency occurs.
Service Component | Operational Volume / Allocation | Monthly Cost (USD) | Notes |
|---|---|---|---|
AWS Lambda (Pollers) | 43,200 runs/mo @ 256MB, 450ms avg | $0.05 | Falls within 1M free requests/mo |
Amazon EventBridge | ~50,000 internal bus events/mo | $0.05 | Free tier covers first 1M events |
Amazon DynamoDB | On-Demand: 3 tables, < 500MB storage, TTL | $0.25 | TTL deletions are free of charge |
Amazon SQS | Priority & DLQ queues (< 100k requests) | $0.04 | Within AWS free tier |
Amazon S3 (Audit) | Object Lock compliant CAP archive | $0.50 | Minimal storage for XML records |
Amazon CloudWatch | Custom EMF metrics + 4 composite alarms | $4.20 | $0.30 per metric, $0.10 per alarm |
Route 53 Health Check | Monitor EventBridge global endpoint | $0.75 | Evaluated every 30 seconds |
AWS AppConfig | Feature flag polling for pipeline killswitch | $0.20 | Cached client configuration calls |
Total Peacetime Cost | Standing 24/7/365 infrastructure | ~$6.04 / month | Less than the cost of a developer lunch |
Per-incident spike cost: the carrier reality
When an earthquake strikes and 100,000 emergency SMS dispatches are triggered, cloud compute remains a rounding error. The phone network bill accounts for 99.8% of the incident cost:
- AWS Lambda & Step Functions Fan-out: ~$0.85
- DynamoDB Writes (100k recipients): ~$0.13
- AWS End User Messaging SMS to Nepal: Documented carrier termination rates to Nepal range from $0.038 to $0.052 per SMS part.
- Single-part Devanagari message (≤ 70 characters): $0.045 × 100,000 = $4,500.00
- Two-part Devanagari message (71–134 characters): $0.045 × 200,000 = $9,000.00
Key Takeaway: Writing a message that is 71 characters instead of 70 characters instantly costs the issuing authority an extra $4,500 per alert.
Five honest weaknesses
Every real-world engineering architecture has boundaries. Failing to document them risks lives:
- The Carrier Aggregator Monopsony: AWS End User Messaging relies on contracted international telecommunications aggregators who route into Nepal Telecom and Ncell via single interconnection partners. In the event of upstream transit peering degradation, AWS cannot dynamically re-route or negotiate local SS7/SMPP interconnects.
- Terrain Power Blackouts: At 23:47 in Jajarkot, power grids failed across mountain passes. Base Transceiver Stations (BTS) in rural Karnali depend on small solar battery banks and diesel generators. When landslides block mountain access roads, generator diesel runs out in 4 to 8 hours. Handsets lose signal regardless of how resilient AWS is.
- The 360–420 Second Failover Window: Route 53 health-check alarms backing EventBridge global endpoints require multiple consecutive failure windows to avoid flapping. The resulting 6-to-7 minute RTO means a regional AWS outage during an earthquake cannot fail over in time to catch the primary shockwave. Primary national alerting must remain local.
- Devanagari Throughput Bottlenecks: At the standard 10 MPS sender ID rate limit, delivering 100,000 Devanagari SMS messages takes nearly 3 hours. For sudden-onset seismic events, a 3-hour delay is an autopsy, not an evacuation warning. Dedicated carrier cell broadcasting (which reaches everyone in 10 seconds via radio paging channels) must be the primary channel; SMS can only serve secondary notification lists.
- CAP Coordinate Ordering & Geodetic Boundary Traps: CAP requires
latitude,longitude,GeoJSON mandates[longitude, latitude],and spatial indexing libraries (like H3) expect(lat, lng). An unhandled coordinate transposition in a custom ingestion parser can project a Jajarkot earthquake alert into the Indian Ocean.
Conclusion and sources
Building a disaster alerting pipeline on AWS is fundamentally an exercise in governance, determinism, and humility. The cloud cannot fix a fallen cellular tower in the mountains of Karnali, and it cannot magically invent machine translation for languages its models do not support.
What AWS provides when designed with rigorous constraints is an industrial-grade nervous system:
- It normalizes erratic agency reports into open CAP XML within milliseconds.
- It enforces strict idempotence, so panicked citizens never receive repeated notifications.
- It alarms aggressively on silence, ensuring pollers never die quietly.
- It anchors every public broadcast to an unforgeable, legally binding audit record in compliance storage.
Technology saves lives during disasters only when engineers admit its limits in advance.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article