Power Outage Data in Datadog

To get power outage data into Datadog, run a short Python script every 15 minutes that reads county outage counts from the PowerOutage.us v2 REST API and submits them as gauge metrics to the Datadog Metrics API (/api/v2/series), tagged with the state id, county id and county name. Metric monitors then alert when a county passes a threshold. Two optional steps cover your own sites: a metric that says whether each one sits inside an active outage, and an alert event with the utility, customers out, cause and estimated restoration when an outage reaches one. The script uses only the Python standard library and runs anywhere you can schedule it.

What you'll have

  • poweroutage.county.customers_out and poweroutage.county.customers_tracked gauges for every county in the states you watch, tagged state_id, county_id and county.
  • A multi alert monitor that notifies once per county when it passes 5,000 customers out, and recovers by itself.
  • An optional poweroutage.site.in_outage gauge, 1 or 0, for each of your sites, with a monitor that notifies per site through your usual handles.
  • Optional alert events in Datadog Event Management, one per outage covering your sites, with an ok event when the outage no longer covers any of them.
  • A predictable custom metric count: two per county, plus one per site.

What you need

An API key (request one with the form below) and these endpoints. Full details are in the API reference.

EndpointMethodUsed forPackage
/outages/countiesGETCounty customersOut and customersTracked, submitted as two gauges per county on every run.Core
/geojson/at-pointPOSTFor the optional site metric and events: checks up to 100 site coordinates per request and returns outageAtPoint and the outages covering each one.Standard + Locations

Step 1: Get an API key and know your Datadog site

Create an API key under Organization Settings > API Keys, or use an existing one. Submitting metrics needs only the API key. An application key, from Organization Settings > Application Keys, is needed once to create monitors through the API, and on every run only if you do the optional events step. Note your Datadog site, the domain in your Datadog URL, such as datadoghq.com, us3.datadoghq.com or datadoghq.eu: the script sends metrics to api. plus that site, and a key from one site is rejected by another. The host that runs the script needs outbound HTTPS to poweroutage.us and to that API host.

Step 2: Write the script

Save this as /opt/poweroutage/poweroutage_datadog.py and change STATE_IDS to the states you watch. It sends the API key in an Authorization: Bearer header and, on a 429, waits the Retry-After seconds, three tries at most, without waiting after the last. Each county becomes two gauges (type 3) stamped with the current time: customersOut to poweroutage.county.customers_out and customersTracked to poweroutage.county.customers_tracked, tagged state_id:<stateId>, county_id:<id> and county:<name>. Datadog lowercases tags and turns spaces into underscores, so Ben Hill becomes county:ben_hill. The series go to /api/v2/series in batches of 500 to stay under its 500 KB request limit; if Datadog rejects a request, the script stops and the next run sends fresh values. Leave SITES_FILE unset to skip the site metric, and DD_APP_KEY unset to skip the events; the next two steps explain both.

python
import json
import os
import time
import urllib.error
import urllib.request
from pathlib import Path

API_KEY = os.environ['POWEROUTAGE_API_KEY']
DD_API_KEY = os.environ['DD_API_KEY']
# Your Datadog site: datadoghq.com, us3.datadoghq.com, us5.datadoghq.com, datadoghq.eu, ap1.datadoghq.com ...
DD_SITE = os.environ.get('DD_SITE', 'datadoghq.com')
SITES_FILE = os.environ.get('SITES_FILE')  # optional; set it only if you do the site step
DD_APP_KEY = os.environ.get('DD_APP_KEY')  # optional; set it only if you do the events step
# 44 is Florida and 45 is Georgia. List ids with GET /outages/states.
STATE_IDS = '44,45'


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 attempt 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 or attempt == 2:
                raise
            time.sleep(int(err.headers.get('Retry-After', '10')))


def send(url, body, extra_headers=None):
    """POST a JSON body to Datadog; any error stops the run."""
    request = urllib.request.Request(
        url,
        data=json.dumps(body).encode(),
        headers={'DD-API-KEY': DD_API_KEY, 'Content-Type': 'application/json', **(extra_headers or {})},
    )
    with urllib.request.urlopen(request, timeout=30) as response:
        response.read()


def gauge(metric, value, tags, now):
    return {'metric': metric, 'type': 3, 'points': [{'timestamp': now, 'value': value}], 'tags': tags}


def county_series(now):
    payload = call(f'https://poweroutage.us/api/v2/outages/counties?stateId={STATE_IDS}')
    series = []
    for county in payload['data']:
        tags = [f"state_id:{county['stateId']}", f"county_id:{county['id']}", f"county:{county['name']}"]
        series.append(gauge('poweroutage.county.customers_out', county['customersOut'], tags, now))
        series.append(gauge('poweroutage.county.customers_tracked', county['customersTracked'], tags, now))
    return series


