Skip to content

Storage ​

How Probeward stores its data in PostgreSQL: the layout of scan history and the measurements behind it, partitioning and retention, rollups, and the credential vault. The code is in crates/probeward-store, the schema in crates/probeward-store/migrations/.

Overview ​

One PostgreSQL database (version 18) holds everything. Configuration, alarms, logs, engine state and scan history all live there. The only file outside the database is the vault key file.

AreaTables
Treeprobes, groups, devices, sensors, dependencies, config_revision
Calendarsschedules, maintenance_windows
People and accessusers, user_recovery_codes, sessions, login_throttle, access_grants, oidc_identities, oidc_login_attempts
Secretsvault_keys, credentials, credential_targets
Remote probesprobe_ca, probe_pairing_tokens, probe_remote
Notificationsnotification_destinations, notification_events, notification_deliveries
Alarms and logsincidents, timeline, audit_log
Engineengine_snapshot, sensor_status, sensor_poll_state
Discoverydiscovery_jobs, discovery_results
Historyscans (partitioned by day), channel_sets
Channel namessensor_channels
Rollupsrollup_5m (by day), rollup_1h (by month), rollup_state, rollup_dirty
Tokensapi_tokens, push_tokens
Globalsettings

Migrations are embedded in the binary and run on start (Store::connect_and_migrate). They only go forward: there are no down migrations, and a test enforces this. migrate::migrate_to brings a database to any earlier version. Upgrade tests use it to start from each released schema and run the current migrations over it; releases are listed in migrate::RELEASED_SCHEMA_VERSIONS.

Configuration revision ​

Any change to a tree table, to dependencies or to notification_destinations increments config_revision. This happens through statement-level triggers, so it covers every path that writes, including hand-written SQL. The engine compares the revision with the one it loaded to know when to reload the tree.

The revision row also acts as a lock. Moving a group takes it with FOR UPDATE before the cycle check. As a result, two crossing moves (A into B and B into A) cannot both pass the check; a test proves this.

Tree loading ​

TreeRepo::load reads the whole tree in six queries inside one read-only, repeatable-read transaction: the revision, probes, groups, devices, sensors and dependencies. Every node carries its NodeSettings as JSONB.

Scan history ​

Layout ​

Each scan is one row:

scans(sensor_id uuid, ts timestamptz, outcome int2, health int2, duration_ms int4,
      channel_set int4, vals float8[], PRIMARY KEY (sensor_id, ts))  PARTITION BY RANGE (ts)
channel_sets(id int4 identity, keys text[] UNIQUE)

channel_sets is a dictionary of channel-key lists. A scan stores only the id of its sorted key list plus the values in the same order. The ChannelKey therefore belongs to each value as it was written. A template that renames, reorders, adds or removes channels produces a new key list for later scans and never changes the meaning of earlier ones. The test template_changes_never_relabel_history checks all four cases. Reordering reuses the same dictionary entry, because keys are sorted before lookup. channel_sets rows are never updated.

outcome is 0 for success or the failure kind (1 to 6). health is NULL when the scan produced none.

sensor_channels(sensor_id, channel_key, name, unit, observed_at) holds the latest display name and unit of the channels a sensor's template cannot describe (what a script, plugin or push sender reported). It is one row per sensor and key, never per scan, and is display only: the key stays the identity of the history, so changing a name or unit relabels nothing. A descriptor replaces the stored one only if its poll started no earlier than the stored one's, and a sensor keeps at most 100 rows. The rows go with the sensor.

Measurements ​

Four layouts were compared with examples/scan_layout_bench.rs (run by hand), all on the same PostgreSQL 18 container:

  • jsonb: an object of key to value.
  • key_arrays: a text[] of keys next to a float8[] of values.
  • dict_float8: a dictionary id plus float8[], the chosen layout.
  • dict_real: a dictionary id plus real[].

Each run stored 2,000 sensors × 24 hours at one scan per minute, which is 2.88 M scans per table, inserted in batches of 1,000.

