Power Outage Data in BigQuery

To get power outage data into BigQuery, run a small Python Cloud Run job every 15 minutes from Cloud Scheduler, with your PowerOutage.us API key in Secret Manager. Each run appends county counts to a partitioned table, so you build a history of every storm, and replaces a table of active outages whose shapes are converted with ST_GEOGFROMGEOJSON into GEOGRAPHY values you can join to your own sites. This is also the Google Cloud setup: the job, the secret and the schedule are ordinary Google Cloud resources, and BigQuery is where the data lands.

What you'll have

  • A county_outages table, partitioned by day, with one row per county per run: customers out, customers tracked and when each county was last reported.
  • An active_outages table with every current outage as a GEOGRAPHY, ready for ST_INTERSECTS and ST_DWITHIN joins against your locations.
  • An API key in Secret Manager, with read access granted to the job's service account alone.
  • A Cloud Run job that runs to completion every 15 minutes, with no server or VM to manage.

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 for the states you choose, with include=fips for joins to census and county data.Core
/geojson/outagesGETEvery active outage as a GeoJSON feature. The job keeps each geometry object for ST_GEOGFROMGEOJSON.Standard

Step 1: Store the key and create a service account

Run these in Cloud Shell or any terminal signed in with gcloud, replacing PROJECT_ID; the first line makes it the default project for every command in this guide. You need permission to enable services, create secrets and service accounts, and grant IAM roles; a project Owner has all of these. The service account poweroutage-sync is the job's identity. It gets Secret Manager Secret Accessor on this one secret and BigQuery Job User on the project, which lets it run load and query jobs. Write access to the dataset comes in the next step. Grant the secret role before you deploy, because Cloud Run checks that the job can read every secret it references.

bash
gcloud config set project PROJECT_ID

gcloud services enable run.googleapis.com cloudscheduler.googleapis.com \
  secretmanager.googleapis.com bigquery.googleapis.com \
  cloudbuild.googleapis.com artifactregistry.googleapis.com

# Paste the key at the prompt. It isn't shown, and it stays out of your shell history.
read -rs POWEROUTAGE_API_KEY
printf '%s' "$POWEROUTAGE_API_KEY" | gcloud secrets create poweroutage-api-key --data-file=-

# The identity the job runs as
gcloud iam service-accounts create poweroutage-sync
SA=poweroutage-sync@PROJECT_ID.iam.gserviceaccount.com
gcloud secrets add-iam-policy-binding poweroutage-api-key \
  --member="serviceAccount:$SA" --role=roles/secretmanager.secretAccessor
gcloud projects add-iam-policy-binding PROJECT_ID \
  --member="serviceAccount:$SA" --role=roles/bigquery.jobUser

Step 2: Create the dataset and tables

Run this in BigQuery Studio. Pick a dataset location near your other data; US is a multi-region. county_outages is partitioned by the date of generated_at, so queries that filter on it read only the days they need. active_outages_load holds each run's raw outages, with the geometry as GeoJSON text, and active_outages holds the same rows with a GEOGRAPHY column. The GRANT gives the service account BigQuery Data Editor on this dataset only. Timestamps from the API are ISO 8601 strings in UTC, which BigQuery loads into TIMESTAMP columns as they are.

sql
CREATE SCHEMA IF NOT EXISTS poweroutage OPTIONS (location = 'US');

-- One row per county per run, so you can chart a county through a storm
CREATE TABLE IF NOT EXISTS poweroutage.county_outages (
  county_id INT64,
  county_name STRING,
  state_id INT64,
  fips STRING,
  customers_out INT64,
  customers_tracked INT64,
  last_updated_at TIMESTAMP,
  generated_at TIMESTAMP
)
PARTITION BY DATE(generated_at);

-- Outages from the latest run, with the geometry still as GeoJSON text
CREATE TABLE IF NOT EXISTS poweroutage.active_outages_load (
  utility_id INT64,
  outage_id STRING,
  customers_out INT64,
  cause STRING,
  estimated_restoration_at TIMESTAMP,
  geometry STRING,
  generated_at TIMESTAMP
);

-- The outages active now, each shape a GEOGRAPHY
CREATE TABLE IF NOT EXISTS poweroutage.active_outages (
  utility_id INT64,
  outage_id STRING,
  customers_out INT64,
  cause STRING,
  estimated_restoration_at TIMESTAMP,
  shape GEOGRAPHY,
  generated_at TIMESTAMP
);

