“Design a geo-fencing service” sounds like a map problem. It is not. The map is the easy part. The interviewer is asking a stream-matching question dressed up in geography: a fleet of moving devices is firing GPS coordinates at you continuously - a phone, a delivery scooter, a shipping container, a kid’s smartwatch - and for each incoming point you must answer, in single-digit milliseconds, “which of the millions of registered fences does this point now sit inside, and did that membership just change since the last point?” The answer to the first half is a spatial-index problem. The answer to the second half - the half most candidates forget - is a state problem, because an alert fires on a transition, not on a position. A device that has been sitting inside a warehouse fence for an hour should not re-fire “entered warehouse” on every 5-second ping. The alert is the derivative of location, and getting that edge-detection right across a distributed, sharded, failing system is the real design.
So the spine of this design is two hard things stacked: point-in-fence matching of a high-rate coordinate stream against millions of arbitrary polygons and circles, and reliable enter/exit transition detection with exactly-the-right-number-of-alerts semantics on top of a store of per-device state. Let me build both properly.
Functional Requirements (FR)
In scope:
- Register a fence. A customer defines a geographic boundary - a circle (center + radius) or an arbitrary polygon (ordered list of vertices) - with metadata (owner, label, which devices it applies to, which transition types it cares about). Millions of fences across all customers.
- Ingest device locations. Devices stream
(device_id, lat, lng, timestamp)updates continuously, every few seconds while moving. - Match and detect transitions. For each location update, determine the set of fences the device is currently inside, compare against the set it was inside at the previous update, and detect
ENTER(now inside, was outside) andEXIT(now outside, was inside) events. - Fire real-time alerts. On a detected transition, deliver an alert (webhook, push, queue message) to the fence owner within ~100ms of the location update arriving, carrying the device, fence, transition type, and location.
- Dwell alerts. Optionally fire when a device has remained inside a fence continuously for longer than a configured duration (e.g. “parked at the depot for 30+ minutes”).
- Query current state. “Which devices are inside fence F right now?” and “Which fences is device D inside right now?”
Explicitly out of scope (own the boundary):
- Map rendering / tiles. Drawing the fence on a map in the customer’s dashboard is a front-end concern; we store and index geometry, we do not render it.
- Device firmware / GPS acquisition. How the device gets its fix and how often it reports is the client’s problem; we define the ingestion contract and assume points arrive.
- Downstream business logic of the alert. What the customer does with an “entered” event (send a coupon, dispatch a truck, bill a toll) is their system. We guarantee delivery of the transition event; we do not run their workflow.
- Routing, ETA, nearby-search. We never ask “what is near this point” over a static dataset. The fences are the query set and the device stream is the driver. That is the opposite shape of a nearby-search system.
The decision that drives everything: this is a write-heavy, stateful stream-matching system, not a read-heavy lookup system. The load is a firehose of location writes, each of which must be matched against an indexed set of fences and diffed against prior state. The hard parts are the spatial index (so matching is not a scan over millions of fences) and the per-device state store (so transitions are detected exactly once). There is no static dataset we are serving reads from; there is a stream we are reacting to.
Non-Functional Requirements (NFR)
- Scale: ~50M active devices reporting, ~10M registered fences. Peak ingestion on the order of a few million location updates per second. Fences are created and edited far less often than devices move - fence writes are a trickle, location writes are a flood.
- Latency: end-to-end from “location update received” to “alert delivered to owner’s endpoint” under ~100ms p99 for the match-and-detect step (network delivery to a slow customer webhook is their latency, not ours). The spatial match itself should be low single-digit milliseconds.
- Availability: 99.99% on ingestion and matching. A dropped location update can mean a missed geofence crossing, which for use cases like child-safety or asset-theft is a real failure. Ingestion must stay up and must not silently drop.
- Consistency: per-device state must be processed in order and exactly-once-effectively - two consecutive points for the same device cannot be processed out of order or a spurious ENTER/EXIT fires. Across devices, no ordering constraint. Fence definitions can be eventually consistent (a new fence becoming active a few seconds late is acceptable); device state cannot.
- Durability: fence definitions are durable and must never be lost (a customer’s configuration). Per-device “last known fence set” is durable enough to survive a node restart without re-firing every alert. Raw location history is optional - we may retain a window for debugging/replay, but the hot path does not depend on long-term storage of every point.
- Correctness of alerts: the headline guarantee. Exactly one ENTER when a device crosses in, exactly one EXIT when it crosses out, no flapping on GPS jitter near a boundary, no duplicate alerts from retries or node failover.
Back-of-the-Envelope Estimation (BoE)
Real numbers with the arithmetic, because they pick the architecture.
Write traffic (the dominant load):
50M active devices.
A moving device reports every ~5s; idle devices report every ~60s.
Assume ~30% moving at peak:
moving: 15M devices / 5s = 3,000,000 updates/sec
idle: 35M devices / 60s = 583,000 updates/sec
Total peak ingestion ≈ 3.6M location updates/sec.
Call it ~3M/sec sustained, ~5M/sec burst.
This is the whole ballgame: millions of writes per second, each triggering a spatial match and a state diff. Compare this to a nearby-search system where reads dominate and writes are tiny - here it is inverted.
Match cost - why a scan is dead on arrival:
Naive: each update checks against every fence.
3M updates/sec * 10M fences = 3 * 10^13 point-in-polygon tests/sec.
Point-in-polygon on a 20-vertex polygon is ~20 float ops.
= 6 * 10^14 ops/sec. Completely impossible.
With a spatial index, each update narrows to the handful of fences
whose cells the device occupies: typically 0-5 candidate fences.
3M * ~5 candidate tests = 15M point-in-polygon tests/sec. Trivial.
The index is not an optimization; it is the difference between “impossible” and “trivial.”
Alert traffic (the output):
A moving device crosses a fence boundary rarely - most updates are
"still inside" or "still outside" with no transition.
Assume ~1 transition per device per ~10 minutes of movement.
15M moving devices / 600s ≈ 25,000 transitions/sec.
So ~25K alerts/sec out of ~3M updates/sec in -> ~0.8% of updates
produce an alert. The match runs on everything; the alert fires rarely.
Storage:
Fences:
Per fence ≈ 1 KB (geometry vertices, metadata, owner, config).
Polygons average ~20 vertices * 16 bytes = 320 bytes + metadata.
10M fences * 1 KB = 10 GB. Small. Fully cacheable in memory.
Fence -> cell index (H3 covering):
Each fence covers, say, ~10-50 H3 cells at the chosen resolution.
10M fences * ~30 cells * ~16 bytes = ~5 GB. In-memory friendly.
Per-device current state ("set of fences I'm inside + last cell"):
Most devices are inside 0-2 fences.
50M devices * ~200 bytes = ~10 GB. Fits in a sharded in-memory store.
Raw location history (optional, rolling 7-day window):
3M updates/sec * 86400 * 7 * ~40 bytes ≈ 70 TB/week.
Only if we retain it; kept in cheap columnar/object storage, not hot.
Bandwidth:
Ingress: 3M updates/sec * ~50 bytes ≈ 150 MB/sec inbound. Modest bytes,
brutal message rate - the cost is per-message processing, not bandwidth.
Egress (alerts): 25K/sec * ~500 bytes ≈ 12 MB/sec. Tiny.
The takeaways: a 3-5M writes/sec firehose where per-message processing cost dominates; a tiny (~10GB) fence set and (~5GB) index that fit in memory; a ~10GB per-device state store that must be sharded and fast; and an alert output that is a small fraction of the input. The architecture is dictated by partitioning the write stream and keeping both the fence index and device state in memory next to the matching compute.
High-Level Design (HLD)
Two planes: a control plane (low-rate: customers register and edit fences, which builds the spatial index) and a data plane (high-rate: the device location firehose, matched against the index, diffed against per-device state, producing alerts). The two meet at the index, which the control plane writes and the data plane reads.
CONTROL PLANE (low rate: fence CRUD) DATA PLANE (high rate: device stream)
┌─────────────┐ ┌──────────────┐
│ Customer │ create/edit fence │ Devices │ (lat,lng,ts)
│ Dashboard │ │ 50M, ~3M/s │
└──────┬──────┘ └──────┬───────┘
│ │
┌──────▼───────┐ ┌──────▼────────┐
│ Fence API │ validate geometry, │ Ingest Gateway │ auth, rate-limit,
│ Service │ compute H3 covering │ (stateless) │ geo-route
└──────┬───────┘ └──────┬────────┘
│ write │ key = device_id
┌──────▼───────────────┐ ┌──────▼─────────────────┐
│ Fence Store (SQL, │ │ Kafka: locations │
│ durable, source of │ publish changes │ partitioned by │
│ truth) + geometry │────────────────────▶│ geo-shard (H3 parent) │
└──────┬───────────────┘ (fence index CDC) └──────┬─────────────────┘
│ │
┌──────▼────────────────────────────┐ ┌───────▼──────────────────┐
│ Spatial Index (H3 cell -> fences)│◀───────│ Matcher Workers │
│ + fence geometry cache │ read │ (consume partition, │
│ replicated in-memory on matchers │ │ match + detect + state) │
└────────────────────────────────────┘ └───────┬──────────────────┘
│
┌────────────────────────────┼─────────────────┐
│ │ │
┌──────▼───────┐ ┌────────▼──────┐ ┌──────▼──────┐
│ Device State │ │ Alert Topic │ │ Location │
│ Store (Redis/ │ │ (Kafka) │ │ History │
│ sharded KV) │ └────────┬──────┘ │ (cold, opt) │
│ dev->fenceset │ │ └─────────────┘
└──────────────┘ ┌────────▼───────┐
│ Alert Dispatcher│ webhook/push,
│ (retry, dedupe) │ at-least-once
└────────────────┘
Fence registration flow (control plane):
- Customer
POSTs a fence (circle or polygon) to the Fence API. It validates the geometry (closed ring, no self-intersection, sane radius), stores the canonical definition in the durable Fence Store, and computes the fence’s H3 cell covering - the set of hexagon cells the fence overlaps. - The
cell -> fence_identries are published to the Spatial Index, which is replicated in memory on every matcher. A new fence becomes matchable within a second or two (eventual, which is fine).
Location matching flow (data plane):
- A device sends a location update to the stateless Ingest Gateway, which authenticates it and writes it to Kafka, partitioned by a geo-shard key so all updates for a geographic region (and crucially, all updates for a single device) land on the same partition in order.
- A Matcher Worker owns that partition. For the incoming point it computes the device’s H3 cell, looks up candidate fences from the in-memory Spatial Index (the fences whose covering includes that cell), and runs an exact point-in-geometry test against each candidate to get the true “currently inside” set.
- It reads the device’s previous fence set from the Device State Store, diffs new-vs-old to find ENTER (in new, not old) and EXIT (in old, not new) transitions, writes the new set back, and for each transition publishes an alert event to the Alert Topic.
- The Alert Dispatcher consumes alerts and delivers them to the owner’s endpoint with retries and dedupe.
The key insight: the fence index is small, static-ish, and replicated into memory next to the compute; the device stream is partitioned so each device’s points are processed in order by a single owner that holds (or can fetch) that device’s state. Match is an in-memory cell lookup plus a few polygon tests; the alert is the diff of two small sets.
Component Deep Dive
The hard parts, naive-first then evolved: (1) the spatial index for matching, (2) exact geometry evaluation for polygons and circles, (3) transition detection and per-device state, (4) partitioning the firehose and handling failover without duplicate or lost alerts.
1. The spatial index: matching a point against millions of fences
The first core problem: given a point, find the fences containing it, out of ~10M fences, in a millisecond, millions of times a second.
Naive approach: test the point against every fence. For each location update, loop over all 10M fences and run a point-in-polygon test on each.
Where it breaks:
- O(F) per update. As the BoE showed, 3M updates/sec times 10M fences is ~10^13 tests/sec - off by orders of magnitude from anything achievable. You are testing a fence in Tokyo to match a device in Toronto.
- No locality. Almost every fence is nowhere near the device, but the scan touches all of them.
First evolution: a bounding-box prefilter in a spatial database (R-tree). Give every fence a bounding box and put the boxes in an R-tree - a tree that groups nearby rectangles into parent rectangles recursively, so a point query descends only into boxes that could contain it. PostGIS does exactly this with GiST indexes: SELECT fence_id FROM fences WHERE ST_Contains(geom, point) uses an R-tree to prune to a few candidate boxes, then runs exact ST_Contains on those.
This is a massive improvement and is genuinely the right tool for ad-hoc spatial queries. But as the primary matcher for a 3M/sec firehose it has two problems:
- A central database is a throughput bottleneck. 3M point-containment queries/sec against a PostGIS cluster, each a tree descent plus exact tests, is far past what a single spatial DB handles. You would shard it heavily, and now you are reinventing partitioning anyway.
- R-tree boxes overlap and need locking on writes. Fences are mostly static so write contention is mild, but the bigger issue is that the R-tree lives in a database you must call over the network per update, adding latency and a dependency on the hot path.
R-trees stay in the design - they are ideal for the control-plane validation and for “which fences overlap this region” admin queries - but the hot-path matcher wants something it can hold in memory and shard trivially.
The answer: a discrete global grid - H3 hexagon indexing - so the point-to-fence match becomes an in-memory hash lookup. H3 (Uber’s hexagonal hierarchical geospatial index) tiles the Earth into hexagonal cells at 16 resolutions. Every (lat, lng) maps to exactly one 64-bit H3 cell ID at a given resolution with an O(1) function. The design:
Index time (control plane, once per fence): compute the fence’s covering - the set of H3 cells that intersect the fence polygon/circle - and store an inverted index h3_cell -> {fence_ids}.
Register fence F (resolution r chosen per size, say r=9 ≈ 0.1 km^2):
cover = h3.polygonToCells(F.geometry, r) // cells overlapping the fence
for cell in cover:
index[cell].add(F.id)
Store index as an in-memory multimap, replicated on every matcher.
Match time (data plane, per update): compute the device’s cell in O(1), look up the candidate fences for that one cell as a hash lookup.
Match point P:
cell = h3.latLngToCell(P.lat, P.lng, r) // O(1)
candidates = index[cell] // hash lookup, ~0-5 fences
inside = { F for F in candidates if exact_contains(F, P) }
Why hexagons over the square cells of geohash/S2 here: every neighbor of a hexagon is equidistant and shares an edge (squares have 8 neighbors at two different distances - edge and corner - which distorts “is this adjacent” logic). For geofencing, where devices move across cell boundaries and we care about proximity to edges, uniform adjacency makes dwell/approach logic and boundary handling cleaner. H3 also has gridDisk(cell, k) to grab the k-ring of neighbors cheaply.
The resolution trade-off. Coarse cells mean each cell lists many fences (more exact tests per match); fine cells mean each fence covers many cells (bigger index, more memory). A single global resolution is a bad fit because fences range from a 50m circle around a house to a 100km polygon around a city.
| Resolution | Approx cell edge | Fence covering | Candidates per match | Fit |
|---|---|---|---|---|
| r=7 (coarse) | ~1.2 km | few cells | many fences/cell | big fences, cheap index |
| r=9 (mid) | ~170 m | moderate | few | the default |
| r=11 (fine) | ~25 m | many cells | ~1 | small precise fences, fat index |
The practical answer is multi-resolution indexing: store each fence at a resolution appropriate to its size (a big fence at a coarse resolution so its covering stays small; a tiny fence at a fine resolution so it does not falsely share a coarse cell with everything nearby). At match time, compute the device’s cell at each indexed resolution and union the candidate sets. This mirrors adaptive subdivision without a tree.
Why not just S2 cells (squares)? S2 is also excellent and Hilbert-ordered for range scans. For geofencing specifically, hexagons’ uniform neighbor distance is the tie-breaker, and H3’s polygonToCells / gridDisk API is purpose-built for exactly the cover-and-neighbor operations we need. Either works; H3 is the opinionated pick for this problem and what the focus calls for.
2. Exact geometry evaluation: polygons and circles
The H3 lookup gives candidate fences - the device’s cell overlaps the fence’s covering - but a cell overlapping a fence does not mean the point is inside the fence. The cell is a coarse approximation; a point in the cell might be in the fence or in the sliver of the cell outside it. So we need an exact test per candidate.
Naive approach: skip the exact test, trust the cell. If the device’s cell is in the fence’s covering, call it inside.
Where it breaks: false positives at the boundary. A fence covering includes every cell the fence touches, including cells only partly inside. A device in the outside sliver of such a cell is reported inside when it is not, firing a spurious ENTER. For a 170m cell and a precise fence, the error band is tens of meters - unacceptable for “did the truck enter the depot.”
The fix: exact point-in-geometry on the small candidate set.
- Circle fence: trivial and cheap.
inside = haversine(point, center) <= radius. One distance computation. Use the equirectangular approximation for speed at short distances, haversine for correctness over longer radii. - Polygon fence: the ray-casting (even-odd) algorithm. Cast a ray from the point in any fixed direction; count how many polygon edges it crosses. Odd = inside, even = outside. O(V) in the vertex count, and V is small (tens), and we only run it on the ~0-5 candidates the index returned.
point_in_polygon(P, poly): // ray-casting, O(V)
inside = false
j = len(poly)-1
for i in 0..len(poly)-1:
if (poly[i].y > P.y) != (poly[j].y > P.y):
x_cross = poly[i].x + (P.y-poly[i].y)/(poly[j].y-poly[i].y)
* (poly[j].x-poly[i].x)
if P.x < x_cross: inside = !inside
j = i
return inside
- Holes and multi-polygons. A fence can be a polygon with holes (inside the outer ring but outside an inner ring = not inside) or several disjoint pieces. Evaluate the outer ring, then subtract any hole the point falls in.
- Precompute an inner/outer H3 classification to skip the exact test. For each fence, split its covering into fully-interior cells (the whole cell is inside the fence) and boundary cells (the cell straddles the edge). If the device’s cell is a fully-interior cell of the fence, the point is definitely inside - skip ray-casting entirely. Only run the exact test when the device is in a boundary cell. Since most of a large fence’s area is interior cells, most “inside” matches resolve with a single hash lookup and no geometry math.
Fence covering split at index time:
interior_cells = cells entirely within the fence -> definitely inside
boundary_cells = cells crossing the fence edge -> run exact test
Match:
if cell in interior_cells[F]: inside (no polygon test)
elif cell in boundary_cells[F]: inside = point_in_polygon(P, F)
This is the elegant payoff of the grid: the index does not just prune which fences to test, it often answers the containment outright, and the expensive polygon math only runs in the thin boundary band.
3. Transition detection and per-device state
This is the part candidates skip and the part that is actually the product. The match tells you the current fence set. An alert fires on a change. You cannot detect a change without remembering the last state.
Naive approach: fire an alert whenever a device is inside a fence. Every update, for every fence the device is in, send “device in fence.”
Where it breaks:
- Alert spam. A device parked inside a fence reports every 60s; you fire “entered” every 60s forever. The customer wanted one ENTER when it arrived and one EXIT when it left, not 1,440 alerts a day.
- No EXIT at all. “Inside” updates can never tell you about leaving; you need to notice the absence of a fence that was present before.
The fix: store each device’s current fence set and diff on every update.
on location update (device D, point P):
new_set = match(P) // from index + exact test
old_set = state[D] // previous fence set
entered = new_set - old_set // fire ENTER for each
exited = old_set - new_set // fire EXIT for each
state[D] = new_set // persist
The Device State Store holds device_id -> {fence_ids, last_cell, per_fence_since_ts}. It is ~10GB, sharded by device_id, in a fast KV store (Redis cluster or a sharded in-memory service). The critical constraint: a single device’s updates must be processed in order by a single owner, or two points processed concurrently race on the read-modify-write of the fence set and you get duplicate or missing transitions. This is why Kafka is partitioned such that a device’s stream is sticky to one partition and one matcher - the per-device state mutation is serialized by partition ownership, no distributed lock needed.
GPS jitter at the boundary (the flapping problem). GPS is noisy by 5-20m. A device sitting right on a fence edge will report points that jitter in and out, and naive diffing fires ENTER/EXIT/ENTER/EXIT every few seconds - a storm of false alerts. Fixes, layered:
- Hysteresis / debouncing. Require N consecutive updates on the new side before committing a transition, or require the point to be more than a small margin past the boundary. A device must be confidently inside (e.g. >15m past the edge, or inside for 2 consecutive fixes) before ENTER fires.
- Accuracy-aware. Devices report an accuracy radius; if the fix is too uncertain (accuracy radius overlaps the boundary), defer the decision rather than flip state on a bad fix.
- Dwell on confirmation. Treat the boundary as a band, not a line: ENTER when clearly inside, EXIT when clearly outside, hold state in the uncertain band.
Dwell alerts. For “inside for 30+ minutes,” store per_fence_since_ts - when the device entered each fence. On each “still inside” update, check now - since_ts >= dwell_threshold and fire a one-time DWELL (mark it fired so it does not repeat). Dwell can also be driven by a timer: on ENTER, schedule a delayed check; if still inside at fire time, emit DWELL.
Handling missing/late/out-of-order points. A device goes through a tunnel and reports nothing for 10 minutes, then reports from the far side of a fence. Did it enter and exit while dark? We cannot know - we only have the points we got, so the transition is detected at the next point we see (it will show as an EXIT if it was inside before and is outside now). For out-of-order points within a partition, use the event timestamp and drop/ignore points older than the last processed one for that device (a stale point must not overwrite newer state).
4. Partitioning the firehose and failover without duplicate or lost alerts
The last hard part is operational: 3M writes/sec, stateful per device, under node failures, with an alert-correctness guarantee.
Naive approach: stateless matchers behind a load balancer, shared state store. Any matcher handles any update, reading/writing the central Device State Store.
Where it breaks:
- Read-modify-write races. Two updates for the same device land on two matchers concurrently; both read old_set, both diff, both write - lost update, double or missing alert. You would need a per-device lock on the state store on every update: 3M lock acquisitions/sec, latency killer, and the lock store becomes the bottleneck.
- Hot shard on the state store. Central store takes the full 3M/sec write load.
The fix: partition the stream by device, co-locate state with compute, serialize per partition.
- Partition Kafka by a key that keeps a device sticky. Keying by
device_idguarantees all of a device’s points are in one partition, processed in order by one consumer - no cross-matcher race, no per-update lock. Each matcher owns a set of partitions and holds the state for those devices in local memory (backed by the durable store), so the read-modify-write is a local in-memory op. - Geo-affinity option. Alternatively key by geo-shard (coarse H3 parent cell) so a matcher owns a region and needs only that region’s slice of the fence index in memory, not the whole 10GB. The trade-off: a device crossing a region boundary hands off to another matcher (and its state must move). Keying by device keeps state simple but each matcher needs the full (small, 10GB) index; keying by geo keeps the index slice small but complicates device handoff. Since the index is only ~10-15GB and fits in memory, key by device and replicate the full index is the simpler, usually-right call.
Failover and exactly-the-right alerts. When a matcher dies, Kafka reassigns its partitions to another consumer. The new owner must rebuild device state.
- Durable state, not just in-memory. The local in-memory state is a cache; the source of truth is the durable Device State Store (or a Kafka-compacted state topic). On failover, the new owner loads the last committed fence set per device, then resumes consuming from the last committed offset.
- At-least-once + idempotent alerts. Kafka gives at-least-once: on failover, a few updates may be reprocessed. If we naively re-diff, we might re-fire an alert. Make alerts idempotent with a dedupe key:
alert_id = hash(device_id, fence_id, transition_type, crossing_sequence_or_bucketed_ts). The Alert Dispatcher drops any alert whose id it has delivered within a dedupe window (a Redis set with TTL). So reprocessing produces the same alert_id, which is deduped - exactly-once effect on top of at-least-once delivery. - Offset commit after state persist. Commit the Kafka offset only after the new device state and the alert are durably written, so a crash cannot acknowledge an update whose transition was never emitted. This is the standard “process, persist, then commit” to avoid lost alerts.
Matcher loop (per partition, single-threaded per device):
for update in partition:
if update.ts <= state[D].last_ts: skip // stale/out-of-order
new_set = match(update.point)
entered, exited = diff(new_set, state[D].fences)
state[D] = {new_set, update.ts, since_ts...} // persist (durable)
for t in entered+exited:
alert = {id: dedupe_key(D, fence, t, ...), ...}
produce(alert_topic, alert) // at-least-once
commit_offset(update.offset) // only after persist
The guarantee falls out of three things stacked: per-device ordering (partition stickiness) removes races, durable state + offset-after-persist removes lost alerts on failover, and idempotent dedupe keys remove duplicate alerts from reprocessing.
API Design & Data Schema
Control plane is CRUD REST; data plane is a stream in, a stream out.
Control plane (fence management, low rate)
POST /api/v1/fences
body: { owner_id, label, type:"polygon"|"circle",
geometry: { // polygon:
vertices:[[lng,lat],...] } // or circle:
// { center:[lng,lat], radius_m: 500 },
device_filter:["dev_*","group:fleet-7"],
transitions:["ENTER","EXIT","DWELL"],
dwell_seconds: 1800,
delivery: { type:"webhook", url:"https://cust/hook" } }
-> 201 { fence_id:"f_8a1", h3_cells: 34, resolution: 9 }
GET /api/v1/fences/{fence_id} -> full definition
PATCH/DELETE /api/v1/fences/{fence_id} -> edit/remove (reindexes covering)
GET /api/v1/fences/{fence_id}/devices -> { inside:[device_id,...], as_of }
GET /api/v1/devices/{device_id}/fences -> { inside:[fence_id,...], as_of }
Data plane (device ingestion, high rate)
// batched, sent every few seconds over a persistent connection (gRPC/MQTT)
POST /api/v1/locations (or stream frame)
{ device_id:"dev_42", fixes:[
{ lat:12.9719, lng:77.5937, ts:1763600000, accuracy_m:8,
speed_mps:4.2, bearing:270 }, ... ] }
-> 202 Accepted // async; matching happens downstream, not inline
Alert payload (service -> owner endpoint)
POST <owner delivery url>
{ alert_id:"a_3f9c", fence_id:"f_8a1", device_id:"dev_42",
transition:"ENTER", at:1763600005, location:[77.5937,12.9719],
fence_label:"Depot-North", dwell_seconds: null }
// owner must treat alert_id as idempotency key (we may retry)
Data stores - the right tool per plane
1. Fence Store - a relational database (PostgreSQL + PostGIS). Fence definitions are the durable, transactional source of truth, with rich geometry and relationships (owner, device filters, delivery config). Writes are low-rate (fence CRUD), so a relational store is perfect: ACID for edits, and PostGIS gives us an R-tree (GiST) index for free for validation and admin spatial queries (overlap checks, “which fences near here”). This is SQL because the entity is relational, low-volume, and benefits from transactions and spatial SQL - the exact opposite of the device stream.
Table: fences
fence_id UUID PRIMARY KEY
owner_id UUID INDEX
label TEXT
kind TEXT -- 'polygon' | 'circle'
geom GEOMETRY(Polygon|Point, 4326) -- GiST (R-tree) INDEX
radius_m INT -- circles only
resolution INT -- chosen H3 resolution for this fence
transitions TEXT[] -- ENTER/EXIT/DWELL
dwell_seconds INT
delivery JSONB
updated_at TIMESTAMPTZ
INDEX gist(geom) -- R-tree for admin/overlap queries
2. Spatial Index - an in-memory inverted multimap, replicated on matchers. Built from the fence coverings, this is the hot-path index: h3_cell -> {fence_ids}, plus per-fence interior_cells / boundary_cells and the geometry needed for exact tests. It is ~10-15GB, rebuilt/updated from a fence-change stream (CDC off the Fence Store). NoSQL/in-memory because the access pattern is a single-key hash lookup at millions/sec - a database call per match would blow the latency budget.
In-memory on each matcher:
index: map<h3_cell(int64), list<fence_id>>
fence_geom: map<fence_id, {kind, vertices|center+radius,
interior_cells:set, boundary_cells:set}>
Updated by: consuming a compacted "fence-changes" Kafka topic.
3. Device State Store - a sharded in-memory KV (Redis Cluster), device_id as key. Current fence set and timing per device, ~10GB, sharded by device_id to match the matcher partitioning. Durable enough (AOF / replicated, or backed by a Kafka-compacted device-state topic) to survive failover without re-firing. NoSQL/in-memory: the access is get/set by device_id at 3M/sec, no relational structure, eventual-durable is fine.
Key: device:{device_id}
fences SET<fence_id> -- currently inside
since MAP<fence_id, ts> -- for dwell
last_ts INT -- for out-of-order rejection
last_cell int64 -- optimization: skip match if same cell
4. Location History - cold columnar/object storage (optional). Raw fixes for replay/debug/analytics, written async off the hot path, partitioned by day and device, TTL’d. Never read by the matcher.
Why SQL for fences but NoSQL/in-memory everywhere on the hot path: the fence set is small, transactional, and relational (it is configuration), so Postgres+PostGIS is ideal and its R-tree is a bonus. The device stream and state are high-volume, key-only, and tolerate eventual durability, so they live in sharded in-memory stores next to the compute. The two meet only through the index, which the slow relational side builds and the fast side reads from memory.
Bottlenecks & Scaling
Where it breaks first, in order, and the fix for each:
1. Matching against all fences (the first wall). 3M updates/sec times 10M fences is impossible as a scan. Fix: H3 inverted index turns each match into an O(1) cell lookup returning ~0-5 candidates, and interior/boundary classification often answers containment with no geometry test at all. This is the single change that makes the system feasible.
2. Per-device state races under concurrency. Concurrent updates for one device corrupt the fence-set diff. Fix: partition the stream by device_id so a device is sticky to one partition and one single-threaded owner; the read-modify-write is a local, serialized, lock-free operation. No per-update distributed lock.
3. Ingestion throughput and backpressure. Millions of messages/sec, bursty. Fix: Kafka as the ingestion buffer, many partitions, stateless gateways in front. Matchers scale horizontally by adding partitions/consumers. Bursts queue in Kafka rather than dropping; the firehose is absorbed, not synchronous.
4. GPS jitter causing alert flapping (a correctness bottleneck, not a load one). Boundary noise fires ENTER/EXIT storms. Fix: hysteresis (N-consecutive-fixes or a margin past the boundary), accuracy-aware deferral, and a boundary band. One ENTER, one EXIT, no chatter.
5. Duplicate or lost alerts on failover. Partition reassignment reprocesses updates. Fix: idempotent alerts with a dedupe key (deduped at the dispatcher with a TTL set) give exactly-once effect over at-least-once delivery; durable device state + commit-offset-after-persist prevents lost transitions. Failover reloads state and resumes.
6. Hot geo-shards. A stadium, airport, or city center concentrates both devices and fences onto a few cells/partitions. Fix: since we key by device_id, device load spreads evenly regardless of geography (two devices in the same stadium hash to different partitions), sidestepping the geographic hotspot entirely. For the index side, multi-resolution keeps dense-area cells from listing thousands of fences. Replicate the (small) index so every matcher has it locally.
7. Index memory and update propagation. The index must be in memory on every matcher and reflect fence edits. Fix: the index is only ~10-15GB - it fits. Propagate fence changes via a compacted Kafka topic the matchers consume, so a new/edited fence reaches all matchers within seconds (eventual, acceptable). No per-match DB call.
8. Alert delivery to slow/failing customer endpoints. A customer webhook that is down or slow must not back up the matcher. Fix: alerts go to a separate Alert Topic consumed by a dispatcher with retries, exponential backoff, and a dead-letter queue. Delivery latency to a slow customer is decoupled from the match path - the matcher’s job ends when it produces the alert event.
9. Fence covering explosion for huge fences. A 100km polygon at fine resolution covers millions of cells. Fix: per-fence resolution chosen by size - large fences indexed at coarse resolution so coverings stay small (tens of cells), small fences at fine resolution for precision. Multi-resolution match unions candidates across the resolutions in use.
10. Single points of failure. No one box can take down ingestion or matching. Fix: stateless gateways behind load balancers; Kafka replicated; matchers are interchangeable consumers that rebuild state from the durable store on reassignment; Redis state store replicated; Postgres with replicas and failover. The whole data plane is horizontally scaled and partition-tolerant, deployed across availability zones, and the only strongly-consistent component (the Fence Store) is off the hot path.
Wrap-Up
The trade-offs that define this design:
- H3 inverted index over R-tree-in-a-database for the hot path. We hold a hexagon
cell -> fencesmap in memory on every matcher so each match is an O(1) hash lookup, not a network call to a spatial database. R-trees (via PostGIS) stay in the control plane for validation and admin queries where ad-hoc spatial SQL is worth the latency, but the firehose cannot afford a per-update DB round trip. - Interior/boundary cell classification over always running point-in-polygon. The grid does double duty: it prunes which fences to test and often answers containment outright for interior cells, so expensive ray-casting runs only in the thin boundary band.
- State-diff transition detection over position alerts. The alert is the derivative of location, so we store each device’s current fence set and fire only on the set-difference - one ENTER, one EXIT - with hysteresis to kill GPS-jitter flapping.
- Partition by device over a shared locked state store. Keying the stream by device_id makes each device’s updates ordered and single-owned, turning the read-modify-write into a lock-free local operation and sidestepping geographic hotspots entirely.
- Exactly-once effect over exactly-once delivery. We accept at-least-once from Kafka and make alerts idempotent with a dedupe key, so failover reprocessing is harmless - cheaper and more robust than trying to make delivery itself exactly-once.
- SQL for configuration, in-memory NoSQL for the stream. The fence set is small, relational, and transactional (Postgres+PostGIS); the device stream and state are high-volume key lookups tolerant of eventual durability (Redis/Kafka). The two planes meet only at the index.
One-line summary: a write-heavy stream-matching service where a multi-million-per-second GPS firehose is partitioned by device onto single-owner matchers that match each point against millions of fences via an in-memory H3 hexagon inverted index (with interior/boundary cells short-circuiting exact ray-casting), diff the result against a durable per-device fence set to detect ENTER/EXIT/DWELL transitions with hysteresis against GPS jitter, and emit idempotent, deduped alerts that give exactly-once effect over Kafka’s at-least-once delivery.
Comments