Rebuilding 6 Years of Cache for Just 5 Days of New Data
A cache with only two states, present or absent, forces me to pay the cost of processing all the data every time I want today's data. What is missing is a third state and a boundary that actually tells me how far the cache is complete.
1-minute summary
- Symptom / problem
- A 90-minute compute stage reruns in full every time a few days of data are added
- Who should read
- Maintainers of pipelines that use time-series caches
- Fix in short
- Add an append mode to the cache, fix the 00:00 check-line bug, spot-check head, tail and middle, and extend .npy files over 2 GB atomically
I had some computation work on a time-series dataset with about 6.3 years of history, aggregated into 8 intervals. The smallest interval had around 30 million rows. A full rebuild of the first pipeline stage took about 90 minutes. The problem was that the source data grew every day, and whenever I wanted results through the latest day, the cache builder saw that the old cache was incomplete, deleted it, and recomputed everything from the first year. I was paying 90 minutes for 5 days of new data.
This article records how I added append mode to a cache builder that previously only knew how to do a full rebuild, including bugs I wrote myself that were caught in code review. I have replaced all stage names, filenames, and paths in this article with generic ones. The numbers and reasoning are real.
The old design: the cache is either complete or incomplete
The cache follows a common time-series layout: two .npy files per interval. One holds a matrix of computed values with dimensions (number of rows, number of columns), and the other holds each row's timestamp as int64 microseconds.
The original builder made a simple decision: if the cache covered the requested date, skip it; otherwise, delete it and rebuild everything. When I first wrote it, that seemed safe, because a full rebuild could not produce incorrect results from a join boundary. But as the data kept growing, that kind of safety got more expensive every day.
One thing to establish first: append has one essential requirement. The computation must be causal, meaning the value of row t uses only data from row t and earlier. Backward-looking rolling statistics meet this requirement. With a centered window that looks both forward and backward, old row values change when new data arrives. That cannot use append; it still needs a full rebuild.
Three modes per stage, with each stage deciding for itself
I split the state into three modes.
| Mode | Condition | Action |
|---|---|---|
first_build |
No cache, or cache validation fails | Compute everything from the start date, including a warmup period |
append |
Cache exists and passes validation, but does not reach the requested date | Drop the last day, compute only the tail, then append |
skip |
Cache already covers the requested date | Do nothing |
One deliberate choice was that the pipeline driver does not pass a mode flag. It passes only the date range, and each stage inspects its own cache and chooses its mode. The reason is that stages lag by different amounts. Stage A might be current through yesterday, while stage B might be stuck three days back. If the driver chose the mode, it would need to know every stage's state, duplicating knowledge the stages already have.
# driver.py — ส่งแค่ช่วงวันที่ ไม่ส่งโหมด
import subprocess, sys
STAGES = [
("A", "build_stage_a.py"), # สเตจหนัก มี append
("B", "build_stage_b.py"), # มี append
("C", "merge_a_b.py"), # รวมผล A กับ B ตามช่วงที่มีร่วมกัน
("D", "build_stage_d.py"), # ปลายน้ำ rebuild เต็มทุกครั้ง
]
def run(start, end):
for name, script in STAGES:
rc = subprocess.run([sys.executable, script, "--start", start, "--end", end]).returncode
if rc != 0:
sys.exit(f"[ERR] สเตจ {name} ล้ม rc={rc} หยุดทั้งสาย")
print(f"[OK] สเตจ {name}")
if __name__ == "__main__":
run(sys.argv[1], sys.argv[2])
I did not add a flag to force a rebuild either. To clear the cache, delete its folder manually first. The stage will see that there is no cache and enter first_build on its own. For downstream stages whose full rebuilds already take less than 5 minutes each (57 seconds, 70 seconds, 21 seconds, and 42 seconds in this job), I left them doing full rebuilds. Adding the complexity of append was not worth it.
A bug I wrote: a 00:00 boundary nothing could reach
I wrote the first skip condition based on the intuition that, when requesting data through date D, the cache was complete once its last timestamp reached 00:00 of the next day. I then compared the minimum across all intervals against that boundary.
# รุ่นแรก — ผิด
target_close_us = day_close_us(end_date) # 00:00 UTC ของวันถัดจาก end_date
if min(cached_ends.values()) >= target_close_us:
mode = "skip"
The mistake was that each row's timestamp marks the start of the interval, not its end. The last 4-hour interval of the day starts at 20:00, not 00:00 of the next day. A cache complete through date D has its last timestamp at 20:00 that day, always 4 hours short of the boundary. The condition was therefore always false. Checking each interval showed that the smallest one fell short too, by 5 seconds. The result was that skip mode could never run. No matter how many times I reran it with the same date, it entered append every time.
I did not catch this bug myself. This code went through 5 rounds of review, and the second round identified 4 issues. This was one of two rated high severity. I missed it because the results were correct: repeating append produced the same values. It just wasted time on every run without anything reporting a problem.
The fix was to calculate the last expected row separately for each interval, and skip only when every interval reached its own expected value.
from datetime import datetime, timedelta, timezone
PERIOD_US = {
"5s": 5_000_000, "15s": 15_000_000, "1min": 60_000_000,
"3min": 180_000_000, "5min": 300_000_000, "15min": 900_000_000,
"1h": 3_600_000_000, "4h": 14_400_000_000,
}
def day_close_us(end_date):
"""00:00 UTC ของวันถัดจาก end_date หน่วยไมโครวินาที"""
nxt = datetime(end_date.year, end_date.month, end_date.day,
tzinfo=timezone.utc) + timedelta(days=1)
return int(nxt.timestamp()) * 1_000_000
def all_covered(cached_ends, end_date):
close_us = day_close_us(end_date)
for name, delta in PERIOD_US.items():
expected_last = close_us - delta # จุดเริ่มของคาบสุดท้ายในวัน end_date
if cached_ends[name] < expected_last:
return False # ขาดแม้คาบเดียวก็ยังไม่ skip
return True
A related issue was the field name in the metadata file. I had written cached_end_us as the maximum across all intervals, which was too optimistic. The interval that reaches furthest does not tell me whether every interval is complete. The value that can support that decision is the minimum, so I split it into two fields with names that state their meaning directly.
{
"cached_end_us": 1777665600000000,
"cached_max_end_us": 1777679995000000,
"cached_ends_us": {"4h": 1777665600000000, "5s": 1777679995000000},
"build_history": [
{"ts": "2026-05-02T01:10:00Z", "mode": "first_build", "end": "2026-04-28"},
{"ts": "2026-05-06T01:10:00Z", "mode": "append", "end": "2026-05-01"}
]
}
cached_end_us is the minimum, used to answer how far the cache is complete. cached_max_end_us is kept only for reference, and build_history is very useful for looking back at which modes a cache has gone through.
Validate the cache before deciding: sample the start, end, and middle
Append has a risk that a full rebuild does not: it trusts old data. If the process died partway through the previous run, the values file might be longer than the timestamp file, or vice versa, and the next run would append to something already broken. I therefore made every stage validate its cache before choosing a mode. If validation fails, it clears the cache and enters first_build immediately. Recovery from corruption is automatic, with no one having to watch it.
My first validator only checked whether the files existed. The same review pointed out that this was insufficient, because it did not compare row counts between the two files. The version I use checks 4 things: all files are present, row counts match, dtypes are correct, and timestamps are strictly increasing.
Checking the last condition in full means running np.diff over the entire array. On 30 million rows, that takes 5 seconds or more per interval. I switched to sampling: the first 100,000 rows, the last 100,000 rows, and 10 short sections of 1,000 rows from the middle. This takes less than a second. The start and end are where interrupted writes tend to leave damage, while random samples from the middle help catch cases where data was appended at the wrong position.
import numpy as np
from pathlib import Path
def validate_cache(cache_dir, names, seed=0):
rng = np.random.default_rng(seed)
for name in names:
vp = Path(cache_dir) / f"{name}_values.npy"
tp = Path(cache_dir) / f"{name}_ts.npy"
if not (vp.exists() and tp.exists()):
return False, f"[{name}] ไฟล์ไม่ครบ"
try:
vals = np.load(vp, mmap_mode="r") # ไฟล์ที่เขียนค้างจะล้มตรงนี้
ts = np.load(tp, mmap_mode="r")
except (ValueError, OSError) as e:
return False, f"[{name}] เปิดไม่ได้: {e}"
if vals.shape[0] != ts.shape[0]:
return False, f"[{name}] values={vals.shape[0]} ts={ts.shape[0]}"
if ts.dtype != np.int64:
return False, f"[{name}] ts dtype={ts.dtype}"
n = ts.shape[0]
segs = [ts[:100_000], ts[max(0, n - 100_000):]]
if n > 1_000:
for s in rng.integers(0, n - 1_000, size=10):
segs.append(ts[s:s + 1_000])
for seg in segs:
if seg.shape[0] >= 2 and (np.diff(np.asarray(seg)) <= 0).any():
return False, f"[{name}] timestamp ไม่เรียงเพิ่ม"
return True, "ok"
Sampling 10 locations works well for catching damage from a process dying partway through, because that leaves traces at the start or end of the file. But it cannot catch isolated bad values in the middle. I accept that tradeoff so I can validate on every run without it feeling slow. For full confidence, keep a separate full validation job to run occasionally, rather than putting it in the normal execution path.
Always drop the last day before appending
If I request a build through the 5th while the 5th is still in progress, the cache will contain only half of that day. On the next run, requesting data through the 7th, using the last row as the append point would mean handling a midday boundary that does not align with larger intervals. A 4-hour interval aggregated from half an interval's data will have a different value once all its data arrives.
I chose an approach that avoids having to reason through this: drop the entire last UTC day in the cache before every append, then recompute that day along with the new data. The cost is recomputing one day, which is small compared with working through all the boundary cases.
DAY_US = 86_400_000_000
def keep_rows_before_last_day(ts):
"""คืนจำนวนแถวที่เก็บไว้ หลังตัดวัน UTC สุดท้ายออก"""
last_day_start = (int(ts[-1]) // DAY_US) * DAY_US # epoch เป็น UTC อยู่แล้ว หารลงตัวที่เที่ยงคืน
cut = int(np.searchsorted(ts, last_day_start, side="left"))
if cut == 0:
raise RuntimeError("ตัดแล้วแคชว่าง ให้ไป first_build แทน")
return cut
Recomputing the tail also requires reading enough raw data before the cutoff to cover the rolling functions' warmup, then discarding the warmup rows before appending. Otherwise, the first rows of the tail will contain values computed from windows that are not yet full.
Before appending, I add another continuity check. The first new row must be at least one interval after the last retained row. Anything less means an overlap. A gap of more than 7 days causes a failure because something is clearly wrong. More than 3 days only triggers a warning, since the source already has normal breaks shorter than 3 days.
def check_continuity(name, kept_end_us, new_ts):
delta = PERIOD_US[name]
gap = int(new_ts[0]) - int(kept_end_us)
if gap < delta:
raise RuntimeError(f"[{name}] ส่วนใหม่ทับของเก่า gap={gap}")
if gap > 7 * DAY_US:
raise RuntimeError(f"[{name}] ช่องว่าง {gap / DAY_US:.1f} วัน ต้องตรวจก่อน")
if gap > 3 * DAY_US:
print(f"[WARN] [{name}] ช่องว่าง {gap / 3_600_000_000:.1f} ชั่วโมง")
My previous threshold was the interval length multiplied by 200,000, which works out to 11.6 days for a 5-second interval. The number looked systematic but meant nothing. It would let ten days of missing data pass. A threshold tied to actual time makes it immediately clear what it guards against.
Atomic appends to files larger than 2 GB
The timestamp file is small enough to write directly to a temporary file with np.save and then swap in with os.replace. But the values file for the smallest interval is larger than 13 GB. Loading it into RAM, concatenating, and saving would require room for the old data, new data, and combined result at the same time. I use np.lib.format.open_memmap to create the destination file at its full size first, then stream the old data into it 1 million rows at a time.
In the actual code, I separate dropping the last day from appending. This example combines the two steps into one function to show the process.
import os
def append_atomic(path, keep, new_rows, chunk=1_000_000):
"""เขียนไฟล์ใหม่ = ของเก่า keep แถวแรก + new_rows แล้วสลับชื่อทีเดียว"""
old = np.load(path, mmap_mode="r")
total = keep + new_rows.shape[0]
tmp = str(path) + ".tmp"
out = np.lib.format.open_memmap(
tmp, mode="w+", dtype=old.dtype, shape=(total,) + old.shape[1:])
for i in range(0, keep, chunk): # memmap -> memmap อ่านเขียนเรียงตามลำดับ
j = min(i + chunk, keep)
out[i:j] = old[i:j]
out[keep:] = new_rows
out.flush()
del out, old # ปิด handle ทั้งสองก่อน rename
os.replace(tmp, path)
os.replace is the single point that makes this safe. If the process dies before that line, the original file remains intact, with only a .tmp file left to delete. But on Windows, if a memmap of either the source or destination file is still open, the rename will be rejected. All variables holding those memmaps must be removed with del first, and no other variables anywhere may still reference them.
Another detail to watch is that the values file and timestamp file are replaced at different moments. If the process dies between those two replacements, their row counts will differ, which is exactly what the validator in the previous section catches. The next run will clear the cache and rebuild it automatically. This is why I validate before every decision, rather than only when I suspect a problem.
Stages that depend on other stages' results
My stage C combines results from stages A and B. If A reaches the 7th but B is still on the 5th, the combined result must cover only their shared range: the minimum of the two. It must also verify that both sides have the same number of rows through that point. Otherwise, the two caches have not been aligned from the start.
def common_range(a_ts, b_ts, name):
common_end = min(int(a_ts[-1]), int(b_ts[-1]))
a_idx = int(np.searchsorted(a_ts, common_end, side="right"))
b_idx = int(np.searchsorted(b_ts, common_end, side="right"))
if a_idx != b_idx:
raise RuntimeError(f"[{name}] จำนวนแถวถึงจุดร่วมไม่เท่ากัน {a_idx} กับ {b_idx}")
return a_idx
Once B catches up, running stage C again brings its results up to date too. Stages where the result for row t depends on data after t do not meet the causal requirement and cannot simply append, because the final rows of the old cache were computed before all the future data arrived. They need to recompute a tail covering their lookahead horizon plus a margin, then merge it with the old data using timestamps as the basis.
Tests before trusting append mode
Append that produces different results from a full rebuild is more dangerous than having no append, because it fails silently. I set 4 gates, all of which must pass before using it.
- Match a full rebuild Build a full cache through date X and keep it, then build another through X minus 3 days and append through X. Compare them: every timestamp must match, and values are compared with
np.allclose(rtol=1e-6). - Skip on a repeat run Request append with the same end date twice in a row. The second run must enter skip. This test directly catches the 00:00 boundary bug.
- Recover from an interrupted cache Truncate the cache so it ends midday, then request append. It must recover to cover the requested date.
- Stages lag by different amounts Have A and B end on different days. Stage C must produce results through the minimum of the two without failing.
These are development tests, not tests that run every time in production. In production, integrity checks and metadata are enough.
Complete, or clear and rebuild
- 5 days of new data cost 90 minutes
- No join boundary problems because there are no joins
- Cache corruption goes unnoticed because old data is never read
- Runtime grows with the entire dataset
first_build / append / skip
- Compute only the old last day and new data
- Validate every run and clear corruption automatically
- Check skip boundaries per interval so repeat runs waste no time
- Require a comparison test against a full rebuild
When computing the tail across multiple processes on Windows, passing large arrays between processes becomes an issue. I covered that in multiprocessing on Windows with arrays of tens of GB. The case where a full rebuild stays quiet long enough to look stuck is covered in A batch job that looks frozen but is still running.
The 3-5 minute append time shown above is my estimate for 5 days of new data, not the result of repeated timed runs. The 90-minute full rebuild time was measured. For me, the lesson from this work is not append itself, but the boundary used to answer how far the cache is complete. If that boundary is defined incorrectly, everything built on top of it wastes time without producing any visible error. Anyone using this structure can adjust the interval-length table and gap thresholds to suit their own data. If I have left anything unexplained or made a typo, I will come back and correct it later.
Hit something like this? Stuck somewhere?
Come trade notes on the LinuxThai board



Comments 0
No comments yet — be the first