-- The job can write to this dataset and nothing else
GRANT `roles/bigquery.dataEditor` ON SCHEMA poweroutage
TO "serviceAccount:poweroutage-sync@PROJECT_ID.iam.gserviceaccount.com";

Step 3: Write the job

Save this as main.py. It reads the key from the POWEROUTAGE_API_KEY environment variable, which Cloud Run fills from Secret Manager, and sends it in an Authorization: Bearer header. On a 429 it waits the Retry-After seconds and tries again. County rows are appended with a load job, which is free. ST_GEOGFROMGEOJSON accepts a GeoJSON geometry object only, not a Feature, so the job stores each feature's geometry member as JSON text and converts it in SQL. make_valid => TRUE repairs polygons that cross themselves, and the SAFE. prefix stores NULL instead of failing the whole insert if a shape cannot be read. The delete and insert run in one transaction, so a query never sees an empty table.

python
import json
import os
import time

import requests
from google.cloud import bigquery

# Set from Secret Manager by --set-secrets, never stored in the code or the image
API_KEY = os.environ['POWEROUTAGE_API_KEY']
# 44 is Florida and 45 is Georgia. List ids with GET /outages/states.
STATE_IDS = '44,45'

REPLACE_ACTIVE_OUTAGES = """
BEGIN TRANSACTION;
DELETE FROM poweroutage.active_outages WHERE TRUE;
INSERT INTO poweroutage.active_outages
SELECT utility_id, outage_id, customers_out, cause, estimated_restoration_at,
       SAFE.ST_GEOGFROMGEOJSON(geometry, make_valid => TRUE), generated_at
FROM poweroutage.active_outages_load;
COMMIT TRANSACTION;
"""


def get(url, params):
    """GET a PowerOutage.us endpoint, waiting out a 429 for as long as Retry-After says."""
    for attempt in range(3):
        response = requests.get(
            url, params=params, headers={'Authorization': f'Bearer {API_KEY}'}, timeout=60
        )
        if response.status_code != 429:
            response.raise_for_status()
            return response.json()
        if attempt < 2:
            time.sleep(int(response.headers.get('Retry-After', '10')))
    raise RuntimeError(f'Still rate limited after 3 tries: {url}')


client = bigquery.Client()

counties = get(
    'https://poweroutage.us/api/v2/outages/counties', {'stateId': STATE_IDS, 'include': 'fips'}
)
client.load_table_from_json(
    [
        {
            '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': counties['meta']['generatedAt'],
        }
        for c in counties['data']
    ],
    'poweroutage.county_outages',  # the table exists, so the load appends with its schema
).result()

outages = get('https://poweroutage.us/api/v2/geojson/outages', {'stateId': STATE_IDS})
rows = [
    {
        'utility_id': f['properties']['utilityId'],
        'outage_id': f['properties']['outageId'],
        'customers_out': f['properties']['customersOut'],
        'cause': f['properties']['cause'],
        'estimated_restoration_at': f['properties']['estimatedRestorationAt'],
        'geometry': json.dumps(f['geometry']),  # the geometry object alone, not the Feature
        'generated_at': outages['meta']['generatedAt'],
    }
    for f in outages['features']
]
client.query('TRUNCATE TABLE poweroutage.active_outages_load').result()
if rows:
    client.load_table_from_json(rows, 'poweroutage.active_outages_load').result()
client.query(REPLACE_ACTIVE_OUTAGES).result()
print(f"{len(counties['data'])} counties, {len(rows)} outages")

Step 4: Deploy it as a Cloud Run job and run it once

Deploying with --source builds a container from main.py, requirements.txt and the Procfile with Cloud Build and stores it in Artifact Registry; the first deploy offers to create the repository. Deploying from source also needs the Cloud Run Admin, Cloud Run Source Developer and Service Account User roles for you, and the Cloud Run Builder role for the build service account. --set-secrets exposes version 1 of the secret as the environment variable; Google recommends a fixed version for environment variables. A failed run gets one retry, and a run is stopped after 5 minutes. --wait prints whether the first execution succeeded; its logs are in Cloud Logging. Cloud Run jobs can reach the internet by default, so no network setup is needed unless you route all egress through a VPC.

bash
# In the folder that holds main.py
printf 'google-cloud-bigquery\nrequests\n' > requirements.txt
printf 'web: python3 main.py\n' > Procfile

