MongoDB
Designing a Geofencing System
Build a geofencing platform to trigger events when devices enter or exit defined geographic boundaries — covering spatial indexing, zone management, and alerts.
S
srikanthtelkalapally888@gmail.com
Geofencing detects when a device crosses the boundary of a defined geographic zone and triggers actions accordingly.
Use Cases
Marketing: Send coupon when user enters store area
Logistics: Alert when truck leaves delivery zone
Parental: Notify when child leaves school zone
Fraud: Alert when card used outside home region
Field service: Track technician arrival at job site
Smart home: Turn on lights when owner approaches
Geofence Types
Circle: Center point + radius (simple, common)
Polygon: Custom shape (precise building footprint)
Route: Corridor along a path (logistics)
Grid: H3 hexagonal cells (analytics)
Architecture
Device Location Updates (every 5-30 sec)
↓
Location Ingestion (Kafka)
↓
Geofence Evaluation Service
├── Load applicable fences
├── Point-in-polygon check
└── State change detection
↓
Event: ENTER / EXIT / DWELL
↓
Action Service (notification, webhook)
Spatial Index
Efficient zone lookup — don't check every zone for every update:
Approach 1: R-Tree index (PostGIS)
geofence table indexed spatially
SELECT * FROM geofences
WHERE ST_Contains(zone, ST_Point(:lng, :lat))
Approach 2: H3 hexagonal grid
Each zone: list of H3 cells it covers
Device at H3 cell C? → Query zones that include C
→ Simple hash lookup, very fast
State Tracking
Track per (device_id, fence_id):
OUTSIDE → (enter) → INSIDE
INSIDE → (exit) → OUTSIDE
INSIDE → (dwell after 5min) → DWELL event
Store state in Redis:
geofence:state:{device_id} → { fence_123: INSIDE, ... }
Point-in-Polygon (Ray Casting)
For each geofence polygon:
Cast a ray from point eastward
Count how many edges it crosses
Odd crossings → INSIDE
Even crossings → OUTSIDE
Optimization: Bounding box pre-check before full algorithm
Event Deduplication
Prevents spam:
ENTER event fires once until EXIT detected
DWELL fires once per dwell_period
Idempotency key: {device_id}:{fence_id}:{event_type}:{date}
Conclusion
Geofencing combines spatial indexing (H3/R-tree), stateful enter/exit tracking, and event-driven alerting. H3 cell-based lookup provides sub-millisecond fence matching at scale.