Power Outage Data in PostGIS

To get power outage data into PostGIS, run ogr2ogr from cron every 15 minutes to read the PostGIS-ready GeoJSON from the PowerOutage.us v2 REST API, with your API key in a GDAL header file only your account can read. ogr2ogr appends each geometry type to a load table, then one psql transaction replaces the tables your maps and queries read, so they never sit empty or half-written. QGIS, GeoServer and your own SQL can then use the outages like any other PostGIS layer. A Python version with psycopg does the same where GDAL is not installed.

What you'll have

  • An outage_points table and an outage_polygons table with a GiST index, customers out, cause and estimated restoration for every active outage in the states you choose.
  • Tables that keep their views, grants and indexes on every refresh, because rows are replaced inside one transaction instead of the tables being dropped.
  • An API key in a file with mode 600, never on the command line, in the crontab or in shell history.
  • Spatial joins between live outages and your own assets with ST_Intersects and ST_DWithin.

What you need

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

EndpointMethodUsed forPackage
/geojson/outagesGETEvery active outage as a GeoJSON feature, requested once with geometryType=point and once with geometryType=polygon so each table holds one geometry type.Standard

Step 1: Check GDAL, the database and network access

You need GDAL with the PostgreSQL driver (ogrinfo --formats lists PostgreSQL), the psql client, and a PostgreSQL database with PostGIS 3. The machine running cron needs outbound HTTPS to poweroutage.us and a connection to the database. Run the setup as a role that can create tables in the target schema, and let the job connect as that same role, so it owns all four tables. CREATE EXTENSION postgis needs a superuser or your cloud provider's admin role, once.

Step 2: Put the key in a GDAL header file and the database login in libpq files

GDAL's GDAL_HTTP_HEADER_FILE option sends every line of a file as an HTTP header, and it reads the file again before each request. Writing it inside umask 077 creates it with mode 600. The key never appears in ps output or the crontab, which it would if you passed it with GDAL_HTTP_HEADERS. A connection service file and ~/.pgpass keep the database password out of the script in the same way; ogr2ogr, psql and psycopg all read them through libpq.

bash
mkdir -p ~/.config/poweroutage
# Paste the key at the prompt; it is not echoed or kept in your shell history
read -rs POWEROUTAGE_API_KEY
( umask 077; printf 'Authorization: Bearer %s\n' "$POWEROUTAGE_API_KEY" \
    > ~/.config/poweroutage/headers )
unset POWEROUTAGE_API_KEY

# Where the outage tables live
cat >> ~/.pg_service.conf <<'EOF'
[outages]
host=db.example.com
dbname=gis
user=outage_loader
EOF

# Then add this line to ~/.pgpass in an editor and run chmod 600 ~/.pgpass:
# db.example.com:5432:gis:outage_loader:<database password>

Step 3: Create the load and outage tables

The two _load tables receive ogr2ogr's output. When it appends to an existing table, ogr2ogr matches the API's camelCase property names to these lower-case columns, ignores properties that have no column, and writes nothing when there are no outages. The outage_points and outage_polygons tables are what you query and map, with snake_case columns, SRID 4326 and a GiST index each. Polygons are stored as MultiPolygon, because utilities report both Polygon and MultiPolygon shapes. Grant SELECT to whichever role your map users connect as.

sql
CREATE EXTENSION IF NOT EXISTS postgis;  -- needs a superuser, once per database

-- Filled by ogr2ogr on each run. Columns are the API's property names in lower case.
CREATE TABLE outage_points_load (
  utilityid integer,
  outageid text,
  customersout integer,
  cause text,
  estimatedrestorationat timestamptz,
  firstseenat timestamptz,
  recordedat timestamptz,
  geom geometry(Point, 4326)
);
CREATE TABLE outage_polygons_load (LIKE outage_points_load);
ALTER TABLE outage_polygons_load ALTER COLUMN geom TYPE geometry(MultiPolygon, 4326);

-- What maps and queries read
CREATE TABLE outage_points (
  utility_id integer NOT NULL,
  outage_id text,
  customers_out integer,
  cause text,
  estimated_restoration_at timestamptz,
  first_seen_at timestamptz,
  recorded_at timestamptz,
  geom geometry(Point, 4326) NOT NULL
);
CREATE TABLE outage_polygons (LIKE outage_points INCLUDING ALL);
ALTER TABLE outage_polygons ALTER COLUMN geom TYPE geometry(MultiPolygon, 4326);
CREATE INDEX ON outage_points USING gist (geom);
CREATE INDEX ON outage_polygons USING gist (geom);

GRANT SELECT ON outage_points, outage_polygons TO gis_readers;

Step 4: Write the load script