def check_sites(now):
    """One gauge per site, plus every outage covering a site, keyed poweroutage:<utilityId>:<outageId>."""
    with open(SITES_FILE) as f:
        sites = json.load(f)  # [{"id": "store-101", "lat": 33.749, "lon": -84.388}, ...]
    series, outages = [], {}
    for i in range(0, len(sites), 100):  # up to 100 points per request
        batch = sites[i : i + 100]
        result = call(
            'https://poweroutage.us/api/v2/geojson/at-point',
            {'points': [{'lat': s['lat'], 'lon': s['lon']} for s in batch]},
        )
        for site, point in zip(batch, result['data']['points']):  # same order as the request
            value = 1 if point['outageAtPoint'] else 0
            series.append(gauge('poweroutage.site.in_outage', value, [f"site:{site['id']}"], now))
            names = {u['utilityId']: u['name'] for u in point['utilities']}
            for outage in point['outages']:
                key = f"poweroutage:{outage['utilityId']}:{outage['outageId']}"
                utility = names.get(outage['utilityId']) or f"Utility {outage['utilityId']}"
                entry = outages.setdefault(key, {'outage': outage, 'utility': utility, 'sites': []})
                entry['sites'].append(site['id'])
    return series, outages


def event(key, status, title, message):
    send(
        f'https://event-management-intake.{DD_SITE}/api/v2/events',
        {'data': {'type': 'event', 'attributes': {
            'category': 'alert',
            'title': title[:500],
            'message': message[:4000],
            'aggregation_key': key[:100],
            'attributes': {'status': status},
        }}},
        {'DD-APPLICATION-KEY': DD_APP_KEY},
    )


def send_events(outages):
    """An error event when an outage first covers a watched site, an ok event when it covers none."""
    state_file = Path(os.environ['STATE_FILE'])  # outages already announced, kept between runs
    announced = json.loads(state_file.read_text()) if state_file.exists() else {}
    try:
        for key, entry in outages.items():
            if announced.get(key) == entry['sites']:
                continue  # already announced for the same sites
            outage = entry['outage']
            out = 'unknown' if outage['customersOut'] is None else f"{outage['customersOut']:,}"
            event(
                key,
                'error',
                f"Power outage at {', '.join(entry['sites'])} ({entry['utility']})",
                f"Customers out: {out}. Cause: {outage['cause'] or 'not reported'}. "
                f"Estimated restoration (UTC): {outage['estimatedRestorationAt'] or 'not given'}.",
            )
            announced[key] = entry['sites']
        for key in [k for k in announced if k not in outages]:
            sites = ', '.join(announced[key])
            event(
                key,
                'ok',
                f'Power outage no longer reported at {sites}',
                'PowerOutage.us no longer reports this outage at these sites.',
            )
            del announced[key]
    finally:
        state_file.write_text(json.dumps(announced))


now = int(time.time())
series, outages = county_series(now), {}
if SITES_FILE:
    site_gauges, outages = check_sites(now)
    series += site_gauges
for i in range(0, len(series), 500):  # keeps each request well under the 500 KB limit
    send(f'https://api.{DD_SITE}/api/v2/series', {'series': series[i : i + 500]})
if SITES_FILE and DD_APP_KEY:
    send_events(outages)
print(f'Submitted {len(series)} series to Datadog')

Step 3: Optional: a metric for each of your sites

Skip this step if county counts are enough. Otherwise list your sites in /opt/poweroutage/sites.json with an id, which becomes the site tag, and coordinates, then set SITES_FILE in the next step. The script posts the coordinates to /geojson/at-point, 100 per request, and submits poweroutage.site.in_outage as 1 when the site sits inside an active outage and 0 when it doesn't. That endpoint is in the Standard + Locations package; without it, leave SITES_FILE unset, because every run with it set would fail. A site whose utilities all report providesGeospatialData: false always reads 0, because those utilities publish counts by area only.

json
[
  {"id": "store-101", "lat": 33.749, "lon": -84.388},
  {"id": "store-214", "lat": 32.0809, "lon": -81.0912}
]

Step 4: Optional: an alert event when an outage reaches a site

This step builds on the site step. Set DD_APP_KEY to an application key and STATE_FILE to a path the job can write, and the script also posts to the Events API v2 at event-management-intake. plus your site, which requires the application key as well as the API key; leave DD_APP_KEY unset to skip it. Each outage covering a watched site becomes one alert category event with status error: the title names the site ids and the utility, the message carries customersOut, cause and estimatedRestorationAt, and aggregation_key is poweroutage:<utilityId>:<outageId>, which Datadog uses to deduplicate the events into one alert. The state file records what was announced, so an event goes out only when an outage first reaches a site or its list of sites changes, and an event with status ok and the same key follows once the outage covers none of them. If an event post fails, the metrics have already been sent and the next run retries the events that were not recorded.

text
POST https://event-management-intake.<your site>/api/v2/events
DD-API-KEY and DD-APPLICATION-KEY headers

{
  "data": {
    "type": "event",
    "attributes": {
      "category": "alert",
      "title": "Power outage at store-214 (Georgia Power)",
      "message": "Customers out: 1,240. Cause: Tree on line. Estimated restoration (UTC): 2026-12-03T21:30:00.000Z.",
      "aggregation_key": "poweroutage:5097:A202633703426",
      "attributes": {"status": "error"}
    }
  }
}