gcloud run jobs deploy poweroutage-sync \
  --source . \
  --region us-central1 \
  --service-account poweroutage-sync@PROJECT_ID.iam.gserviceaccount.com \
  --set-secrets POWEROUTAGE_API_KEY=poweroutage-api-key:1 \
  --max-retries 1 \
  --task-timeout 5m

gcloud run jobs execute poweroutage-sync --region us-central1 --wait

Step 5: Run it every 15 minutes with Cloud Scheduler

Grant the service account Cloud Run Invoker on the job, then create a Scheduler job that calls the Cloud Run Admin API's :run endpoint with an OAuth token for that account. Creating it needs Cloud Scheduler Admin and Service Account User on the account. The Scheduler location doesn't have to match the job's region. The schedule runs in UTC unless you add --time-zone. You can do the same from the job's Triggers tab in the console with Add Scheduler Trigger. Every 15 minutes is enough for most uses. The data updates every minute, so */2 * * * * gets the latest numbers. Avoid running every minute: each run loads each table once, and BigQuery allows 1,500 table operations, load jobs included, per table per day.

bash
# Let the service account start the job
gcloud run jobs add-iam-policy-binding poweroutage-sync --region us-central1 \
  --member="serviceAccount:poweroutage-sync@PROJECT_ID.iam.gserviceaccount.com" \
  --role=roles/run.invoker

gcloud scheduler jobs create http poweroutage-sync-every-15-min \
  --location us-central1 \
  --schedule '*/15 * * * *' \
  --uri 'https://run.googleapis.com/v2/projects/PROJECT_ID/locations/us-central1/jobs/poweroutage-sync:run' \
  --http-method POST \
  --oauth-service-account-email poweroutage-sync@PROJECT_ID.iam.gserviceaccount.com

Step 6: Query outages next to your own data

Filter county_outages on generated_at so BigQuery prunes partitions, and group by county_id, because county names repeat across states. The latest snapshot is the rows whose generated_at equals the table's maximum, and the gap between last_updated_at and generated_at shows how long ago each county was reported. ST_GEOGPOINT takes longitude first. A point outage has no area, so ST_INTERSECTS will not match it; the second query catches sites within 500 meters of one. Each half joins on one spatial predicate with a constant distance, the form BigQuery documents for optimized spatial joins, so a large sites table isn't compared with every outage.

sql
-- Peak customers out per county over the last 7 days
SELECT county_id, county_name, state_id, MAX(customers_out) AS peak_out
FROM poweroutage.county_outages
WHERE generated_at >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 7 DAY)
GROUP BY county_id, county_name, state_id
ORDER BY peak_out DESC
LIMIT 20;

-- Your sites inside an outage polygon, or within 500 m of an outage point
SELECT s.site_name, o.utility_id, o.outage_id, o.customers_out, o.estimated_restoration_at
FROM mydataset.sites AS s
JOIN poweroutage.active_outages AS o
  ON ST_INTERSECTS(o.shape, ST_GEOGPOINT(s.longitude, s.latitude))
WHERE ST_GEOMETRYTYPE(o.shape) != 'ST_Point'
UNION ALL
SELECT s.site_name, o.utility_id, o.outage_id, o.customers_out, o.estimated_restoration_at
FROM mydataset.sites AS s
JOIN poweroutage.active_outages AS o
  ON ST_DWITHIN(o.shape, ST_GEOGPOINT(s.longitude, s.latitude), 500)
WHERE ST_GEOMETRYTYPE(o.shape) = 'ST_Point';

Tips for BigQuery

  • BigQuery allows 1,500 load jobs per table per day. On a 15-minute schedule the job uses 96 on each table, so there is room for a shorter retry or a second job.
  • With on-demand pricing each query is billed at least 10 MB for every table it reads. The transaction that replaces active_outages reads two small tables, so a day of runs stays far inside the free monthly query allowance.
  • To rotate the key, add a new secret version and point the job at it with gcloud run jobs update poweroutage-sync --region us-central1 --update-secrets POWEROUTAGE_API_KEY=poweroutage-api-key:2. The next execution uses it.
  • If you set the job to send all egress through a VPC, it needs Cloud NAT or another route to the internet to reach poweroutage.us.
  • Each state can include a county named Unknown for customers a utility could not place in a county. Its fips is null, so it drops out of FIPS joins.
  • /geojson/outages covers only utilities that publish outage locations, so county totals can be higher than the sum of customers_out in active_outages.

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.