Save this as ~/poweroutage/load-outages.sh. It empties the load tables, then runs ogr2ogr once per geometry type. GDAL opens the HTTPS URL with the header from the file. GDAL retries a 429 or a 5xx response up to twice, at least GDAL_HTTP_RETRY_DELAY seconds apart; the API's rate-limit window is 10 seconds, so a 10-second delay waits out a 429. -nlt PROMOTE_TO_MULTI turns every polygon into a MultiPolygon so it fits the column. If a download fails, ogr2ogr exits with an error, set -e stops the script, and the outage tables keep the last good data.

bash
#!/bin/sh
# ~/poweroutage/load-outages.sh: replace the outage tables with what the API reports now
set -eu
cd "$(dirname "$0")"
DB=service=outages
HEADERS="$HOME/.config/poweroutage/headers"
STATES=44,45  # Florida and Georgia. List ids with GET /outages/states.

psql "$DB" -q -c 'TRUNCATE outage_points_load, outage_polygons_load'

ogr2ogr --config GDAL_HTTP_HEADER_FILE "$HEADERS" \
  --config GDAL_HTTP_MAX_RETRY 2 --config GDAL_HTTP_RETRY_DELAY 10 \
  -append -nln outage_points_load "PG:$DB" \
  "https://poweroutage.us/api/v2/geojson/outages?stateId=$STATES&geometryType=point"

ogr2ogr --config GDAL_HTTP_HEADER_FILE "$HEADERS" \
  --config GDAL_HTTP_MAX_RETRY 2 --config GDAL_HTTP_RETRY_DELAY 10 \
  -append -nln outage_polygons_load -nlt PROMOTE_TO_MULTI "PG:$DB" \
  "https://poweroutage.us/api/v2/geojson/outages?stateId=$STATES&geometryType=polygon"

psql "$DB" -q -1 -v ON_ERROR_STOP=1 -f swap-outages.sql

Step 5: Swap the rows in one transaction

Save this as ~/poweroutage/swap-outages.sql, next to the script. psql -1 runs the whole file as one transaction and ON_ERROR_STOP rolls it back on any error, so other sessions see either the previous outages or the new ones. DELETE rather than TRUNCATE lets readers keep querying while it runs. The field mapping is in the two INSERT statements: utilityid to utility_id, outageid to outage_id, customersout to customers_out, and so on. ST_MakeValid repairs self-intersecting polygons, and ST_CollectionExtract keeps only their polygon parts.

sql
-- ~/poweroutage/swap-outages.sql, run with psql -1: one transaction, so readers
-- keep seeing the previous outages until it commits
DELETE FROM outage_points;
INSERT INTO outage_points (utility_id, outage_id, customers_out, cause,
                           estimated_restoration_at, first_seen_at, recorded_at, geom)
SELECT utilityid, outageid, customersout, cause,
       estimatedrestorationat, firstseenat, recordedat, geom
FROM outage_points_load;

DELETE FROM outage_polygons;
INSERT INTO outage_polygons (utility_id, outage_id, customers_out, cause,
                             estimated_restoration_at, first_seen_at, recorded_at, geom)
SELECT utilityid, outageid, customersout, cause,
       estimatedrestorationat, firstseenat, recordedat,
       ST_Multi(ST_CollectionExtract(ST_MakeValid(geom), 3))  -- repair self-intersections
FROM outage_polygons_load;

Step 6: Run it every 15 minutes with cron

Run the script once by hand and check the counts with SELECT count(*) FROM outage_points. Then add a crontab entry. Cron starts jobs with a minimal PATH and without your shell profile, so set PATH to include the folders where ogr2ogr and psql live. Two runs at once would empty and fill the same load tables, so the entry wraps the script in flock -n (part of util-linux on Linux), which skips a run while the previous one is still going. Every 15 minutes is enough for most uses. The data updates every minute, so for the latest rows run it every 1 or 2 minutes (* * * * * or */2 * * * *). Each run makes two API requests.

bash
chmod +x ~/poweroutage/load-outages.sh
~/poweroutage/load-outages.sh   # once by hand; it prints nothing when it works

crontab -e
# cron's PATH is minimal; include wherever ogr2ogr and psql are installed
PATH=/usr/local/bin:/usr/bin:/bin
# flock -n skips a run while the previous one still holds the lock
*/15 * * * * flock -n $HOME/poweroutage/.lock $HOME/poweroutage/load-outages.sh >> $HOME/poweroutage/load.log 2>&1

Step 7: Query outages next to your own assets

