Geofencing Architecture: Location-Aware Systems at Scale
Geofencing defines virtual boundaries around real-world locations and triggers actions when devices enter or exit those boundaries. From delivery zone validation to proximity marketing, geofencing architecture powers a wide range of location-aware applications.
Geofence Types#
Circular geofences are defined by a center point (latitude, longitude) and a radius. They are the simplest to implement and the cheapest to evaluate — a single haversine distance calculation determines containment. Most mobile OS APIs (iOS Core Location, Android Geofencing API) natively support circular fences.
Polygon geofences use a series of vertices to define arbitrary shapes. They model real-world boundaries more accurately — city blocks, delivery zones, warehouse footprints. Containment checks use the ray-casting algorithm or winding number method, both running in O(n) where n is the vertex count.
Corridor geofences define a buffered path along a route. Useful for monitoring whether a driver stays on the designated road or a train follows its expected track.
Enter and Exit Events#
The core abstraction in any geofencing system is the state machine per device-fence pair:
- Outside — The device is not within the geofence boundary.
- Inside — The device is within the boundary.
- Enter — Transition from outside to inside.
- Exit — Transition from inside to outside.
- Dwell — The device has remained inside for a configured duration.
Debouncing is critical. GPS jitter near fence edges produces false enter/exit oscillations. Common strategies:
- Hysteresis buffer — Use a slightly larger radius for exit than for enter (e.g., enter at 100 m, exit at 120 m).
- Time-based debounce — Require the device to remain in the new state for a minimum duration (5 to 30 seconds) before firing the event.
- Consecutive readings — Require multiple sequential location fixes confirming the new state.
Client-Side vs Server-Side Geofencing#
Client-side geofencing runs on the mobile device. The OS monitors registered fences and wakes the app on transitions.
Advantages:
- Works offline.
- Low latency (events fire locally).
- Battery-optimized by the OS.
Limitations:
- iOS limits 20 monitored regions per app; Android allows around 100.
- Fence definitions must be pushed to the device and updated periodically.
- Limited to circular fences on most platforms.
Server-side geofencing evaluates device locations against fences on the backend.
Advantages:
- Unlimited fence count and arbitrary shapes.
- Centralized logic, easier to update and audit.
- Can correlate multiple devices and fences simultaneously.
Limitations:
- Requires continuous location streaming, increasing battery drain and bandwidth.
- Latency depends on reporting interval and network conditions.
- Higher infrastructure cost.
Most production systems combine both: client-side fences for the highest-priority zones (under 20) and server-side evaluation for the full geofence catalog.
Location Tracking Pipeline#
A server-side geofencing system processes a continuous stream of device locations:
- Device reports location — via GPS, Wi-Fi positioning, or cell tower triangulation. Reporting interval balances accuracy against battery life (15 seconds for active tracking, 5 minutes for background).
- Ingestion layer — A message broker (Kafka, Kinesis) absorbs the location stream and fans out to consumers.
- Geofence evaluation — A processing layer checks each location update against relevant fences using spatial indexing.
- State management — A fast data store (Redis, DynamoDB) tracks the current state (inside/outside) per device-fence pair.
- Event emission — State transitions produce enter/exit/dwell events published to downstream consumers.
- Action execution — Downstream services send push notifications, update dashboards, trigger workflows, or log analytics.
Spatial Indexing#
Evaluating every location update against every geofence is O(n * m) and does not scale. Spatial indexes reduce the candidate set:
Geohash grid — Encode each geofence into the geohash cells it overlaps. When a location arrives, compute its geohash and look up only fences sharing that cell. Simple to implement with Redis sorted sets or a key-value store.
R-tree — A balanced tree that indexes bounding rectangles. Supports range and nearest-neighbor queries efficiently. Libraries like libspatialindex, PostGIS (GIST index), and Turf.js provide R-tree implementations.
S2 Geometry (Google) — Maps the earth's surface onto a Hilbert curve, dividing it into hierarchical cells. Excellent for global-scale systems with varying fence densities. Used internally at Google and Uber.
H3 (Uber) — A hexagonal hierarchical grid system. Hexagons tile without edge distortion, making them ideal for density analysis and proximity queries.
For most systems, geohash-based indexing with a resolution of 6 to 7 characters provides a good balance of precision and performance.
Real-Time Alerts#
Geofence events must propagate to users and systems with minimal delay:
- Push notifications — FCM/APNs for mobile alerts when a device enters or exits a zone.
- WebSocket channels — Live dashboard updates for fleet monitoring or asset tracking.
- Webhook callbacks — Notify partner systems (e.g., a delivery platform triggers "driver arriving" when the courier enters the customer's zone).
- Event bus — Publish to Kafka or SNS for downstream microservices to consume asynchronously.
Target end-to-end latency from location fix to alert delivery should be under 5 seconds for critical use cases.
Battery Optimization#
Location tracking is the largest battery drain in mobile apps. Optimization strategies:
- Adaptive reporting intervals — Increase frequency near geofence boundaries, decrease when far from any fence.
- Significant location changes — Use the OS significant-change API (iOS) or activity recognition (Android) to wake the app only on meaningful movement.
- Geofence proximity tiers — Monitor coarse regions (large radius) and switch to fine-grained tracking only when the device enters a coarse zone.
- Server-side prediction — Given the device's last known position and velocity, the server estimates when it might approach a fence and requests a location update only then.
- Wi-Fi and cell positioning — Use lower-power positioning methods when high GPS accuracy is not needed.
A well-optimized implementation consumes under 3% additional battery per day in background monitoring mode.
Use Cases#
Delivery zones — Validate that a delivery address falls within a serviceable polygon. Trigger "driver approaching" and "delivered" events based on courier proximity to the drop-off point.
Proximity marketing — Send promotional push notifications when a customer enters a retail store's geofence. Dwell time events trigger deeper engagement (e.g., a coupon after 5 minutes in-store).
Fleet management — Monitor vehicle positions against route corridors and depot fences. Alert dispatchers on unauthorized stops, route deviations, or extended idle time.
Asset tracking — Geofence warehouses, construction sites, or secure areas. Trigger alerts when high-value equipment leaves the designated zone.
Workforce management — Automate clock-in/clock-out when employees enter or leave job sites. Enforce compliance with designated work areas.
Safety and compliance — Keep drones within approved flight zones, monitor parolees' exclusion zones, or alert parents when a child leaves a safe area.
Architecture Diagram#
Device GPS Fix
|
v
Ingestion (Kafka / Kinesis)
|
v
Geofence Evaluator (spatial index lookup)
|
v
State Store (Redis — device-fence state)
|
v
Event Bus (enter / exit / dwell events)
|
+---> Push Notification Service
+---> Dashboard (WebSocket)
+---> Analytics Pipeline
+---> Webhook Dispatcher
Key Takeaways#
- Use circular fences for simplicity and polygon fences for real-world boundary accuracy.
- Debounce transitions with hysteresis and time thresholds to eliminate GPS jitter noise.
- Combine client-side OS fencing (limited count, low power) with server-side evaluation (unlimited fences, flexible shapes).
- Spatial indexes (geohash, R-tree, S2) are mandatory once you exceed a few hundred fences.
- Optimize battery by adapting reporting intervals based on proximity to fence boundaries.
- Target under 5 seconds end-to-end latency from location fix to alert delivery.
If you found this guide useful, explore more system design deep dives at codelit.io.
This is article #214 in the Codelit engineering blog series.
Continue learning
Go deeper on system design
As an Amazon Associate I earn from qualifying purchases. Codelit may receive a commission at no extra cost to you.
Building Microservices
Sam Newman · 2021
600 pages on splitting a monolith: service boundaries, data decomposition, migration order.
Release It!
Michael T. Nygard · 2018
Post-mortems of real outages, then the stability patterns (circuit breaker, bulkhead) that stop them.
4.6 (501)#4 in Client-Server Networking SystemsA Philosophy of Software Design
John Ousterhout · 2021
Short book on module depth and complexity, with before/after code showing why an interface is too wide.
Database Internals
Alex Petrov · 2019
Explains B-trees, LSM trees and consensus protocols so you can predict how a datastore will behave.
4.6 (560)#2 in Management Information Systems