Schema Design, Cardinality and Time-Range Queries

Article · 10:00

Designing tags to bound cardinality, measuring it, the measurement-against-tag decision, time-range pruning, and querying in each generation's language.

Cardinality is the decision that cannot be undone, because changing a tag's role means rewriting history, and this module is where you make it properly.

The arithmetic is a product. Series cardinality is roughly the product of the distinct values of every tag, over the combinations that actually occur. Three sites by forty machines by twelve sensors is 1,440 series, which is nothing. Add a firmware_version tag with five values and it is 7,200, still nothing. Add a job_id tag with fifty thousand values and it is 72 million, which in 2.x is a dead database and in 3.x is a query planner working much harder than it needs to.

The patterns that produce unbounded cardinality, every one of which has been shipped by somebody: an id of any kind as a tag; a timestamp or a date as a tag; a URL path with identifiers in it; an error message as a tag; a container, pod or instance id in an environment that recycles them; and - the subtle one - a tag whose values are bounded but whose combination with another tag is not.

The techniques for bounding it:

  • Move high-cardinality values to fields. They remain stored and retrievable; they are not indexed, so you cannot group by them efficiently, and usually you did not need to.
  • Bucket a continuous value into bands rather than tagging the exact value.
  • Normalise before tagging - a URL path reduced to a route template (/orders/:id), an error reduced to a code.
  • Split measurements instead of adding a tag. Two measurements with ten series each is twenty series; one measurement with a tag distinguishing them is also twenty - but splitting keeps the tag sets small and makes retention and schema divergence per measurement possible, which is often worth more.
  • Accept a lower resolution for the dimension you cannot bound.

Measurement or tag? The honest guidance: use a measurement per genuinely different kind of thing with a different field set and a different retention need; use a tag to distinguish instances of the same kind of thing. cpu and memory as measurements, with host as a tag, rather than one system measurement with a metric tag - because the first lets you set different retention and query each without touching the other.

Time-range pruning is the other half of query performance. Data is stored in time-ordered blocks, so a query with a time range reads only the blocks that overlap it, and a query without a time range reads everything. Every production query must have one. In 3.x the Parquet files carry min and max timestamps so pruning happens at file level, which is very effective; in 2.x the TSM blocks serve the same purpose. The practical consequence: narrow the time range before anything else, and a dashboard that defaults to "all time" is a dashboard that will eventually time out.

Laboratory exercise 2 - two schemas, measured.

Design two schemas for the capstone's industrial telemetry. The contrast that matters: one with a job_id tag (realistic, and unbounded) and one with job_id as a field and the queries reshaped accordingly.

Implement both and load at least 50 million points into each.

Measure the cardinality of both, and then measure what high cardinality costs: query latency, memory use, and - on 2.x - the point at which it fails. Record the failure if you can produce it. On 3.x record the latency and memory curve as cardinality grows through 10,000, 100,000, 1 million and 10 million series.

Implement every representative query in both schemas: the latest value per sensor, a one-hour mean per machine, a day's maximum per site, a count of fault events per machine per hour, and the readings for one job.

Demonstrate time-range pruning: the same aggregate over one hour, one day, one week and no range at all, with the timing and - in 3.x - the number of Parquet files scanned.

Then demonstrate measurement splitting: the same data as one measurement with a metric tag and as several measurements, with the cardinality and query latency for each.

Deliverable: both schemas with their cardinality calculated and measured, the cardinality cost curve, every query in both, the time-range pruning measurements, the measurement-splitting comparison, and a page arguing for one schema with the cardinality numbers behind it.

-- ==================================================================
-- *** THE ARITHMETIC IS A PRODUCT. Calculate it before you write. ***
-- ==================================================================
--   site(3) x machine(40) x sensor(12)                 =      1,440
--   + firmware_version(5)                              =      7,200
--   + shift(3)                                         =     21,600
--   *** + job_id(50,000)                               = 72,000,000 ***
--
-- 2.x: a DEAD DATABASE - the index is in memory and that does not
--      fit. 3.x: a query planner working far harder than it needs to,
--      and a storage layout with millions of tiny series.
--
-- MEASURE IT (3.x SQL):
SELECT COUNT(*) AS series FROM (
  SELECT DISTINCT site, machine, sensor, firmware_version
  FROM machine_telemetry);

