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.
In Python (you may reference scikit-learn or scipy), implement or describe a function that returns the k nearest drivers to a rider location when n can be up to 100k drivers. Explain coordinate choices (use BallTree with haversine vs KDTree on projected coordinates), memory/time complexity, and how you would support dynamic updates when driver positions change.
Sample Answer
Direct answer
For 100k drivers in one process, build a scikit-learn BallTree over driver positions using the haversine metric (great-circle distance on a sphere), converted to radians with latitude first, and call query(k=...). Build costs O(n log n), a query is roughly O(log n + k) on spread-out 2-D data, and memory is O(n), a few MB. Because these trees are static, handle moving drivers by keeping live positions in a plain array, rebuilding the tree as a snapshot every couple of seconds, and over-fetching candidates from the snapshot so they can be re-ranked by where each driver is NOW.
Terms used
- k-nearest-neighbour (kNN) query: "give me the k points closest to this one."
- Haversine distance: the shortest distance between two points along the surface of a sphere (the great-circle distance). It needs angles in radians.
- KDTree: a tree that repeatedly splits space with axis-aligned cuts (first by x, then by y, and so on). It assumes a flat, Euclidean space.
- BallTree: a tree that groups points into nested "balls" (a centre and a radius). It only needs a valid distance function, so it works with haversine.
- Projection: converting (lat, lon) degrees into flat x/y metres so ordinary Euclidean distance is meaningful.
Approach
- Pick coordinates that make the distance honest. Degrees of longitude shrink with latitude: at 37.75° N one degree of longitude is about 111.2 × cos(37.75°) ≈ 87.9 km, while one degree of latitude is about 111.2 km. Feeding raw (lat, lon) degrees into a Euclidean KDTree therefore ranks neighbours with a stretched ruler. Three correct options exist; this answer commits to the first (BallTree + haversine) and uses it for the rest of the code below, the other two are useful context, not the default:
- BallTree + haversine on
[lat, lon]in radians. Exact on the sphere, works everywhere, including across the 180° meridian (the antimeridian). - KDTree on projected metres (for example a local equirectangular projection centred on the city: x = R·lon·cos(lat0), y = R·lat). Fast and fine for one metro area, but distortion grows as you move away from the centre latitude, and it breaks at the antimeridian.
- KDTree on 3-D unit vectors (x, y, z on the unit sphere), a niche trick for when only a plain Euclidean KDTree library is available. Straight-line chord distance (a straight segment connecting two points, cutting through the Earth's interior rather than following its curved surface) through the Earth grows monotonically (it only ever increases, never decreases, as the true great-circle distance increases) with great-circle distance, so the neighbour ORDER is exact globally. Convert back with angle = 2·asin(chord/2).
- BallTree + haversine on
- Scale the result.
BallTree(metric="haversine")returns distances in radians on a unit sphere; multiply by the Earth radius (6,371,008.8 m, the mean radius) to get metres. - Verify against brute force. For a new index, always compare with an O(n) exact scan on a sample. It catches the classic bug of passing
[lon, lat]or degrees.
Code: static kNN and the coordinate choices
Requires numpy and scikit-learn.
import numpy as np
from sklearn.neighbors import BallTree, KDTree
EARTH_RADIUS_M = 6_371_008.8
rng = np.random.default_rng(42)
# 100k synthetic drivers in a San Francisco Bay Area box, columns = [lat, lon] in degrees
N = 100_000
drivers_deg = np.column_stack([
rng.uniform(37.60, 37.90, N),
rng.uniform(-122.55, -122.20, N),
])
def build_index(latlon_deg):
# haversine metric in scikit-learn expects [lat, lon] in RADIANS, latitude first
# leaf_size caps how many points sit in a leaf before the tree stops splitting
# and falls back to a linear scan inside it; it trades memory for query speed
# (memory drops roughly in proportion to leaf_size) without changing which
# neighbours are returned. 40 is scikit-learn's own default.
return BallTree(np.radians(latlon_deg), metric="haversine", leaf_size=40)
def k_nearest(tree, rider_lat, rider_lon, k=5):
q = np.radians([[rider_lat, rider_lon]])
dist_rad, idx = tree.query(q, k=k) # distances come back in radians (unit sphere)
return idx[0], dist_rad[0] * EARTH_RADIUS_M # scale by Earth radius to get meters
def brute_force(latlon_deg, rider_lat, rider_lon, k=5):
lat, lon = np.radians(latlon_deg[:, 0]), np.radians(latlon_deg[:, 1])
p, l = np.radians(rider_lat), np.radians(rider_lon)
a = np.sin((lat - p) / 2) ** 2 + np.cos(p) * np.cos(lat) * np.sin((lon - l) / 2) ** 2
d = 2 * EARTH_RADIUS_M * np.arcsin(np.sqrt(np.clip(a, 0, 1)))
order = np.argsort(d)[:k]
return order, d[order]
tree = build_index(drivers_deg)
rider = (37.7749, -122.4194)
idx, dist_m = k_nearest(tree, *rider, k=5)
bf_idx, bf_d = brute_force(drivers_deg, *rider, k=5)
print("BallTree ids:", idx.tolist())
print("BallTree m :", np.round(dist_m, 1).tolist())
print("brute force ids match:", idx.tolist() == bf_idx.tolist(), "| max |diff| m:", float(np.max(np.abs(dist_m - bf_d))))
# KDTree cannot use haversine; it only supports Minkowski-family metrics
# (distance formulas built from raw coordinate differences, such as Euclidean
# or Manhattan distance, that assume a flat space)
print("'haversine' in KDTree.valid_metrics:", "haversine" in KDTree.valid_metrics)
# Alternative 1: local equirectangular projection to meters, then KDTree (Euclidean)
lat0 = np.radians(rider[0])
def project(latlon_deg):
lat, lon = np.radians(latlon_deg[:, 0]), np.radians(latlon_deg[:, 1])
return np.column_stack([EARTH_RADIUS_M * lon * np.cos(lat0), EARTH_RADIUS_M * lat])
kd = KDTree(project(drivers_deg))
kd_d, kd_i = kd.query(project(np.array([rider])), k=5)
print("KDTree(projected) ids match:", kd_i[0].tolist() == bf_idx.tolist(), "| max |diff| m:", round(float(np.max(np.abs(kd_d[0] - bf_d))), 3))
# Alternative 2: 3D unit vectors + KDTree. Chord length is monotonic in great-circle angle,
# so the neighbor ORDER is exact anywhere on Earth (poles, antimeridian included).
def to_xyz(latlon_deg):
lat, lon = np.radians(latlon_deg[:, 0]), np.radians(latlon_deg[:, 1])
return np.column_stack([np.cos(lat) * np.cos(lon), np.cos(lat) * np.sin(lon), np.sin(lat)])
kd3 = KDTree(to_xyz(drivers_deg))
chord, i3 = kd3.query(to_xyz(np.array([rider])), k=5)
arc_m = 2 * np.arcsin(chord[0] / 2) * EARTH_RADIUS_M
print("KDTree(xyz) ids match:", i3[0].tolist() == bf_idx.tolist(), "| max |diff| m:", round(float(np.max(np.abs(arc_m - bf_d))), 6))
# Antimeridian check: two drivers either side of 180 degrees, rider at lon 179.99
edge = np.radians([[0.0, 179.995], [0.0, -179.995], [0.0, 179.0]])
edge_tree = BallTree(edge, metric="haversine")
d, i = edge_tree.query(np.radians([[0.0, 179.99]]), k=3)
print("antimeridian order:", i[0].tolist(), "meters:", np.round(d[0] * EARTH_RADIUS_M, 1).tolist())
Output:
BallTree ids: [49604, 87224, 30155, 78708, 38563]
BallTree m : [37.4, 48.0, 72.1, 94.9, 106.4]
brute force ids match: True | max |diff| m: 0.0
'haversine' in KDTree.valid_metrics: False
KDTree(projected) ids match: True | max |diff| m: 0.0
KDTree(xyz) ids match: True | max |diff| m: 0.0
antimeridian order: [0, 1, 2] meters: [556.0, 1667.9, 110083.1]
All three correct methods agree with the brute-force scan, and KDTree confirms it has no haversine metric. The antimeridian test puts the driver at longitude -179.995 (1,667.9 m away) ahead of the one at 179.0 (110 km away), which a naive "subtract the longitudes" approach gets backwards.
Supporting dynamic updates
scikit-learn's BallTree/KDTree and SciPy's KDTree have no insert, delete or move operation: changing a point means rebuilding. With drivers sending a GPS ping every 4 s, 100,000 drivers produce 100,000 / 4 = 25,000 updates per second, so updating the tree per ping is not an option. The design I would commit to for a single-city, in-process service:
- Live state is an array, one row per driver. An update is an O(1) write; availability (online, not on a trip) is a boolean per driver.
- The tree is a snapshot rebuilt on a timer (every 2 s here) off the request path, then swapped in atomically, so a reader never sees a half-built tree.
- Queries over-fetch and re-rank. Ask the snapshot for k + 20 candidates, drop unavailable drivers, then rank those candidates by haversine distance from their CURRENT positions.
import threading
import numpy as np
from sklearn.neighbors import BallTree
EARTH_RADIUS_M = 6_371_008.8
def haversine_m(lat1, lon1, lat2, lon2):
lat1, lon1, lat2, lon2 = map(np.radians, (lat1, lon1, lat2, lon2))
a = np.sin((lat2 - lat1) / 2) ** 2 + np.cos(lat1) * np.cos(lat2) * np.sin((lon2 - lon1) / 2) ** 2
return 2 * EARTH_RADIUS_M * np.arcsin(np.sqrt(np.clip(a, 0, 1)))
class DriverIndex:
"""Live positions are updated in O(1); the BallTree is a periodic snapshot.
Queries over-fetch from the snapshot, then re-rank the candidates by their
CURRENT position, so a moved driver is scored where it is now.
"""
def __init__(self, latlon_deg):
self.pos = latlon_deg.copy() # live [lat, lon] per driver id
self.available = np.ones(len(latlon_deg), bool)
self._lock = threading.Lock()
self.rebuild()
def update(self, driver_id, lat, lon): # O(1): no tree touched
self.pos[driver_id] = (lat, lon)
def set_available(self, driver_id, flag):
self.available[driver_id] = flag
def rebuild(self): # O(n log n), run on a timer off the hot path
# (the latency-sensitive code that handles each
# incoming request; kept separate so a query is
# never blocked on this rebuild)
snapshot = self.pos.copy()
tree = BallTree(np.radians(snapshot), metric="haversine")
with self._lock: # atomic swap (the tree reference changes in one
# indivisible step): readers never see a half-built tree
self._tree = tree
def k_nearest(self, lat, lon, k=5, overfetch=20):
with self._lock:
tree = self._tree
_, cand = tree.query(np.radians([[lat, lon]]), k=k + overfetch)
cand = cand[0][self.available[cand[0]]] # drop drivers who went offline or got a trip
live = self.pos[cand]
d = haversine_m(lat, lon, live[:, 0], live[:, 1])
order = np.argsort(d)[:k]
return cand[order], d[order]
rng = np.random.default_rng(7)
N = 100_000
drivers = np.column_stack([rng.uniform(37.60, 37.90, N), rng.uniform(-122.55, -122.20, N)])
index = DriverIndex(drivers)
# Between two rebuilds every driver moves up to 30 m (15 m/s for 2 s) in a random direction
step_m = rng.uniform(0, 30, N)
heading = rng.uniform(0, 2 * np.pi, N)
dlat = np.degrees(step_m * np.cos(heading) / EARTH_RADIUS_M)
dlon = np.degrees(step_m * np.sin(heading) / (EARTH_RADIUS_M * np.cos(np.radians(drivers[:, 0]))))
for i in range(N):
index.update(i, drivers[i, 0] + dlat[i], drivers[i, 1] + dlon[i])
index.set_available(123, False)
riders = np.column_stack([rng.uniform(37.65, 37.85, 1000), rng.uniform(-122.50, -122.25, 1000)])
for overfetch in (0, 20):
exact = 0
for lat, lon in riders:
got, _ = index.k_nearest(lat, lon, k=5, overfetch=overfetch)
d = haversine_m(lat, lon, index.pos[:, 0], index.pos[:, 1])
d[~index.available] = np.inf
truth = np.argsort(d)[:5]
exact += got.tolist() == truth.tolist()
print(f"stale snapshot, overfetch={overfetch:2d}: exact top-5 for {exact}/1000 riders")
index.rebuild()
exact = sum(
index.k_nearest(lat, lon, 5)[0].tolist()
== np.argsort(np.where(index.available, haversine_m(lat, lon, index.pos[:, 0], index.pos[:, 1]), np.inf))[:5].tolist()
for lat, lon in riders
)
print(f"fresh snapshot, overfetch=20: exact top-5 for {exact}/1000 riders")
Output:
stale snapshot, overfetch= 0: exact top-5 for 586/1000 riders
stale snapshot, overfetch=20: exact top-5 for 1000/1000 riders
fresh snapshot, overfetch=20: exact top-5 for 1000/1000 riders
Why 20 extra candidates is enough here (and when it is not)
The simulated box is 0.30° × 111.2 km ≈ 33.4 km tall by 0.35° × 87.9 km ≈ 30.8 km wide, about 1,027 km², so density ρ ≈ 100,000 / 1,027 ≈ 97 drivers per km². For randomly scattered points, a circle of radius r centred on the query point holds on average rho x pi x r^2 drivers (density times the circle's area); setting that equal to k and solving for r gives the distance to the k-th nearest neighbour, roughly
rk≈πρkwhich gives about 128 m for k = 5 and about 286 m for k = 25. A driver can only be wrongly left out if it sat beyond the 25th candidate at snapshot time and moved inside the true top 5 before the next rebuild. The gap is about 286 − 128 ≈ 158 m, and in 2 s at 15 m/s (54 km/h) a driver moves at most 30 m, so the over-fetch margin is roughly five times what motion can consume. Without over-fetch, only 586 of 1,000 riders got the exact top 5. If drivers are sparser (suburbs) or the rebuild interval is longer, re-derive the over-fetch from the same inequality rather than keeping 20.
Complexity
| Operation | Time | Memory |
|---|---|---|
| Build BallTree / KDTree | O(n log n) | O(n): 100,000 × 2 float64 = 1.6 MB of coordinates plus 0.8 MB of int64 index array and node bounds |
| kNN query | about O(log n + k) for spread-out low-dimensional data; O(n) worst case when points are pathologically clustered (nearly all crammed into one tiny region, so the tree's branching gives it no leverage) | O(k) |
| Brute-force check | O(n) per query | O(n) temporary distances |
| Position update (snapshot design) | O(1) | none extra |
| Query with over-fetch m and re-rank | O(log n + k + m), plus O((k + m) log(k + m)) to sort | O(k + m) |
Edge cases
- Order and units: haversine in scikit-learn wants
[lat, lon]in radians. Passing degrees or[lon, lat]returns wrong neighbours silently. - Fewer than k drivers (or fewer than k + m after filtering):
queryraises if k exceeds n; clamp k to the number of points and return what exists. - Antimeridian and poles: fine with haversine or 3-D vectors; broken with a flat projection.
- Ties and duplicates (drivers queued at an airport at the same coordinate): order among equals is arbitrary; add a tie-breaker such as time since last trip if fairness matters.
- Stale drivers: a driver whose last ping is older than, say, 3 missed intervals should be marked unavailable, not matched at an old position.
Trade-offs and pitfalls
- Straight-line distance is a candidate filter, not the answer. A driver 300 m away across a river or on the wrong side of a divided highway may be 10 minutes out. Production dispatch takes the kNN shortlist (say 20 to 50) and ranks it by road-network ETA (estimated time of arrival) from a routing engine.
- Projected KDTree vs BallTree: inside one city a projected KDTree gives the same neighbours (shown above) and is simpler to reason about in metres. Choose BallTree or 3-D vectors when the service spans many latitudes or the antimeridian (Fiji, or New Zealand together with its Chatham Islands).
- When to leave the in-process tree: once positions must be shared across many stateless API servers, or the fleet spans many cities, move the live index out of process. Common choices are a grid index (bucket drivers by geohash or H3 cell, where an update is an O(1) move between buckets and a query scans the rider's cell plus neighbouring cells), or Redis GEO commands (
GEOADDto upsert a position,GEOSEARCH ... BYRADIUS ... ASC COUNT kto query). The snapshot-and-re-rank idea still applies to any index that is cheaper to rebuild than to update. - Rebuild cost is O(n log n) per interval, so doubling the fleet or halving the interval roughly doubles background CPU. Measure it on your hardware before choosing the interval rather than assuming.
You need a schema and SQL query patterns for storing time-series metrics at high write throughput (millions of writes per minute) with efficient downsampling and retention. Consider OLTP vs OLAP characteristics, partitioning, compression, and whether to use a native TSDB or a SQL warehouse. Provide DDL examples and sample queries to compute per-minute max and one-hour aggregates.
Sample Answer
Direct answer
"Millions of writes per minute" is tens of thousands of writes per second (3 million/min = 50,000/s), a write-heavy OLTP-shaped ingest feeding OLAP-shaped reads (online transaction processing: many small writes; online analytical processing: large scans and aggregations). No single row-store table serves both well. My design: an append-only raw table partitioned by time, a 1-minute rollup table holding max, min, sum and count per series per minute, and hourly or daily answers computed from the rollup rather than from raw rows. I would run this on a store built for time series (TimescaleDB on Postgres, or ClickHouse) rather than a SQL warehouse, because the warehouse's loading model adds minutes of latency and charges for the frequent small loads this workload needs. The warehouse is where the rollups go for long-term cross-domain analysis.
Approach
- Raw table: append-only, range-partitioned by day, one row per sample. Only a BRIN index on time (a block range index: it stores min and max per group of pages, so it is tiny and fits naturally ordered time data).
- Rollup table: keyed by
(metric_id, minute), storingmax,min,sum,count. Store sum and count, not an average: an hourly average issum(sum) / sum(count), whereas the average of 60 per-minute averages is wrong whenever minutes hold different sample counts. - Rollup job: every minute, recompute the most recent closed window from raw rows and overwrite the rollup rows (
ON CONFLICT ... DO UPDATE SET col = EXCLUDED.col). Overwriting makes the job idempotent: running it twice, or re-running it for late data, gives the same answer. Adding to existing sums would double-count on a retry. - Hourly queries read 60 rollup rows per series instead of 360 raw rows (at a 10-second interval).
- Retention: drop raw daily partitions after, say, 30 days; keep rollups for about 13 months.
- Compression: plain Postgres does not compress small rows, so raw data is the expensive part; on TimescaleDB, convert chunks older than a few hours to its compressed columnstore (segmented by
metric_id), and in ClickHouse the per-column codecs below do it on write.
PostgreSQL implementation (runnable)
Run with psql -f on PostgreSQL 16 (\echo is a psql command):
SET TIME ZONE 'UTC';
DROP TABLE IF EXISTS metrics, metrics_1m CASCADE;
CREATE TABLE metrics (
metric_id int NOT NULL,
ts timestamptz NOT NULL,
value double precision NOT NULL
) PARTITION BY RANGE (ts);
CREATE TABLE metrics_2026_03_01 PARTITION OF metrics
FOR VALUES FROM ('2026-03-01 00:00+00') TO ('2026-03-02 00:00+00');
CREATE TABLE metrics_2026_03_02 PARTITION OF metrics
FOR VALUES FROM ('2026-03-02 00:00+00') TO ('2026-03-03 00:00+00');
CREATE INDEX ON metrics USING brin (ts);
CREATE TABLE metrics_1m (
metric_id int NOT NULL,
minute timestamptz NOT NULL,
max_value double precision NOT NULL,
min_value double precision NOT NULL,
sum_value double precision NOT NULL,
n bigint NOT NULL,
PRIMARY KEY (metric_id, minute)
);
-- 3 metrics, one point every 10 s, 2 hours
INSERT INTO metrics (metric_id, ts, value)
SELECT m, timestamptz '2026-03-01 10:00+00' + s * interval '10 seconds', (m * 7 + s * 13) % 100
FROM generate_series(1, 3) AS m, generate_series(0, 719) AS s;
-- rollup job for one closed window [start, end); safe to re-run
INSERT INTO metrics_1m (metric_id, minute, max_value, min_value, sum_value, n)
SELECT metric_id, date_trunc('minute', ts), max(value), min(value), sum(value), count(*)
FROM metrics
WHERE ts >= '2026-03-01 10:00+00' AND ts < '2026-03-01 12:00+00'
GROUP BY 1, 2
ON CONFLICT (metric_id, minute) DO UPDATE
SET max_value = EXCLUDED.max_value, min_value = EXCLUDED.min_value,
sum_value = EXCLUDED.sum_value, n = EXCLUDED.n;
\echo per-minute max, metric 1, first 3 minutes
SELECT minute, max_value FROM metrics_1m WHERE metric_id = 1 ORDER BY minute LIMIT 3;
\echo one-hour aggregates from the 1-minute rollup
SELECT metric_id, date_trunc('hour', minute) AS hour, max(max_value) AS max_value,
min(min_value) AS min_value, round((sum(sum_value) / sum(n))::numeric, 2) AS avg_value, sum(n) AS samples
FROM metrics_1m
WHERE minute >= '2026-03-01 10:00+00' AND minute < '2026-03-01 12:00+00'
GROUP BY 1, 2 ORDER BY 1, 2;
\echo hours where rollup disagrees with raw (expect 0)
SELECT count(*) AS mismatches FROM (
SELECT metric_id, date_trunc('hour', ts) h, max(value) mx, avg(value) av FROM metrics GROUP BY 1, 2) r
JOIN (
SELECT metric_id, date_trunc('hour', minute) h, max(max_value) mx, sum(sum_value) / sum(n) av FROM metrics_1m GROUP BY 1, 2) u
USING (metric_id, h)
WHERE r.mx <> u.mx OR abs(r.av - u.av) > 1e-9;
\echo re-run the same window, then count samples in the rollup (expect 2160)
INSERT INTO metrics_1m (metric_id, minute, max_value, min_value, sum_value, n)
SELECT metric_id, date_trunc('minute', ts), max(value), min(value), sum(value), count(*)
FROM metrics
WHERE ts >= '2026-03-01 10:00+00' AND ts < '2026-03-01 12:00+00'
GROUP BY 1, 2
ON CONFLICT (metric_id, minute) DO UPDATE
SET max_value = EXCLUDED.max_value, min_value = EXCLUDED.min_value,
sum_value = EXCLUDED.sum_value, n = EXCLUDED.n;
SELECT sum(n) AS samples_in_rollup FROM metrics_1m;
Output:
per-minute max, metric 1, first 3 minutes
minute | max_value
------------------------+-----------
2026-03-01 10:00:00+00 | 72
2026-03-01 10:01:00+00 | 98
2026-03-01 10:02:00+00 | 89
(3 rows)
one-hour aggregates from the 1-minute rollup
metric_id | hour | max_value | min_value | avg_value | samples
-----------+------------------------+-----------+-----------+-----------+---------
1 | 2026-03-01 10:00:00+00 | 99 | 0 | 49.39 | 360
1 | 2026-03-01 11:00:00+00 | 99 | 0 | 49.39 | 360
2 | 2026-03-01 10:00:00+00 | 99 | 0 | 49.44 | 360
2 | 2026-03-01 11:00:00+00 | 99 | 0 | 49.44 | 360
3 | 2026-03-01 10:00:00+00 | 99 | 0 | 49.78 | 360
3 | 2026-03-01 11:00:00+00 | 99 | 0 | 49.22 | 360
(6 rows)
hours where rollup disagrees with raw (expect 0)
mismatches
------------
0
(1 row)
re-run the same window, then count samples in the rollup (expect 2160)
samples_in_rollup
-------------------
2160
(1 row)
The third query proves the hourly answers from the rollup match the hourly answers computed straight from raw rows, and the last one proves the re-run did not double-count (3 series × 720 samples = 2,160).
For production at 50,000 writes/s, the same shapes carry over to TimescaleDB, where a continuous aggregate (a materialized view the extension refreshes incrementally, with a refresh policy handling the late-data window) replaces the hand-written job.
ClickHouse implementation (runnable)
In ClickHouse the rollup is maintained on insert by a materialized view feeding an AggregatingMergeTree, a table engine that merges rows with the same sort key by applying the stated aggregate. Run with clickhouse local --multiquery < file.sql (tested on 24.10):
CREATE TABLE metrics (
metric_id UInt32,
ts DateTime64(3, 'UTC') CODEC(DoubleDelta, ZSTD),
value Float64 CODEC(Gorilla, ZSTD)
) ENGINE = MergeTree
PARTITION BY toDate(ts)
ORDER BY (metric_id, ts);
-- SimpleAggregateFunction(fn, type) tells the AggregatingMergeTree engine below to merge two rows
-- that share a key by applying fn (max, min, sum) to this column, instead of keeping both rows
CREATE TABLE metrics_1m (
metric_id UInt32,
minute DateTime('UTC'),
max_value SimpleAggregateFunction(max, Float64),
min_value SimpleAggregateFunction(min, Float64),
sum_value SimpleAggregateFunction(sum, Float64),
n SimpleAggregateFunction(sum, UInt64)
) ENGINE = AggregatingMergeTree
PARTITION BY toYYYYMM(minute)
ORDER BY (metric_id, minute);
CREATE MATERIALIZED VIEW metrics_1m_mv TO metrics_1m AS
SELECT metric_id, toStartOfMinute(ts) AS minute,
max(value) AS max_value, min(value) AS min_value, sum(value) AS sum_value, count() AS n
FROM metrics GROUP BY metric_id, minute;
INSERT INTO metrics
SELECT m, toDateTime64('2026-03-01 10:00:00', 3, 'UTC') + s * 10, (m * 7 + s * 13) % 100
FROM (SELECT number + 1 AS m FROM numbers(3)) AS a CROSS JOIN (SELECT number AS s FROM numbers(720)) AS b;
SELECT metric_id, toStartOfHour(minute) AS hour, max(max_value) AS max_value,
round(sum(sum_value) / sum(n), 2) AS avg_value, sum(n) AS samples
FROM metrics_1m GROUP BY metric_id, hour ORDER BY metric_id, hour
FORMAT PrettyCompactMonoBlock;
-- retention: raw kept 30 days, rollups about 13 months (expired rows removed during merges)
ALTER TABLE metrics MODIFY TTL toDateTime(ts) + INTERVAL 30 DAY;
ALTER TABLE metrics_1m MODIFY TTL minute + INTERVAL 400 DAY;
Output:
┌─metric_id─┬────────────────hour─┬─max_value─┬─avg_value─┬─samples─┐
1. │ 1 │ 2026-03-01 10:00:00 │ 99 │ 49.39 │ 360 │
2. │ 1 │ 2026-03-01 11:00:00 │ 99 │ 49.39 │ 360 │
3. │ 2 │ 2026-03-01 10:00:00 │ 99 │ 49.44 │ 360 │
4. │ 2 │ 2026-03-01 11:00:00 │ 99 │ 49.44 │ 360 │
5. │ 3 │ 2026-03-01 10:00:00 │ 99 │ 49.78 │ 360 │
6. │ 3 │ 2026-03-01 11:00:00 │ 99 │ 49.22 │ 360 │
└───────────┴─────────────────────┴───────────┴───────────┴─────────┘
Same answers as Postgres. Two details matter: the materialized view fires per insert block (the batch of rows one INSERT writes at a time; the view's query runs separately against each block rather than across the whole table), so one minute can have several partial rows until a background merge combines them, which is why the query still does GROUP BY and sum(n); and the codecs DoubleDelta (stores each timestamp as the change in the gap since the previous one, which is nearly constant for a fixed polling interval, so it shrinks to a couple of bytes) and Gorilla (XORs each float against the previous one and keeps only the bits that changed, small when a metric moves gradually) are the time-series compression schemes that give this engine its storage advantage.
Per-minute max straight from raw data
When you need it ad hoc (for example, to backfill), the raw query is:
SELECT metric_id, date_trunc('minute', ts) AS minute, max(value) AS max_value
FROM metrics
WHERE ts >= '2026-03-01 10:00+00' AND ts < '2026-03-01 11:00+00'
GROUP BY 1, 2;
Always use a half-open range (>= start, < end) so a sample exactly on the boundary is counted once.
OLTP vs OLAP, TSDB vs warehouse
| Native TSDB (time-series database) or time-series extension | SQL warehouse (BigQuery, Snowflake, Redshift) | |
|---|---|---|
| Ingest of 50k rows/s continuously | Designed for it | Micro-batch (loading small batches of rows every few seconds to minutes, rather than continuously) or streaming ingest with extra cost and latency |
| Freshness | Seconds | Typically minutes |
| Rollups | Built-in (continuous aggregates, materialized views) | Scheduled SQL or dynamic tables (Snowflake's feature for a table that auto-refreshes from a query on a schedule, the warehouse equivalent of a continuous aggregate) |
| Joins with business data, ad-hoc analysis | Limited | Strong |
| Retention | Drop chunks or parts | Partition expiration |
Decision: TSDB (or TimescaleDB) as the system of record for metrics; export hourly rollups daily to the warehouse. What would flip it: if freshness of 5 to 15 minutes is acceptable and analysts join metrics with sales data all day, loading micro-batches straight into the warehouse and skipping the TSDB is simpler.
Complexity
- Rollup job per window: one scan of the window's raw rows, O(r) for r rows, plus O(k log k) to upsert k (series, minute) keys through the primary-key B-tree.
- Hourly query: O(60 × s) rollup rows for s series, independent of the raw sampling rate.
- Storage: raw grows with sample rate; the 1-minute rollup grows with (series × minutes), so at 50,000 series it adds 50,000 × 1,440 = 72 million rows/day regardless of how often each series is sampled.
Edge cases
- Late data: re-run the job over a trailing window (for example the last 10 minutes) every minute; the overwrite makes that safe.
- Time zones:
date_truncontimestamptzuses the session time zone, which is why the script sets UTC. WithoutSET TIME ZONE 'UTC', a session in America/Los_Angeles labels the first bucket2026-03-01 02:00:00-08, and daily buckets follow local midnight (with 23- and 25-hour days at daylight-saving changes) instead of UTC midnight. - Missing partitions: an insert for a day with no partition fails; create partitions ahead of time.
- Empty minutes: the rollup has no row for a minute with no samples; charts must treat that as a gap, not zero.
- Percentiles: max, min, sum and count merge correctly across minutes; a p99 (99th percentile) does not, so store a mergeable sketch if you need one (a small approximate summary, such as a t-digest or HDR histogram, that you update one sample at a time, can merge across minutes or series exactly the way
sumandcountmerge here, and then read an approximate percentile back out of; unlike keeping every raw sample, it stays a fixed, small size no matter how much data feeds it).
A ride-hailing analytics team needs one geospatial data model to power city-wide demand heatmaps, neighborhood-level rollups, and route-level analysis, all refreshed continuously as new trips complete. Design that model: how would you represent and index the space so it serves all three zoom levels efficiently, and what would you pre-compute versus compute on the fly?
Sample Answer
Direct answer
Tag every trip once, at the moment it completes, with a fine hexagonal grid cell for its pickup and dropoff (H3 resolution 9), its neighbourhood ID from a point-in-polygon lookup, and the ordered list of fine cells its route crossed. From those tags, a stream job (a long-running process that consumes trip-completion events as they arrive and updates its output continuously, instead of a scheduled batch job that runs once an hour) maintains small additive rollup tables: counts per cell per 5-minute bucket (rolled up to coarser cells for the city view), counts per neighbourhood per hour, and origin-destination (OD) counts between coarse cells. Heatmaps and rollups read only these pre-computed tables; anything non-additive, arbitrary-shaped or rarely asked is computed on the fly from the tagged trip table.
The spatial index: why a hexagon grid
Key terms.
- A discrete global grid divides the Earth into cells with stable IDs, so "where" becomes a join key instead of a geometry calculation.
- H3 is Uber's open-source hexagonal grid. It has 16 resolutions (0 to 15); each step is roughly 7 times finer. Per the H3 resolution table, the average cell area is 5.16 km² at resolution 7, 0.737 km² at resolution 8 and 0.10533 km² at resolution 9, with an average edge length of about 200 m at resolution 9. A hexagon's flat-to-flat width runs about 1.7 times its edge length and its corner-to-corner width exactly twice its edge length, so a roughly 200 m edge gives an across-the-cell distance of about 350 m to 400 m depending which way you measure, the figure used later when sizing how much a hexagon boundary can misalign with a neighbourhood boundary.
- Additive measure: one you can sum across cells or time buckets and get the right total (trip counts, fare sums). Non-additive: medians, percentiles, distinct counts, which cannot simply be summed.
Why hexagons rather than square grids such as geohash: every hexagon has six neighbours that share an edge and sit at the same centre-to-centre distance, so smoothing a heatmap ("this cell plus its ring of neighbours", gridDisk in the H3 API) treats every direction equally. A square cell has 4 edge neighbours and 4 corner neighbours about 1.41 times further away, which produces visible directional artefacts in heatmaps.
One H3 property must be designed around: a resolution-8 cell's seven resolution-9 children do not tile it exactly (hexagons cannot be split perfectly into smaller hexagons). So define the coarse levels by parent ID (cellToParent(r9_cell, 7)) and never by testing points against the coarse hexagon's outline. Then every level sums exactly to the level below it, which is the property a dashboard needs.
The model
flowchart LR
A[Trip completed event] --> B[Enrich once: r9 pickup and dropoff cells, neighbourhood ID, route cells]
B --> C[(Tagged trips table)]
B --> D[Stream aggregator]
D --> E[(cell_5min at r9)]
E --> F[(cell_5min at r8 and r7 via parent)]
D --> G[(neighbourhood_hour)]
D --> H[(od_r7_hour and route_cell_hour)]
F --> I[City heatmap]
G --> J[Neighbourhood rollups]
H --> K[Route analysis]
C --> L[Ad hoc and non-additive queries]
Tagged trips table (source of truth, one row per trip): trip_id, completed_at, pickup_ts, pickup_lat, pickup_lon, pickup_r9, dropoff_r9, pickup_nbhd_id, dropoff_nbhd_id, route_cells (array of r9 IDs in order), distance_m, duration_s, fare. Partitioned by date and clustered by pickup_r9 (the storage engine physically groups rows with the same pickup_r9 value together on disk, so a query filtered to one cell reads far fewer blocks than a query scattered across the whole partition).
Pre-computed tables:
| Table | Grain | Serves |
|---|---|---|
cell_5min | (resolution, cell, 5-min bucket): pickups, dropoffs, requests, unfulfilled requests, fare sum | City heatmap at three zoom levels |
neighbourhood_hour | (neighbourhood, hour): same measures plus a mergeable quantile sketch for wait time (a small approximate summary of many wait-time values, built so that two sketches from different workers or time windows can be combined into one and still estimate a percentile such as p50 or p90 accurately; a plain stored average or min/max cannot be combined this way) | Neighbourhood rollups |
od_r7_hour | (origin r7 cell, destination r7 cell, hour): trips, duration sum, distance sum | Route-level flows between areas |
route_cell_hour | (r9 cell, hour): trips traversing, time spent sum | Corridor congestion along routes |
Neighbourhoods are a separate key on purpose. Administrative boundaries do not follow hexagon edges, so summing cells to approximate a neighbourhood mis-assigns trips along every boundary (a resolution-9 cell is roughly 350 to 400 m across, per the edge-length note above). A point-in-polygon lookup per trip at write time is exact and costs one indexed lookup per completed trip.
Route cells come from the map-matched route line (the GPS trace snapped to roads), converted to the sequence of resolution-9 cells it passes through. This turns "which trips used this corridor" into an array-contains or join query instead of line-intersection geometry.
Pre-compute versus on the fly
| Pre-compute (continuously) | Compute on the fly |
|---|---|
| Counts and sums per cell, neighbourhood, OD pair and time bucket (additive, bounded row counts, hit on every dashboard load) | Arbitrary drawn polygons and corridors (unbounded shapes, rare) |
| Mergeable sketches for percentiles and distinct counts (t-digest, a specific mergeable quantile-sketch algorithm, for percentiles such as p90 wait time; HyperLogLog, a mergeable sketch that estimates how many distinct values, such as distinct riders, were seen using a small fixed amount of memory regardless of the true count, for distinct counts) | Exact percentiles for a one-off analysis |
| Coarse levels by parent roll-up | Multi-filter slices ("airport trips by premium riders in the rain") that would explode the rollup key space |
Heatmap smoothing (gridDisk over already-aggregated cells: cheap, and the kernel size, how many rings of neighbouring cells to blend into each cell's displayed value (k=1 averages a cell with its 6 immediate neighbours, k=2 pulls in the next ring too), is a UI choice) |
The rule: pre-compute what is additive, frequently read and bounded in size; compute what is non-additive, shaped by the user, or rarely asked.
Worked example: row counts for one city
Take a 1,000 km² metro with 500,000 completed trips a day, 5-minute buckets (288 per day).
r9 cellsr9 dense upper boundr9 actual (trip endpoints)r8 upper boundr7 upper bound≈1000/0.10533≈9,494=9,494×288=2,734,272 rows/day≤500,000×2=1,000,000 rows/day=1,356×288=390,528 rows/day=194×288=55,872 rows/dayThe 1,000,000 figure comes from the schema itself: cell_5min holds one row per (cell, bucket) that any event touched, and each of the 500,000 daily trips can touch at most two such rows, its pickup and, when the dropoff lands in a different cell or bucket, its dropoff. This is still well under the 2,734,272 dense upper bound (about 37% of it), so most cell-bucket combinations stay empty on an ordinary day, which is the property that keeps every read small. Request and unfulfilled-request events add further rows on top of this trip-endpoint bound, concentrated in the cells with the heaviest unmet demand; this worked example does not size them because no request volume was given, only completed-trip volume.
The city-wide view at resolution 7 reads at most 194 rows for one bucket, a neighbourhood view reads one row per neighbourhood, and the street-level view reads at most a few thousand resolution-9 rows for the visible window. Every read is small regardless of how many trips have happened, which is what "serves all three zoom levels efficiently" means in practice.
Keeping it continuously fresh
- The stream job keys aggregates by (cell, bucket) and upserts them, so replays after a failure overwrite rather than double count (the aggregation is idempotent: running it twice gives the same row).
- Trips complete late relative to their pickup time. Aggregate on pickup time with a watermark (the stream processor's estimate of how late events can arrive), keep recent buckets open for, say, two hours, and let a nightly batch recompute the previous day from the tagged trips table to absorb anything later.
- Coarse levels are derived from the fine level after each bucket closes, not aggregated independently from raw events, so the levels can never disagree.
Trade-offs and pitfalls
- Resolution choice: resolution 9 (about 0.1 km²) is fine enough for street-level demand without making most cells empty; resolution 10 multiplies cell count by roughly 7 and mostly adds sparsity and noise.
- Non-additive metrics such as median wait time summed across cells are simply wrong; store sketches or compute on demand.
- Small counts leak privacy: a resolution-9 cell with one trip at 3 a.m. can identify a home. Suppress or coarsen cells below a minimum count in shared dashboards.
- What would change the design: if the warehouse natively supports S2 (Google's hierarchical grid of square-ish cells) or geohash (a string-encoded rectangular grid) and not H3, use that grid, whose cells nest exactly so the parent-ID caveat disappears, and accept the less uniform neighbour geometry. If route analysis needs per-road-segment speeds, key
route_cell_hourby road segment ID from the map matcher instead of by cell.
Write PostgreSQL/TimescaleDB SQL to:
- Create a hypertable for host metrics with schema: metric_id serial PK, host text, metric_name text, metric_value double precision, ts timestamptz NOT NULL.
- Create a 5-minute continuous aggregate (rollup) for CPU metric per host.
- Show a query that returns the 5-minute avg CPU per host for the last 24 hours, sorted by highest spike.
- Add a retention policy to drop raw chunks older than 7 days.
Provide correct TimescaleDB functions and explain any assumptions about chunk interval.
Sample Answer
Direct answer
Create a normal table, convert it to a hypertable with create_hypertable(..., by_range('ts', INTERVAL '1 day')), build a continuous aggregate with time_bucket('5 minutes', ts) filtered to metric_name = 'cpu', give it a refresh policy, query the aggregate for the last 24 hours ordered by each host's peak, and add add_retention_policy('host_metrics', drop_after => INTERVAL '7 days'). Two details trip people up: the primary key must include ts, and the aggregate's refresh window must stay inside the 7-day raw retention, or a refresh will erase aggregated history.
Terms used
- TimescaleDB: a PostgreSQL extension for time-series data.
- Hypertable: a table that looks like one table but is stored as many chunks, each chunk holding one time range (here, one day). Queries on recent time touch only recent chunks, and old data is removed by dropping whole chunks, which is much cheaper than
DELETE. - Continuous aggregate: a materialized view (a stored query result) that TimescaleDB refreshes incrementally, recomputing only the time buckets whose raw data changed.
time_bucket: rounds a timestamp down to the start of its bucket, so 10:03:27 becomes 10:00:00 for 5-minute buckets.- Retention policy: a background job that drops chunks older than a threshold.
Code
-- 1) Table and hypertable
CREATE EXTENSION IF NOT EXISTS timescaledb;
CREATE TABLE host_metrics (
metric_id bigserial,
host text NOT NULL,
metric_name text NOT NULL,
metric_value double precision,
ts timestamptz NOT NULL,
PRIMARY KEY (metric_id, ts) -- a unique key on a hypertable must include the time column
);
SELECT create_hypertable('host_metrics', by_range('ts', INTERVAL '1 day'));
-- lookups are "this metric, this host, recent time"
CREATE INDEX host_metrics_name_host_ts ON host_metrics (metric_name, host, ts DESC);
-- 2) 5-minute continuous aggregate for CPU per host
CREATE MATERIALIZED VIEW cpu_5m
WITH (timescaledb.continuous) AS
SELECT time_bucket(INTERVAL '5 minutes', ts) AS bucket,
host,
avg(metric_value) AS avg_cpu,
max(metric_value) AS max_cpu,
count(*) AS samples
FROM host_metrics
WHERE metric_name = 'cpu'
GROUP BY time_bucket(INTERVAL '5 minutes', ts), host
WITH NO DATA;
-- keep it refreshed: every 5 minutes, recompute the window from 3 days ago to 5 minutes ago
SELECT add_continuous_aggregate_policy('cpu_5m',
start_offset => INTERVAL '3 days',
end_offset => INTERVAL '5 minutes',
schedule_interval => INTERVAL '5 minutes');
-- optional: include the newest, not-yet-materialized data at query time
ALTER MATERIALIZED VIEW cpu_5m SET (timescaledb.materialized_only = false);
-- 3) Last 24 hours of 5-minute averages, hosts with the biggest spike first
SELECT host,
bucket,
round(avg_cpu::numeric, 1) AS avg_cpu_5m,
round(max(avg_cpu) OVER (PARTITION BY host)::numeric, 1) AS host_peak_5m
FROM cpu_5m
WHERE bucket >= now() - INTERVAL '24 hours'
ORDER BY host_peak_5m DESC, host, bucket;
-- 4) Drop raw chunks older than 7 days (the aggregate keeps its own rows)
SELECT add_retention_policy('host_metrics', drop_after => INTERVAL '7 days');
Key points
1. The primary key. The requested schema says metric_id serial PK. On a hypertable every unique index, including the primary key, must contain all partitioning columns, because uniqueness is enforced per chunk. PRIMARY KEY (metric_id) alone makes create_hypertable fail, so the key becomes (metric_id, ts). I also changed serial to bigserial, deliberately. serial is a 32-bit integer that stops at 2,147,483,647. At 2,000 hosts x 50 metrics x one sample every 10 s:
Many metrics tables drop the surrogate metric_id altogether, because nothing looks rows up by it.
2. Chunk interval assumption (1 day). TimescaleDB's default is 7 days. Its documented guideline is to size chunks so the indexes of the chunk currently being written fit in about 25% of RAM; its own example is that 10 GB of index growth per day on a 64 GB server calls for a 1-day interval. I chose 1 day for two reasons. At about 864M rows a day, a 7-day chunk's indexes would not stay in memory. And the retention policy drops only chunks that are fully older than 7 days, so with 1-day chunks raw data lives between 7 and 8 days, while 7-day chunks would keep up to 14 days.
3. The aggregate. WITH NO DATA creates the view instantly instead of scanning all history in one transaction; the policy (or a manual CALL refresh_continuous_aggregate(...)) fills it. Storing max_cpu and samples next to avg_cpu is cheap and means a later question like "worst single sample in that 5 minutes" needs no raw data. In current TimescaleDB versions materialized_only defaults to true, so the view returns only refreshed buckets; setting it to false adds the latest raw data at query time ("real-time aggregation") at some extra query cost.
4. The query. "Sorted by highest spike" is read as: hosts ordered by their worst 5-minute average in the window, each host's buckets in time order. The window function max(avg_cpu) OVER (PARTITION BY host) attaches each host's peak to every row without collapsing them. For only the single worst buckets across all hosts, use ORDER BY avg_cpu DESC LIMIT 20 instead.
5. Retention and the refresh window. Dropping raw chunks does not delete the aggregate's rows, as long as the aggregate is never refreshed over the dropped time range. If it were, TimescaleDB would see "raw data gone" and remove the aggregated buckets too. Here start_offset is 3 days and raw retention is 7 days, so refreshes never reach dropped data. To bound the aggregate as well, give it its own longer policy, for example add_retention_policy('cpu_5m', drop_after => INTERVAL '90 days').
Complexity
- Insert: one B-tree insert per index into the current chunk. The table stays fast only while those indexes fit in memory, which is what the chunk interval controls.
- Aggregate refresh: proportional to the rows in buckets that changed since the last refresh, not to the whole table.
- The 24-hour query reads 288 buckets per host from the aggregate (24 x 60 / 5), so 2,000 hosts means 576,000 small rows instead of about 864M raw rows.
- Retention: dropping a chunk is a metadata operation plus file removal, with no row-by-row
DELETEand no table bloat.
Edge cases
- Late-arriving samples older than
start_offset(3 days) are stored in raw data but never folded into the aggregate. Widen the offset or refresh that range manually. - Hosts that stop reporting simply have no buckets; the aggregate does not create zero rows. Use
time_bucket_gapfillon a query over the aggregate if a chart needs explicit gaps. - Time zones: 5-minute buckets are the same everywhere, but daily buckets default to UTC boundaries.
- Newer syntax: TimescaleDB 2.20 and later also accept
CREATE TABLE ... WITH (tsdb.hypertable, tsdb.partition_column = 'ts', tsdb.chunk_interval = '1 day'), which replaces the separatecreate_hypertablecall. The function form shown above still works.
Compare range-based sharding vs hash-based sharding for a time-series logging database that stores billions of rows. Discuss which approach better supports time-range queries, compaction/TTL, rebalancing costs, and how TTL/archival interacts with each approach.
Sample Answer
Direct answer
For a time-series logging database, range (time-based) sharding wins for time-range queries and for TTL, because a query for "the last hour" touches only the shards that hold that hour, and expiring old data means dropping whole old shards. Hash sharding wins for write balance, because every write lands on a random shard instead of all writes hitting the newest one. I would not pick either alone at billions of rows: I recommend range partitioning on time at the top level (daily partitions) with hash distribution on a source key (host or service) inside each time range. That keeps TTL as a cheap partition drop and spreads the write hot spot.
Range sharding assigns each shard a contiguous interval of the key, here time (shard 1 holds 1 to 2 September, shard 2 holds 2 to 3 September). Hash sharding computes hash(key) mod N or places the key on a consistent-hash ring, which scatters neighbouring keys across shards. TTL (time-to-live) is the rule that deletes data older than some age. Compaction is the background process that merges small files into large ones and physically removes deleted rows.
Comparison on the four named axes
| Axis | Range on time | Hash on key (host, or row ID) |
|---|---|---|
| Time-range queries | Excellent: "last 1 h" is 1 shard; "last 7 d" is 7 daily shards | Poor: every time-range query fans out to all N shards (the single query is sent to every shard in parallel, and it only completes once every one of them has replied), because any shard may hold rows from that hour |
| Write load | Bad on its own: all current writes hit the newest shard (the hot shard) | Excellent: writes spread evenly |
| Compaction and TTL | Cheap: TTL is dropping a whole shard or partition, a metadata operation with no rewrite | Expensive: TTL becomes row-level deletes on every shard, producing tombstones (deletion markers) that compaction must later rewrite files to purge |
| Rebalancing cost | Low for new data (future ranges are simply placed on new nodes); moving an existing range is a bulk copy of a cold, immutable shard | Adding a node moves data: with consistent hashing about 1/(N+1) of all rows move; with plain mod N almost every row moves |
| How TTL and archival interact | Archival is the same operation as TTL: detach the oldest partition, write it to object storage (for example as Parquet), then drop it | Archival needs a scan-and-filter of every shard for old rows, then a delete, then compaction |
Why those rebalancing fractions. A consistent-hash ring places every node at a point on a circle (a "ring" of hash values from 0 up to some maximum, wrapping back to 0); each node owns the arc running clockwise from the previous node's point to its own. A key is hashed to a point on the same circle and belongs to the first node reached going clockwise from it. Adding a node adds one more point, which only splits the single arc it lands inside: every other node's arc, and every key in it, is untouched. Once the new node joins, there are N+1 points cutting the ring into N+1 arcs, and by symmetry no arc is special, so each one, including the new node's own arc, has an expected length of 1/(N+1) of the ring. Since only the keys in that one arc change hands, the expected fraction of all keys that move is 1/(N+1): with 4 existing nodes, a 5th takes an expected 1/5 = 20%, and every other node keeps everything it had.
Plain hash(key) mod N has no such locality: moving from mod N to mod (N+1) changes almost every key's target node, not just a fifth of them, because the two functions agree only where k mod N and k mod (N+1) happen to coincide. Running that check for keys 0 to 19 against mod 4 and mod 5 makes it concrete:
keys = range(20)
same = [k for k in keys if k % 4 == k % 5]
print(f"stay on the same node under mod4->mod5: {len(same)} of {len(keys)} ({100*len(same)/len(keys):.0f}%)")
stay on the same node under mod4->mod5: 4 of 20 (20%)
16 of the 20 keys, 80%, land on a different node purely from adding one node, which is what "almost every row moves" means in practice; a real deployment growing from 4 shards to 5 under plain mod N would have to physically relocate about 80% of its rows in one operation.
Worked example
Assume 2 billion log rows/day at roughly 100 bytes/row compressed, 30-day retention, 16 nodes.
- Average write rate: 2,000,000,000 / 86,400 = 23,148 rows/s (peaks are higher).
- Storage: 2e9 × 100 B = 200 GB/day, so 6 TB for 30 days.
- Pure range, one shard per day: the whole 23,148 rows/s average lands on one node while the other 15 idle. That is the classic hot-shard failure.
- Pure hash over 16 nodes: each node takes about 1,447 rows/s, but a "last 15 minutes of errors" query must ask all 16 nodes and each one has to scan all 30 days of its data, since nothing about the layout says where "recent" rows are. The tail latency of the query (its response time is set by the slowest handful of requests, not the average or median) is set by the slowest of those 16 full-table scans. Each day, TTL has to delete 2 billion rows spread across 16 nodes, generating tombstones that compaction must rewrite 200 GB of files to purge.
- Composite (recommended): partition by day; within each day, distribute by
hash(host)across 16 nodes. Writes spread (about 1,447 rows/s per node). A query scoped to one host and 15 minutes prunes to that host's slice of one day's partition on effectively one node, the best case. A query that is not host-scoped, such as "last 15 minutes of errors across the fleet", still has to ask all 16 nodes, exactly as under pure hash, since every node holds a slice of every host; what the day partition buys there is not fewer nodes but far less data per node: each node scans only today's partition instead of all 30 days, roughly a 30x cut in rows scanned even though the same 16 nodes are still involved. TTL drops yesterday-minus-30's partition on every node, removing 200 GB with no rewrite. Adding a 17th node only needs to own a share of future partitions; old partitions age out on their own in 30 days, so you often never move historical data at all.
Trade-offs and pitfalls
- Partition granularity. Too fine (hourly × host) creates millions of tiny partitions and files, which hurts query planning (the database has to decide, before a query even runs, which of the many small files could hold matching rows) and compaction. Daily is a good default at this volume; hourly only if a single day's partition is too large to manage.
- Late-arriving rows. Logs arrive minutes or hours late. Range partitioning must accept writes into older partitions, so do not make partitions read-only the instant their day ends, and do not run TTL so aggressively that a late row lands in an already-dropped partition.
- Skewed hash keys. Hashing by host works only if hosts are roughly balanced. One chatty service producing 30% of logs will make its hash bucket hot; add a salt (hash of host plus a small random suffix) for known heavy hitters.
- Queries that are not time-bounded ("all logs ever for request ID X") are bad under both schemes. Serve them with a secondary index or a separate lookup table rather than bending the sharding key.
- When pure hash is right: a key-value workload that fetches single records by ID and has no time-range reads and no bulk TTL. That is not a logging workload.
Unlock Full Question Bank
Get access to all Geospatial and Time-Series Data interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.