Partitioning Time-Series Archives by Work Cycle Instead of Month
The unit used to split files on disk should match the actual operating cycle of the data, not the unit the source files happen to be packaged in. Get this decision wrong at the start, and every job that reads the archive will have to handle the boundaries itself indefinitely.
1-minute summary
- Symptom / problem
- The parquet store is split by the source files' months or years, which do not match the data's real work cycle
- Who should read
- People designing a time-series store as parquet files on disk
- Fix in short
- Partition by the real working-week cycle, store time as Int64 microseconds, use a three-column dedup key, and watch for three traps when writing with polars.
I needed to convert 10 years of historical files from a data provider into a parquet archive that analytical jobs could read quickly. The source came as ZIP files containing CSV files, one per month, with yearly files included for some years as well, across 7 datasets in total. My first thought was to partition the output by month to match the source: the simplest approach, one file in, one file out. But once I looked at how the data actually behaved, months did not line up with anything useful. So I reworked the partitioning completely before starting the conversion. This article records how I ended up splitting it, why, and what I ran into along the way.
I have replaced the provider name, dataset names, and measured-value column names with generic names. I call the test dataset in this article dataset B, which is the smallest of the seven. The row counts, file counts, sizes, and timings are from actual runs.
Why months are a poor partitioning unit
This dataset has a clear operating cycle. The source sends data continuously for five working days, Monday through Friday, then stops over the weekend. Almost every job that reads the archive also works in weekly or daily cycles. None asks for "the data for March." If I split files by month, the boundary falls in the middle of a workweek almost every month. A job that needs one week has to open two files and trim the excess itself.
The second problem is the day boundary. The source's working day does not start at 00:00 UTC. Data for a new week starts arriving on Sunday night in UTC. Splitting by UTC calendar days would leave a partial Sunday file with one to two hours of data, and a boundary in the middle of every working day's cycle. So I set a fixed day boundary at 22:00 UTC throughout the year. Data from 22:00 UTC on the previous day to 22:00 UTC on the current day counts as one daily cycle, labeled with the date on which that cycle ends.
Monthly, with days split at 00:00 UTC
Matches source files one to one, but month boundaries fall midweek, Sundays leave partial files, and every reader has to join the pieces each time
By workweek, with days split at 22:00 UTC
One folder holds a full five-day workweek. One file holds a complete daily cycle, with no partial files. Readers can take a whole folder or file directly
I label each workweek with the ISO year and week of its daily cycles, such as 2024-W37. All five daily cycles in the same week always receive the same label, because I calculate it from the time shifted to account for the boundary, rather than from raw UTC time.
I deliberately keep the 22:00 UTC boundary fixed throughout the year instead of shifting it with the source's daylight saving changes. The reason is simplicity: I can calculate day IDs with addition and integer division, without relying on a timezone database everywhere the archive is read. The tradeoff is that in some seasons the boundary does not exactly match the source's actual closing time, which I accept in exchange for a simple formula that is the same everywhere
Store time as Int64 microseconds and use integer arithmetic throughout
Every file in the archive stores time in an Int64 column named time_ts, in microseconds since 1970-01-01 UTC. I do not store it as a datetime type or include a timezone in the file. There are three reasons. First, no tool can misinterpret it: an integer is an integer, whichever library opens it. Second, comparisons and sorting are fast. Third, I can calculate the daily cycle ID with a one-line formula.
import polars as pl
SHIFT_US = 2 * 3600 * 1_000_000 # 7_200_000_000 ดัน 22:00 UTC ไปชนเที่ยงคืน
DAY_US = 86_400 * 1_000_000 # 86_400_000_000
def add_partition_keys(df: pl.DataFrame) -> pl.DataFrame:
"""เพิ่ม work_day_id (จำนวนวันจาก 1970-01-01) กับ week_id (ปี ISO x 100 + สัปดาห์ ISO)"""
shifted = (pl.col("time_ts") + SHIFT_US).cast(pl.Datetime("us", "UTC"))
return df.with_columns(
((pl.col("time_ts") + SHIFT_US) // DAY_US).cast(pl.Int32).alias("work_day_id"),
(shifted.dt.iso_year() * 100 + shifted.dt.week()).cast(pl.Int32).alias("week_id"),
)
def week_label(week_id: int) -> str:
iy, iw = divmod(int(week_id), 100)
return f"{iy:04d}-W{iw:02d}" # 202437 -> "2024-W37"
work_day_id is an Int32 that can be compared directly using greater-than and less-than operators, which turned out to be more useful than I initially expected. The rules for which process may write which day in the article on a live feed overwriting historical data are all expressed as conditions using this number.
Two versions of the disk layout
My first version used one file per workweek, stored flat in the folder for each resolution, with work_day_id kept as a column inside the file so that a single day could be filtered quickly from a weekly file. After using it for six days, I switched to the second version: one folder per week, containing one file per daily cycle.
archive/<dataset>/
├── raw/<YYYY-WNN>/<YYYY-MM-DD>.parquet ข้อมูลดิบ หนึ่งไฟล์ต่อหนึ่งรอบวัน
├── s5/<YYYY-WNN>/<YYYY-MM-DD>.parquet ตารางสรุปคาบ 5 วินาที
├── s15/... m1/... m5/... h1/... d1/... รวม 13 ระดับ ตั้งแต่ 5 วินาทีถึง 1 วัน
├── calendar.json จำนวนแถวต่อวัน + สถานะวัน
└── metadata.json บันทึกการรัน
Datasets whose sources stop over the weekend have five files per weekly folder. The other two datasets, whose sources send data 24 hours a day, 7 days a week, have seven files. To migrate from the first version to the second, I wrote a one-off splitting script that read each weekly file and split it by the work_day_id already present in the file, without having to convert the source again.
What the second version adds is a smaller overwrite unit: one day. A job that repairs or fills in data one day at a time can replace that day's entire file without reading and rewriting the other four days. Jobs that need a whole week can still read the entire folder in one command.
The raw data schema has four columns, while the interval summary tables have eleven. Every resolution uses the same schema.
| File | Column | Type |
|---|---|---|
| Raw data | time_ts | Int64 microseconds UTC |
| Raw data | work_day_id | Int32 |
| Raw data | val_a, val_b | Float64 |
| Summary table | time_ts (interval start time) | Int64 microseconds UTC |
| Summary table | First, maximum, minimum, and last values in the interval, plus other summaries | Float64 |
| Summary table | Number of raw rows in the interval | UInt32 |
A three-column dedup key for overlapping source files
My source files are a mixture of monthly and yearly files, and they overlap. Years with a yearly file also have monthly files for some months. Reading every file directly would load the overlapping periods twice. The seemingly simple choice is to read only one format, but that does not work, because some yearly files contain early months for which no monthly files are available. Discard the yearly files and those periods disappear; discard the monthly files and years without yearly files disappear too. So I had to read both and deduplicate afterward.
The question is what to use as the key. Using time_ts alone would be wrong, because during busy periods the source really can have multiple rows with timestamps identical down to the microsecond. Those rows are separate records with different values. Deduplicating by time alone would delete real data. The correct key combines the timestamp with both value columns. Duplicate rows from overlapping files match in all three fields and collapse into one row, while rows with the same timestamp but different values remain intact.
import os
from datetime import date, timedelta
from pathlib import Path
EPOCH = date(1970, 1, 1)
def atomic_write_parquet(df: pl.DataFrame, final: Path) -> None:
"""เขียนลง .tmp ก่อนแล้ว rename ทับ ไฟล์ปลายทางไม่มีสภาพครึ่งไฟล์ให้ใครอ่านเจอ"""
final.parent.mkdir(parents=True, exist_ok=True)
tmp = final.with_name(final.name + ".tmp")
df.write_parquet(tmp, compression="zstd", compression_level=3)
os.replace(tmp, final)
def merge_week(week_shard_dir: Path, out_raw_dir: Path) -> dict:
"""รวม shard ทั้งหมดของหนึ่งสัปดาห์ -> เรียง -> ตัดซ้ำ -> แยกเขียนเป็นไฟล์ต่อรอบวัน"""
shards = sorted(week_shard_dir.glob("*.parquet"))
df = pl.concat([pl.read_parquet(s) for s in shards], how="vertical_relaxed")
n_before = len(df)
df = (df.sort("time_ts")
.unique(subset=["time_ts", "val_a", "val_b"], keep="first", maintain_order=True))
for sub in df.partition_by("work_day_id", include_key=True):
d = EPOCH + timedelta(days=int(sub.get_column("work_day_id")[0]))
out = out_raw_dir / week_shard_dir.name / f"{d.isoformat()}.parquet"
atomic_write_parquet(sub.select(["time_ts", "work_day_id", "val_a", "val_b"]), out)
return {"week": week_shard_dir.name, "dropped_dup": n_before - len(df)}
The order to preserve is to convert timestamps to integer microseconds first, sort by time, and then deduplicate. Evidence that this works comes from week 2017-W39 of dataset B, where monthly and yearly files overlap. The merge step reported removing 5,271 duplicate rows.
For data arriving at sub-millisecond intervals, rows with matching timestamps are normal, not duplicates. The dedup key must always include the value columns. True duplicates match in every field; rows that happen to share a timestamp differ in their values. If you are unsure whether the source has rows with matching timestamps, count them before defining the key
Inferring a holiday calendar from row counts
The sources have holidays and half-days, but nobody supplied a calendar, and each dataset follows a different holiday schedule. I did not want to look up ten years of holiday calendars and enter them manually, so I let the data tell me. The method is to count the rows in each daily cycle, find the median for days considered to have actual activity—those with more than 1,000 rows—and classify every day against that median.
| Status | Condition |
|---|---|
| normal | Row count at least 0.5 times the median |
| half | At least 0.1 times but less than 0.5 times the median |
| closed | Below 0.1 times the median |
def classify_days(days: list[dict]) -> dict:
"""days = [{"date": "YYYY-MM-DD", "n_rows": int, ...}] เรียงตามวันที่
เติม status ให้ทุกวัน แล้วคืนค่าสรุปของชุดข้อมูล"""
active = sorted(d["n_rows"] for d in days if d["n_rows"] > 1000)
median_active = active[len(active) // 2] if active else 0
half_thresh = max(int(median_active * 0.5), 1)
closed_thresh = max(int(median_active * 0.1), 1)
for d in days:
n = d["n_rows"]
d["status"] = ("normal" if n >= half_thresh
else "half" if n >= closed_thresh
else "closed")
return {
"median_rows_active": median_active,
"n_normal": sum(d["status"] == "normal" for d in days),
"n_half": sum(d["status"] == "half" for d in days),
"n_closed": sum(d["status"] == "closed" for d in days),
}
The results go into calendar.json beside each dataset's data folder. It contains daily entries with row counts, first-row timestamps, last-row timestamps, and status, plus dataset-level summaries, including normal opening and closing times calculated from the median first-row and last-row timestamps of normal days only. I checked the results for dataset B in 2016 against what I already knew and got the following.
| Case checked | Rows in the daily cycle | Resulting status |
|---|---|---|
| One of the source's public holidays | 1 | closed |
| Saturdays with stray rows | 1-2 | closed |
| Working days with less data than usual | 6,000-10,000 | half |
| Normal working days | 21,000 or more | normal |
Jobs reading the archive therefore do not need to know the source's calendar. They read calendar.json and select only normal days, or include half days as well, depending on the job. The 0.5 and 0.1 thresholds work for my data. Datasets with more variable daily volumes may need different thresholds.
Pipeline stages that keep rebuilds from failing
The whole archive can always be rebuilt from the source, and rebuilding must not consume enough RAM to freeze the machine or leave half-written files behind when interrupted. I split the work into four stages that can be run separately.
- Split into shards: read CSV files from ZIP files one at a time, convert timestamps to Int64, add partition keys, and write one shard per source-file/week pair to a staging folder separate from the archive
- Merge by week: read all shards for one week, sort, deduplicate, write separate files for each daily cycle, then delete that week's shards
- Summarize by interval: read a full week's raw data files, summarize into tables one resolution at a time, split by daily cycle, and write each resolution as soon as it is finished
- Calendar: scan only the timestamp column of every raw data file, count rows, classify statuses, and write calendar.json
What makes this resilient is that the unit of work in the memory-intensive stages is always limited to one week. No matter how many years the archive spans, the merge stage never needs to hold more than one week of data in memory. The first stage is the heaviest because it has to load an entire CSV file. The largest yearly file expands to about 1 GB, which is still manageable per worker. I parallelize at the dataset level, with one process per dataset and a default of 4 workers. Within each process, I let polars use its own threads.
Every file write goes through the same atomic_write_parquet function: write to .tmp, then replace the destination with os.replace. If the job is killed midway, it leaves only a .tmp file that nobody reads. The destination remains the complete file from the previous run.
import sys
# บรรทัดแรก ๆ ของสคริปต์: บังคับ stdout เป็น UTF-8 กันคอนโซล Windows ล้มกลางงาน
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
def resample(raw: pl.DataFrame, every: str) -> pl.DataFrame:
"""ข้อมูลดิบ -> ตารางสรุปตามคาบ every เช่น "5s", "1m", "1h"
group_by_dynamic ไม่รับ Int64 ต้อง cast เป็น Datetime เฉพาะช่วงสรุป แล้ว cast กลับ"""
return (
raw.with_columns(pl.col("time_ts").cast(pl.Datetime("us", "UTC")).alias("_dt"))
.sort("_dt")
.group_by_dynamic("_dt", every=every, closed="left", label="left")
.agg([
pl.col("val_a").first().alias("first"),
pl.col("val_a").max().alias("high"),
pl.col("val_a").min().alias("low"),
pl.col("val_a").last().alias("last"),
pl.len().cast(pl.UInt32).alias("n_rows"),
])
.filter(pl.col("n_rows") > 0)
.with_columns(pl.col("_dt").cast(pl.Int64).alias("time_ts"))
.drop("_dt")
)
In the example above, I reduced the summary columns to five to make it easier to read. The real version has more, but the structure is the same.
3 pitfalls when writing with polars
First, partition_by does not write files. It only returns a list of smaller DataFrames in memory. The name suggests that it will split data into files on disk, but it does not. So I wrote my own loop and called the atomic writer for each partition, as in the merge_week function above. Newer versions of polars offer a partitioned sink mode, but I chose not to depend on it because my own loop gives me exactly the control I need over filenames and atomic writes.
Second, group_by_dynamic does not accept an Int64 column; it requires Datetime or Date, which conflicts with the archive's rule of storing timestamps as integers. The solution is to cast to Datetime only while summarizing intervals, then cast back to Int64 before writing. This is a library limitation, not a bug, and it is not a reason to change the type stored in the files.
Third, a Windows console using a Western codepage will immediately throw UnicodeEncodeError when a script prints a character outside that codepage, such as table borders or Thai text. A job that has been running for minutes fails because of a single print statement. I fixed this by reconfiguring stdout to UTF-8 at the start of the script. The point to remember is that if you use a short python -c command to inspect a file, that reconfigure line does not run along with it. Write it as a .py file or wrap it in a PowerShell script instead.
I always run the pipeline on dataset B, the smallest dataset, with a single worker first, then check the week count, the number of duplicate rows removed, and the calendar's daily statuses against what I already know. Only after that passes do I start the larger datasets. Converting ten years of data with the wrong layout and having to rerun everything costs far more than a minute and a half of testing
Numbers from an actual run
The 6,638-file count was measured while I was still using the first layout, with one file per week. After splitting into files per daily cycle, the file count increased with the number of days in each week. Some useful size figures by resolution are 285 MB for raw data, 454 MB for 5-second summaries, 224 MB for 15-second summaries, 80 MB for 1-minute summaries, and just 1.8 MB for 1-day summaries. The 5-second summaries are actually larger than the raw data. My understanding is that this is because summary rows have eleven columns while raw rows have four, and this dataset is not dense enough for aggregation into 5-second intervals to reduce the row count much. Anyone planning to store that fine a resolution should first check whether they will actually use it.
What I took away from this work was not about parquet or polars, but about units. The file unit needs to match the data's operating cycle, the time unit needs to be an integer that every tool reads the same way, and the unit of work in each stage needs to be small enough to survive interruption without damage. The shape of the data inside each row—whether to store it as a blob or split it into columns—is a separate topic that I covered in the article on moving time-series data from JSON into columns. If you use this layout, feel free to adjust the boundary and holiday thresholds to suit your own source. 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