LayoutChannelsHeap B/scanIndex B/scanTotal B/scanInsert rows/sDownsampled p50 / p95 ms
jsonb1101.269.5170.7207,6544.19 / 6.18
key_arrays1126.169.5195.6227,6023.00 / 4.21
dict_float81101.269.5170.7228,9883.23 / 3.50
dict_real193.169.5162.6——
jsonb4182.169.5251.6169,56210.45 / 12.25
key_arrays4199.969.5269.4——
dict_float84126.169.5195.6218,7176.50 / 7.03
dict_real4109.369.5178.8——
jsonb8303.569.5373.0135,38518.36 / 19.94
key_arrays8303.569.5373.0201,519—
dict_float88157.669.5227.1209,37911.29 / 12.20
dict_real8126.169.5195.6207,417—

A dash means the figure was not recorded for that combination.

Decision: dict_float8.

  • It is the smallest layout that keeps full precision, and it grows slowest as channels are added.
  • It inserts fastest, and it downsamples fastest at 4 and 8 channels.
  • real would save another 15 to 30 bytes per scan, but it loses precision on large counters. A 32-bit float cannot hold 1e9 bps exactly.
  • jsonb repeats every key in every row.

Indexes ​

The only index is the primary key (sensor_id, ts). It also makes a replayed scan a no-op (ON CONFLICT DO NOTHING).

  • BRIN on ts: it was measured (24 to 40 kB per table) but is not created. Partition pruning already narrows every time-range query to the right days, and every chart query names a sensor.
  • Index cost: the btree costs about 69.5 bytes per scan. Most of that comes from page splits, because inserts arrive in time order across all sensors. Rebuilding closed partitions (REINDEX) would probably shrink it. This was not measured and is not done.

Partitions ​

Partitions hold one UTC day each and are named scans_pYYYYMMDD. There is deliberately no default partition, for two reasons:

  • A default partition makes creating a new partition scan the default for rows that belong in it.
  • A default partition forbids DETACH ... CONCURRENTLY.

Creating partitions

  • ensure_partitions(now, days_ahead) creates today and the next few days ahead of time. The server's housekeeping task calls it.
  • A partition is built as a plain table with a matching CHECK constraint and then attached. Only the attach needs a lock on scans (SHARE UPDATE EXCLUSIVE), so inserts and queries keep running.
  • An advisory transaction lock serialises creation across processes, so two servers racing to create the same day are safe.
  • insert also creates a missing partition on demand. If a partition disappears under an insert, the insert refreshes its cache and retries once.

Accepted window. insert(now, scans) stores a scan only when both of these hold:

  • Its day is not before the oldest retained day, (now − retention_days). Older scans are counted as rejected_expired. A scan replayed after a probe outage, for example 23 hours late, is accepted; its partition is created if needed.
  • It is no more than one day ahead of now. Later scans come from a wrong clock and are counted as rejected_future.

Scans that list the same channel twice are counted as rejected_invalid, and duplicates of already stored scans are counted as duplicates.

Batched inserts. Rows go in chunks of 5,000. Each chunk is one INSERT ... SELECT FROM UNNEST(...) with all values in a single flat float8[] that SQL slices per row. A chunk is one round trip with one binary parameter per column.

Retention

  • expire(now, retention_days) drops whole days older than the cutoff day.
  • Each day is first detached with DETACH PARTITION ... CONCURRENTLY, which waits for running queries instead of blocking new ones, and then dropped.
  • A session advisory lock keeps two expiry runs, or an expiry and a partition creation, from interleaving.
  • Leftovers from an interrupted run are finished on the next run. A detached table that was never dropped is removed. A partition left half-detached is finished with FINALIZE.
  • now is a parameter, so tests simulate time passing: retention_drops_whole_days_as_simulated_time_passes.
  • expiry_runs_safely_alongside_inserts_and_queries drops 35 days while 4,000 scans are inserted and 200 chart queries run. Nothing fails and nothing is lost.

Deleting a sensor deletes its scans in the same transaction as the tree delete. Retention never needs to know about deleted sensors.

Queries ​

Every query takes an explicit sensor and an explicit time range, except latest.

  • raw(sensor, from, to, channels): returns the stored scans, optionally filtered to some channels.
  • downsampled(sensor, from, to, max_points, channels):
    • The bucket width is ceil((to − from) / max_points) seconds, with buckets aligned to from.
    • SQL unnests each row's keys and values and groups by bucket and key, returning min/avg/max/count per channel.
    • A chart never receives more than max_points points per channel.
  • latest(sensor, n): returns the newest n scans.
  • outcomes(sensor, from, to): returns success or failure, health and duration, without values. It serves uptime bars and failure history.