When the outage no longer covers any watched site, the same aggregation_key is sent with
"title": "Power outage no longer reported at store-214" and "attributes": {"status": "ok"}.

Step 5: Run it every 15 minutes

Keep the keys in an environment file that only the job's account can read, and schedule the script from that account's crontab; set -a exports every line to the script, and the shell reads the file, so keep every value in single quotes, as shown. Uncomment the optional lines only for the steps you did. A Lambda function, a Kubernetes CronJob or any other scheduler works the same way if it passes these environment variables from its own secret store, as long as the events state file survives between runs, which the local disk of a Lambda function does not guarantee. Every 15 minutes is enough for most uses. The data updates every minute, so for the latest values run it every 1 or 2 minutes (* * * * * or */2 * * * *). After the first run, the metrics appear in the Metrics Explorer within a few minutes.

text
# /opt/poweroutage/datadog.env: owned by the account that runs the job, chmod 600.
# Put every value in single quotes, as below; write a single quote inside a value as '\''.
POWEROUTAGE_API_KEY='...'
DD_API_KEY='...'
DD_SITE='datadoghq.com'
# SITES_FILE='/opt/poweroutage/sites.json'            (only with the optional site step)
# DD_APP_KEY='...'                                     (only with the optional events step)
# STATE_FILE='/opt/poweroutage/datadog-events.json'   (only with the optional events step)

# crontab -e, as that account
*/15 * * * * set -a && . /opt/poweroutage/datadog.env && /usr/bin/python3 /opt/poweroutage/poweroutage_datadog.py >> /opt/poweroutage/poweroutage_datadog.log 2>&1

Step 6: Create the monitors

Creating monitors through the API needs an application key as well as the API key, and the key's owner needs permission to write monitors; you only run this once. Replace @slack-noc-alerts with the notification handles you use, such as @pagerduty-<service> or an email address. The county monitor groups by county_id and county, so it alerts separately for each county, and by id because county names repeat across states. Both monitors take the highest value of the last 20 minutes, a window that always holds the latest point, so they alert on the first run that crosses the threshold and recover within about 20 minutes. require_full_window is off because a point arrives only every 15 minutes. To build the same monitors in the UI, choose Monitors > New Monitor > Metric and enter the query, threshold and message from each definition.

bash
read -rs DD_API_KEY    # paste the API key; it is not echoed
read -rs DD_APP_KEY    # paste an application key that can write monitors
DD_SITE=datadoghq.com  # your Datadog site

curl -sS -X POST "https://api.$DD_SITE/api/v1/monitor" \
  -H "DD-API-KEY: $DD_API_KEY" -H "DD-APPLICATION-KEY: $DD_APP_KEY" \
  -H 'Content-Type: application/json' -d @- <<'EOF'
{
  "name": "Power outage: county over 5,000 customers out",
  "type": "query alert",
  "query": "max(last_20m):max:poweroutage.county.customers_out{*} by {county_id,county} > 5000",
  "message": "{{#is_alert}}{{value}} customers out in {{county.name}} (county_id {{county_id.name}}).{{/is_alert}}{{#is_recovery}}{{county.name}} is no longer over 5,000 customers out.{{/is_recovery}} @slack-noc-alerts",
  "options": {"thresholds": {"critical": 5000}, "require_full_window": false}
}
EOF

# Only with the optional site step
curl -sS -X POST "https://api.$DD_SITE/api/v1/monitor" \
  -H "DD-API-KEY: $DD_API_KEY" -H "DD-APPLICATION-KEY: $DD_APP_KEY" \
  -H 'Content-Type: application/json' -d @- <<'EOF'
{
  "name": "Power outage at a watched site",
  "type": "query alert",
  "query": "max(last_20m):max:poweroutage.site.in_outage{*} by {site} >= 1",
  "message": "{{#is_alert}}{{site.name}} is inside an active power outage.{{/is_alert}}{{#is_recovery}}{{site.name}} is no longer inside a reported outage.{{/is_recovery}} @slack-noc-alerts",
  "options": {"thresholds": {"critical": 1}, "require_full_window": false}
}
EOF

Tips for Datadog

  • Datadog bills each combination of metric name and tag values as one custom metric. This setup adds two per county, about 460 for Florida and Georgia and about 6,600 for every US county, plus one per site. Compare that with your plan's custom metric allotment before you widen STATE_IDS, or drop the customers_tracked gauge if you only alert on counts.
  • For percent of customers out on a dashboard, graph poweroutage.county.customers_out as a and poweroutage.county.customers_tracked as b, both by county_id, and add the formula a / b * 100.
  • Turn on Notify if data is missing on the site monitor so a stopped script raises an alert instead of going quiet.
  • Each state can include a county named Unknown for customers a utility could not place in a county. It arrives as county:unknown with its own county_id.

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.