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.
Design a retention and compaction policy for time-series sensor data with different SLAs: raw data retained for 30 days with high-resolution, summarized data kept for 3 years. Explain how to implement rollups, partition pruning, and how to support queries that need both raw and rolled-up data.
Sample Answer
Direct answer
Store raw readings in a table partitioned by day and keep 30 days of partitions; build hourly rollups from raw continuously and keep them 3 years; build daily rollups from the hourly table and keep them 3 years too, purely to make multi-year queries fast. Expire data by dropping whole partitions, never by DELETE. Every query carries a time predicate so the database reads only the partitions in range (partition pruning). A thin query layer (a view or a small service) routes each request: the part of the range within the last 30 days comes from raw, the older part from the rollup tier, stitched at a fixed boundary. At 10 million points per day this keeps the database around 16 GB instead of more than 500 GB for 3 years of raw data.
Key terms
- Retention: how long a tier keeps data. SLA (service-level agreement) here means the commitment: raw at full resolution for 30 days, summaries for 3 years.
- Rollup: a pre-computed summary per sensor per bucket (hour, day): min, max, sum, count.
- Compaction: replacing many small units of data with fewer, larger ones. Here it means turning raw rows into rollup rows and dropping the raw rows, and, for columnar storage, merging many small files into large ones.
- Partition: a physical slice of a table, here one per day for raw data. The database treats it as a separate table underneath, so dropping it is instant.
- Partition pruning: the planner (the part of Postgres that decides how to execute a query, including which partitions it actually needs to open) skips partitions whose time range cannot match the
WHEREclause. A query for "yesterday" opens 1 partition out of 30.
The tiering table
| Tier | Resolution | Retention | Partition size | Built from | Serves |
|---|---|---|---|---|---|
| Raw | as sent (about every 8.6 s per sensor) | 30 days | 1 day | ingestion | investigations, exports, anything under 30 days needing exact values |
| Hourly | 1 hour | 3 years | 1 month | raw, every 15 min | charts from 2 days to 1 year, anomaly review |
| Daily | 1 day | 3 years | 1 year | hourly, once a day | multi-year trends, reports |
Storage cost vs latency, the explicit trade-off. Each coarser tier costs storage and one more job, and buys query latency on long ranges. The hourly tier is mandatory (the 3-year SLA requires summaries to exist once raw is gone). The daily tier is optional: it costs about 4% of the hourly tier's storage (1/24) and cuts a 3-year chart from 26,280 rows per sensor to 1,095. That is cheap latency, so I keep it. A further tier (weekly, monthly) would save almost nothing more and is not worth the extra job.
Worked example at 10 million points per day
Assume 1,000 sensors, each sending one reading about every 8.64 seconds (86,400 / 10,000), so 10,000,000 points per day. Take 48 bytes per raw row in a row store (timestamp, sensor id, value, plus per-row overhead) and 64 bytes per rollup row; these are planning assumptions, not measurements.
raw, 30 dayshourly, 3 yearsdaily, 3 yearsraw kept 3 years instead=107×30=3×108 rows≈14.4 GB=1,000×24×1,095=26,280,000 rows≈1.68 GB=1,000×1,095=1,095,000 rows≈0.07 GB=107×1,095×48 B≈525.6 GBTotal about 16.2 GB against 525.6 GB. Columnar compression would shrink both sides, but the ratio is what matters.
Implementing the rollups
- Hourly job, every 15 minutes, recomputes the last 3 hours of buckets from raw with an upsert (
INSERT ... ON CONFLICT (sensor_id, hour) DO UPDATE). Recomputing a trailing window picks up readings that arrived late, for example from a sensor that reconnected. Upserts make the job idempotent: running it twice gives the same result, so retries after a crash are safe. - Daily job runs after midnight plus a margin (say 03:00) and aggregates the previous day's 24 hourly rows: min of mins, max of maxes, sum of sums, sum of counts. These combine exactly, which an average of averages would not.
- Watermark table: each job records the latest bucket it completed. The retention job reads it (next section).
Retention and compaction by partition
-- PostgreSQL declarative partitioning, one partition per day for raw
CREATE TABLE readings (
sensor_id int NOT NULL,
ts timestamptz NOT NULL,
value double precision NOT NULL
) PARTITION BY RANGE (ts);
CREATE TABLE readings_2026_09_28 PARTITION OF readings
FOR VALUES FROM ('2026-09-28') TO ('2026-09-29');
CREATE INDEX ON readings (sensor_id, ts); -- propagates to every partition
A scheduler (pg_partman, a PostgreSQL extension that creates and drops partitions on a schedule, or a cron job) creates partitions a few days ahead and drops old ones:
- Check the hourly watermark covers the whole partition's day, plus the 3-hour late-data window the hourly job recomputes (see "Implementing the rollups" above), so a drop never runs ahead of data the rollup job might still need.
ALTER TABLE readings DETACH PARTITION readings_2026_08_28;thenDROP TABLE readings_2026_08_28;- If the watermark is behind, do not drop: alert instead. A 31st day of raw data costs 0.48 GB; a lost day of summaries is unrecoverable.
Dropping a partition is a metadata operation (it just removes an entry from the table's list of partitions and unlinks a file; it never opens or touches a row inside it). DELETE FROM readings WHERE ts < now() - interval '30 days' would touch 10 million rows a day: each deleted row still has to be recorded in the write-ahead log (WAL, the append-only file Postgres writes every change to before applying it, so it can recover after a crash), and each becomes a dead row (an old row version Postgres keeps around rather than erasing in place) that VACUUM (Postgres's background cleanup process) later has to scan and reclaim.
Pruning only works if queries let it. WHERE ts >= '2026-09-01' AND ts < '2026-09-08' prunes to 7 partitions. WHERE date_trunc('day', ts) = '2026-09-01' wraps the column in a function and may force a scan of all 30.
Serving queries that need both raw and rolled-up data
flowchart LR
C[Client: sensor, range, resolution] --> R{Query router}
R -->|range within 30 days| RAW[(Raw partitions)]
R -->|older part of range| H[(Hourly)]
R -->|range over 1 year| D[(Daily)]
RAW --> M[Merge at boundary]
H --> M
D --> M
M --> C
- Rule 1: choose the output resolution first. A 90-day chart at hourly resolution is 2,160 points per sensor. Serve it entirely from the hourly table (which covers the last 30 days too), rather than stitching, so the line is consistent.
- Rule 2: stitch only when the caller needs raw detail for the recent part. Example: "last 60 days, raw where available". The router splits at the boundary
now() - 30 daysrounded down to a whole hour: raw rows after it, hourly rows before it, returned with aresolutionfield on each point so the client can draw them differently. - Rule 3: return the same shape from every tier (min, max, avg as
sum / count, count), so a raw point is presented as a bucket of count 1. - A SQL
UNION ALLview across raw and hourly with complementary time predicates works for simple cases; a service layer is better once you have several tiers and caching.
Trade-offs and pitfalls
- Dropping raw before the rollup covers it is the one failure that loses data permanently. Gate every drop on the watermark.
- Percentiles cannot be rebuilt from min, max, sum, count. If the 3-year SLA includes percentiles, store a fixed-bucket histogram per hour (a count of readings falling into fixed value ranges, like 0-10, 10-20, which can be summed across hours and used to estimate a percentile, unlike a single stored percentile number).
- Too-small partitions (hourly partitions for raw) mean 720 partitions to plan over for 30 days and slower planning; too-large ones (monthly) mean retention can only be exact to the month. Daily matches the 30-day SLA.
- What would change it: at 1 billion points per day instead of 10 million, raw storage moves to a columnar TSDB (a time-series database that stores each column of data compressed together, built for that scale) or Parquet files (a compressed, columnar file format) in object storage, but the tier table, watermark-gated drops and the router stay the same.
A colleague who has only worked with relational databases asks why your team is standing up a dedicated time-series database instead of just using Postgres for metrics and logs. Explain the key differences in how the two kinds of systems are built and used, and give concrete examples of the data you'd put in each.
Sample Answer
Direct answer
A relational database like Postgres is built to store, update and join individual rows correctly; a time-series database (TSDB) is built for one very specific shape of data: huge volumes of timestamped measurements that are appended once, never updated, read back as ranges and aggregates over time, and deleted wholesale when they age out. Because it can assume that shape, a TSDB stores each series as a compressed stream (on the order of 1 to 2 bytes per point, against about 84 bytes per point measured below for a plain indexed Postgres table), expires old data by dropping whole blocks, and answers "average over the last hour, per service" without touching individual rows. So metrics go in the TSDB, and orders, users, configuration and anything you update or join goes in Postgres.
How the two are built differently
Key terms. A series is one metric for one source, such as CPU usage for host web-3; a series is a list of (timestamp, value) points. Labels (or tags) are the key-value pairs that identify it (host="web-3", region="eu"). Retention is how long data is kept before deletion.
| Aspect | Relational (Postgres) | Time-series database (Prometheus, InfluxDB, and similar) |
|---|---|---|
| Unit of storage | A row, stored with a header (Postgres adds about 24 bytes per row plus a 4-byte pointer) and indexed individually | A series: many points packed together in time order |
| Writes | Inserts, updates and deletes, each transactional and logged | Append-only; old points are never modified |
| Compression | General-purpose page compression (shrinking each stored block by finding repeated bytes), at best | Specialised: store each timestamp as the difference from the previous difference (usually 0 for regular scrapes, the periodic pulls of current metric values from a service) and each value as its XOR (exclusive-or) with the previous value, so repeated or slowly changing numbers take a few bits (worked example below) |
| Indexing | B-trees over columns you choose | An inverted index from each label value to the series that carry it, plus time ranges per block |
| Deleting old data | DELETE row by row, then vacuum (a background pass that physically reclaims the disk space those deleted rows leave behind) to actually free the space | Drop whole time blocks: deleting a day is removing files |
| Typical query | "Get order 1234", joins, filters on any column | "Rate of errors per service over the last 6 hours, in 1-minute steps" |
| Correctness model | ACID (atomicity, consistency, isolation, durability) transactions, constraints, foreign keys | Best-effort ingestion; losing a few points is acceptable |
| Downsampling | Do it yourself | Built in or standard: keep 15-second data for days, 5-minute averages for months |
Why the compression actually works, in five points. Take a CPU metric scraped every 15 seconds, at timestamps 0, 15, 30, 45 and 60 seconds, with values 42.0, 42.0, 43.5, 43.5 and 43.5. The raw deltas between timestamps are 15, 15, 15, 15; from the second delta onward the delta-of-delta (the change in that delta) is 0, 0, 0, because the interval never changes, and this scheme encodes a delta-of-delta of 0 as a single bit. For the values, XOR-ing each one with the one before it: 42.0 XOR 42.0 is 0 (identical numbers have identical bits, so every bit cancels out), encoded as a single bit; 43.5 XOR 43.5 is 0 again for the last two points. Only the one real change, 42.0 XOR 43.5, is non-zero: bit for bit it comes out to 0x0000c00000000000, which has 16 leading zero bits, 46 trailing zero bits, and just 2 bits of real information sandwiched between them, so the scheme stores a short header plus those 2 bits (well under 20 bits total) instead of a fresh 64-bit value. Three of the four points in this tiny run cost 1 bit each and the one real change costs a few bits, against 64 bits apiece stored raw: that is where the 1.37-bytes-per-point average below comes from, not a black box.
Worked example: the storage difference, measured
One million metric samples stored the "obvious" way in Postgres 16 (timestamp, series ID, value, plus an index on series and time so range queries are fast):
CREATE TABLE metrics_rows (ts timestamptz NOT NULL, series_id int NOT NULL, value double precision NOT NULL);
INSERT INTO metrics_rows
SELECT timestamptz '2026-01-01' + (i/100) * interval '15 seconds', i % 100, (i % 1000)::float8
FROM generate_series(0, 999999) i;
CREATE INDEX metrics_rows_series_ts ON metrics_rows (series_id, ts);
VACUUM ANALYZE metrics_rows;
SELECT pg_relation_size('metrics_rows'), pg_indexes_size('metrics_rows'), pg_total_relation_size('metrics_rows');
52183040|31563776|83787776
That is 52.2 bytes per sample for the table plus 31.6 bytes for the index: 83.8 bytes per sample. The raw information is 16 bytes (an 8-byte timestamp and an 8-byte value); the rest is per-row overhead and indexing. Facebook's Gorilla paper (a published engineering write-up describing an in-memory TSDB; the delta-of-delta and XOR scheme walked through above is what it introduced, and most modern TSDBs copied it) reported an average of about 1.37 bytes per point with that scheme. At that ratio:
samples per dayPostgres rowsGorilla-style=100,000 series×86,400/15=576,000,000=576×106×83.8 B≈48.3 GB/day=576×106×1.37 B≈0.79 GB/dayAbout 61 times less storage, before any downsampling, for a modest 100,000-series fleet scraped every 15 seconds. (The Postgres figure is measured above; the 1.37 bytes is the paper's reported average on Facebook's data, so your ratio will vary with how noisy your values are.)
What goes where, concretely
| Put in the TSDB | Keep in Postgres |
|---|---|
| Request rate, error count and latency histograms per service | Users, orders, payments, inventory |
| CPU, memory, disk and network per host or container | Feature-flag and service configuration |
| Queue depth, consumer lag (how many messages a reader has not yet caught up on), cache hit rate | Incident records, on-call schedules, SLO (service-level objective) definitions |
| Business counters used for dashboards (checkouts per minute) | The individual checkout records those counters summarise |
Logs are a third case: they are time-oriented but consist of text events with many unique fields, so they go in a log store (Elasticsearch, a full-text search engine, or its open-source fork OpenSearch; Loki, a log-aggregation tool that indexes only the labels and keeps the text itself cheap to store; or a columnar warehouse), not in either of these. Prometheus-style TSDBs deliberately store only numbers.
Trade-offs and the middle option
- TimescaleDB (a Postgres extension that partitions a table into time chunks and compresses older chunks column-wise) is the right choice when the time-series data must be joined with relational data using SQL, or when the team wants one database to operate. It closes most of the storage gap with compression, at the cost of running and tuning Postgres at metrics volume.
- A dedicated TSDB wins for infrastructure and application metrics at fleet scale: the monitoring ecosystem (scrapers, alerting rules, Grafana, the dashboarding tool most teams use to chart this data) is built around it, and it should keep working when your main database is the thing that is down.
- The weakness of a TSDB is everything outside its shape: no transactions, no joins, poor at high-cardinality identifiers (a label per user ID creates one series per user and exhausts memory), and awkward for correcting historical data.
- Recommendation for the colleague: metrics in the TSDB, business entities in Postgres, logs in a log store, and use exemplars (individual raw requests a monitoring tool attaches to a metric point as a sample) or trace IDs (identifiers that let you follow one request across every service it touched) to link a spike on a graph to the specific requests behind it.
Explain different write paths used by TSDBs: append-only with WAL, direct columnar writes, and write buffering with compaction. For each, describe impact on write latency, durability, recovery time after crash, and read performance.
Sample Answer
Direct answer
The three write paths differ in where a sample is safe the moment the client gets "OK". With append-only WAL (write-ahead log), the sample is appended to a sequential log and synced to disk, then placed in an in-memory buffer; writes are fast and durable, but a crash means replaying the log, so recovery time grows with how much is unflushed. With direct columnar writes, each insert is written straight into immutable column files; durability and recovery are simple, but each write is expensive, so it only works with large batches. With write buffering plus compaction, samples sit in memory and are flushed to files periodically, then merged in the background; this gives the lowest latency and best file layout, but anything in the buffer is lost on a crash unless something upstream can resend it. My default for a metrics TSDB is WAL plus in-memory buffer plus background compaction (the design Prometheus and InfluxDB use), because it is the only one of the three that is fast and durable per write at the same time.
Key terms
- WAL (write-ahead log): an append-only file where every change is recorded before it is applied elsewhere. After a crash, the system replays it to rebuild what was in memory.
- fsync: the call that forces the operating system to put buffered data physically on disk. Until then a power loss can lose it. Group commit means one fsync covers many writes.
- Columnar: storing each column (timestamps, values, labels) in its own compressed file, so a query reading only values reads only that file.
- Compaction: background merging of many small files into fewer large ones, with better compression and sorting.
- Write amplification: bytes physically written per byte ingested. WAL plus flush plus two compactions means each sample is written about four times.
- Head block / memtable: the in-memory structure holding recent, not yet flushed samples.
- Series and scrape: a series is one metric plus one set of labels; a scrape is Prometheus's term for pulling a fresh set of values from a target on a fixed interval (here, 15 seconds).
The three paths
1. Append-only WAL + in-memory buffer (Prometheus, InfluxDB TSM engine)
InfluxDB's documented path: points are compressed and written to a WAL segment, the file is fsynced, the data is added to the in-memory cache, and only then is success returned. The cache is later snapshotted into TSM (time-structured merge) files, which are compacted through several levels. Prometheus keeps the current 2-hour window in an in-memory head block protected by a WAL in 128 MB segments (the WAL is split into fixed-size files; older ones are deleted once no longer needed for replay), and replays the WAL on restart.
2. Direct columnar writes (ClickHouse MergeTree, ClickHouse's default storage engine family that stores rows sorted on disk and merges files in the background, with synchronous inserts)
Each INSERT is sorted and written as a new immutable part (a directory of column files) on disk; there is no separate log. Background merges combine parts. ClickHouse's documentation warns that many small synchronous inserts create many parts, which hurts query performance and causes errors, so clients must batch.
3. Write buffering + compaction (no per-write log)
Samples are collected in memory (in the client, an agent, or the server) and flushed as a file when the buffer is full or a timer fires, then compacted. ClickHouse asynchronous inserts are an example of server-side buffering: by default (wait_for_async_insert = 1) the server acknowledges only after the buffer is flushed to disk, which makes it durable but adds the flush delay (default timeout 200 ms, or 1,000 ms on ClickHouse Cloud) to write latency; with wait_for_async_insert = 0 it acknowledges on buffering, and ClickHouse's docs state there is then no guarantee the data is persisted.
Comparison
| WAL + buffer | Direct columnar | Buffer + compaction (ack before flush) | |
|---|---|---|---|
| Write latency per request | Low: sequential append plus a group-committed fsync | High per insert (sort, compress, write several files); acceptable only per large batch | Lowest: memory only |
| Durability at ack | Durable once the WAL fsync completes | Durable once the part is written | Not durable: buffer lost on crash unless an upstream source (Kafka, the device) can resend |
| Recovery after crash | Replay WAL since last checkpoint; time grows with unflushed data | Near zero: parts are already complete; incomplete parts are discarded | Near zero restart, but data loss or an upstream replay |
| Read performance | Recent data served from memory (fast); older from compacted files | Good once merged; poor with many small parts | Good after flush and compaction; unflushed data is invisible or served from memory |
| Main risk | Long replay and memory pressure with high series counts | "Too many parts" from small inserts | Silent data loss |
Worked example: 1 million series at a 15-second scrape
samples per secondsamples in a 2-hour head=1,000,000/15≈66,667=66,667×7,200≈480,000,000- WAL: Prometheus's own head holds up to 2 hours before being flushed to a block (as noted above), so a crash just before the flush means replaying up to about 480 million samples. Replay time is proportional to that count (and to the number of series, since each needs its in-memory structure rebuilt). Flushing and checkpointing (recording how far into the WAL has already been safely applied, so replay after a crash starts from that point instead of from the beginning) more often shortens recovery at the cost of more, smaller files and more compaction.
- Group commit: instead of every single write forcing its own fsync (a disk operation that typically costs single-digit milliseconds), writes are batched and one fsync covers a whole batch; each write inside a batch waits for that shared fsync, adding at most one batch's worth of delay. Fsyncing each 10,000-sample batch means about 6.7 fsyncs per second instead of 66,667, which is what keeps WAL write latency low: 66,667 individual fsyncs per second would make the disk the bottleneck long before the WAL itself did.
- Direct columnar: sending one insert per 100 samples would create about 667 new parts per second. Batching into 100,000-row inserts brings it to about 0.67 parts per second, which background merges can keep up with.
- Buffering with a 5-second flush: at any moment up to 66,667 x 5, about 333,000 samples are in memory only. Acceptable if the source is Kafka (a durable, replayable message queue that can resend data on request) and the consumer commits its offset only after the flush, meaning it only tells Kafka "I'm done with these messages" once they are safely on disk, so a crash before that point makes Kafka replay them; not acceptable if the source is a device that already discarded the data.
Trade-offs and pitfalls
- These are layers, not exclusive choices. An LSM-style (log-structured merge: writes land in memory first, are flushed as sorted immutable files, and are merged together in the background) TSDB is WAL + buffer + compaction together. The real design question is which component gives durability at acknowledgement time.
- An fsync per request turns the WAL into the bottleneck. Always group-commit.
- Buffering without an upstream replay source is how metrics silently disappear during a restart. If you buffer, make the acknowledgement to the upstream (Kafka offset commit) happen after the flush.
- Recovery time is an SLO (service-level objective) input. If the TSDB must be queryable within minutes of a crash, limit the head size or run replicas so a restart is not on the critical path.
- What would flip the default: for bulk loads of historical data, or an analytics store fed from Kafka in large batches, direct columnar writes are simpler and give better read layout from the start.
Describe common spatial indexing structures used for proximity queries in ride-matching: quadtree, KD-tree, R-tree, and geohash-based grids. For each: explain their query and update complexity, memory characteristics, and suitability for highly dynamic datasets where drivers update position frequently. Which structure(s) would you pick for city-scale real-time matching and why?
Sample Answer
Direct answer
For city-scale real-time matching the workload is write-heavy: every online driver sends a location every few seconds, while ride requests are far rarer. That favours structures with O(1) updates: a uniform grid or geohash grid (cell ID to a set of drivers) held in memory and sharded by city or region. Quadtrees adapt to uneven density but pay tree maintenance on every move; KD-trees are excellent for static nearest-neighbour search but degrade under constant updates, so they fit only as periodically rebuilt snapshots; R-trees are built for rectangles and polygons on disk, so they belong to the static layer (airports, pickup zones, city boundaries), not to the moving drivers. My pick: an in-memory geohash (or H3) cell grid per city shard for live drivers, plus an R-tree for static geofences.
Terms used
- Uniform grid (grid-based tiling): the map is cut into equal cells; each cell keeps a list of the drivers inside it.
- Geohash grid: the same idea, with cells named by geohash strings so they nest (a cell's children share its prefix) and can be stored in a sorted key-value store.
- Quadtree: a tree where each node covers a square and splits into four children when it holds too many points, so dense areas get small cells and empty areas stay large.
- KD-tree: a binary tree that alternately splits points by x and by y at the median.
- R-tree: a tree of nested bounding rectangles, where each node's rectangle encloses its children; designed for shapes and for disk pages.
- k: the number of results returned by a query.
- Redis: an in-memory key-value data store. Its
GEOADD/GEOSEARCHcommands keep locations as geohash scores in a sorted set, a data structure that keeps its members ordered by a score so a range of scores can be fetched quickly. - N and M (in the Redis complexity figures below): Redis's own docs define these per command, and they are not the same variable each time. For
GEOADD, N is the number of elements already in the sorted set (the whole index). ForGEOSEARCH, N is the number of elements in the grid cells that coarsely overlap the query shape, and M is the number of those elements that actually fall inside the exact shape once filtered. Both differ from this answer's k.
Comparison
| Structure | Update (move one driver) | Range / radius query | Memory | Dynamic data |
|---|---|---|---|---|
| Uniform grid | O(1): remove from old cell set, add to new; only on a cell change | O(cells touched + points in them) | O(n + number of cells) | excellent, but hot cells (cells holding far more points than average, such as one over an airport) in dense areas get large |
| Geohash grid | O(1) in a hash map; O(log n) in a sorted set (Redis GEOADD is O(log N)) | O(cells + candidates); Redis GEOSEARCH is O(N + log M) | O(n), no empty cells stored | excellent; precision is fixed per index |
| Quadtree | O(depth) delete plus O(depth) insert, depth about log n for spread-out data, with node splits and merges | O(depth + nodes visited + k) | O(n), more pointer overhead | good, adapts to density, but splits and merges churn under movement |
| KD-tree | insert unbalances the tree; delete is awkward; usually a full O(n log n) rebuild | O(sqrt(n) + k) for a range in a balanced 2-D tree; nearest-neighbour typically O(log n) | O(n), compact | poor; use as a read-only snapshot |
| R-tree | O(log n) insert with node splits; delete needs re-insertion of orphaned entries | typically O(log n + k), no worst-case guarantee because rectangles overlap | O(n), page-oriented | fair; heavy churn makes rectangles overlap and queries slow down |
Framing by workload characteristics
Worked numbers for one large city (example inputs): 50,000 online drivers pinging every 4 s, peak 300 ride requests per second.
- Update frequency: 50,000 / 4 = 12,500 location writes per second. Only those that cross a cell boundary change the index; with 150 m cells and cars averaging 8 m/s, a ping moves about 8 x 4 = 32 m, so on a simple model where the chance of landing in a new cell scales with (step length) / (cell size), that is 32 / 150, roughly 1 in 5: most pings stay in the same cell, and only about 12,500 x (32 / 150), around 2,700, writes per second actually touch the index.
- Query rate (QPS, queries per second): 300 ride requests/s. If each triggers a nearby-driver search plus a few retries (expanding the search radius), call it about 1,000 searches/s.
- Read/write ratio: roughly 1,000 : 12,500, about 1 : 12.5. Writes dominate, so the structure must make writes nearly free, which rules out anything that rebalances on insert.
- Data size: 50,000 drivers x (8-byte ID + two 8-byte coordinates + cell ID) is a few megabytes, so the whole index fits in one process's memory; durability is unnecessary because positions are rebuilt from the next ping within seconds.
Placement in a distributed real-time matching architecture
- Partition by geography: one shard (or a primary node that takes writes, plus a replica that mirrors it for redundancy and read scaling) per city or per region of a large city. Queries are local, so almost all traffic stays inside one shard.
- Boundary queries: a rider near a shard border needs cells owned by the neighbour shard; the matcher fans out (sends the same query to several shards in parallel) to at most the few adjacent shards and merges candidates.
- Hot spots: an airport or stadium cell can hold thousands of drivers. The grid handles this by switching those areas to a finer precision, or by storing drivers in the hot cell in a small secondary structure. A quadtree handles it automatically, which is its main advantage.
- Snapshots for heavy reads: if a batch matcher needs many k-nearest-neighbour queries at once, build a KD-tree snapshot of the grid every second or two and query that, accepting a slightly stale view and re-checking the chosen drivers' latest positions.
- Static layer: airports, restricted zones and pricing areas are polygons that change rarely: an R-tree (for example the GiST, Generalized Search Tree, index in PostGIS, the spatial extension for PostgreSQL) answers "which zone is this point in" quickly.
Recommendation and what would flip it
City-scale real-time matching: in-memory geohash (or H3) grid, sharded by city, cell size chosen so a typical search touches 9 to 25 cells (a 3x3 block, one ring of neighbours, at the tightest; a 5x5 block, two rings, when the first ring comes up short), with an exact distance or travel-time filter afterwards. I would flip to a quadtree if density varied by orders of magnitude within one shard and fixed cells produced either huge hot cells or many empty lookups. I would use a KD-tree only for offline or batch nearest-neighbour work over a static snapshot, and an R-tree when the indexed objects are shapes or the index must live on disk in a database.
Pitfalls
- Benchmarking with query-only workloads, which makes KD-trees look best while hiding the update cost.
- Choosing structures by big-O alone: at 50,000 points, constant factors, cache locality (how often the data a CPU needs is already in its fast on-chip cache rather than main memory) and lock contention (threads waiting on each other for the same lock) on hot cells matter more.
- Persisting every ping to a database index (for example an R-tree) at 12,500 writes/s per city, which turns an in-memory problem into a write-amplification problem (one logical write turning into many more physical disk writes than expected).
Design the data pipeline and storage for powering real-time 'nearest available driver' matching: drivers stream GPS pings every few seconds, and a rider request needs a ranked list of nearby available drivers in well under a second. Cover how you'd represent and index driver locations for fast proximity lookup, how you'd keep that index fresh under heavy ping volume, and what you'd fall back to if the index is temporarily stale or unavailable.
Sample Answer
Direct answer
Keep the live "where is every available driver" state in memory, sharded by city, in a structure that answers radius queries directly: a geohash-keyed sorted set (Redis GEO) is the pragmatic choice. GPS pings flow through a partitioned log (Kafka) into a location service that overwrites each driver's single latest position, so the index size tracks online drivers, not ping history. A rider request does one radius query for the nearest 20 or so available drivers, filters out anyone whose last ping is too old, and re-ranks the short list by estimated time of arrival (ETA). If the index is stale or down, fall back in steps: widen the radius and the staleness tolerance, then query a coarser, slower copy of recent positions, and only then fail the request with a clear retry.
Requirements and load (inputs stated, arithmetic shown)
Assumptions for a large multi-city service: 500,000 drivers online at peak, one ping every 4 seconds, the biggest city holding 60,000 of them, 2,000 ride requests per second at peak across all cities, and a matching budget of well under a second (target: the proximity lookup under 20 ms at p99, the 99th-percentile latency).
ping writeslargest city shardstaleness from ping interval=500,000/4=125,000 per second overall=60,000/4=15,000 writes per second=15 m/s×4 s=60 m of movement between pings at 54 km/hSo the index is write-heavy (125,000 writes against 2,000 reads per second) and small (one entry per online driver). Storage of history is a separate, append-only concern.
Architecture
flowchart LR
D[Driver app] -->|ping every 4 s| G[Ingest gateway]
G --> K[(Kafka topic partitioned by city)]
K --> L[Location service]
L --> R[(In-memory geo index per city)]
L --> S[(Driver state: status and last seen)]
K --> W[(Cold store for analytics)]
Q[Rider request] --> M[Matching service]
M --> R
M --> S
M --> E[ETA service]
Why a log in the middle. Kafka (a durable, partitioned, append-only message log) absorbs bursts, lets the location service restart and resume from its last offset (the position number of the next unread message in its partition; storing just that number, not the pings themselves, is what makes a restart cheap), and lets analytics consume (read) the same pings without touching the hot path. Kafka splits a topic into partitions (independent, ordered logs); partitioning by city keeps each city's writes on one partition, read by one consumer (a process reading a partition in order), so a driver's pings stay in order.
Representing and indexing driver locations
How Redis GEO works. A Redis sorted set keeps members ordered by a numeric score. GEOADD encodes longitude/latitude into a 52-bit geohash (an interleaving of latitude and longitude bits, so nearby points usually share leading bits) and uses it as the score. GEOSEARCH ... BYRADIUS scans the few score ranges covering the circle and then checks exact distance. Re-adding a member overwrites its position, which is exactly the "latest position only" semantics needed. Run against Redis 7 (redis-cli output, with each result's nested reply compacted onto one line):
> GEOADD drivers:available -97.7431 30.2672 d1 -97.7400 30.2700 d2 -97.7000 30.3000 d3 -97.9000 30.1000 d4
(integer) 4
> GEOSEARCH drivers:available FROMLONLAT -97.7420 30.2680 BYRADIUS 3 km ASC COUNT 10 WITHDIST
1) 1) "d1" 2) "0.1381"
2) 1) "d2" 2) "0.2939"
> GEOADD drivers:available -97.7419 30.2681 d4
(integer) 0
> GEOSEARCH drivers:available FROMLONLAT -97.7420 30.2680 BYRADIUS 3 km ASC COUNT 10 WITHDIST
1) 1) "d4" 2) "0.0148"
2) 1) "d1" 2) "0.1381"
3) 1) "d2" 2) "0.2939"
d3 (about 5 km away) is excluded. The second GEOADD returned 0 because d4 already existed: its position was updated in place and it now ranks first.
Committed layout, per city:
drivers:available:{city}: the geo set holding only drivers who can take a ride right now. Available-only membership means a query never wastes itsCOUNTon busy drivers.drivers:lastseen:{city}: a sorted set scored by last ping time, used to evict drivers whose app went silent.driver:{id}: a hash with status, vehicle type and the ping's own timestamp.- Status changes (driver accepts a trip, goes offline) remove the driver from the available set and update the hash in one atomic step (a
MULTItransaction: Redis's way of running several commands as one all-or-nothing batch, or a small Lua script: a short program Redis runs server-side in a single atomic step instead of several separate round trips), so a busy driver is never offered.
Why not the alternatives. A PostGIS table with a GiST index answers the same query well, but PostgreSQL never updates a row in place: an UPDATE writes a brand-new copy of the row and marks the old copy a dead row version, left for a background process called vacuum to reclaim later. So 15,000 row updates per second in one city means 15,000 dead row versions and 15,000 index entries per second for vacuum to clean up, for data that is worthless 30 seconds later; vacuum falling behind that rate bloats the table and slows every query on it. An in-process grid (hash map from cell ID to driver set) is the fastest option and is what very large operators build eventually, but it means writing your own replication and sharding. Redis is the middle: in-memory, replicated, with the radius query built in.
Keeping the index fresh under heavy ping volume
- Overwrite, never append: one member per driver, so memory is bounded by online drivers.
- Coalesce: if the consumer falls behind, apply only the newest ping per driver from each batch (use a pipeline of
GEOADDcalls: send many Redis commands back to back without waiting for each individual reply, so one network round trip carries the whole batch). Applying 5 old pings for the same driver is pure waste. - Drop out-of-order pings: compare the ping's device timestamp with the stored one; ignore older ones so a delayed retry cannot move a driver backwards.
- Evict the silent: every few seconds,
ZRANGEBYSCORE drivers:lastseen:{city} -inf (now - 30s)and remove those drivers from the available set: this reads every member scored from negative infinity up to, but not including (the leading(), "now minus 30 seconds", which is exactly the drivers whose last ping is more than 30 seconds old. Sorted-set members have no per-member expiry, so this sweep is required. - Check age at read time too: the matcher drops any candidate whose last ping is older than, say, 15 seconds, so a sweep that lags does not produce ghost offers.
- Watch consumer lag: the gap, in seconds, between the newest message at the head of the Kafka partition (the most recently written offset) and the offset the location service has actually processed. Track it as the freshness SLO (service-level objective), for example 99% of pings applied within 2 seconds.
Serving a request
GEOSEARCHradius 3 km,ASC COUNT 20 WITHDISTon the rider's city set.- Drop stale or ineligible candidates (wrong vehicle type, rating filters).
- Straight-line distance is a poor proxy across rivers and one-way grids, so send the short list to the ETA service and rank by estimated pickup time.
- If fewer than 3 candidates survive, retry with 6 km, then 10 km.
- Offer to the best candidate with a short reservation (a lock with an expiry on that driver) so two riders cannot both be matched to the same driver.
Fallbacks when the index is stale or unavailable
| Condition | Detection | Behaviour |
|---|---|---|
| Consumer lag of a few seconds | Lag metric above threshold | Serve normally; widen the staleness filter from 15 s to 30 s and prefer candidates with fresher pings. |
| Index replica down | Health check, connection errors | Fail over to the replica (Redis Sentinel, the Redis component that detects a failed primary and promotes a replica, or Redis Cluster failover). Positions refill within one ping interval (4 s) because every online driver re-pings. |
| Whole city index unavailable | Failover failed | Degraded mode: query a coarse table of last-known positions (updated every 10 to 30 seconds from the same Kafka topic, bucketed by geohash cell) and accept worse ranking. |
| Everything down | Both fail | Return a "finding drivers" state and retry with backoff (wait, then retry, increasing the wait between attempts so a struggling system is not hit with an immediate retry storm); never offer drivers from an unknown-age snapshot. |
The key property is that the index is rebuildable: it is a cache of the last 4 seconds of pings, so recovery is "wait one ping interval", not "restore a backup".
Trade-offs and pitfalls
- Hot cities and events: a stadium letting out concentrates demand into a few cells. Sharding by city handles steady load; a single dense city may need splitting by geohash prefix.
- Memory is not the constraint: 60,000 members per city is a small sorted set. Write rate per shard is the real limit, which is why the city split and coalescing matter.
- Ping rate is a cost lever: halving the interval to 2 seconds doubles writes to 250,000 per second and only reduces the staleness from 60 m to 30 m. Adaptive rates (faster while en route to a pickup, slower while idle) usually beat a global increase.
- What would change the design: if matching needed road-network proximity for every candidate across a very dense city, an in-process grid co-located with the ETA engine would replace the network hop to Redis.
Unlock Full Question Bank
Get access to all 16 Geospatial and Time-Series Data interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.