Disk use ​

disk_usage(now, window_days) reports:

  • the database size;
  • per-partition bytes (pg_total_relation_size) and row estimates;
  • bytes per day and per scan, averaged over complete recent days.

estimate_retention(usage, free_bytes, retention_days) turns this into the number of days the disk can hold. It also gives days until full when retention does not bound growth within the free space. Free space on the volume is the caller's to measure: the database cannot see it.

Performance ​

Measured with examples/chart_bench.rs (release build, run by hand) against the development PostgreSQL 18 container on one workstation. It used 4 channels per scan, one scan per sensor per minute, and random values up to 1e9.

RunScansInsertBytes/scanChart p50 / p95Raw 1 h p50Latest 10 p50
10,000 sensors × 1 day14.4 M174,500 scans/s195.124 h: 10.7 / 13.8 ms0.24 ms0.12 ms
300 sensors × 30 days13.0 M218,400 scans/s194.924 h: 7.7 / 8.4 ms; 7 d: 63 / 75 ms; 30 d: 291 / 356 ms0.23 ms0.51 ms

The other results from these runs:

  • Load and retention: loading the whole tree takes a median 18 ms at 10,000 sensors. Expiring 30 day-partitions takes 193 ms.
  • Scale: at one scan per minute, 10,000 sensors produce about 167 scans per second, about 1,000 times less than the insert rate above. A day of such history takes about 2.8 GB.
  • Long charts: a 30-day chart over raw data aggregates 43,200 scans and takes about 0.3 s. Charts over a week are served from the rollups instead.

Not measured: insert rate under concurrent chart load, behaviour once the data exceeds RAM, index size after REINDEX of closed partitions, and anything on other hardware.

Rollups ​

Raw scans are kept for 30 days by default. Longer graphs and availability figures come from two levels of pre-computed buckets, kept much longer:

LevelBucketTablePartitionsDefault retention
rawone scanscansone per UTC day (scans_pYYYYMMDD)30 days
5 minutes[hh:m0, hh:m0 + 5 min) UTCrollup_5mone per UTC day (rollup_5m_pYYYYMMDD)90 days
1 hour[hh:00, hh+1:00) UTCrollup_1hone per UTC month (rollup_1h_pYYYYMM)730 days

Retention of each level is a setting (Settings, Global; raw_retention_days, rollup_5m_retention_days, rollup_1h_retention_days, 1 to 3650 days). The levels are independent: lowering the raw retention does not shorten the rollups. Retention drops whole partitions, so a level keeps its data for at least the number of days set and, for the hourly level, up to one month longer (a month partition goes when it ends before the cutoff day). The System panel shows disk use, row count and progress of every level.

Layout ​

A rollup row summarises one sensor over one bucket:

rollup_5m(sensor_id uuid, bucket timestamptz, polls int4, failed int4, up int4, warn int4,
          down int4, channel_set int4, stats float8[], PRIMARY KEY (sensor_id, bucket))
          PARTITION BY RANGE (bucket)

rollup_1h is the same. Channels are identified by stable key, as in the raw layout: channel_set points into the same channel_sets dictionary the scans use (only channels with at least one known value in the bucket are listed, in byte order), and stats holds four numbers per channel in that order: minimum, maximum, sum and count. Sum and count rather than an average mean a bucket of a coarser level is an exact merge of finer ones (an hourly bucket is the merge of its twelve 5-minute buckets), and a template change never relabels history, for the same reason as in the raw layout.

The poll counts are polls (every scan), failed (scans that produced no result: a collection failure), and up, warn and down (scans that did, by health). The availability figure is (up + warn) / polls: a poll that found the sensor Down and a poll that failed both count against it. It is a share of polls, which equals the share of time only while the sensor is polled at a steady interval; the rollups do not weigh polls by the time between them, because that would make a bucket depend on its neighbours and break exact recomputation.

