30 min read · Smart factory

A factory starts by connecting a few dozen sensors. It sets them to log every second because that is easy. A year later there are two hundred points, the disk is full, charts of past data are slow, and nobody dares delete anything. When someone says to cut the data, there is a real chance it gets cut the wrong way, and the short spike that caused a machine stop disappears from the database.
This article does three things with code that actually runs. It reduces the number of stored points and measures how much accuracy that costs. It summarizes data per minute and per hour without losing spikes or data gaps. And it lays out storage tiers, calculates the space they need, and picks the right tier at query time. It uses TypeScript that Node 24 runs directly. A manager can read the tables and explanations, and an engineer can run the code and follow along.
The real problem: reducing data and losing what you need
There are two kinds of data reduction that people often mix up. The first reduces data at collection time (compression or exception): points that are not needed are never recorded. Data that was not recorded cannot be recovered. The second reduces data later (rollup or downsampling): raw data is kept for a while and then summarized into coarser time periods. The first is riskier, so you need to know what can go wrong.
Consider three hypothetical situations. They are not projects of any BT San customer.
- A hypothetical plastic injection factory: The motor current deadband is set to 8 amps because the chart looks smooth. A brief motor jam that pulls the current up another 6 amps is never recorded. When the team looks for the cause of a machine hiccup, there is no trace at all.
- A hypothetical drying oven: The hourly report keeps only the average. In an hour where pressure briefly exceeds its limit, the average still looks normal. In an hour where the gateway drops out for ten minutes, nothing says data is missing. The average of the remaining data looks like a full hour.
- A hypothetical system administrator who has kept raw per-second data for two years: The disk fills up early, and charts of the past three months load slowly, because the query reads a raw table of hundreds of millions of rows when it only needs an hourly trend.
These three cases are solved by three linked steps. Choose a collection-time reduction method and know its error bound. Summarize by keeping min, max, count, first and last, not just the average. And lay out storage tiers so the query picks the tier itself.
What the documents say, and what not to assume
| Topic | What the document says | Effect on the design |
|---|---|---|
| swinging door | The academic paper on SDT describes it as lossy compression that replaces many points with a straight trend line. The key parameter is the compression deviation, the largest difference allowed, and it must be set before running | Choose the deviation from the accuracy of the instrument, and know that what is cut cannot be recovered |
| exception vs. compression | AVEVA's slides on PI use two stages: exception deviation (ExcDev) on the receiving side and compression deviation (CompDev) on the storage side. They recommend setting CompDev no larger than the instrument's resolution and ExcDev at half of CompDev | Think of two separate layers, and do not set either wider than what the instrument can distinguish |
| continuous rollup | The TimescaleDB documentation describes a continuous aggregate as a view that refreshes automatically in the background and can be read like a normal table | Summary tiers of 1 minute and 1 hour are work the database can do for you |
| raw data retention policy | TimescaleDB drops data one chunk at a time once it passes the set period, for example add_retention_policy with a 24-hour example. It warns that dropping raw data can make an aggregate NULL. If the data falls in the refresh window, set the aggregate's start_offset shorter than the raw data retention period | The order of policies matters. It is not enough to set the two separately |
| downsampling in InfluxDB | The InfluxDB 2 documentation uses a task to aggregate data into time windows and write it to a separate destination bucket. It says to schedule the task to run before the source bucket's retention deadline, and to set an offset if data may arrive late | Same idea, different tool: summarize before deleting, and allow for late data |
This article does not cite real size figures for any database. The bytes per point in the example are made-up numbers. Measure them on your own system.
Overview of the example
The example creates 5 hypothetical tags, each at 1 point per second for 6 hours. They are a slowly changing temperature, a noisy pressure, a motor current with a 5-second spike, a run/stop state, and a 16-bit counter that wraps around. A 10-minute gap is inserted where every tag is missing at once, like a gateway dropout.
| File | Role |
|---|---|
| gen.ts | Generates the hypothetical data, including the spike and the gap |
| compress.ts | deadband, swinging door, value reconstruction, error measurement |
| rollup.ts | rollup with min max avg count first last, time-weighted average, re-roll, finding missing buckets, counter rollover |
| parse.ts and data/irregular.csv | Reads irregular data and drops bad rows with a reason |
| tiers.ts | Storage tier plan and size calculator |
| query.ts | Picks the tier by time range and reads from in-memory SQLite |
| timescale.sql | SQL draft for TimescaleDB, not yet run against a real database |
| demo.ts, historian.test.ts, output.txt | The run script, the test suite and the real output |
Step 1: Deadband: store a point when the value moves outside the band from the last stored value
A deadband is the simplest method. The first point is always stored. A later point is stored when its value is farther than the band from the last stored value. When reading back, assume the value stays unchanged until the next stored point (hold). The advantage is that you can say directly that every point that was not stored differs from the held value by no more than the band. The disadvantage is that if the band is wider than the movement you want to see, that movement is never recorded.
export function deadband(pts: Point[], band: number): Point[] {
if (pts.length === 0) return [];
const kept = [pts[0]];
for (const p of pts) {
if (Math.abs(p.v - kept[kept.length - 1].v) > band) kept.push(p);
}
return kept;
}The error function reconstructs the value at the time of every raw point and finds the largest difference. The result is the real figure for that data set, not theory.
export function valueAt(kept: Point[], t: number, mode: "hold" | "linear"): number {
let lo = 0;
let hi = kept.length - 1;
while (lo < hi) {
const mid = (lo + hi + 1) >> 1;
if (kept[mid].t <= t) lo = mid;
else hi = mid - 1;
}
const a = kept[lo];
const b = kept[lo + 1];
if (mode === "hold" || !b || t <= a.t) return a.v;
return a.v + ((b.v - a.v) * (t - a.t)) / (b.t - a.t);
}Step 2: Swinging door: replace many points with a straight line
Swinging door does not ask how far the value is from the last point. It asks whether a single straight line from the start point can still pass within the deviation of every point in this segment. The upper and lower doors are the limits of the slopes still allowed. When the doors close (no usable straight line is left), it stores the end point of the line and starts a new segment. Data that changes gradually along a straight line, such as a slowly rising temperature, ends up with only a few points.
export function swingingDoor(pts: Point[], dev: number): Point[] {
if (pts.length < 3) return pts.slice();
let anchor = pts[0];
const kept = [anchor];
let up = -Infinity; // ความชันต่ำสุดที่ยอมได้
let low = Infinity; // ความชันสูงสุดที่ยอมได้
let prev = pts[0];
for (let i = 1; i < pts.length; i++) {
const p = pts[i];
const dt = p.t - anchor.t;
const nUp = Math.max(up, (p.v - dev - anchor.v) / dt);
const nLow = Math.min(low, (p.v + dev - anchor.v) / dt);
if (nUp > nLow) {
const slope = (up + low) / 2;
anchor = { t: prev.t, v: anchor.v + slope * (prev.t - anchor.t) };
kept.push(anchor);
const d2 = p.t - anchor.t;
up = (p.v - dev - anchor.v) / d2;
low = (p.v + dev - anchor.v) / d2;
} else {
up = nUp;
low = nLow;
}
prev = p;
}
const last = pts[pts.length - 1];
const slope = Number.isFinite(up) ? (up + low) / 2 : 0;
kept.push({ t: last.t, v: anchor.v + slope * (last.t - anchor.t) });
return kept;
}This example stores points on the middle line of the door, not the true value of the earlier point. This way the error can be proven directly to stay within the deviation and can be checked in the test suite. Real systems such as PI store the true snapshot value and have extra minimum/maximum time parameters, so their behavior differs slightly from the example.
Real run: what you lose when you reduce data
The first part of the demo measures against a motor current that has a real spike of 16.08 amps from a normal level of about 10 amps.
const show = (name: string, kept: typeof cur, mode: "hold" | "linear") => {
const seen = Math.max(...cur.filter((p) => p.t >= SPIKE.from && p.t <= SPIKE.to).map((p) => valueAt(kept, p.t, mode)));
console.log(`${name.padEnd(18)} ${String(kept.length).padStart(5)} ${f((kept.length / cur.length) * 100, 1).padStart(5)}% ${f(maxError(cur, kept, mode), 3).padStart(10)} ${f(seen).padStart(8)} A`);
};
for (const band of [0.5, 2, 8]) show(`deadband ${band} A`, deadband(cur, band), "hold");
for (const dev of [0.5, 2]) show(`swinging door ${dev}`, swingingDoor(cur, dev), "linear");== 1. ข้อมูลดิบ: 21600 วินาที x 5 tag, ช่องว่าง 600 วินาที ==
temp 21000 จุด
pressure 21000 จุด
current 21000 จุด
run 21000 จุด
counter 21000 จุด
== 2. deadband และ swinging door (กระแสมอเตอร์มี spike 5 วินาที +6 A) ==
spike จริงสูงสุด 16.08 A, ปกติ ~10 A
วิธี เก็บ สัดส่วน error สูงสุด spike ที่เห็นหลังกู้คืน
deadband 0.5 A 216 1.0% 0.500 15.91 A
deadband 2 A 5 0.0% 0.707 15.91 A
deadband 8 A 3 0.0% 6.116 9.96 A
swinging door 0.5 468 2.2% 0.500 16.08 A
swinging door 2 10 0.0% 1.951 17.90 A
temp swinging door 0.5 -> เก็บ 243 จาก 21000 (1.2%), error 0.500
pressure swinging door 0.5 -> เก็บ 65 จาก 21000 (0.3%), error 0.500
== 3. rollup 1 นาที / 1 ชั่วโมง ==
นาทีที่มี spike: min 9.63 max 16.08 avg 10.44 count 60
bucket 1 นาทีที่ไม่มีข้อมูล: 10 (150..159 นาทีจากจุดเริ่ม)
ชั่วโมง count min max avg twa ครอบคลุม
0 3600 9.59 10.41 10.00 10.00 100.0%
1 3600 9.57 10.42 10.00 10.00 100.0%
2 3000 -0.12 10.42 9.02 9.02 83.3%
3 3600 9.58 16.08 10.01 10.01 100.0%
4 3600 9.58 10.40 10.00 10.00 100.0%
5 3600 9.59 10.40 10.00 10.00 100.0%
run state: เวลาที่เครื่องเดินต่อชั่วโมง 60.0 นาที, 60.0 นาที, 47.0 นาที, 60.0 นาที, 60.0 นาที, 60.0 นาที
counter: ผลต่างรวมเมื่อจัดการ rollover = 21043, ค่าสุดท้าย 20509
== 4. ข้อมูลไม่สม่ำเสมอ: average ธรรมดา เทียบ time-weighted ==
ปฏิเสธบรรทัด 10: เวลาซ้ำ (3330,80.9,good)
ปฏิเสธบรรทัด 11: เวลาย้อนหลัง (3325,81.0,good)
ปฏิเสธบรรทัด 12: ค่าไม่ใช่ตัวเลข (3340,not_a_number,good)
ปฏิเสธบรรทัด 13: คุณภาพไม่ใช่ good (3350,80.1,bad)
รับ 11 จุด: simple avg 63.71, time-weighted 23.51, ครอบคลุม 97.2%
== 5. แผนเก็บและขนาด (ไบต์ต่อจุดเป็นค่าสมมติ) ==
200 tag: raw 11.59 GiB + r1m 15.66 GiB + r1h 1.31 GiB = 28.56 GiB; ดิบทั้งหมด 10 ปี = 1409.77 GiB
2000 tag: raw 115.87 GiB + r1m 156.64 GiB + r1h 13.05 GiB = 285.57 GiB; ดิบทั้งหมด 10 ปี = 14097.69 GiB
== 6. query เลือก tier ==
10 นาทีล่าสุด -> raw (raw: ~600 จุด <= 1000) ได้ 600 แถว
6 ชั่วโมงล่าสุด -> r1m (r1m: ~360 จุด <= 1000) ได้ 350 แถว
90 วันก่อนถึงวันนี้ -> r1h (r1h: ~2160 จุด <= 5000) ได้ 6 แถว
12 ปีก่อน -> r1h (เก่ากว่าทุกชั้น (4380 วัน) ได้เท่าที่ r1h มี) ได้ 6 แถว- Deadband 0.5 A stores 216 of 21000 points (1.0 percent). The maximum error is 0.500, exactly equal to the band, and the spike is still visible at 15.91 A.
- Deadband 2 A stores only 5 points with an error of 0.707. The spike is still visible at 15.91 A because the spike is much taller than the band. This number looks reassuring, but only because the band is narrower than the spike, not because the method is always safe.
- Deadband 8 A stores only 3 points and the spike disappears. The reconstruction gives only 9.96 A when the truth is 16.08 A. The error of 6.116 is still within the 8 A band, so nothing warns you that something was lost. This is what happened in the hypothetical plastic injection factory.
- Swinging door 0.5 stores 468 points (2.2 percent) with an error of 0.500. With deviation 2 it is down to 10 points with an error of 1.951, and the spike is reconstructed as 17.90 A, higher than the truth, because a straight line can pass through the spike region on average within the deviation.
- The slowly changing temperature is down to 243 of 21000 points, and the oscillating pressure to 65 points at deviation 0.5, with error no more than 0.5 for both. These figures apply only to this hypothetical data set. Measure on real data.
The lesson is that a measured error against the band only tells you the value is not wrong by more than the band. It does not tell you that no event was lost. Before choosing a band, ask how large the shortest event you must see is, then set the band clearly smaller than that. For run/stop states and other discrete values, store on change (on change) and do not use a deadband.
Step 3: Rollup: keep min, max, count, first, last and a time-weighted average
If the per-minute summary keeps only the average, a brief spike is averaged away, and there is no way to know how many points the bucket held. The example keeps eight fields per bucket: count, min, max, avg, first, last, wsum and cov. The last two are used to compute the time-weighted average and to see how much of the period the data covers.
A plain average suits data collected at an even rate. But data stored on change has dense points while the value swings and sparse points while it is steady. A plain average therefore leans toward the swinging periods. A time-weighted average weights each point by how long that value stayed. The example limits holding a value to maxHold seconds. If points are farther apart than that, the value is treated as unknown and is not filled in with the old value.
export function rollup(pts: Point[], bucketSec: number, maxHold = 120): Rollup[] {
const out = new Map<number, Rollup>();
const key = (t: number) => Math.floor(t / bucketSec) * bucketSec;
for (const p of pts) {
let r = out.get(key(p.t));
if (!r) {
r = { t: key(p.t), count: 0, min: Infinity, max: -Infinity, avg: 0, first: p.v, last: p.v, wsum: 0, cov: 0 };
out.set(r.t, r);
}
r.count++; r.avg += p.v; r.last = p.v;
r.min = Math.min(r.min, p.v); r.max = Math.max(r.max, p.v);
}
for (let i = 0; i + 1 < pts.length; i++) {
const p = pts[i];
// ช่องว่างเกิน maxHold: ถือค่าต่อได้แค่ในชั่วโมง/นาทีของจุดนั้นเอง ที่เหลือถือว่าไม่รู้
const end = Math.min(pts[i + 1].t, p.t + maxHold);
for (let s = p.t; s < end; ) {
const e = Math.min(key(s) + bucketSec, end);
const rb = out.get(key(s));
// simplified: ส่วนที่ตกใน bucket ที่ไม่มีจุดเลยจะถูกทิ้ง (ไม่นับเป็นความครอบคลุม)
if (rb) { rb.wsum += p.v * (e - s); rb.cov += e - s; }
s = e;
}
}
return [...out.values()].sort((a, b) => a.t - b.t).map((r) => ({ ...r, avg: r.avg / r.count }));
}Keeping wsum and cov means the 1-minute tier can be rolled into 1 hour without going back to the raw data, because the sum of wsum divided by the sum of cov gives the same value as computing from raw. The plain average is combined by weighting with count.
export function reroll(src: Rollup[], bucketSec: number): Rollup[] {
const out = new Map<number, Rollup>();
for (const s of src) {
const b = Math.floor(s.t / bucketSec) * bucketSec;
const r = out.get(b);
if (!r) { out.set(b, { ...s, t: b, avg: s.avg * s.count }); continue; }
r.count += s.count; r.avg += s.avg * s.count; r.last = s.last;
r.min = Math.min(r.min, s.min); r.max = Math.max(r.max, s.max);
r.wsum += s.wsum; r.cov += s.cov;
}
return [...out.values()].map((r) => ({ ...r, avg: r.avg / r.count }));
}Irregular data is read from a CSV file that contains deliberately bad rows: duplicate times, times going backward, non-numeric values and bad quality. The reader drops these rows and gives a reason. It does not fail the whole file and does not average them in. For the 16-bit counter that wraps around, a negative difference is treated as a full wrap.
export function counterDelta(pts: Point[], modulus = 65536): number {
let sum = 0;
for (let i = 1; i < pts.length; i++) {
const d = pts[i].v - pts[i - 1].v;
sum += d >= 0 ? d : d + modulus;
}
return sum;
}Real run: the rollup shows the spike, the gap and different averages
Here is how to read sections 3 and 4 of output.txt above.
- The minute with the spike has a max of 16.08 but an avg of only 10.44. If you kept only the average, you would see just a small rise. Keeping the max preserves the spike even though 60 points were reduced to 1 row.
- Hour 2 has a count of 3000, not 3600, and 83.3 percent coverage. It also has 10 per-minute buckets that are missing as whole rows. The gap from the gateway dropout is therefore visible and is not hidden by an average that looks normal.
- The run/stop state is computed as actual running minutes per hour. Hour 2 gets 47.0 minutes, and the period with missing data is not counted as running time.
- The 16-bit counter went through one wrap. The total difference of 21043 is correct even though the last value read is only 20509.
- The 11 accepted irregular points give a simple average of 63.71 but a time-weighted value of 23.51. The value 80 has densely recorded points but lasted only about 200 seconds at the end of the hour. The value 20 has sparse points but lasted about 3300 seconds. The figure that reflects what the process really did is 23.51.
Step 4: Storage tiers and the space calculator
The plan in the example is raw 1-second data kept for 30 days, a 1-minute tier kept for 2 years and a 1-hour tier kept for 10 years. These numbers are examples. The real answer comes from asking why you need to look back: investigating faults, looking at monthly trends, or retaining data to meet a customer requirement. Then go back and set the resolution you need for each age range.
export const PLAN: Tier[] = [
{ name: "raw", resSec: 1, keepDays: 30, bytesPerPoint: 24 },
{ name: "r1m", resSec: 60, keepDays: 730, bytesPerPoint: 80 },
{ name: "r1h", resSec: 3600, keepDays: 3650, bytesPerPoint: 80 },
];export function sizing(tags: number, plan: Tier[], keptFraction = 1): Sizing[] {
return plan.map((t) => {
const points = Math.round(tags * (86400 / t.resSec) * t.keepDays * (t.name === "raw" ? keptFraction : 1));
return { tier: t.name, points, gib: (points * t.bytesPerPoint) / 1024 ** 3 };
});
}| Number of tags | Raw 30 days | 1 minute 2 years | 1 hour 10 years | Total | Raw only, 10 years |
|---|---|---|---|---|---|
| 200 | 11.59 GiB | 15.66 GiB | 1.31 GiB | 28.56 GiB | 1409.77 GiB |
| 2000 | 115.87 GiB | 156.64 GiB | 13.05 GiB | 285.57 GiB | 14097.69 GiB |
What the table shows: the 1-minute tier is larger than the 30-day raw tier, because it keeps eight fields per row and keeps them much longer. Keeping raw per-second data for ten years is many times larger than the three-tier plan in this example. If the 1-minute tier is too large for the budget, the options are to drop fields you do not use, keep it for a shorter time, or keep only the important tags.
The SQL draft in timescale.sql shows the form of the commands for TimescaleDB as described in the documentation: a per-minute continuous aggregate, a refresh policy and a raw data retention policy. The order matters, as the documentation warns. The start_offset of the refresh policy must not be longer than the raw data retention period. Otherwise a refresh may overwrite the rollup with empty values. This file has not been run against a real database. Test it before use.
CREATE MATERIALIZED VIEW tag_1min
WITH (timescaledb.continuous) AS
SELECT tag,
time_bucket(INTERVAL '1 minute', time) AS bucket,
min(v) AS vmin, max(v) AS vmax, avg(v) AS vavg, count(*) AS n,
first(v, time) AS vfirst, last(v, time) AS vlast
FROM tag_raw
GROUP BY tag, bucket;
-- start_offset ต้องไม่ยาวกว่า retention ของข้อมูลดิบ ไม่งั้นการ refresh จะเขียนทับ rollup ด้วยค่าว่าง
SELECT add_continuous_aggregate_policy('tag_1min',
start_offset => INTERVAL '7 days',
end_offset => INTERVAL '1 minute',
schedule_interval => INTERVAL '1 minute');
-- ดิบเก็บ 30 วัน (ลบทีละ chunk) ส่วน rollup คงอยู่
SELECT add_retention_policy('tag_raw', INTERVAL '30 days');Step 5: The query must pick the tier itself
If a user opens a chart of the past three months and the system reads the raw tier, the result is slow, and the raw data is no longer there anyway. The example picks the finest tier that still reaches back to the start time and whose point count does not exceed what the screen can draw. If no tier reaches that far, it answers with what the coarsest tier has and says why.
export function chooseTier(plan: Tier[], from: number, to: number, now: number, maxPoints: number): Choice {
const ageDays = (now - from) / 86400;
const covering = plan.filter((t) => ageDays <= t.keepDays);
if (covering.length === 0) {
const last = plan[plan.length - 1];
return { tier: last, reason: `เก่ากว่าทุกชั้น (${ageDays.toFixed(0)} วัน) ได้เท่าที่ ${last.name} มี` };
}
for (const t of covering) {
const n = Math.ceil((to - from) / t.resSec);
if (n <= maxPoints) return { tier: t, reason: `${t.name}: ~${n} จุด <= ${maxPoints}` };
}
const coarse = covering[covering.length - 1];
return { tier: coarse, reason: `ทุกชั้นเกิน ${maxPoints} จุด ใช้ ${coarse.name} แล้วควรลดช่วงหรือรวมต่อ` };
}The end of output.txt tries four requests with these results.
- The last ten minutes use the raw tier with 600 rows, which the screen can draw.
- The last six hours would be 21600 raw points, over 1000, so it uses the 1-minute tier and gets 350 rows, not 360, because the missing 10 minutes have no rows at all. The chart therefore shows the real gap.
- Ninety days is beyond the raw tier's age (30 days), so it uses the 1-hour tier.
- Twelve years ago is older than every tier. The system answers with what it has and says why. It does not stay silent.
In the example the real data covers only six hours, so a request going back three months returns 6 rows. What is being tested is the tier selection, not the data volume.
The test suite: what it checks
The test suite historian.test.ts runs with node --test on the same data as the demo. It checks the following.
- deadband: the error does not exceed the band at 0.5 and 2 amps, and at a band of 8 amps the recovered spike is below 11 amps, which confirms that a band that is too wide makes the spike disappear.
- swinging door: the error does not exceed the deviation at three values (0.3, 0.5, 2) across three tags, and the number of stored points is lower than raw.
- rollup: count, min, max, first and last for one minute match direct calculation from raw, and re-rolling 1 minute into 1 hour gives the same result as computing from raw, except for the hour with a gap, where coverage is slightly lower.
- gap: the hour with the gap has a count of 3000 and incomplete coverage.
- time-weighted differs from the simple average on irregular data, with the correct value worked out in the test suite itself.
- The CSV reader drops bad rows with a reason, plus counter rollover and tier selection.
test("deadband: error ไม่เกิน band และ band กว้างเกินทำให้ spike หาย", () => {
for (const band of [0.5, 2]) assert.ok(maxError(cur, deadband(cur, band), "hold") <= band);
const spikeSeen = (kept: typeof cur) =>
Math.max(...cur.filter((p) => p.t >= SPIKE.from && p.t <= SPIKE.to).map((p) => valueAt(kept, p.t, "hold")));
assert.ok(spikeSeen(deadband(cur, 2)) > 15);
assert.ok(spikeSeen(deadband(cur, 8)) < 11); // band 8 A > spike 6 A
});test("time-weighted ต่างจาก simple average เมื่อข้อมูลไม่สม่ำเสมอ", () => {
const pts = [{ t: 0, v: 20 }, { t: 3000, v: 80 }, { t: 3010, v: 80 }, { t: 3020, v: 80 }, { t: 3599, v: 80 }];
const r = rollup(pts, 3600, 3600)[0];
assert.equal(r.avg, 68); // (20+80*4)/5
// 20 ถือ 3000 วินาที, 80 ถือ 599 วินาที (จุดสุดท้ายไม่มีช่วงถือ)
assert.ok(Math.abs(twa(r) - (20 * 3000 + 80 * 599) / 3599) < 1e-9);
assert.ok(twa(r) < 40);
});If you use it for real: what else to do
- Store the value's quality alongside it, and filter out bad values before the rollup. This example drops bad-quality rows when reading the CSV, but a real system should also keep the count of dropped rows in the rollup.
- Set ExcDev and CompDev (or the deadband) per instrument type, not one value for the whole factory, and review them when a sensor is replaced.
- Check the time before the rollup. If the clock shifts or data arrives late, the buckets will be wrong. See the linked article on gaps and time in factory data.
- Test recovery from backup. A rollup can be recalculated from raw, but once the raw data is deleted, the rollup is the only data left, so back up the rollup tiers separately.
- Watch the real size per tag per day and compare it with the calculator. Adjust the plan as the number of tags grows.
- For TimescaleDB, test the order of start_offset and retention with real data before turning it on, as the documentation warns about aggregates becoming NULL.
Hypothetical examples: adapting it to three jobs
Monitoring motor current to find the cause of machine hiccups
The goal is to see short spikes, so use a band smaller than the smallest spike you must see. Keep raw data long enough to investigate causes, and always keep max in the rollup. Use the raw tier when you drill into a specific event.
Energy report per production unit
A cumulative energy counter must handle rollover and resets. The counter difference within a bucket gives a more accurate report than the average of power. See the linked idea in the article on measuring energy per production unit.
Data stored on change from older machines
Older machines connected later often send irregular data. Use a time-weighted average and set maxHold according to the nature of the signal, so an old value is not held across a period you do not actually know.
Common mistakes, and a checklist
- Setting a wide deadband because you want a smooth chart, until short events disappear.
- Keeping only the average in the rollup, so spikes and gaps disappear together.
- Using a plain average on data stored on change.
- Setting the raw data retention policy before the rollup refresh policy, until the summary tier becomes empty values.
- Not handling a wrapping counter, which gives negative differences in reports.
- Nobody knows data is missing, because the rollup does not keep a count.
- Having queries always read the raw tier even though the old data is no longer there.
- List the tags: value type, purpose, the resolution you need and how far back you must look.
- Find the shortest event you must see, and set the deadband or deviation smaller than that.
- Measure the error and the point reduction on each tag's real data.
- Have the rollup keep count, min, max, avg, first and last, and use time-weighted averages for irregular data.
- Lay out the storage tiers, calculate space with measured bytes per point, and allow for indexes and backups.
- Set the policy order so refresh comes before deletion, and test it with trial data.
- Have the query pick the tier by time range, and tell the user when the data is older than what is kept.
Cautions for the example: hypothetical data, hypothetical bytes per point, a short-form swinging door, no counting of index/WAL/compression, no handling of late-arriving data, and the TimescaleDB SQL not tested against a real database. Use it as a learning model, not as ready-to-deploy code.
References
- Tiger Data (TimescaleDB): About continuous aggregates (accessed 2026-11-21)
- Tiger Data (TimescaleDB): Refresh policies (start_offset, end_offset, schedule_interval) (accessed 2026-11-21)
- Tiger Data (TimescaleDB): Drop data from continuous aggregates (accessed 2026-11-21)
- Tiger Data (TimescaleDB): Create a retention policy (accessed 2026-11-21)
- InfluxData: Downsample data with InfluxDB (tasks, buckets, retention) (accessed 2026-11-21)
- AVEVA (UC 2023): Exception, Compression, and their Impacts on PI System Performance (accessed 2026-11-21)
- Swinging Door Trending Compression Algorithm for IoT Environments (accessed 2026-11-21)