Your sites.geom must also be SRID 4326; PostGIS refuses to compare geometries with different SRIDs, so wrap another SRID in ST_Transform(s.geom, 4326). A point outage has no area, so match it by distance; casting to geography makes ST_DWithin take meters. The geography cast skips the GiST index, which is fine for a few thousand outages; for large site tables, add an index on (geom::geography) or transform both sides to a projected SRID. Group by utility_id, not by utility name. recorded_at is when each outage was last read from the utility.

sql
-- Your sites inside an outage polygon, or within 500 m of an outage point
SELECT s.name, o.utility_id, o.outage_id, o.customers_out, o.estimated_restoration_at
FROM sites s
JOIN outage_polygons o ON ST_Intersects(o.geom, s.geom)
UNION ALL
SELECT s.name, o.utility_id, o.outage_id, o.customers_out, o.estimated_restoration_at
FROM sites s
JOIN outage_points o ON ST_DWithin(o.geom::geography, s.geom::geography, 500);

-- Customers out by utility, largest first
SELECT utility_id, sum(customers_out) AS customers_out, count(*) AS outages
FROM (SELECT utility_id, customers_out FROM outage_points
      UNION ALL
      SELECT utility_id, customers_out FROM outage_polygons) o
GROUP BY utility_id
ORDER BY customers_out DESC NULLS LAST
LIMIT 10;

Step 8: Or load it with Python instead

Where GDAL is not available, this script does the same with requests and psycopg 3 (pip install requests "psycopg[binary]"). It reads the same header file and service name, downloads both geometry types before touching the database, and replaces both tables in one transaction: psycopg.connect used in a with block commits at the end and rolls back if anything fails. ST_GeomFromGeoJSON takes each feature's geometry object. Run it from cron the same way, without the load tables.

python
import json
import os
import time

import psycopg
import requests

# The same "Authorization: Bearer <key>" line that ogr2ogr reads
with open(os.path.expanduser('~/.config/poweroutage/headers')) as file:
    name, value = file.read().strip().split(': ', 1)
HEADERS = {name: value}
# 44 is Florida and 45 is Georgia. List ids with GET /outages/states.
STATE_IDS = '44,45'
TABLES = {'point': 'outage_points', 'polygon': 'outage_polygons'}
SHAPES = {
    'point': 'ST_SetSRID(ST_GeomFromGeoJSON(%s), 4326)',
    'polygon': 'ST_Multi(ST_CollectionExtract(ST_MakeValid(ST_SetSRID(ST_GeomFromGeoJSON(%s), 4326)), 3))',
}


def get_outages(geometry_type):
    """GET one geometry type of outages, waiting out a 429 for as long as Retry-After says."""
    for attempt in range(3):
        response = requests.get(
            'https://poweroutage.us/api/v2/geojson/outages',
            params={'stateId': STATE_IDS, 'geometryType': geometry_type},
            headers=HEADERS,
            timeout=60,
        )
        if response.status_code != 429:
            response.raise_for_status()
            return response.json()['features']
        if attempt < 2:
            time.sleep(int(response.headers.get('Retry-After', '10')))
    raise RuntimeError('Still rate limited after 3 tries')


def row(feature):
    p = feature['properties']
    return (p['utilityId'], p['outageId'], p['customersOut'], p['cause'],
            p['estimatedRestorationAt'], p['firstSeenAt'], p['recordedAt'],
            json.dumps(feature['geometry']))


features = {kind: get_outages(kind) for kind in TABLES}  # download both before writing
with psycopg.connect('service=outages') as conn:  # commits when the block ends, rolls back on error
    for kind, table in TABLES.items():
        conn.execute(f'DELETE FROM {table}')
        conn.cursor().executemany(
            f'INSERT INTO {table} (utility_id, outage_id, customers_out, cause, '
            'estimated_restoration_at, first_seen_at, recorded_at, geom) '
            f'VALUES (%s, %s, %s, %s, %s, %s, %s, {SHAPES[kind]})',
            [row(f) for f in features[kind]],
        )

Tips for PostGIS

  • Do not point ogr2ogr -overwrite at a table that views depend on. It drops and recreates the table with CASCADE, which silently removes those views and resets grants. That is why this setup appends to load tables and swaps rows in SQL.
  • In QGIS, add outage_points and outage_polygons as PostGIS layers and turn on Refresh layer at interval with Reload data in Layer Properties > Rendering. Every QGIS user then sees the same live data with no API key on their machine.
  • To keep history, create outage_points_history (LIKE outage_points, loaded_at timestamptz) and add INSERT INTO outage_points_history SELECT *, now() FROM outage_points; to the end of the swap file. Do the same for polygons.
  • Add &minCustomersOut=100, &countyId= or &utilityId= to the URLs to load only the outages you care about.
  • /geojson/outages covers only utilities that publish outage locations. A utility that reports counts by area only is in /outages/counties, not in these tables.

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.