All buckets are aligned to the UTC epoch. Nothing depends on the database's or the viewer's time zone, so a daylight-saving change cannot add, drop or split a bucket.

How the job works ​

The housekeeping task (every 15 minutes, and at once while it is catching up) runs run_rollups(now) before raw expiry. It keeps one watermark per level in rollup_state: every bucket that ends at or before it has been computed.

  1. Advance. The 5-minute level folds the window from its watermark to now - 15 min, in windows of at most one hour (never across an hour boundary, so a window sits in one partition). Each window is one transaction that aggregates the raw scans into a temporary table, adds any new channel key lists to the dictionary, upserts the rows and moves the watermark. The hourly level does the same from the 5-minute rows, in windows of up to a day. A crash or a restart leaves the old watermark and none of the new rows, or both; running a window twice gives the same rows. A day with no raw partition is skipped without work.
  2. Late data. A remote probe that was cut off replays its buffered scans up to 24 hours later, after the watermark has passed their buckets. Scanning forward would never see them. So the raw insert, in the same transaction that stores the scans, marks the 5-minute bucket of every scan that is more than 10 minutes older than the insert's now in rollup_dirty. The next pass recomputes each marked bucket from the raw scans (deleting the row if no scan is left), and the hourly bucket that contains it from the 5-minute rows, then deletes exactly the marks it handled: a mark carries a sequence number that changes whenever the bucket is marked again, so a mark added while a pass is running survives it. Scans younger than 10 minutes are never marked, which is safe because the watermark stays 15 minutes behind now: by the time it passes a bucket, every scan that was not marked is committed. That reasoning assumes an insert transaction does not stay open for more than the 5-minute margin; a database stall that long during one insert can lose one bucket's late scan until that bucket is next marked. Raw scans older than the raw retention are refused on insert, and a mark whose raw partition is gone is dropped rather than processed, so a recomputation never erases a good row for lack of data.
  3. Catch-up. The first pass on a database that already holds raw history (the upgrade from M1) starts at the oldest raw day, or at the 5-minute retention if that is shorter, and works through it in windows, at most 96 windows per level per pass; the housekeeping task repeats at once while a pass reports it is behind. probeward admin rollup does the same from the command line and prints the result. A job that was down for longer than the raw retention skips the raw data that no longer exists.
  4. Deleted sensors. Deleting a node removes the history of its sensors at every level and its late marks, after taking FOR UPDATE on the sensor rows. A rollup transaction takes FOR KEY SHARE NOWAIT on the sensors it writes for in the transaction that writes the rows, so either it commits first (and the delete then removes its rows) or the delete commits first (and the rollup finds no sensor). NOWAIT makes the rollup retry later instead of waiting, so the two cannot deadlock. A stress test deletes sensors while passes run and checks that no row of a deleted sensor survives.
  5. One at a time. A session advisory lock keeps two processes from running the job together.

Series and availability ​

GET /api/v1/sensors/{id}/series picks the level from the range and the requested number of points: raw scans for ranges up to 48 hours or while a point would span less than 5 minutes, then the 5-minute level, then the hourly level from one hour per point. If the preferred level does not reach back to the start of the range, the next coarser one is used. level=raw|5m|1h forces one. A rollup-served series combines buckets into points of a whole multiple of the level's width, aligned to the epoch, and returns minimum, average (sum over count) and maximum per point so a graph can draw a band. The newest part of the range, which the job has not reached yet, is computed from raw scans on the same grid (tail_from says where), so a graph never ends 30 minutes early. The response says which level served it, and carries per-bucket poll counts, so failed polls stay visible where the raw scans are gone.

GET /api/v1/sensors/{id}/availability sums the poll counts over a range, from raw scans up to 48 hours, the 5-minute level up to 14 days, the hourly level beyond, with the same raw tail.

Measured ​

examples/rollup_bench.rs (release build, run by hand, PostgreSQL 18 in Docker on the host described in capacity): 10,000 sensors, one scan a minute for one day, four channels per scan, 14.4 M raw scans.

LevelRowsSizeBytes per bucket (heap and index)Raw bytes it summarises
raw14,400,0002,812 MB195.3 per scan
5 minutes2,880,031839 MB291.45 scans, 977 B
1 hour240,00066.5 MB277.260 scans, 11.7 kB

