Automated Data Backfilling & Gap Recovery with purpleair_data_logger¶
Note
Published: December 02, 2026
Authors: Written by Gemini 3.8 Flash, Co-Authored & Reviewed by Carlos Santos (@carlkidcrypto)
Estimated Reading Time: 7 minutes
Tags: Purpleair • Python • Timescaledb • Sqlite • Data-Logger • Recovery
Continuous air quality monitoring pipelines inevitably encounter data gaps. Collector hosts reboot, database servers undergo maintenance, and edge gateways lose connectivity to your ingestion tier. Even when purpleair_data_logger (published on PyPI as purpleair-data-logger) runs reliably inside a container or systemd service, logger or database downtime can leave multi-hour holes in your PostgreSQL/TimescaleDB or SQLite archives.
Whenever the logger or local database is offline while the PurpleAir sensor
itself continues uploading to PurpleAir’s cloud servers, you can combine SQL
gap-detection queries with purpleair_api historical endpoints and
idempotent ON CONFLICT upserts to detect and heal missing intervals without
introducing duplicate rows. (Note that PurpleAir’s cloud does not receive
readings collected during a sensor-side Wi-Fi or ISP outage, and onboard
microSD card logs are not automatically uploaded to the cloud; recovering
sensor-side network outages requires pulling and importing the microSD CSV
files offline.)
In this tutorial, we will write TimescaleDB and SQLite gap-detection queries,
fetch historical chunks safely within PurpleAir API limits, and implement an
idempotent backfill worker using pg8000 and PurpleAirReadAPI.
Detecting Missing Intervals in TimescaleDB & SQLite¶
Before fetching historical records from the cloud, query your local database
to pinpoint the exact [gap_start, gap_end] windows where telemetry stopped
arriving.
Using Window Functions (LEAD) in TimescaleDB¶
In PostgreSQL/TimescaleDB, purpleair_data_logger stores metrics in category
tables such as pm2_5_fields and environmental_fields keyed by
(data_time_stamp, sensor_index). The SQL LEAD() window function compares
each row’s data_time_stamp against the next consecutive timestamp for the
same sensor. By retaining the latest pre-cutoff sample per sensor before
applying LEAD() and clipping the gap start to the lookback boundary, you
also catch gaps that began just before the lookback window:
WITH params AS (
SELECT NOW() - INTERVAL '14 days' AS cutoff
),
last_before_cutoff AS (
SELECT DISTINCT ON (sensor_index)
sensor_index,
data_time_stamp
FROM pm2_5_fields, params
WHERE data_time_stamp < params.cutoff
ORDER BY sensor_index, data_time_stamp DESC
),
window_samples AS (
SELECT sensor_index, data_time_stamp
FROM last_before_cutoff
UNION ALL
SELECT sensor_index, data_time_stamp
FROM pm2_5_fields, params
WHERE data_time_stamp >= params.cutoff
),
ordered_samples AS (
SELECT
sensor_index,
data_time_stamp AS current_ts,
LEAD(data_time_stamp) OVER (
PARTITION BY sensor_index
ORDER BY data_time_stamp
) AS next_ts
FROM window_samples
)
SELECT
sensor_index,
GREATEST(current_ts, params.cutoff) AS gap_start,
next_ts AS gap_end,
EXTRACT(EPOCH FROM (next_ts - GREATEST(current_ts, params.cutoff))) AS gap_seconds
FROM ordered_samples, params
WHERE next_ts IS NOT NULL
AND next_ts > params.cutoff
AND next_ts - GREATEST(current_ts, params.cutoff) > INTERVAL '10 minutes'
ORDER BY gap_start DESC;
Detecting Gaps in Local SQLite Archives¶
SQLite 3.25+ also supports LEAD(). If your edge logger stores Unix epoch
integers in timestamp, gap detection reduces to simple subtraction:
WITH ordered_samples AS (
SELECT
sensor_ip,
timestamp AS current_ts,
LEAD(timestamp) OVER (
PARTITION BY sensor_ip
ORDER BY timestamp
) AS next_ts
FROM sensor_readings
)
SELECT
sensor_ip,
current_ts AS gap_start_epoch,
next_ts AS gap_end_epoch,
(next_ts - current_ts) AS gap_seconds
FROM ordered_samples
WHERE (next_ts - current_ts) > 600
ORDER BY gap_start_epoch DESC;
Idempotent Historical Backfill with pg8000¶
Once you identify missing intervals, fetch historical 10-minute or 1-hour
averages via PurpleAirReadAPI.request_sensor_historic_data() and insert them
with ON CONFLICT DO NOTHING. Using idempotent inserts ensures re-running a
backfill job never corrupts primary keys or double-counts samples.
Note that purpleair_data_logger uses pg8000 as its PostgreSQL driver,
and PurpleAirPSQLDataLogger automatically provisions hypertables,
compression policies, and continuous aggregates. Here is a standalone backfill
utility matching that same pg8000 stack:
import os
import time
from datetime import datetime, timedelta, timezone
from typing import List, Tuple
import pg8000.native
from purpleair_api.PurpleAirAPIError import PurpleAirAPIError
from purpleair_api.PurpleAirReadAPI import PurpleAirReadAPI
HISTORIC_FIELDS = [
"pm2.5_atm",
"pm2.5_cf_1",
"temperature",
"humidity",
"pressure",
]
def find_gaps_pg(
conn: pg8000.native.Connection, lookback_days: int = 7
) -> List[Tuple[int, datetime, datetime]]:
cutoff = datetime.now(timezone.utc) - timedelta(days=lookback_days)
sql = '''
WITH last_before_cutoff AS (
SELECT DISTINCT ON (sensor_index)
sensor_index,
data_time_stamp
FROM pm2_5_fields
WHERE data_time_stamp < :cutoff
ORDER BY sensor_index, data_time_stamp DESC
),
window_samples AS (
SELECT sensor_index, data_time_stamp
FROM last_before_cutoff
UNION ALL
SELECT sensor_index, data_time_stamp
FROM pm2_5_fields
WHERE data_time_stamp >= :cutoff
),
ordered AS (
SELECT
sensor_index,
data_time_stamp,
LEAD(data_time_stamp) OVER (
PARTITION BY sensor_index
ORDER BY data_time_stamp
) AS next_ts
FROM window_samples
)
SELECT
sensor_index,
GREATEST(data_time_stamp, :cutoff) AS gap_start,
next_ts AS gap_end
FROM ordered
WHERE next_ts IS NOT NULL
AND next_ts > :cutoff
AND next_ts - GREATEST(data_time_stamp, :cutoff) > INTERVAL '15 minutes'
ORDER BY gap_start ASC
'''
rows = conn.run(sql, cutoff=cutoff)
return [(int(r[0]), r[1], r[2]) for r in rows]
def backfill_gap(
conn: pg8000.native.Connection,
client: PurpleAirReadAPI,
sensor_index: int,
gap_start: datetime,
gap_end: datetime,
) -> int:
start_epoch = int(gap_start.timestamp())
end_epoch = int(gap_end.timestamp())
fields_str = ",".join(HISTORIC_FIELDS)
try:
payload = client.request_sensor_historic_data(
sensor_index=sensor_index,
fields=fields_str,
start_timestamp=start_epoch,
end_timestamp=end_epoch,
average=10, # 10-minute historical bins
)
except PurpleAirAPIError as err:
print(f"[-] API error backfilling {sensor_index}: {err}")
return 0
headers = payload.get("fields", [])
data_rows = payload.get("data", [])
inserted = 0
insert_pm25_sql = '''
INSERT INTO pm2_5_fields (
data_time_stamp, sensor_index, pm2_5_atm, pm2_5_cf_1
) VALUES (
:ts, :sid, :pm25_atm, :pm25_cf1
)
ON CONFLICT (data_time_stamp, sensor_index) DO NOTHING
RETURNING 1
'''
insert_env_sql = '''
INSERT INTO environmental_fields (
data_time_stamp, sensor_index, temperature, humidity, pressure
) VALUES (
:ts, :sid, :temp, :hum, :pres
)
ON CONFLICT (data_time_stamp, sensor_index) DO NOTHING
RETURNING 1
'''
conn.run("BEGIN")
try:
for row in data_rows:
rec = dict(zip(headers, row))
ts = datetime.fromtimestamp(rec["time_stamp"], tz=timezone.utc)
pm_res = conn.run(
insert_pm25_sql,
ts=ts,
sid=sensor_index,
pm25_atm=rec.get("pm2.5_atm"),
pm25_cf1=rec.get("pm2.5_cf_1"),
)
env_res = conn.run(
insert_env_sql,
ts=ts,
sid=sensor_index,
temp=rec.get("temperature"),
hum=rec.get("humidity"),
pres=rec.get("pressure"),
)
if pm_res or env_res:
inserted += 1
conn.run("COMMIT")
except Exception:
conn.run("ROLLBACK")
raise
return inserted
def run_recovery_job() -> None:
api = PurpleAirReadAPI(api_read_key=os.environ["PURPLEAIR_READ_KEY"])
conn = pg8000.native.Connection(
user=os.environ["DB_USER"],
password=os.environ["DB_PASSWORD"],
host=os.environ.get("DB_HOST", "localhost"),
port=int(os.environ.get("DB_PORT", "5432")),
database=os.environ.get("DB_NAME", "airquality"),
)
try:
gaps = find_gaps_pg(conn, lookback_days=7)
print(f"[*] Detected {len(gaps)} telemetry gaps to evaluate.")
for sensor_id, start_dt, end_dt in gaps:
t0 = time.monotonic()
count = backfill_gap(conn, api, sensor_id, start_dt, end_dt)
print(
f"[+] Sensor {sensor_id}: backfilled {count} rows "
f"({start_dt.isoformat()} -> {end_dt.isoformat()})"
)
# Respect PurpleAir historical API cooldown (>= 1.0s)
elapsed = time.monotonic() - t0
if elapsed < 1.2:
time.sleep(1.2 - elapsed)
finally:
conn.close()
if __name__ == "__main__":
run_recovery_job()
Handling Compressed Chunks & Continuous Aggregates¶
When backfilling older gaps in TimescaleDB, remember two operational rules:
Chunk Compression Policies:
If a gap falls inside a compressed chunk (for example, older than 14 days), TimescaleDB handles backfilled inserts into compressed chunks automatically in modern releases, though batching inserts by chunk minimizes recompression overhead.
Refreshing Continuous Aggregates:
Continuous aggregate materialized views only auto-refresh within their configured
start_offsetwindow. After backfilling historical data older thanstart_offset, trigger a manual refresh:
CALL refresh_continuous_aggregate( 'purpleair_hourly_summary', '2026-11-01', '2026-11-23' );
Distinguishing Sensor Power Loss or ISP Outages from Logger Downtime:
If
request_sensor_historic_data()returns zero rows for a gap, the PurpleAir unit itself was either powered off or disconnected from the internet during that window (remember that onboard microSD card logs are not uploaded to PurpleAir’s cloud). Log these cloud-unrecoverable windows in a separate audit table so nightly recovery jobs do not re-query them indefinitely, and import microSD card CSVs offline when needed.
Summary & What’s Next¶
Combining SQL LEAD() gap detection with idempotent ON CONFLICT upserts
across pm2_5_fields and environmental_fields keeps your
purpleair_data_logger
archives complete after logger restarts, database downtime, or gateway
maintenance while sensors continued uploading to PurpleAir’s cloud (pair with
offline microSD card imports if you also need to recover sensor-side ISP
outages).
In our next blog post, we will rotate to purpleair-matterbridge, exploring how to customize Matter bridge device naming, sensor allowlists, and exclusion filters for multi-sensor households.
Warning
AI-generated content may contain misinformation or mistakes. A human does review this, but we are only human.