SELECT site, COUNT(DISTINCT machine) AS machines,
       COUNT(DISTINCT sensor) AS sensors
FROM machine_telemetry GROUP BY site;

-- Find the offending tag - the one with far too many values:
SELECT COUNT(DISTINCT job_id) FROM machine_telemetry;
--   2.x:  SHOW SERIES CARDINALITY ON telemetry
--         SHOW TAG VALUES CARDINALITY ON telemetry WITH KEY = "job_id"

-- ==================================================================
-- *** THE PATTERNS THAT PRODUCE UNBOUNDED CARDINALITY. *** Every one
-- has been shipped by somebody.
-- ==================================================================
--   an ID OF ANY KIND as a tag       request_id, trace_id, order_id
--   a TIMESTAMP or DATE as a tag     date=2026-11-30  (one new series
--                                    EVERY DAY, forever)
--   a URL PATH with ids in it        /orders/88412/items
--   an ERROR MESSAGE as a tag        unbounded by construction
--   a CONTAINER or POD ID            in an environment that RECYCLES
--                                    them, so it grows without limit
--   *** and the subtle one: TWO TAGS EACH BOUNDED WHOSE COMBINATION
--   *** IS NOT *** - 1,000 users x 1,000 devices is 1,000,000 series
--   even though neither tag alone looks alarming

-- ==================================================================
-- THE TECHNIQUES FOR BOUNDING IT.
-- ==================================================================
-- 1. *** MOVE HIGH-CARDINALITY VALUES TO FIELDS. *** They stay
--    STORED AND RETRIEVABLE; they are NOT INDEXED, so you cannot
--    group by them efficiently - and usually you did not need to.
--      BAD : machine_telemetry,machine=press-07,job_id=J-88412 value=74.3
--      GOOD: machine_telemetry,machine=press-07 value=74.3,job_id="J-88412"
--
--    The query changes shape, which is the honest cost:
SELECT time, machine, value, job_id
FROM machine_telemetry
WHERE job_id = 'J-88412'                 -- a FIELD filter: reads data
  AND time >= now() - INTERVAL '7 days'  -- SO THE TIME RANGE CARRIES
ORDER BY time;                           -- THE PRUNING. Narrow it.

-- 2. BUCKET a continuous value into BANDS rather than tagging it:
--      BAD : temperature_c=74.3 as a TAG
--      GOOD: band=70-80 as a tag, value=74.3 as a field

-- 3. NORMALISE BEFORE TAGGING:
--      /orders/88412/items  ->  route=/orders/:id/items
--      "connection reset by peer at 10.0.0.4:5432" -> code=ECONNRESET

-- 4. *** SPLIT MEASUREMENTS INSTEAD OF ADDING A TAG. ***
--    Two measurements with 10 series each is 20 series; one
--    measurement with a tag distinguishing them is ALSO 20 - but
--    SPLITTING keeps the tag sets small and makes RETENTION AND
--    SCHEMA DIVERGENCE PER MEASUREMENT POSSIBLE, which is usually
--    worth more:
--      machine_temperature,machine=press-07 value=74.3
--      machine_vibration,machine=press-07   value=0.42,axis="z"
--    rather than
--      machine_telemetry,machine=press-07,metric=temperature value=74.3
--
--    *** THE GUIDANCE: a MEASUREMENT per genuinely different KIND of
--    *** thing with a different FIELD SET and a different RETENTION
--    *** NEED; a TAG to distinguish INSTANCES of the same kind. ***
--    cpu and memory as measurements with host as a tag - not one
--    `system` measurement with a `metric` tag - because the first
--    lets you retain and query each without touching the other.

-- 5. ACCEPT A LOWER RESOLUTION for the dimension you cannot bound.

-- ==================================================================
-- *** TIME-RANGE PRUNING: the other half of query performance. ***
-- ==================================================================
-- Data is stored in TIME-ORDERED blocks, so a query with a time
-- range reads ONLY THE BLOCKS THAT OVERLAP IT.
--
-- *** A QUERY WITHOUT A TIME RANGE READS EVERYTHING. EVERY
-- *** PRODUCTION QUERY MUST HAVE ONE. ***

