Geospatial and Time-Series Data Questions
Specialized data shapes and their stores: geospatial data types, spatial indexing, and location queries; and time-series data with high-ingest, retention, downsampling, and cardinality management. Covers storage-engine tuning such as compression, chunking, and indexing for range queries, and when purpose-built extensions or databases beat general-purpose stores for these workloads. A niche but recurring topic for location- and telemetry-heavy systems.
How would you optimize time-series queries in a distributed database or data warehouse? Discuss partitioning, bucketing, parallelism, and materialized views.
Sample Answer
Direct answer
In a distributed database or warehouse, the goal is to read as little data as possible and do it in parallel without shuffling it across the network. For time-series tables that means: partition by date so queries prune to the days they ask for; bucket or cluster by the entity key (host, device, series ID) so one entity's rows sit together and joins or group-bys on that key avoid a shuffle; size partitions and files so parallelism is balanced (no skew, no swarm of tiny files); and serve the recurring dashboards from materialized views holding pre-aggregated rollups. My default layout: daily partitions, clustered by (entity, timestamp), hourly and daily rollup views for dashboards.
Terms: partitioning splits a table into separately stored pieces by a column's value (here the date). Bucketing (a term from Hive and Spark, open-source distributed data-processing systems for large batch and SQL workloads on data lakes) or clustering (BigQuery clustered tables, Snowflake clustering keys) orders or hashes rows within partitions by another column so related rows share files. A shuffle is redistributing rows across machines over the network so matching keys meet, usually the most expensive step of a distributed query. A materialized view stores a query's result and keeps it updated so later queries read the result instead of the raw table.
The four levers
1. Partitioning (prune by time)
- Partition on the event date (not ingestion date, unless queries filter on ingestion date).
- Always filter on the partition column in queries; wrapping it in a function the planner (the part of the engine that decides how to execute a query, including which partitions and files it can skip) cannot see through (
CAST(event_ts AS STRING) LIKE '2026-09%') can disable pruning. - Keep partition count sane: daily for high volume, monthly for low volume. Never partition by a high-cardinality key.
2. Bucketing and clustering (co-locate by entity)
- Cluster within each date partition by
(host, event_ts)or(series_id, event_ts). Every file already stores the minimum and maximum value of each column it contains (per-file min/max statistics); once rows are clustered by host, one file's host values fall in a narrow range, so a query for "host = X" can skip any file whose stored range does not include X without opening it. - Bucket both sides of a frequent join (metrics and events) by the same key into the same number of buckets, so the engine joins bucket i with bucket i locally instead of shuffling both tables (a bucketed or co-located join).
- Clustering degrades as new data arrives; schedule re-clustering or compaction (a background job that rewrites many small files into fewer, larger, well-sorted ones, undoing the drift new writes cause): Delta Lake OPTIMIZE with Z-ordering (Delta Lake's own compaction command; Z-ordering interleaves the bits of several columns so files stay well-sorted, and therefore prunable, on more than one column at once), Iceberg rewrite (the equivalent rewrite-and-resort procedure for Apache Iceberg tables), or the warehouse's automatic clustering.
3. Parallelism (balanced, not just more)
- Parallelism is per partition, file or bucket. Target files of roughly hundreds of MB; thousands of tiny files spend more time on task scheduling and metadata than on reading.
- Watch for skew: one host or tenant with 20% of the rows makes one task run long while others idle. Salt the key (append a small random suffix and aggregate in two stages) for known heavy hitters.
- Aggregate before shuffling: partial aggregates per worker, then a final merge (two-phase aggregation), so only small partial results cross the network.
4. Materialized views (pre-compute the repeated work)
- Build hourly rollups (per host: sum, count, min, max) and daily rollups from the hourly ones. Dashboards read the rollups.
- Prefer incremental refresh that processes only new partitions over full recomputation.
- Handle late data: recompute the last N partitions on each refresh, where N covers your maximum lateness.
Worked example
A metrics table receives 3 TB/day, 1 year kept, 10,000 hosts, roughly even data per host.
| Layout | Query: one host, last 7 days | Data scanned |
|---|---|---|
| No partitioning | Full table scan | 3 TB × 365 = 1,095 TB |
| Daily partitions | 7 partitions | 3 TB × 7 = 21 TB |
| Daily partitions + clustered by host | Per-file min/max skips other hosts | Ideal lower bound 21 TB / 10,000 = 2.1 GB, higher in practice because file boundaries do not align perfectly with hosts |
| Hourly rollup view | 7 × 24 = 168 rows for that host | Kilobytes |
The wrong turn to avoid: partitioning by (date, host) gives 365 × 10,000 = 3.65 million partitions per year, each holding a tiny slice of data (3 TB / 10,000 = 300 MB per host per day, split into many small files as it streams in). Planning and metadata operations then dominate. Clustering by host inside daily partitions gets nearly the same pruning without that explosion.
Trade-offs and pitfalls
- Clustering helps only queries that filter on the clustering key. A query that filters on region but clusters on host still scans the day. Cluster on the column the hot queries filter by.
- Materialized views cost storage and refresh compute, and they are only right if they are fresh. Track refresh lag and state it on the dashboard.
- Averages of averages are wrong when combining rollups; store sum and count.
- Bucketed joins break if the two tables use different bucket counts or hash functions; change them together.
- More parallelism is not free: beyond the point where each task reads a reasonably sized file, extra tasks add scheduling overhead for the planner (more units to place onto workers) and more shuffle partitions (the pieces a shuffle splits its output into: more of them means more small files and coordination, even though each piece is small).
- What would change the design: if queries are almost always "all hosts, last 5 minutes" (live dashboards), a real-time store with a time-first sort order (or a TSDB) serves them better than a warehouse tuned for entity-first history.
Explain what downsampling and rollups are in TSDBs. Provide an example policy for converting 1-second resolution to 1-minute and 1-hour rollups and describe the query implications for dashboards and alerts.
Sample Answer
Direct answer
Downsampling means replacing many fine-grained samples with fewer coarse ones: sixty 1-second readings become one 1-minute summary. A rollup is the stored result of that summary, usually several statistics per bucket (minimum, maximum, sum, count, sometimes a last value), kept in its own table or series. A TSDB (time-series database, a store built for timestamped measurements) uses rollups so that long-range queries read thousands of rows instead of millions and so old data can be kept cheaply. A sensible policy: keep 1-second raw data for 7 days, 1-minute rollups for 90 days, 1-hour rollups for 2 years. Dashboards then pick the coarsest tier that still draws a smooth line; alerts evaluate on raw data, because a rollup can hide a short spike and always arrives late.
Key terms, in plain language
- Resolution: the time between stored points. 1-second resolution means 86,400 points per series per day.
- Series: one metric with one fixed set of labels, for example
cpu_usage{host="web-12"}. - Bucket: a fixed time window (one minute, one hour) that a rollup summarizes.
- Gauge vs counter: a gauge is a value that goes up and down (temperature, queue depth). A counter only increases (requests served since start) and is useful only as a rate of change.
- Retention: how long each tier is kept before it is deleted.
The example policy
| Tier | Resolution | Kept for | Stored per bucket | Built from |
|---|---|---|---|---|
| Raw | 1 s | 7 days | the value | ingestion |
| Minute rollup | 1 min | 90 days | min, max, sum, count, last | raw |
| Hour rollup | 1 h | 2 years | min, max, sum, count, last | minute rollup |
Why store sum and count instead of the average. Averages cannot be combined correctly. If minute A has 60 samples averaging 10 and minute B has 30 samples (a gap) averaging 40, the true combined average is (600 + 1,200) / 90 = 20, but averaging the two averages gives 25. With sum and count kept, the hour rollup is just sum of sums divided by sum of counts, which is exact.
Why build the hour tier from the minute tier. Sixty minute rows per hour are much cheaper to read than 3,600 raw rows, and min, max, sum and count all combine exactly (min of mins, max of maxes, sum of sums, sum of counts). This is called a hierarchical rollup.
Counters need a different rollup. For a counter, store the increase over the bucket (last value minus first value), corrected for resets when the process restarts and the counter drops back to zero, not the average of the raw counter value, which is meaningless. Concretely: if a counter reads 1,000,000 at the start of a minute and the process restarts partway through, ending the minute at 15,000 (climbing again from zero), a plain last - first gives 15,000 - 1,000,000 = -985,000, an impossible negative increase for a value that only ever goes up. Detecting the reset (the minute's last value is lower than its first) and instead recording that minute's increase as just the post-restart value, 15,000, gives a sensible positive number: everything before the reset was already counted in the rollups written before it happened, so only the climb from zero to 15,000 is new.
Schedule. A rollup job runs every minute over the minute that closed a little while ago (for example, the minute that ended 2 minutes ago, so late-arriving samples have landed), and every hour over the hour that closed. Deletion jobs drop raw data older than 7 days and minute data older than 90 days. The deletion must never run ahead of the rollup: if raw data for a minute is deleted before that minute's rollup is written, that minute is lost for good.
Worked example: what the policy buys per series
Counting stored values per series (each rollup row holds 4 numeric aggregates, ignoring last to keep the arithmetic simple):
Keeping 1-second raw data for the full 2 years instead would be 86,400 x 730 = 63,072,000 values, about 53 times more.
The query side is where the difference is felt. A 30-day dashboard panel for one series reads:
| Source | Points read |
|---|---|
| 1 s raw | 30 x 86,400 = 2,592,000 |
| 1 min rollup | 30 x 1,440 = 43,200 |
| 1 h rollup | 30 x 24 = 720 |
A panel is roughly 1,000 pixels wide, so 720 hourly points already fill it. Reading 2.6 million raw points to draw 1,000 pixels is pure waste.
Query implications for dashboards
-
Pick the tier by time range. Rule of thumb: choose the coarsest tier that still gives at least a few hundred points across the panel. Last 1 hour: raw. Last 7 days: minute (10,080 points). Last 90 days and beyond: hour. Most TSDB query layers can do this automatically or through a variable in the query: for example, Grafana paired with Thanos or Mimir (long-term storage layers that sit behind Prometheus, adding object-storage retention and a query API spanning wide time ranges), or TimescaleDB continuous aggregates (materialized rollup views that TimescaleDB keeps incrementally up to date as new raw rows arrive, so the coarse tier is only a few seconds behind instead of needing a separate batch job).
-
Show the right statistic. A line of hourly averages hides a 30-second outage. Plot max (or a max band) alongside the average for latency and saturation panels (dashboard panels tracking how full a limited resource is, such as queue depth or percent of disk used), so spikes stay visible at coarse resolution.
-
Percentiles do not roll up. You cannot compute the p99 (99th percentile) for an hour from sixty minute-level p99 values. If percentiles matter, store, per time bucket, a histogram (here "bucket" shifts meaning: not the time window above, but a range of VALUES, such as "100 to 150 ms", with a count of how many samples fell in that range) or a mergeable sketch (a small approximate summary built so that two of them, from different time windows or workers, can be combined into one and still estimate a percentile accurately, unlike a plain average), and compute the percentile at query time by merging the value-histograms (or sketches) from every time bucket in the query range.
A tiny worked example: merging two minutes' latency histograms (bin edges in ms) gives
[0,50): 80, [50,100): 60, [100,150): 45, [150,200): 15, 200 samples total. For p90, the target rank is 0.90 x 200 = 180. Walking the bins, the running count reaches 80 after the first bin and 140 after the second, still short of 180; the third bin,[100,150)with 45 samples, carries the count from 140 to 185, which is where the target rank of 180 falls. Estimate the value by interpolating inside that bin: 100 + (180 - 140) / 45 x 50, about 144 ms. That interpolated estimate, not an exact reconstruction of every raw sample, is what a merged histogram buys you. -
Tier boundaries. A query spanning "last 10 days" crosses the raw-to-minute boundary at day 7. Either query only the minute tier for the whole range (simplest, consistent), or stitch raw and minute data and accept a visible change in smoothness at the boundary.
Query implications for alerts
- Evaluate alerts on raw data. An alert like "CPU above 95% for 20 seconds" needs samples finer than the window. On raw data, a minute containing 20 seconds at 100% and 40 seconds at 50% fires it. On minute rollups, that minute's average is (20 x 100 + 40 x 50) / 60, about 67%, so an alert on the average never fires.
- Rollups are late by design. A minute rollup written 2 minutes after the minute closes adds that delay to any alert built on it.
- If an alert must run on a rollup (a slow trend over weeks, like disk filling), use max or last for threshold alerts and a rate over the counter increase for throughput alerts, never the average of a spiky gauge.
Trade-offs and pitfalls
- Rollups lose information permanently. After 7 days you cannot answer "what exactly happened at 14:03:17". Decide which questions need raw data and set raw retention from that, not from disk size alone.
- Late data. A sample that arrives after its minute was rolled up is missing from the rollup unless the job re-processes a trailing window (for example, always recompute the last 10 minutes).
- Averaging averages and averaging percentiles are the two classic errors. Keep sum, count and a histogram, and derive everything else.
- Retention ordering bug. A deletion job that runs before the rollup job has covered the same window silently erases history. Make the rollup lag strictly smaller than the raw retention.
Design a storage solution for metrics/time-series: system must handle 100 million unique series, an ingest rate of 500k writes/sec, queries for arbitrary time ranges and rollups, retention of 1 year at full resolution and 7 years of aggregated resolution. Recommend database family and explain compression, downsampling, partitioning/shard placement, and lifecycle.
Sample Answer
Direct answer
Use a horizontally scaled, Prometheus-compatible TSDB (time-series database: a store built around series of timestamped values) whose immutable data blocks live in object storage, in the style of Grafana Mimir, Thanos or Cortex. Put a durable log (Kafka) in front of it so ingest survives backend hiccups, keep full-resolution data for one year, and keep hourly rollups (min, max, sum, count per series per hour) for seven. A relational database or a generic key-value store would force you to rebuild the three things this workload lives on: a label index over 100 million series, type-aware compression, and whole-block retention.
Two terms used throughout. A series is one metric plus one exact set of labels, such as http_requests_total{service="checkout", zone="a"}. A sample is one (timestamp, value) point in a series. Cardinality is the number of distinct series.
Requirements, with the arithmetic
| Quantity | Calculation | Result |
|---|---|---|
| Samples per day | 500,000 × 86,400 | 43.2 billion |
| Samples per year | 500,000 × 31,536,000 | 15.77 trillion |
| Average interval per series | 100,000,000 / 500,000 per s | one sample every 200 s |
| Raw size per year (8 B timestamp + 8 B float) | 15.77 T × 16 B | 252 TB |
| Compressed per year at 1.37 B/sample (Facebook's Gorilla paper) | 15.77 T × 1.37 B | 21.6 TB |
| Compressed per year at 1 to 2 B/sample (Prometheus storage docs) | 15.77 T × 1 to 2 B | 15.8 to 31.5 TB |
The 200-second figure matters: it tells you many series are sparse or short-lived. I would confirm with the team whether 100 million is active series or series ever seen, because the in-memory index is sized by active series.
Scale framings you may be given instead: 1 PB per year of raw data is 31.7 MB/s, about 2 million samples/s at 16 B each, and roughly 86 TB/yr once compressed at 1.37 B. At that size the question is no longer "can it store it" but "what does recent, low-latency storage cost versus cheap long-term storage", which is exactly the hot/cold split below. At 200,000 samples/s the same design works with fewer ingesters (about 8.6 TB/yr compressed).
Architecture
flowchart LR
A[Apps and exporters] --> B[Collector agents with local WAL]
B --> K[(Kafka, partitioned by series hash)]
K --> I[Ingesters x3 replicas: in-memory head + WAL]
I -->|2h blocks| O[(Object storage)]
O --> C[Compactor: merge, dedupe, downsample, delete]
C --> O
O --> G[Store gateways]
Q[Query frontend: split by time, cache] --> I
Q --> G
Five components do the work in that diagram. Ingesters are the stateful services that accept writes: each holds its most recent data in memory (the head, a mutable, not-yet-compressed block) and periodically seals it into a compressed 2-hour block. Object storage is the durable, low-cost store that holds those sealed blocks once ingesters write them: it needs no replication logic of its own because the provider already replicates every object, which is why the design does not keep paying for 3x storage past the first day. The compactor runs in the background, merging the small blocks written by many ingester replicas into larger ones, removing the duplicate copies, and writing the downsampled rollups. Store gateways hold no data of their own; they serve queries against the historical blocks sitting in object storage by reading each block's index. The query frontend is what clients actually talk to: it splits a query into pieces, routes recent pieces to ingesters and older pieces to store gateways, and caches finished results.
The ingestion pipeline, component by component
- Instrumentation. Client libraries expose counters (values that only ever increase, like a request count), gauges (values that go up or down, like current memory usage) and histograms (bucketed counts of observed values, like request durations); agents scrape (pull) metrics themselves or run as exporters (small adapters that expose a third-party system's internal numbers, such as a database's connection-pool size, in scrapeable form) or receive pushes. Cardinality control starts here: a label like
user_idturns one series into millions, so relabel rules (agent-side configuration that rewrites or drops specific labels before ingestion) drop or aggregate such labels before they leave the host. - Buffering. Each agent writes to a local WAL (write-ahead log: an append-only file written before anything is acknowledged) so a restart or a network blip does not lose samples. The buffer is bounded in bytes and hours.
- Streaming. Kafka decouples producers from the TSDB. At an assumed 100 B per sample on the wire, 500k samples/s is 50 MB/s; six hours of retention is about 1.1 TB per replica, which lets you replay after an ingester outage.
- Backpressure (a slow consumer pushing back on producers rather than being overwhelmed). Queues are bounded; when full, the write path returns an HTTP 429 or 503 and agents retry with exponential backoff and jitter (each retry waits roughly twice as long as the last, with a bit of randomness added, so retrying agents do not all hammer the system at the same instant). Per-tenant ingestion limits (samples/s and active series, applied separately to each team or customer sharing the cluster, a "tenant") stop one team's cardinality explosion from starving everyone. If you must shed, shed low-priority debug series first, never alerting series.
- Durability. Acknowledge a write only after it is in the WAL on a quorum (majority) of replicas: with a replication factor of 3, two of three. Kafka producers use
acks=all.
Compression
A TSDB compresses timestamps and values separately, the scheme from Facebook's Gorilla paper (VLDB 2015) that Prometheus-family engines follow:
- Timestamps: delta-of-delta. Scrapes arrive at a steady interval, so the difference between consecutive gaps is usually 0 and costs 1 bit.
- Values: XOR with the previous value. Identical values cost 1 bit; similar floats share leading and trailing bits, so only the middle "meaningful" bits are stored.
This program counts the bits that scheme needs (bucket sizes from the paper). It shows why "1 to 2 bytes per sample" is an average, not a guarantee. The bucket sizes below follow Gorilla's own design: a short control prefix says which size range a non-zero delta-of-delta falls into, then the value is stored in exactly that many bits, so smaller, more common changes cost less. For the XOR value encoding, reusing the previous value's leading/trailing-zero window costs just 2 control bits plus the meaningful bits (2 + (64 - lead_w - trail_w)); starting a new window costs 2 control bits plus 5 bits to record the leading-zero count plus 6 bits to record the meaningful-bit count (2 + 5 + 6), then the meaningful bits themselves (the leading-zero count is capped at 31, the largest value 5 bits can hold):
import random, struct
def f2u(x):
return struct.unpack('>Q', struct.pack('>d', x))[0]
def gorilla_bits(ts, vals):
"""Bits needed by Gorilla-style encoding (Pelkonen et al., VLDB 2015)."""
bits = 64 + 64 # first timestamp and first value stored raw
prev_delta = ts[1] - ts[0]
bits += 14 # first delta
for i in range(2, len(ts)):
delta = ts[i] - ts[i - 1]
dod = delta - prev_delta # delta-of-delta
prev_delta = delta
if dod == 0:
bits += 1
elif -63 <= dod <= 64:
bits += 2 + 7
elif -255 <= dod <= 256:
bits += 3 + 9
elif -2047 <= dod <= 2048:
bits += 4 + 12
else:
bits += 4 + 32
prev = f2u(vals[0]); lead_w, trail_w = None, None
for v in vals[1:]:
x = f2u(v) ^ prev; prev = f2u(v)
if x == 0:
bits += 1 # identical to previous value
continue
lead = min(64 - x.bit_length(), 31)
trail = (x & -x).bit_length() - 1
if lead_w is not None and lead >= lead_w and trail >= trail_w:
bits += 2 + (64 - lead_w - trail_w) # reuse previous window
else:
bits += 2 + 5 + 6 + (64 - lead - trail) # new window
lead_w, trail_w = lead, trail
return bits
random.seed(7)
n = 720 # 2 hours at a 10 s scrape interval
ts_regular = [1_700_000_000 + 10 * i for i in range(n)]
ts_jitter = [t + random.choice([0, 0, 0, 1, -1]) for t in ts_regular]
counter, c = [], 0.0
for _ in range(n):
c += random.randint(0, 50) # request counter: whole numbers going up
counter.append(c)
gauge_flat = [42.0] * n # e.g. a config value that never changes
gauge_noisy = [round(random.gauss(55.0, 3.0), 3) for _ in range(n)] # CPU temp, 3 decimals
for name, ts, vals in [("flat gauge, regular ts", ts_regular, gauge_flat),
("counter, jittered ts", ts_jitter, counter),
("noisy gauge, jittered ts", ts_jitter, gauge_noisy)]:
b = gorilla_bits(ts, vals)
print(f"{name:26s} {b / 8 / n:5.2f} bytes/sample (raw: 16.00)")
Output (Python 3, seed pinned):
flat gauge, regular ts 0.27 bytes/sample (raw: 16.00)
counter, jittered ts 2.66 bytes/sample (raw: 16.00)
noisy gauge, jittered ts 7.56 bytes/sample (raw: 16.00)
Lesson for capacity planning: value entropy dominates. A noisy gauge with three meaningful decimals costs almost 30 times a flat one. Rounding at the source (store 55.2, not 55.2381) is a real storage lever, so budget with your own data, not the fleet average.
Downsampling for the 7-year tier
Store, per series per bucket, min, max, sum and count (plus a quantile sketch, a compact, mergeable summary structure that approximates a percentile without storing every raw value, if you need percentiles). Sum and count let you compute a correct average for any coarser bucket; an average of averages is wrong whenever buckets hold different numbers of samples. A counter only ever increases, until the process that owns it restarts and it resets to zero; min, max, sum and count assume the raw values themselves are meaningful to bound or add, which is true for a gauge but not for a counter, where what matters is the rate of change. Counters need a rate-aware rollup that stores the increase over the bucket and handles resets: it detects a reading lower than the previous one as "the counter restarted", not as "the value dropped", so the computed rate stays correct across the restart.
Pick the bucket from the data, not from habit. Each series here produces 18 raw stored numbers per hour (3,600 / 200: one value per sample, since timestamps sit on a regular grid and are not stored separately). A 5-minute rollup stores 12 buckets, each holding 4 numbers (min, max, sum, count), so 48 stored numbers per hour, more than the 18 raw values. A 1-hour rollup stores 1 bucket x 4 numbers = 4 stored numbers per hour, about 4.5x fewer than the 18 raw values (18 / 4 = 4.5). So the 7-year tier is hourly (daily for anything older if queries allow). If every series were active all year: 100 M × 8,760 hours × 4 values = 3.5 trillion values/yr, about 7 TB/yr at an assumed 2 B per value, about 49 TB for seven years.
Partitioning and shard placement
- By series: hash the full label set onto a consistent-hash ring (nodes own token ranges, so adding a node moves only a slice of series). Hash all labels, not the metric name, or one huge metric lands on one node. Each series goes to 3 ingesters in 3 availability zones (physically separate data-center facilities within a region, so one facility failing does not take out all 3 replicas).
- By time: ingesters cut 2-hour blocks; the compactor merges them into larger blocks (typically up to a day), removes the duplicate copies written by the 3 replicas, and writes the rollups.
- Load per ingester: with 50 ingesters, 500k × 3 replicas / 50 = 30k samples/s each. Memory is set by active series: measure bytes per series in a load test; at an assumed 2 KB, 100 M × 3 × 2 KB is 600 GB of RAM spread across the fleet.
- Queries route by age: the last ~24 hours to ingesters, older ranges to store gateways that read block indexes from object storage. The frontend splits a 30-day query into day-sized pieces, runs them in parallel and caches finished days.
Lifecycle
| Age | Where | Resolution |
|---|---|---|
| 0 to 24 h | Ingester RAM and local SSD | Raw |
| 1 day to 1 year | Object storage, standard class | Raw, compacted blocks |
| 1 to 7 years | Object storage, infrequent-access class | Hourly rollups |
| Older than 7 years | Deleted by the compactor |
Retention deletes whole blocks, never individual rows, so it costs a metadata operation instead of a scan. Raw object storage holds one copy (about 21.6 TB/yr compressed); the provider handles durability, so you do not pay for the 3× ingest replication beyond the first day.
Trade-offs and pitfalls
- What would change the choice: if the long-term workload is ad-hoc analytics joined with business data, keep the TSDB for the recent operational tier and export rollups to a columnar store (Parquet files or ClickHouse). If "100 M" turns out to be lifetime series with a few million active, a much smaller cluster is enough.
- Cardinality is the failure mode, not throughput. Enforce per-tenant series limits and alert on series growth rate.
- Small blocks in object storage multiply request costs and slow queries; compaction is not optional.
- Query limits (max series touched, max samples per query) protect ingesters from one dashboard asking for a year of raw data across all series.
What storage formats are suitable for time-series data to optimize compression and query performance?
Sample Answer
Direct answer
Use a columnar layout sorted by series and time, with time-series encodings (delta or delta-of-delta for timestamps, delta or XOR encoding for values, dictionary or run-length encoding for tags) followed by a general compressor such as ZSTD. In practice that means a TSDB's native chunk format (Prometheus blocks, InfluxDB TSM files, TimescaleDB compressed chunks), a columnar database table (ClickHouse MergeTree with codecs), or Parquet (or ORC) files on object storage for analytics and archive. Row formats such as CSV and JSON lines are fine for transport, not for storage.
Terms: columnar stores each column's values together instead of each row's values together, so similar values sit next to each other and compress well, and a query reads only the columns it needs. Delta encoding stores the difference from the previous value. Delta-of-delta stores the difference between consecutive deltas, which is zero when samples arrive at a regular interval. XOR encoding (from Facebook's Gorilla paper) stores only the bits of a floating-point value that changed from the previous one. Run-length encoding stores "value, count" instead of repeating a value. Varint (variable-length integer) spends only as many bytes as a number actually needs instead of a fixed 4 or 8. Zigzag remaps signed numbers to unsigned ones so small negative deltas stay small too (-1 to 1, 1 to 2, -2 to 3, and so on), which matters because varint is cheap only for small non-negative numbers.
Product names used below: MergeTree is ClickHouse's core storage engine. TSM is InfluxDB's "Time-Structured Merge" on-disk file format, its version of an LSM-tree. ORC is a columnar file format similar to Parquet, common in the Hadoop and Hive ecosystem. Trino and DuckDB are SQL query engines that read Parquet files directly without importing them into a database first. A row group is Parquet's internal chunk of rows, each with its own compression and min/max statistics.
Formats compared
| Format | Layout | Strengths | Weaknesses | Use for |
|---|---|---|---|---|
| TSDB native chunks (Prometheus, InfluxDB TSM, TimescaleDB compressed chunks) | Per-series chunks, time-ordered | About 1 to 2 bytes per sample in Prometheus (per its docs); fast recent reads | Tied to one engine | Operational metrics |
| Columnar table with codecs (ClickHouse MergeTree) | Columns sorted by a key | SQL, rich aggregation, per-column codecs such as DoubleDelta and Gorilla | Many tiny inserts need batching | High-volume metrics and logs with SQL |
| Parquet or ORC | Columnar files with row groups and min/max statistics | Open format, readable by Spark, Trino, DuckDB and warehouses; cheap on object storage | Immutable files; poor for per-point updates or real-time reads | Archive, data lake, ML feature extraction |
| CSV or JSON lines | Row-oriented text | Human-readable, universal | Large, slow to parse, types lost | Ingest and exchange only |
Worked example: why layout matters more than the compressor
The script below generates one day of CPU readings for 100 hosts at a 10-second interval (864,000 points, pinned seed), stores it three ways and compresses each with the same compressor (zlib level 9):
import random, zlib, json
random.seed(42)
SERIES, POINTS, STEP = 100, 8640, 10 # 100 series, one day at a 10 s interval
T0 = 1_788_220_800 # 2026-09-01 00:00:00 UTC, epoch seconds
rows = []
for s in range(SERIES):
v = 50.0
for i in range(POINTS):
v = min(100.0, max(0.0, v + random.gauss(0, 0.5)))
rows.append((f"host-{s:03d}", T0 + i * STEP, round(v, 1)))
rows.sort(key=lambda r: (r[1], r[0])) # arrival order: interleaved by time
# 1) JSON lines, one object per point (typical log/ingest format)
jsonl = "".join(json.dumps({"host": h, "ts": t, "cpu": v}) + "\n" for h, t, v in rows).encode()
# 2) CSV, one row per point
csv = "".join(f"{h},{t},{v}\n" for h, t, v in rows).encode()
# 3) columnar, sorted by (host, ts): host stored once per run, timestamps as
# delta-of-delta varints, values as fixed-point deltas (tenths) zigzag varints
def zz(n): return (n << 1) ^ (n >> 63)
def varint(n, out):
while n >= 0x80:
out.append((n & 0x7F) | 0x80); n >>= 7
out.append(n)
by_series = sorted(rows)
hosts, ts_col, val_col = bytearray(), bytearray(), bytearray()
prev_h = None
for h, t, v in by_series:
if h != prev_h:
hosts += f"{h}:{POINTS};".encode() # run-length encoded host column
prev_t, prev_d, prev_v, prev_h = t, 0, 0, h
varint(zz(t), ts_col); varint(zz(int(round(v * 10))), val_col)
prev_v = int(round(v * 10)); continue
d = t - prev_t
varint(zz(d - prev_d), ts_col); prev_t, prev_d = t, d
iv = int(round(v * 10)); varint(zz(iv - prev_v), val_col); prev_v = iv
columnar = bytes(hosts) + bytes(ts_col) + bytes(val_col)
print(f"points: {len(rows):,}")
for name, blob in [("JSON lines", jsonl), ("CSV", csv), ("columnar+delta", columnar)]:
z = zlib.compress(blob, 9)
print(f"{name:15s} raw {len(blob):>10,} B zlib-9 {len(z):>9,} B "
f"{len(z)/len(rows):5.2f} B/point")
print(f"timestamp column: {len(ts_col):,} B for {len(rows):,} timestamps")
Output (Python 3):
points: 864,000
JSON lines raw 44,873,715 B zlib-9 4,176,075 B 4.83 B/point
CSV raw 21,545,715 B zlib-9 3,757,019 B 4.35 B/point
columnar+delta raw 1,729,900 B zlib-9 534,940 B 0.62 B/point
timestamp column: 864,400 B for 864,000 timestamps
What it shows:
- What the encoder is doing, line by line:
zz(n)is the zigzag step described above;varintthen writes that zigzagged number out 7 bits at a time, setting the top bit (0x80) on every byte except the last to say "more bytes follow" (the same varint format Protocol Buffers and Parquet use). For the timestamp column it zigzag-varint-encodes the delta-of-delta (d - prev_d, almost always 0 for a regular 10 s interval, so it becomes a single zero byte); for the value column it does the same to the delta between consecutive fixed-point tenths (iv - prev_v, the value rounded to the nearest 0.1 and stored as an integer count of tenths). - The same compressor gets 4.35 bytes per point from CSV but 0.62 from the columnar, delta-encoded layout, about 7 times smaller. Layout and encoding did the work, not the compressor.
- Delta-of-delta turns a perfectly regular 10-second interval into a stream of zeros: one byte per timestamp before compression (864,400 bytes for 864,000 timestamps), and almost nothing after.
- Values here are stored as exact tenths, so the encoding is lossless for this data. Real float data uses XOR encoding instead.
Trade-offs and pitfalls
- Irregular timestamps and noisy values compress worse. Delta-of-delta shines on fixed scrape intervals; event data with random timing gets less benefit. Measure on your own data.
- Sort order is part of the format. The same Parquet file sorted by time only, with hosts interleaved, compresses and prunes worse than one sorted by (host, time).
- Row-group and file size matter for Parquet: row groups that are too small add metadata and reduce compression; too large reduce parallelism and skipping granularity.
- Do not store floats as strings and do not store tags repeated on every row uncompressed; dictionary-encode them.
- Choose by access pattern: real-time dashboards want a TSDB or columnar database; long-term archive and data-science access want Parquet on object storage. Many platforms use both, exporting aged TSDB data to Parquet.
Your table stores time-series events and needs to answer 'rolling metrics for this user over the last 7/30/90 days' at query time, without maintaining separate precomputed rollup tables. Design the schema, partitioning, clustering, and secondary indexes that would keep those queries fast as the table grows, and explain the query pattern you'd use to compute the rolling windows efficiently.
Sample Answer
Direct answer
Partition the events table by time (monthly), and give every partition a composite index on (user_id, event_ts) that includes the measured value. Then a 90-day lookup for one user is one contiguous index range per partition, answered without reading the table. Compute all three windows in one pass over the last 90 days with conditional aggregation (FILTER (WHERE event_ts >= as_of - interval '7 days')), because the 7- and 30-day windows are subsets of the 90-day one. For a rolling time series (a 7-day value for every day), bucket events into days first, then use a window function with a RANGE frame on the day, so the work grows with the number of days, not the number of events.
Schema, partitioning and indexes
CREATE TABLE events (
user_id bigint NOT NULL,
event_ts timestamptz NOT NULL,
amount numeric(12,2) NOT NULL
) PARTITION BY RANGE (event_ts);
CREATE TABLE events_2026_09 PARTITION OF events FOR VALUES FROM ('2026-09-01') TO ('2026-10-01');
-- one partition per month
CREATE INDEX ON events (user_id, event_ts) INCLUDE (amount);
- Partitioning by month: a 90-day query touches at most 4 partitions however long history grows, and retention drops old months.
- Clustering by user: the composite index gives one user's events in time order inside each partition. In a columnar warehouse the same idea is
PARTITION BY DATE(event_ts)plus clustering or sort key onuser_id. INCLUDE (amount)makes the scan index-only: Postgres answers from the index without fetching table rows, as long as autovacuum (Postgres's background process that runs VACUUM to reclaim space and keep this bookkeeping current) keeps the table's visibility map (a per-table bitmap marking which pages hold only rows every transaction can see) current.- No other secondary indexes on this path. Add one only for a different access pattern, such as
(event_type, event_ts)for per-type analytics.
The query patterns, runnable
This script builds five monthly partitions, gives user 42 exactly one 10.00 event per day from 1 May to 29 September 2026, adds noise rows for 1,999 other users, and computes the windows as of 30 September 00:00 UTC. The as-of time is a literal so the output is reproducible; in production it is now() or a parameter. Run it with psql -f on PostgreSQL 16:
SET TIME ZONE 'UTC';
DROP TABLE IF EXISTS events CASCADE;
CREATE TABLE events (
user_id bigint NOT NULL,
event_ts timestamptz NOT NULL,
amount numeric(12,2) NOT NULL
) PARTITION BY RANGE (event_ts);
CREATE TABLE events_2026_05 PARTITION OF events FOR VALUES FROM ('2026-05-01') TO ('2026-06-01');
CREATE TABLE events_2026_06 PARTITION OF events FOR VALUES FROM ('2026-06-01') TO ('2026-07-01');
CREATE TABLE events_2026_07 PARTITION OF events FOR VALUES FROM ('2026-07-01') TO ('2026-08-01');
CREATE TABLE events_2026_08 PARTITION OF events FOR VALUES FROM ('2026-08-01') TO ('2026-09-01');
CREATE TABLE events_2026_09 PARTITION OF events FOR VALUES FROM ('2026-09-01') TO ('2026-10-01');
CREATE INDEX ON events (user_id, event_ts) INCLUDE (amount);
-- user 42: one 10.00 purchase per day from 2026-05-01 to 2026-09-29; other users as noise
INSERT INTO events
SELECT 42, timestamptz '2026-05-01 12:00' + d * interval '1 day', 10.00
FROM generate_series(0, 151) AS d;
INSERT INTO events
SELECT u, timestamptz '2026-05-01 00:00' + (u * 37 + d) % 150 * interval '1 day', 1.00
FROM generate_series(1, 2000) AS u, generate_series(0, 19) AS d WHERE u <> 42;
ANALYZE events;
\echo one pass, three windows, as of 2026-09-30 00:00 UTC
SELECT
sum(amount) FILTER (WHERE event_ts >= timestamptz '2026-09-30' - interval '7 days') AS sum_7d,
sum(amount) FILTER (WHERE event_ts >= timestamptz '2026-09-30' - interval '30 days') AS sum_30d,
sum(amount) AS sum_90d,
count(*) AS events_90d
FROM events
WHERE user_id = 42
AND event_ts >= timestamptz '2026-09-30' - interval '90 days'
AND event_ts < timestamptz '2026-09-30';
\echo rolling 7-day sum per day, last 3 days
SELECT day, rolling_7d FROM (
SELECT day,
sum(daily) OVER (ORDER BY day RANGE BETWEEN interval '6 days' PRECEDING AND CURRENT ROW) AS rolling_7d
FROM (
SELECT date_trunc('day', event_ts) AS day, sum(amount) AS daily
FROM events
WHERE user_id = 42
AND event_ts >= timestamptz '2026-09-30' - interval '96 days'
AND event_ts < timestamptz '2026-09-30'
GROUP BY 1
) d
) w ORDER BY day DESC LIMIT 3;
\echo plan
EXPLAIN (COSTS OFF)
SELECT sum(amount) FROM events
WHERE user_id = 42 AND event_ts >= timestamptz '2026-09-30' - interval '90 days' AND event_ts < timestamptz '2026-09-30';
Output:
one pass, three windows, as of 2026-09-30 00:00 UTC
sum_7d | sum_30d | sum_90d | events_90d
--------+---------+---------+------------
70.00 | 300.00 | 900.00 | 90
(1 row)
rolling 7-day sum per day, last 3 days
day | rolling_7d
------------------------+------------
2026-09-29 00:00:00+00 | 70.00
2026-09-28 00:00:00+00 | 70.00
2026-09-27 00:00:00+00 | 70.00
(3 rows)
plan
QUERY PLAN
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Aggregate
-> Append
Subplans Removed: 2
-> Index Only Scan using events_2026_07_user_id_event_ts_amount_idx on events_2026_07 events_1
Index Cond: ((user_id = 42) AND (event_ts >= ('2026-09-30 00:00:00+00'::timestamp with time zone - '90 days'::interval)) AND (event_ts < '2026-09-30 00:00:00+00'::timestamp with time zone))
-> Index Only Scan using events_2026_08_user_id_event_ts_amount_idx on events_2026_08 events_2
Index Cond: ((user_id = 42) AND (event_ts >= ('2026-09-30 00:00:00+00'::timestamp with time zone - '90 days'::interval)) AND (event_ts < '2026-09-30 00:00:00+00'::timestamp with time zone))
-> Index Only Scan using events_2026_09_user_id_event_ts_amount_idx on events_2026_09 events_3
Index Cond: ((user_id = 42) AND (event_ts >= ('2026-09-30 00:00:00+00'::timestamp with time zone - '90 days'::interval)) AND (event_ts < '2026-09-30 00:00:00+00'::timestamp with time zone))
(9 rows)
Check the numbers by hand: 90 days before 30 September is 2 July, so the window holds 2 July to 29 September, which is 90 daily events of 10.00 = 900.00. The last 30 days hold 30 events (300.00) and the last 7 hold 7 (70.00). The plan shows the May and June partitions removed ("Subplans Removed: 2") and an index-only scan on the other three.
Why these patterns
- One pass, three windows: three separate queries would read the last 7 days three times and the last 30 twice.
FILTERevaluates all three sums while scanning the 90-day range once. - Bucket, then window:
RANGE BETWEEN interval '6 days' PRECEDING AND CURRENT ROWmeans "rows whose day is within 6 days before this one", which is correct even when a user has no events on some days. AROWS BETWEEN 6 PRECEDINGframe would silently span more than 7 calendar days whenever days are missing. - Scanning 96 days for a 90-day series: the first output day needs 6 days of history before it, otherwise its 7-day value is truncated.
Keeping it fast as the table grows
Cost per query is proportional to one user's events in the window, not to table size, because the index range and partition pruning bound it. Worked example: a heavy user with 200 events/day has 18,000 events in 90 days; that is about 18,000 index entries across 4 partitions, which is a small read. The worst case is a bot account with millions of events: add a per-user daily cap at ingest, or accept that such users need a pre-aggregated path.
Two things silently break it:
- Stable functions and pruning.
now()is a stable function (a Postgres function guaranteed to return the same value for every row within one query, but not a fixed literal Postgres already knows ahead of time), sonow() - interval '90 days'is not a constant at planning time (the step where Postgres works out, before running the query, which partitions could possibly match). Instead it prunes partitions (skips the ones that cannot match) at executor start (the moment it actually begins running the query, once "now" is known); that is still effective, as the plan shows, it just happens a beat later than pruning on a literal timestamp would. Wrapping the column, as inWHERE date(event_ts) >= ..., defeats both pruning and the index; always compare the raw column to a computed bound. - Index-only scans need a current visibility map. On a table with heavy updates or deletes, the scan falls back to fetching rows from the table itself (shown in
EXPLAINoutput as heap fetches) instead of answering from the index alone. Events are insert-only, so this holds if autovacuum keeps up.
Trade-offs and pitfalls
- Time zones:
date_trunc('day', event_ts)uses the session time zone. Set it explicitly (the script uses UTC), or compute days in the user's own zone withAT TIME ZONE. - Window boundaries: decide whether "last 7 days" means the last 168 hours (as here) or the last 7 calendar days including today; they differ by up to a day of events.
- Batch many users: for a feature pipeline scoring millions of users, the same
FILTERquery withGROUP BY user_idover one 90-day scan is better than millions of index lookups. - What would change the design: if the SLO (service-level objective) is single-digit milliseconds at thousands of requests per second, the "no rollups" constraint is worth challenging, because incrementally maintained daily per-user totals (a background job adds each day's events to a running per-user-per-day row as they arrive, instead of a request recomputing sums from scratch) turn each request into reading at most 90 small rows.
Unlock Full Question Bank
Get access to all 12 Geospatial and Time-Series Data interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.