So at four channels a 5-minute bucket costs about a third of the raw scans it replaces and an hourly bucket about one fortieth. Both levels grow by one row per sensor per bucket, whatever the polling interval, so a sensor polled every 10 seconds costs the same as one polled every minute at the rollup levels. Each extra channel adds four 8-byte numbers (32 bytes) to a bucket, by arithmetic; this was not measured separately.

At 10,000 sensors with four channels the defaults come to about 84 GB of raw scans (30 days), 76 GB of 5-minute rows (90 days) and 49 to 52 GB of hourly rows (730 days, plus up to a month): about 210 GB in all. The 5-minute level at 90 days costs about as much as raw at 30 days; shorten rollup_5m_retention_days first if disk is the constraint, since the hourly level covers long graphs.

The cost of the job itself, the replay of a probe's buffer and the series queries are in capacity.

Receiver events ​

sensor_events holds the messages a receiver sensor matched (migration 0011): one row per message with a key that is stable for it (the receiver's run and its sequence number), so a message reported twice is stored once, its time, its level, a one-line summary of at most 300 characters and the parsed message as JSON. Rows go with the sensor, past the timeline's retention (housekeeping prunes them with the timeline), and past 1,000 per sensor (the newest stay, enforced when the rows are written). They are for reading and never feed alerting; the counts the sensors report are ordinary channels in the scan history. The messages a receiver counts from live in the probe's memory and not here; see receivers.

The flow sensors use the same table for one row per poll that found new intervals: a summary of the top sources, destinations, conversations and services of those minutes (a few kilobytes), never a flow. The aggregates they count from live in the probe's memory with their own limits; see flow collectors.

Credential vault ​

Credentials are encrypted with envelope encryption using XChaCha20-Poly1305:

  • Each credential has its own random 256-bit data key, which encrypts the serialised credential.
  • The data key is encrypted under the master key.
  • Both blobs are stored as format byte 0x01, then a 24-byte random nonce, then ciphertext and tag.

Associated data binds every blob to where it belongs:

  • the credential: probeward/credential/v1/{credential id};
  • the data key: probeward/data-key/v1/{credential id}/{key id}.

A flipped bit, a truncated blob or two rows' blobs swapped all fail to decrypt, and the error names the credential, not its content. Tests cover each case.

The master key is 32 random bytes in a key file outside the database.

  • The file is created with mode 0600 on first start.
  • A file readable by group or others is refused, as is a file of the wrong length.
  • vault_keys stores the key id (the first 8 bytes of a SHA-256 over the key) and a check value (an AEAD encryption of a fixed string). Starting with the wrong key file, or with the file missing while the database holds credentials, fails at start with a message that says what to restore.
  • Key material is zeroed on drop.
  • Debug on keys, the vault and credentials never shows secret values. Error messages never contain them either.

Rotation. rotate_master_key re-wraps every data key under a new master key in one transaction. The bulk ciphertext is unchanged. Write the new key file first; once the rotation commits, only the new file opens the database. If any row fails to decrypt, the whole rotation rolls back. No command exposes it yet (known gaps).

What is stored. Credentials are listed with their in-use count. The count covers node settings and sensor params that mention the credential id, notification destinations, and active discovery jobs. A credential in use cannot be deleted. Users' TOTP secrets are vault entries with purpose totp, hidden from the list.

Backup and restore ​

A backup is two things: a pg_dump of the database and a copy of the vault key file. Neither is useful without the other; backup and restore gives the procedure. The integration test dump_and_restore_keeps_tree_history_and_credentials does the following:

  1. Runs pg_dump -Fc inside the PostgreSQL container (docker exec).
  2. Restores the dump with pg_restore into a fresh database.
  3. Opens the restored database with a copy of the key file.
  4. Checks that the tree, the scan history and an open incident match, and that every credential decrypts.
  5. Checks that partitions, retention and inserts keep working on the restored database.
  6. Checks that a different key file is refused with WrongKey.

The container name comes from PROBEWARD_TEST_PG_CONTAINER (default probeward-dev-postgres-1). The test needs docker on the path.

AGPL-3.0-only