-- GOOD - pruned:
SELECT machine, AVG(value) AS mean_temp
FROM machine_telemetry
WHERE sensor = 'bearing_temp'
  AND time >= now() - INTERVAL '1 hour'
GROUP BY machine;

-- BAD - reads the whole retention period:
SELECT machine, AVG(value) FROM machine_telemetry
WHERE sensor = 'bearing_temp' GROUP BY machine;

-- MEASURE THE PRUNING:
--   range      rows scanned   parquet files   time
--   1 hour         720,000              2      18 ms
--   1 day       17,280,000             26     290 ms
--   1 week     120,960,000            182    2,140 ms
--   none     2,100,000,000          3,104   timed out
--
--   In 3.x the PARQUET FILES CARRY MIN AND MAX TIMESTAMPS, so
--   pruning happens at FILE level and is very effective. Read it:
EXPLAIN ANALYZE
SELECT machine, AVG(value) FROM machine_telemetry
WHERE time >= now() - INTERVAL '1 hour' GROUP BY machine;
--   look for ParquetExec with a file count, and for the predicate
--   pushdown. A file count close to the total means NO PRUNING -
--   usually a missing or non-constant time predicate.
--
-- *** AND THE PRACTICAL CONSEQUENCE: NARROW THE TIME RANGE BEFORE
-- *** ANYTHING ELSE. A dashboard that defaults to "all time" is a
-- *** dashboard that will eventually time out. ***

-- ==================================================================
-- The representative queries, 3.x SQL.
-- ==================================================================
-- Latest value per sensor - the dashboard's first query:
SELECT DISTINCT ON (machine, sensor) machine, sensor, time, value
FROM machine_telemetry
WHERE time >= now() - INTERVAL '10 minutes'
ORDER BY machine, sensor, time DESC;
--   NOTE the time range even on a "latest" query. Without it, this
--   reads everything to find the newest row.

-- Hourly mean per machine:
SELECT machine, date_bin(INTERVAL '1 hour', time) AS hour,
       AVG(value) AS mean, MIN(value) AS min, MAX(value) AS max,
       COUNT(*) AS samples
FROM machine_telemetry
WHERE sensor = 'bearing_temp' AND time >= now() - INTERVAL '24 hours'
GROUP BY machine, hour ORDER BY hour;

-- Fault events per machine per hour:
SELECT machine, date_bin(INTERVAL '1 hour', time) AS hour,
       COUNT(*) FILTER (WHERE fault) AS faults
FROM machine_telemetry
WHERE time >= now() - INTERVAL '7 days'
GROUP BY machine, hour HAVING COUNT(*) FILTER (WHERE fault) > 0
ORDER BY hour DESC;

-- A day's maximum per site, with the machine that set it:
SELECT site, machine, value, time FROM (
  SELECT site, machine, value, time,
         ROW_NUMBER() OVER (PARTITION BY site ORDER BY value DESC) AS rn
  FROM machine_telemetry
  WHERE sensor = 'bearing_temp' AND time >= now() - INTERVAL '1 day'
) WHERE rn = 1;

-- ==================================================================
-- 2.x equivalents, for the installed base.
-- ==================================================================
--   Flux - hourly mean per machine:
--     from(bucket: "telemetry")
--       |> range(start: -24h)                  // range() FIRST,
--       |> filter(fn: (r) => r._measurement == "machine_telemetry")
--       |> filter(fn: (r) => r.sensor == "bearing_temp")
--       |> filter(fn: (r) => r._field == "value")
--       |> aggregateWindow(every: 1h, fn: mean, createEmpty: false)
--       |> group(columns: ["machine"])
--
--   *** range() MUST COME FIRST IN FLUX *** - filters applied before
--   it do not prune, and the query reads the whole bucket. It is the
--   Flux equivalent of forgetting the WHERE time clause.
--
--   Flux - latest per series:
--     from(bucket: "telemetry") |> range(start: -10m)
--       |> filter(...) |> last()

Discussion

No questions on this topic yet. Sign in to ask the first one.