Power Outage Data in AWS
To get power outage data into AWS, run a Python Lambda function on an EventBridge Scheduler schedule, read the API key from Secrets Manager, and write each response to S3 as JSON lines that Athena can query. The same function can check your own sites against live outages and publish an SNS alert when any of them lose power. This guide uses only the Python standard library and the boto3 SDK that ships with the Lambda runtime, so there is nothing to package beyond one file.
What you'll have
- A growing history of county outage counts in S3, partitioned by day and queryable from Athena with plain SQL.
- An optional SNS alert, by email, SMS or any subscriber, when one of your watched sites sits inside an active outage.
- A Lambda that reads its key from Secrets Manager and runs every 15 minutes on EventBridge Scheduler.
- No layers or dependencies to package:
urlliband boto3 come with the Python runtime.
What you need
An API key (request one with the form below) and these endpoints. Full details are in the API reference.
| Endpoint | Method | Used for | Package |
|---|---|---|---|
/outages/counties | GET | County customersOut and customersTracked for a state, written to S3 on every run. | Core |
/geojson/at-point | POST | Checks up to 100 site coordinates against active outages in one request, for the SNS alert. | Standard + Locations |
Step 1: Store the key in Secrets Manager
Create a secret whose value is the bare API key. Reading it with read -s keeps it out of your shell history. The function reads the secret at cold start, so the key never appears in its code or environment variables.
read -rs POWEROUTAGE_API_KEY # paste the key; it is not echoed or saved to history
aws secretsmanager create-secret \
--name poweroutage/api-key \
--secret-string "$POWEROUTAGE_API_KEY" Step 2: Write the Lambda function
Save this as lambda_function.py. It calls the API with the key in an Authorization: Bearer header and, on a 429, waits the Retry-After seconds before trying again. Each county becomes one line of JSON, the format Athena reads, under a dt=YYYY-MM-DD prefix so queries can skip days they do not need. Keys are snake_case so Athena column names match them exactly. When the TOPIC_ARN environment variable is set, the handler also runs the optional site alert from the next step.
import json
import os
import time
import urllib.error
import urllib.request
from datetime import datetime, timezone
import boto3
s3 = boto3.client('s3')
sns = boto3.client('sns')
# Read once per cold start. The secret's value is the bare API key.
API_KEY = boto3.client('secretsmanager').get_secret_value(
SecretId=os.environ['API_KEY_SECRET']
)['SecretString']
def call(url, body=None):
"""GET, or POST a JSON body, waiting out a 429 for as long as Retry-After says."""
request = urllib.request.Request(
url,
data=None if body is None else json.dumps(body).encode(),
headers={'Authorization': f'Bearer {API_KEY}', 'Content-Type': 'application/json'},
)
for _ in range(3):
try:
with urllib.request.urlopen(request, timeout=30) as response:
return json.load(response)
except urllib.error.HTTPError as err:
if err.code != 429:
raise
time.sleep(int(err.headers.get('Retry-After', '10')))
raise RuntimeError(f'Still rate limited after 3 tries: {url}')
def handler(event, context):
# 45 is Georgia's stateId. List ids with GET /outages/states.
payload = call('https://poweroutage.us/api/v2/outages/counties?stateId=45&include=fips')
generated_at = payload['meta']['generatedAt']
lines = [
json.dumps({
'county_id': c['id'],
'county_name': c['name'],
'state_id': c['stateId'],
'fips': (c['fips'] or {}).get('full'),
'customers_out': c['customersOut'],
'customers_tracked': c['customersTracked'],
'last_updated_at': c['lastUpdatedAt'],
'generated_at': generated_at,
})
for c in payload['data']
]
now = datetime.now(timezone.utc)
s3.put_object(
Bucket=os.environ['BUCKET'],
Key=f'county-outages/dt={now:%Y-%m-%d}/{now:%H%M%S}.json',
Body='\n'.join(lines).encode(),
)
if os.environ.get('TOPIC_ARN'): # the optional site alert in the next step
alert_on_sites() Step 3: Optional: alert when a watched site is in an outage
Skip this step if you only want the S3 history: leave out this code and the TOPIC_ARN variable, and the handler never calls it. Otherwise add it to the same file. It POSTs your site coordinates to /geojson/at-point, which answers in the same order with outageAtPoint and the matching outages for each point. When any site is affected, it publishes one SNS message listing them. The next step creates the topic and subscribes an email address; a phone number or a queue works too. A site whose utilities all have providesGeospatialData: false cannot be confirmed either way, so check that flag before treating false as all clear.
# Move this list to S3, DynamoDB or Parameter Store once it grows.
SITES = [
{'name': 'Store 101, Atlanta', 'lat': 33.749, 'lon': -84.388},
{'name': 'Store 214, Savannah', 'lat': 32.0809, 'lon': -81.0912},
]
def alert_on_sites():
result = call(
'https://poweroutage.us/api/v2/geojson/at-point',
{'points': [{'lat': s['lat'], 'lon': s['lon']} for s in SITES]}, # up to 100 per call
)
lines = []
for site, point in zip(SITES, result['data']['points']): # same order as SITES
if point['outageAtPoint']:
worst = max(point['outages'], key=lambda o: o['customersOut'] or 0)
eta = worst['estimatedRestorationAt'] or 'not given'
lines.append(f"{site['name']}: {worst['customersOut']} customers out, restoration {eta}")
if lines:
sns.publish(
TopicArn=os.environ['TOPIC_ARN'],
Subject=f'{len(lines)} watched site(s) in a power outage',
Message='\n'.join(lines),
) Step 4: Deploy with the right permissions and timeout
The execution role needs the AWSLambdaBasicExecutionRole managed policy for logs, plus secretsmanager:GetSecretValue on the secret, s3:PutObject on county-outages/* in your bucket, and, for the optional alert, sns:Publish on the topic. Leave TOPIC_ARN out of the environment if you skipped the alert. Raise the timeout from the 3-second default to 60 seconds so a slow response or a Retry-After wait fits.
# Optional: the SNS topic for site alerts, with an email subscriber
aws sns create-topic --name site-outages
aws sns subscribe --topic-arn arn:aws:sns:us-east-1:123456789012:site-outages \
--protocol email --notification-endpoint ops@example.com
zip function.zip lambda_function.py
aws lambda create-function \
--function-name poweroutage-sync \
--runtime python3.13 \
--handler lambda_function.handler \
--role arn:aws:iam::123456789012:role/poweroutage-sync \
--timeout 60 \
--zip-file fileb://function.zip \
--environment '{"Variables": {
"API_KEY_SECRET": "poweroutage/api-key",
"BUCKET": "outage-data-lake"}}'
# Optional: only if you added the alert step
aws lambda update-function-configuration \
--function-name poweroutage-sync \
--environment '{"Variables": {
"API_KEY_SECRET": "poweroutage/api-key",
"BUCKET": "outage-data-lake",
"TOPIC_ARN": "arn:aws:sns:us-east-1:123456789012:site-outages"}}'
# A failed run waits for the next schedule instead of being retried twice
aws lambda put-function-event-invoke-config \
--function-name poweroutage-sync \
--maximum-retry-attempts 0 Step 5: Run it every 15 minutes with EventBridge Scheduler
Create a rate-based schedule that targets the function. The schedule role must trust scheduler.amazonaws.com and allow lambda:InvokeFunction on the function. Every 15 minutes is enough for most uses. The data updates every minute, so use rate(1 minute) or rate(2 minutes) if you need the latest numbers. Scheduler invokes the function asynchronously, which is why the retry count was set to 0 above.
aws scheduler create-schedule \
--name poweroutage-sync-every-15-min \
--schedule-expression 'rate(15 minutes)' \
--flexible-time-window '{"Mode": "OFF"}' \
--target '{
"Arn": "arn:aws:lambda:us-east-1:123456789012:function:poweroutage-sync",
"RoleArn": "arn:aws:iam::123456789012:role/poweroutage-scheduler"}' Step 6: Query the history with Athena
Create a table over the S3 prefix with the Hive JSON SerDe. Partition projection computes the dt partitions from the date range, so new days are queryable without MSCK REPAIR TABLE or a Glue crawler. Timestamps are stored as ISO 8601 strings; from_iso8601_timestamp converts them in queries.
CREATE EXTERNAL TABLE county_outages (
county_id bigint,
county_name string,
state_id bigint,
fips string,
customers_out bigint,
customers_tracked bigint,
last_updated_at string,
generated_at string
)
PARTITIONED BY (dt string)
ROW FORMAT SERDE 'org.apache.hive.hcatalog.data.JsonSerDe'
LOCATION 's3://outage-data-lake/county-outages/'
TBLPROPERTIES (
'projection.enabled' = 'true',
'projection.dt.type' = 'date',
'projection.dt.format' = 'yyyy-MM-dd',
'projection.dt.range' = '2026-01-01,NOW'
);
-- Peak customers out per county over the last 7 days
SELECT county_id, county_name, state_id, max(customers_out) AS peak_out
FROM county_outages
WHERE dt >= cast(current_date - interval '7' day AS varchar)
GROUP BY county_id, county_name, state_id
ORDER BY peak_out DESC
LIMIT 20;
-- Latest snapshot, with minutes since each county was reported
SELECT county_name,
customers_out,
customers_tracked,
date_diff('minute', from_iso8601_timestamp(last_updated_at),
from_iso8601_timestamp(generated_at)) AS minutes_since_report
FROM county_outages
WHERE dt = cast(current_date AS varchar)
AND generated_at = (SELECT max(generated_at) FROM county_outages
WHERE dt = cast(current_date AS varchar))
ORDER BY customers_out DESC; Tips for AWS
- If the function runs in a VPC, it needs a NAT gateway or other outbound route to reach
poweroutage.us. Outside a VPC, Lambda has internet access by default. - The alert fires on every run while a site stays dark. To alert once per outage, store the
utilityIdandoutageIdpairs you have already reported, in DynamoDB for example, and publish only new ones. /geojson/at-pointtakes up to 100 points per request. For more sites, send batches of 100 and keep under 10 requests per 10 seconds./outages/countiesis in the Core package, which is all the S3 history needs. The site alert calls/geojson/at-point, which is part of Standard + Locations; without it every run withTOPIC_ARNset fails after the S3 write.- Each state can include a county named
Unknownfor customers a utility could not place in a county. Itsfipsis null.
Used by
Related integrations
FAQ
Here are some commonly asked questions
Request API access
Tell us what you're building and we'll set you up with a trial key.