Interactive Geospatial Property Search Service
Medium · System Design · Backend Engineer · Technical Screen
Prompt
Design the backend platform behind an interactive residential real-estate map and synchronized listing feed. Whenever a buyer pans or zooms across neighborhoods or metropolitan regions, the client fetches homes inside the visible rectangular viewport (min_lat, min_lon, max_lat, max_lon) filtered by buyer-selected property criteria.
For example, a buyer browsing Denver (min_lat=39.68, min_lon=-105.05, max_lat=39.79, max_lon=-104.90 at zoom=13) filters for status=active, price between $450,000 and $850,000, beds >= 3, and property_type in {single_family, townhouse}, then zooms out to view all of Colorado (22,000+ matching homes) while an agent elsewhere marks listing #74210 as sold.
Functional requirements:
- Viewport spatial search: Return matching homes (or aggregated map clusters at wide zoom levels) inside (min_lat, min_lon, max_lat, max_lon) alongside sorted, paginated property cards.
- Multi-attribute filtering: Support live filters over listing status (active, pending, sold), price bounds, bedroom/bathroom counts, and property category.
- Fluid map interaction: Maintain fast, jitter-free responses while buyers rapidly drag and zoom the viewport.
Scale & operational constraints:
- Throughput & latency: Serve 10,000 requests/second at peak with < 200 ms end-to-end latency.
- Update freshness: Inventory mutations—such as price drops or status transitions to sold—appear across active maps within seconds (target < 5 s).
- Spatial & list consistency: Overlapping viewport pans must display consistent markers without pins popping in and out, and scrolling list pages must avoid skipping or duplicating homes while inventory changes.
Scope & Expectations
- Define HTTP request/response schemas for viewport and tile searches, pin-versus-cluster payloads, and paginated listing cards.
- Propose a storage model and 2D-to-1D spatial index separating compact filterable search fields from bulky property media/descriptions.
- Design the serving architecture to absorb hot metropolitan traffic surges and deliver stable pagination over changing inventory.
- Detail multi-layer geospatial caching and race-free invalidation powered by a real-time listing update stream.
Step-by-step walkthrough
Clarify requirements and scope
When a user drags or zooms a real-estate map, the app asks for homes inside the visible bounding box—the geographic rectangle defined by its south-west corner
(min_lat, min_lon)and north-east corner(max_lat, max_lon). Three details make this much harder than a plainWHERE lat BETWEEN ... AND lon BETWEEN ...database query: 1. Uncacheable raw coordinates: Every tiny pan produces brand-new floating-point bounds (like39.739214vs39.739268), so caching raw bounding-box URLs yields a near-zero cache hit rate. 2. Dense zoomed-out views: A city-wide viewport can contain30,000+homes; sending30,000pins over JSON blows the200 mslatency budget and freezes the browser. 3. Live mutations during exploration: When a home's price drops or its status flips tosold, maps must reflect that within seconds—without pins flickering on pan or list pages duplicating homes mid-scroll.Functional requirements
- Spatial search: Return properties inside
(min_lat, min_lon, max_lat, max_lon). - Dynamic filtering: Filter by listing status (
activeby default, pluspendingandsold), price range, minimum bedrooms/bathrooms, and property type (single_family,condo,townhouse,multi_family). - Dual map + list experience: Render pins or summary clusters (grouped count bubbles) smoothly during rapid panning/zooming, alongside a sorted, paginated list of property cards.
Non-functional requirements
- Throughput and latency: Sustain
10,000 requests/sat peak with end-to-end latency< 200 ms(target serverp50 ~20 ms,p99 < 100 ms). - Freshness: Status changes (such as
sold) and price edits appear globally within5 seconds(p99). - Spatial and temporal consistency: Two overlapping map positions must show the exact same homes in their shared area, and a user must never see a home's price revert to an older value.
- Availability: Reads remain available (
99.99%) even during primary database maintenance; a few seconds of staleness during pipeline hiccups is acceptable, corrupt or flickering results are not.
Scope assumptions
- Single-country scale first (for example,
~5Mactive, pending, and recently sold US listings), with a clear path to100M+global listings. - Map search results depend only on geography and filters (not per-user ML ranking), making spatial results shareable across thousands of concurrent viewers; personal state ("Saved heart", "Viewed") is overlaid on the client.
- Spatial search: Return properties inside
Back-of-the-envelope capacity estimates
To decouple fast spatial filtering from bulky listing media, split every property into two representations: a tiny spatial search record and a rich property detail document.
1. Data footprint (5M searchable listings: 1.5M active, 0.5M pending, 3M recently sold) Compact search record per listing: listing_id (8B), leaf_key (8B), lat/lon (16B), price (8B), beds/baths/type/status bitfields (8B), sqft (4B), version (8B) + B-tree overhead -> ~160 bytes/listing * 5,000,000 = ~800 MB total! Rich property card & detail metadata: address, 30 photo URLs, description, HOA/tax history (~10 KB/listing) -> 10 KB * 5,000,000 = ~50 GB total 2. Write rate (MLS feeds, pricing engine updates, agent edits) 1,000,000 updates/day / 86,400 s = ~12 writes/s average MLS batch feed bursts = ~500 writes/s peak 3. Read rate and viewport scale 10,000 req/s peak (60% map viewport/tile queries, 30% paginated list queries, 10% card fetches) Web Mercator viewport size (1200 x 800 px screen near 39.7 deg latitude): Zoom 16 (neighborhood): ~2.2 x 1.5 km -> ~10-80 homes (return individual pins) Zoom 13 (city district): ~18 x 12 km -> ~500-3,000 homes (pins or clusters) Zoom 10 (metro region): ~142 x 95 km -> ~15,000-40,000 homes (MUST return clusters) 4. CPU and network per query In-memory B-tree range scan of a few thousand compact records: ~0.2-0.5 ms CPU 10,000 req/s * 0.5 ms CPU = ~5 full CPU cores (6 x 8-core replicas = 9x headroom) Typical response: 250 pins * ~100 B JSON = ~25 KB raw (~5 KB gzipped)Three design insights jump right out of the math:
- The entire
~800 MBspatial index fits in RAM on a single server. Every search replica can hold a full in-memory copy of all5Mcompact search records. That eliminates cross-network scatter-gather during spatial queries and means no geographic shard can ever become a single-machine bottleneck when a city gets hot. - Separating
160 Bsearch records from10 KBproperty cards keeps RAM tiny and lets each tier use its ideal cache key. - Writes (
500/speak) are tiny compared to reads (10,000/s), so every search replica can easily consume an ordered stream of all property updates in real time.
- The entire
API contract: bounding-box search, map tiles, and batch cards
We expose the explicit bounding-box search contract required by the prompt, alongside a discrete map tile endpoint (splitting the world into standard
2^z × 2^zWeb Mercator grid squares(z, x, y), the same grid used by Google Maps and Mapbox) and a batch metadata endpoint.1. Bounding-box search endpoint (supports both map pins/clusters and sorted list pagination):
GET /v1/listings/search ?min_lat=39.68&min_lon=-105.05&max_lat=39.79&max_lon=-104.90&zoom=13 &status=active&price_min=450000&price_max=850000&beds_min=3&types=single_family,townhouse &sort=price_asc&limit=40&cursor=eyJycyI6... -> 200 OK { "index_seq": 81234567, "total_count": 764, "map": { "mode": "pins", "pins": [ {"id": 74210, "lat": 39.7392, "lon": -104.9903, "price": 625000, "beds": 3, "status": "active", "v": 7} ], "clusters": null }, "list": { "result_set_id": "rs_8a4d12e9", "items": [ {"id": 74210, "price": 625000, "beds": 3, "baths": 2.5, "sqft": 1680, "address": "1420 Blake St", "thumb_url": "https://cdn.../74210_1.webp", "status": "active", "v": 7} ], "next_cursor": "eyJycyI6InJzXzhhNGQxMmU5Iiwib2ZmIjo0MH0=" } }2. Discrete map-tile endpoint (for rapid panning/zooming via CDN edge cache): When panning smoothly, map clients fetch individual data tiles (
GET /v1/map/tiles/{z}/{x}/{y}?status=active&...) so dragging the map by20%only requests the2–4newly uncovered edge squares instead of re-downloading the whole viewport:GET /v1/map/tiles/11/426/775?status=active&beds_min=3 -> 200 OK (Cache-Control: public, max-age=2) { "tile": {"z": 11, "x": 426, "y": 775}, "index_seq": 81234567, "mode": "clusters", "count": 4320, "pins": null, "clusters": [ {"cell_id": 174812096, "count": 1180, "lat": 39.7420, "lon": -104.9850, "min_price": 455000} ] }3. Decoupled card & detail endpoints: -
POST /v1/listings:batchGet {"items": [{"id": 74210, "v": 7}, ...]}returns cachedListingCardobjects. -GET /v1/listings/{id}returns the full10 KBproperty page when a user clicks a pin.API guardrails and filter normalization: Validate
min_lat < max_lat,min_lon < max_lon, latitudes within[-85.0511, 85.0511],zoomin[3, 20], andlimit <= 100. Sort multi-value filters (types=single_family,townhouse) and snap UI slider steps into canonical order so identical searches always generate the exact same cache key.Storage schema and 1D Quadtree / Z-order spatial indexing
Why not run
SELECT ... WHERE lat BETWEEN ? AND ? AND lon BETWEEN ? AND ?on two regular database B-tree indexes? A B-tree onlatalone selects a horizontal band stretching across the entire country, and a B-tree onlonselects a vertical band from Canada to Mexico; intersecting two huge index scans10,000times per second wastes massive CPU.Instead, we convert 2D
(lat, lon)coordinates into a 1D integer key using a Quadtree with Morton (Z-order) bit interleaving: - At zoom1, split the world map into2 × 2 = 4quadrants: top-left(x=0, y=0 -> bits 00), top-right(x=1, y=0 -> bits 01), bottom-left(x=0, y=1 -> bits 10), bottom-right(x=1, y=1 -> bits 11). - Subdivide each square into 4 smaller squares recursively down to zoom20(~38 meterswide). Interleaving the20bits ofyand20bits ofxyields one40-bitinteger calledleaf_key:Zoom 1 quadrants (yx bits): Zoom 2 sub-quadrants inside top-left (00): +-------------+-------------+ +------+------+ | 00 (NW) | 01 (NE) | | 0000 | 0001 | <- every sub-tile inside 00 +-------------+-------------+ => +------+------+ starts with prefix 00, so all | 10 (SW) | 11 (SE) | | 0010 | 0011 | keys in 00 form ONE contiguous +-------------+-------------+ +------+------+ integer range [0000..0011]!Because every child square shares its parent square's bit prefix, all homes inside any tile
(z, x, y)sit side-by-side in one contiguous integer range[lo, hi)! (Geohash uses the exact same bit-interleaving trick encoded as base-32 strings like"9q8yy"; we choose Web Mercator quadtree integers here so one key aligns directly with screen map tiles, caches, and clusters.)Durable source of truth (PostgreSQL + PostGIS, off the hot search path):
Table: listings listing_id BIGINT PRIMARY KEY status TEXT NOT NULL -- active | pending | sold | off_market property_type TEXT NOT NULL -- single_family | condo | townhouse | multi_family price BIGINT NOT NULL beds SMALLINT NOT NULL baths_half SMALLINT NOT NULL -- 2.5 baths stored cleanly as integer 5 sqft INTEGER lat DOUBLE PRECISION NOT NULL lon DOUBLE PRECISION NOT NULL leaf_key BIGINT NOT NULL -- 40-bit zoom-20 Morton quadtree key updated_at TIMESTAMPTZ NOT NULL version BIGINT NOT NULL -- monotonically increments (+1) on every edit Table: listing_details listing_id BIGINT PRIMARY KEY card_json JSONB NOT NULL -- ~1 KB summary card (address, thumbnail) full_json JSONB NOT NULL -- ~10 KB full listing page version BIGINT NOT NULL Table: listing_outbox -- written in the SAME SQL transaction as listings seq BIGSERIAL PRIMARY KEY listing_id BIGINT NOT NULL version BIGINT NOT NULL search_record JSONB NOT NULL -- complete compact fields for search replicasHere is the exact coordinate-to-range math used by the indexer and search replicas:
import math LEAF_ZOOM = 20 MAX_LAT = 85.05112878 # Web Mercator projection latitude limit def tile_xy(lat: float, lon: float, zoom: int) -> tuple[int, int]: """Convert (lat, lon) into Web Mercator tile coordinates (x, y) at `zoom`.""" clamped_lat = max(-MAX_LAT, min(MAX_LAT, lat)) clamped_lon = max(-180.0, min(180.0, lon)) grid_size = 1 << zoom # 2 ** zoom tiles per axis raw_x = int((clamped_lon + 180.0) / 360.0 * grid_size) lat_rad = math.radians(clamped_lat) mercator_y = (1.0 - math.asinh(math.tan(lat_rad)) / math.pi) / 2.0 raw_y = int(mercator_y * grid_size) # Clamp both ends to [0, grid_size - 1] so boundary floats never underflow or overflow x = max(0, min(grid_size - 1, raw_x)) y = max(0, min(grid_size - 1, raw_y)) return x, y def morton_encode(x: int, y: int, zoom: int) -> int: """Interleave bits of y and x from most significant bit down to bit 0.""" key = 0 for bit in range(zoom - 1, -1, -1): y_bit = (y >> bit) & 1 x_bit = (x >> bit) & 1 key = (key << 2) | (y_bit << 1) | x_bit return key def compute_leaf_key(lat: float, lon: float) -> int: """40-bit spatial key stored with every listing.""" x, y = tile_xy(lat, lon, LEAF_ZOOM) return morton_encode(x, y, LEAF_ZOOM) def tile_key_range(x: int, y: int, zoom: int) -> tuple[int, int]: """Contiguous half-open range [lo, hi) of all zoom-20 leaf keys inside tile (x, y, zoom).""" shift = 2 * (LEAF_ZOOM - zoom) prefix = morton_encode(x, y, zoom) return prefix << shift, (prefix + 1) << shiftEach search replica stores all
5Mcompact records in an ordered in-memory B-tree keyed by(leaf_key, listing_id).High-level system architecture
Browser / Mobile Map Client (100 ms pan debounce, client tile cache, per-listing version map) | 1a. GET /v1/map/tiles/{z}/{x}/{y} | 1b. GET /v1/listings/search?min_lat=... ^ v | | 4. SSE live +-----------------------+ | +--------+--------+ | CDN Edge (tiles only) | public, max-age=2s | | SSE Push Gateway| | Collapsed forwarding | | | (open viewports)| +-----------+-----------+ | +--------^--------+ v v | +------------------------------------------------------------+ | | API Gateway (rate limit, filter normalization, sticky hash)| | +----------------+----------------------------+--------------+ | v v | +---------------------------------+ +------------------------------+ | | Search Replicas (6+ stateless | | Listing Card Service | | | nodes across 3 AZs, ~800MB RAM) |-->| L1 hot-card LRU (1s TTL) | | | - B-tree on (leaf_key, id) | | L2 Redis: key = (id, version)| | | - Versioned tile result cache | +---------------+--------------+ | | - Low-zoom cluster aggregates | | cache miss (<1%) | +----------------^----------------+ v | | 3. Consume in commit order +------------------------------+ | | (index_seq) | PostgreSQL + PostGIS | | +----------------+----------------+ | listings, listing_details, |<-- MLS, | | Kafka: listing-changes |<----------| listing_outbox (same SQL tx) | pricing | | (1 ordered stream + heartbeats) | CDC relay +------------------------------+ | +----------------+----------------+ | +------------------------------------------------------------------------+ v +---------------------------------+ | Snapshot Worker -> S3 (~800 MB checkpoint + seq every 5 min for fast replica boot) | +---------------------------------+Notice how cleanly the read and write paths separate: - Zero database queries on the search hot path: Search replicas answer spatial + filter queries directly out of RAM, and the Card Service fetches rich card JSON from Redis by
(listing_id, version). - Client-side request hygiene: While a user drags the map rapidly, the client debounces pan gestures by~100 ms, aborts in-flight HTTP requests for tiles that scrolled off-screen, and reuses locally cached tiles.Deep dive 1: Bounding-box decomposition, pins vs clusters
How does
/v1/listings/searchexecute an arbitrary(min_lat, min_lon, max_lat, max_lon)rectangle using our 1D index? 1. Pick a tile zoom levelzwhere the rectangle overlaps4 to 12tiles. 2. Classify each overlapping tile(z, x, y)as either an interior tile (completely enclosed inside the user's bounding box) or an edge tile (straddling the rectangle border). 3. Scan[lo, hi)for each tile (or read its cached tile result): interior tiles skip coordinate checks completely; edge tiles verifymin_lat <= lat <= max_latandmin_lon <= lon <= max_lonso homes just outside the rectangle border are excluded.What when a zoomed-out view matches
10,000+homes? Returning a "top 300" subset is a classic mistake: as the user pans slightly, a$650khome enters the box and pushes a$640khome out, making pins pop in and out unpredictably! Instead, enforce an all-or-nothing rule per tile and switch dense tiles to world-anchored grid clusters:PIN_LIMIT = 300 # Return all individual pins up to 300 matches; above 300, return clusters CLUSTER_SUBZOOM = 3 # Subdivide dense tile into 2^3 x 2^3 = 64 fixed sub-cells def query_tile(btree_index, z: int, x: int, y: int, filters) -> dict: """Scan one tile's 1D key range, apply dynamic filters, and return all pins or exact clusters.""" lo, hi = tile_key_range(x, y, z) matches = [] # One contiguous B-tree scan visits only listings inside tile (z, x, y) for listing in btree_index.range_scan(lo, hi): if filters.matches(listing): matches.append(listing) if len(matches) <= PIN_LIMIT: return {"mode": "pins", "count": len(matches), "pins": matches} clusters = build_grid_clusters(matches, cell_zoom=z + CLUSTER_SUBZOOM) return {"mode": "clusters", "count": len(matches), "clusters": clusters} def build_grid_clusters(listings: list, cell_zoom: int) -> list[dict]: """Group listings into fixed world-grid cells in O(N) using bit-shifts on leaf_key.""" shift = 2 * (LEAF_ZOOM - cell_zoom) buckets = {} for item in listings: # Shifting right strips lower zoom bits, leaving the cell's exact quadtree ID cell_id = item.leaf_key >> shift if cell_id not in buckets: buckets[cell_id] = { "count": 0, "lat_sum": 0.0, "lon_sum": 0.0, "min_price": item.price, } b = buckets[cell_id] b["count"] += 1 b["lat_sum"] += item.lat b["lon_sum"] += item.lon b["min_price"] = min(b["min_price"], item.price) result = [] for cell_id, b in buckets.items(): # Place the cluster bubble at the true center of mass (centroid) of its homes result.append({ "cell_id": cell_id, "count": b["count"], "lat": b["lat_sum"] / b["count"], "lon": b["lon_sum"] / b["count"], "min_price": b["min_price"], }) return resultWhy fixed-grid centroid clustering works so well: - Zero pan jitter: Because cell boundaries are fixed to the Earth's quadtree grid rather than the screen border, panning never splits or merges clusters, while using the centroid (average latitude and longitude of member homes) places bubbles naturally over real neighborhoods instead of an artificial grid. - Sub-millisecond metro views: For unfiltered low-zoom views (
z <= 10), each replica maintains pre-aggregated(count, lat_sum, lon_sum, min_price)counters per cell as updates stream in (~9parent cells updated per write); custom-filtered metro views scan~30,000in-memory structs in~1 msand cache the result.Deep dive 2: Multi-layer geo-caching and instant invalidation
Decomposing viewports into discrete tiles
(z, x, y)plus normalized filter strings turns chaotic floating-point boxes into high-hit-rate cache keys across four layers:Cache Tier Cache Key TTL / Eviction How Stale Data Is Invalidated Browser client (z, x, y, filter_hash)30 sLRULive SSE push patches/removes changed pins by versionCDN edge (tiles) Tile URL + normalized query max-age=2(2 s)Expires automatically within 2 s; zero purge stormsSearch replica RAM (z, x, y, filter_hash)~1 GBLRUO(1) per-tile version counter check on every read Card metadata (Redis) (listing_id, version)24 hLRUImmutable versioned key—new edit writes a new key How O(1) version-counter invalidation avoids cache-delete races: Deleting cache keys over the network after a database write suffers from a classic race condition: a concurrent reader that missed right before the write can write stale data back into the cache right after your delete! Instead, each search replica holds a fixed
16,777,216-entry array (64 MBof 4-byte integers) oftile_versions, indexed byhash(z, x, y) & 0xFFFFFF. - Whenever a replica applies a Kafka change event for a listing, it incrementstile_versionsfor that listing's18ancestor tiles (z = 3..20; and its old18tiles if its coordinates changed). At500 writes/speak,9,000integer increments/s in RAM takes microseconds. - Each cached tile entry stores thetile_versionsnapshot taken before it was computed. On lookup, ifentry.tile_version != tile_versions[slot], it is treated as an instant cache miss—zero network purges, zero stale hits (and rare hash collisions only cause a harmless extra cache recompute).At the CDN edge, a
2-secondmax-agepaired with request coalescing (also called collapsed forwarding or single-flight, where1,000concurrent requests for the same expired tile wait on1origin fetch instead of stampeding the backend) cuts origin traffic on popular city tiles by99.9%while keeping CDN staleness<= 2 s.Deep dive 3: Hot regions, stable pagination, and 5-second freshness
1. Absorbing hot neighborhoods: Suppose a viral listing or booming market puts
5,000simultaneous users onto downtown Denver: - No geographic shard hotspot: If we sharded a database by state or city, the Colorado shard would melt while Wyoming sat idle. Because every search replica holds the full~800 MBindex, the load balancer distributes Denver queries evenly across every replica in the fleet. (If we later expand to100Mglobal listings and partition by continent/country, each regional shard scales its read-replica pool independently based on CPU.) - CDN + single-flight coalescing: Repeated tile requests collapse at the CDN (2 sTTL) and inside each replica's single-flight lock, so one cold tile is computed once, not5,000times. - Hot-card L1 cache: A viral home's card in Redis could hammer one Redis shard; keeping a tiny1-secondin-process LRU of the top10,000hottest(listing_id, version)cards inside each Card Service pod absorbs hot-key spikes in local memory.2. Stable pagination while listings change: Standard
OFFSET 40 LIMIT 40breaks on live data: if item#12sells and disappears while the user reads page 1, item#41slides back to index39and gets skipped on page 2! We combine two techniques: - Snapshot pagination (primary, 15-min window): Page 1 sorts matching items by a deterministic total order—such as(price ASC, listing_id ASC)using a bounded heap of size1,000—and saves the<= 1,000listing_ids (8 KB) in Redis underresult_set_id(TTL = 15 min). At2,500page-1 list searches/s at peak,2,500 × 8 KB × 900 s ≈ 18 GBof Redis memory. Page 2 slices[40:80]from that frozen ID list and callsbatchGetfor fresh cards: if home#52just sold, it stays calmly in slot#52with a"Sold"badge instead of shifting the whole list! - Keyset (seek) fallback: The opaquenext_cursoralso embeds the last item's(price, listing_id). If a user resumes scrolling after 20 minutes when the Redis snapshot expired, the replica seamlessly queriesWHERE (price, listing_id) > (last_price, last_id)—zero skipped or duplicated unchanged homes.3. Real-time 5-second freshness pipeline and monotonic consistency:
Agent marks home "Sold" -> SQL tx commits listings (v=8) + listing_outbox row [0.0 s] -> CDC relay tails Postgres Write-Ahead Log (commit order) -> Kafka [+0.2 s] -> All Search Replicas apply v=8 & bump tile_versions (RAM cache invalidated) [+0.4 s] -> Path A (Open map tabs): SSE Push Gateway broadcasts {id: 74210, status: sold, v: 8} to coarse-tile subscribers -> pin disappears on open screens! [~1.0 s] -> Path B (New pans via CDN): CDN 2s max-age expires -> fresh tile served [~2.5 s] Total global propagation: ~1-3 seconds (well inside the 5-second SLA)Three subtle correctness safeguards keep this pipeline rock-solid: - Tail Postgres via Change Data Capture (CDC), never
SELECT ... WHERE seq > last_seen: PostgresBIGSERIALassignsseq=100atINSERTtime, notCOMMITtime. If transaction101commits before slower transaction100, pollingseq > 101permanently skips100! Reading Postgres logical replication (Write-Ahead Log, WAL) streams rows strictly in commit order. - Idempotent version checks: Replicas apply an event only ifevent.version > current.version, making at-least-once Kafka replays harmless. - Client-side monotonic state: Each client tracks the highestindex_seqseen (passingmin_seqon uncached list searches so a lagging replica either waits<= 50 msor yields to an up-to-date replica) and tracks the highestversionperlisting_idso a2-second-old CDN tile can never resurrect a home the client already learned was sold via SSE.Failure modes, global scaling, and trade-off summary
Failure handling and observability
- Fast replica boot & crash recovery: A background worker writes an
~800 MBbinary snapshot +index_seqto S3 every 5 minutes. A replacement replica downloads the snapshot in~2 seconds, replays<= 5 minutesof Kafka events (<= 150,000messages), and joins the load balancer once its lag is< 2 s. - Relative lag readiness (avoiding cascading blackouts): The CDC relay emits a
heartbeatevent every second. If one replica stalls (e.g., GC pause) and falls> 2 sbehind its peers, readiness fails and traffic shifts to healthy replicas. Crucially, if all replicas lag together because Kafka is paused, do not mark all replicas unready (which would cause a100%outage!)—keep serving current RAM state with"stale": trueand page on-call if lag exceeds5 s. - End-to-end canary monitoring: Update a hidden synthetic listing in the Pacific Ocean every 60 seconds and probe it from regional edges to measure true commit-to-map visibility latency.
- Bad MLS feed quarantine: Reject or quarantine upstream records with invalid coordinates (such as
(0.0, 0.0)"Null Island" or negative prices) at ingestion before they hit the outbox.
Summary of key trade-offs
- Full in-memory replicas vs sharded index / Elasticsearch: Holding
~800 MBin RAM on every replica gives sub-millisecond scans and eliminates hot shards at US scale, trading custom index + snapshot code for extreme speed and simplicity; move to regional shards or OpenSearch/Elasticsearch if adding full-text search or100M+global listings. - Tile snapping + bounding-box decomposition vs raw bbox caching: Decomposing boxes into quadtree tiles adds edge-tile coordinate filtering and multiple small tile fetches on the map, in exchange for turning uncacheable float boxes into high-hit-rate CDN and RAM cache keys.
- World-anchored grid clusters vs distance-based adaptive clusters: Fixed quadtree sub-cells compute in
O(N)bit-shifts and never jitter when panning, trading slightly less organic bubble spacing for exact counts and cacheability. - 2-second CDN TTL + internal version counters vs active CDN purges: A short
2 sedge TTL shields hot neighborhoods while guaranteeing< 5 sfreshness without fragile distributed cache-purge pipelines. - Snapshot pagination + keyset fallback vs pure keyset: Redis ID snapshots freeze list positions for 15 minutes (
~18 GBRAM at peak) so sold homes don't shift neighboring rows, falling back cleanly to stateless keyset cursors afterward.
- Fast replica boot & crash recovery: A background worker writes an
Intuition & how it works
Imagine organizing 5 million paper flyers for homes across the country. If you keep two separate alphabetical binders—one sorted only by north-south latitude and another sorted only by east-west longitude—finding homes inside a six-block neighborhood forces you to pull out every home across the entire country at that latitude, pull out every home from border to border at that longitude, and cross-check the two giant stacks by hand. Instead, imagine laying a grid over the map that splits the country into 4 numbered squares (0, 1, 2, 3), splits each square into 4 smaller squares (00..03), and repeats 20 times until each tiny square is the size of a backyard. When you file every home in a single cabinet ordered by its grid number, every home inside any neighborhood square sits right next to its neighbors in one small, consecutive folder!
Why does a naive database + cache design fail here? Querying two standard SQL B-tree columns (lat, lon) 10,000 times per second wastes CPU scanning huge geographic stripes, while caching raw (min_lat, min_lon, max_lat, max_lon) URLs fails because dragging a map by two pixels produces brand-new decimals that never match another user's cache key. Worse, zooming out over Colorado matches 22,000+ homes—sending all 22,000 pins stalls the network, while arbitrarily returning "the first 300" makes homes pop in and out as the user pans.
Here is a tiny concrete walkthrough showing how the system handles our Denver search scenario (4 sample listings and a live sale on #74210):
1. Index in 1D: Four Denver-area homes are converted via bit-interleaving (Morton / Z-order coding, which weaves the binary bits of x and y tile coordinates into one integer) into 40-bit keys 61204 (#74210), 61207, and 61211 (inside tile T_D) plus 74890 (outside T_D), stored as ~160-byte compact records (~800 MB total for 5M homes, fitting completely in RAM on every search server).
2. Pan and query: A buyer pans over T_D filtering for status = active, price in [$450k, $850k], and beds >= 3; the client snaps to tile T_D (hitting a 2-second CDN edge cache or performing a sub-millisecond in-memory B-tree range scan [61200, 61300)), returning matching pins 61204 (#74210, v=7) and 61211 (v=3), while 10 KB photo/address cards are fetched separately by (id, version) from Redis.
3. Zoom out: The buyer zooms out to all of Colorado (22,000 matches > 300 pin limit); instead of 22,000 individual pins, the server shifts each leaf_key right to group homes into fixed 8 × 8 sub-cells and returns summary clusters (such as {"count": 1180, "min_price": 455000} centered at the homes' average coordinates).
4. Live "Sold" update (< 5 s): Listing #74210 (leaf_key=61204) sells (v=8), committing to PostgreSQL and a transactional outbox in one transaction -> Change Data Capture (CDC) streams v=8 through Kafka in < 0.5 s -> every search replica updates RAM and bumps T_D's version counter (instantly invalidating T_D's local cache), Server-Sent Events (SSE) removes pin #74210 on open browsers in ~1 s, and CDN copies expire within 2 s.
Key trade-offs
- Full in-memory index replicas vs geographic sharding or an external search cluster. Because
5Mcompact search structs occupy~800 MB, keeping the full dataset in RAM on every search replica eliminates network hops and prevents popular cities from overloading a single geographic shard. The trade-off is maintaining custom snapshot-and-replay code, whereas Elasticsearch / OpenSearch provides built-in geo/text queries at the cost of higher memory overhead and cluster operations (and becomes preferable once listings exceed50M–100Mor need full-text keyword search). - 1D Quadtree Morton keys vs Geohashes vs hexagonal grids (H3). All three map 2D points to 1D prefix cells. Web Mercator Quadtree keys match map-client viewport tiles
1-to-1, so one key powers the B-tree, tile cache, and grid clusters; Geohash strings work identically but have non-square aspect ratios that vary by latitude, while H3 hexagons have uniform neighbor distances but do not nest cleanly into exact parent-child bit ranges. - Discrete map tiles vs raw bounding-box queries. Decomposing viewports into standard
(z, x, y)tiles makes overlapping user views share the exact same CDN and RAM cache keys and lets small pans fetch only newly exposed edge tiles. The trade-off is4–12lightweight tile requests per initial map load and an exactlat/lonboundary filter on edge tiles for strict bounding-box list queries. - World-anchored grid clustering vs distance-based (k-means / DBSCAN) clustering. Grouping homes by shifting quadtree key bits runs in a single
O(N)pass, produces exact counts, and never reshuffles bubbles as a user pans. Distance-based clustering produces slightly more organic visual groupings but shifts unpredictably when the viewport moves and is expensive to recompute on live updates. - Short
2-secondCDN TTL + internal tile-version counters vs distributed cache purges. Expiring CDN tiles after2 secondsshields hot regions from99%+of duplicate hits while meeting the5-secondfreshness target with zero purge infrastructure; inside replicas, incrementing an in-memory per-tile version counter gives instant, race-free invalidation. - Snapshot list pagination vs pure keyset (cursor) pagination. Caching the ordered list of up to
1,000matchinglisting_ids (8 KB) in Redis for15 minutesprevents newly sold homes from shifting list rows under a scrolling user's finger (costing~18 GBof Redis RAM at peak), while encoding(sort_value, listing_id)inside the cursor provides a stateless fallback once the snapshot expires.
Common mistakes
- Using two separate SQL B-tree indexes on
latitudeandlongitudeinstead of a true 2D-to-1D spatial index (Quadtree, Geohash, PostGIS R-tree, or BKD tree), causing expensive full-stripe scans at10,000 req/s. - Using raw floating-point bounding boxes as cache keys, which misses the cache on almost every pan because two users rarely share identical 6-decimal viewport coordinates.
- Returning
10,000+raw pins when zoomed out—or silently truncating to "top 300 pins", which either crashes browser rendering or causes pins to pop in and out inconsistently as the user pans. - Skipping the exact
lat/loncheck on boundary cells, returning properties that sit inside an overlapping edge tile/geohash cell but outside the requested(min_lat, min_lon, max_lat, max_lon)box. - Packing
10 KBdescriptions and photo arrays into the spatial search index, bloating index memory60×and forcing spatial caches to invalidate whenever a photo caption changes. - Using SQL
OFFSETpagination on live listings, which skips or duplicates homes whenever an earlier listing sells or changes price. - Sharding listings strictly by city or state at small data sizes, turning high-traffic markets like Denver, NYC, or Seattle into chronic single-shard CPU hotspots.
- Polling an outbox table with
WHERE seq > last_seeninstead of tailing the database Write-Ahead Log (CDC), which permanently skips slow transactions whose auto-increment ID was allocated before a faster transaction committed. - Deleting cache keys asynchronously after database writes without version numbers, allowing slow concurrent readers to repopulate the cache with stale prices or resurrect sold homes.
Follow-up questions
- How do you prevent skipped or duplicated property cards when a buyer pages through sorted search results while prices and statuses mutate underneath? Enforce a deterministic, unique sort key such as
(price ASC, listing_id ASC)so identically priced listings never tie, and never use SQLOFFSET. During page 1, materialize up to1,000orderedlisting_ids (~8 KB) in Redis under aresult_set_idwith a15-minuteTTL; later page fetches slice[offset : offset + limit]from that frozen ID array and batch-load freshListingCardobjects by ID, keeping any home that just sold anchored in its slot with a"Sold"badge rather than shifting subsequent cards. Also pack the final card's(price, listing_id)inside the signed cursor so sessions resuming after the15-minuteRedis TTL fall back seamlessly to keyset pagination ((price, listing_id) > (last_price, last_id)), while newly listed homes surface through an explicit"New homes match—Refresh"pill. - When a zoomed-out metro viewport contains tens of thousands of matching homes, how do you aggregate them into stable map clusters without panning jitter? Apply an all-or-nothing per-tile pin ceiling (such as
300matches) above which the search replica switches that tile from raw pins to fixed world-grid clusters by subdividing the tile into an8 × 8child quadtree grid (zoom + 3). Because each home's child cell ID is obtained via a single bit-shift on its40-bitMortonleaf_key(leaf_key >> shift), aggregating20,000–30,000in-memory records finishes in ~1 ms, accumulating exact counts, minimum price, and the true geographic centroid(sum_lat / count, sum_lon / count)so bubbles rest naturally over dense neighborhoods and never split or jump as the viewport pans. For default unfiltered views at wide zoom (zoom <= 10), replicas maintain incremental per-cell counters as Kafka events arrive, serving state- and country-wide clusters in microseconds. - Walk through the end-to-end streaming update path that removes a newly sold home from active map views worldwide within 5 seconds. Committing
status = 'sold'(bumpingversion = v + 1) writes both thelistingsrow and alisting_outboxrecord inside one atomic PostgreSQL transaction, which Change Data Capture (CDC) tails from the Write-Ahead Log and publishes to an ordered Kafka topic in< 0.5 seconds. Every search replica consumes that event, updates its in-memory B-tree ifevent.version > stored.version, and increments the listing's18ancestor tile version counters in RAM (invalidating local tile caches instantaneously), while CDN edge tiles age out automatically via their2-secondmax-ageheader. Simultaneously, an SSE (Server-Sent Events) gateway pushes{id, status: "sold", version}to browsers subscribed to that coarse region so open maps erase the pin in~1 secondand record(id -> version)client-side to ignore any slightly older2-secondCDN tile; a synthetic canary listing mutated every 60 seconds continuously verifies end-to-end SLA compliance.
Follow-up questions
- How do you prevent skipped or duplicated property cards when a buyer pages through sorted search results while prices and statuses mutate underneath?
- When a zoomed-out metro viewport contains tens of thousands of matching homes, how do you aggregate them into stable map clusters without panning jitter?
- Walk through the end-to-end streaming update path that removes a newly sold home from active map views worldwide within 5 seconds.
Similar questions
- Transactional Key-Value Store with Expiring Keys
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform
- Prior Authorization Status Engine, Clinical Worklists, and Digests
- Diagnosing and Optimizing Full-Stack Web Request Latency