Tracks and Geofences: Time Semantics Before Spatial Boundaries
Avoiding track reversals and noisy geofence alerts by separating event time from receive time and distinguishing PostGIS ST_Covers, ST_Contains, and ST_DWithin.

Why Tracks Appear to Jump Backwards
On the pet tracker project, I used PostGIS to handle location tracks and geofences. In location backend design, persisting coordinates and running a basic lookup is straightforward; the subtler decisions sit in delayed uploads, points falling directly on a fence perimeter, and GPS drift near buildings. The following is an illustrative design drawn from that problem space to examine time and spatial semantics rather than a direct transcription of a production database schema.
Consider a hypothetical scenario. A pet walks into a park geofence and enters a shaded underpass with poor cellular coverage, where the tracker buffers coordinates locally. Minutes later, the pet exits the park and regains connectivity. Suppose the tracker uploads its freshest fix (outside the park) first, and flushes the older buffered fixes (inside the park) a few seconds later.
If the backend stores only a single server-side created_at column, two things break immediately. Ordering the route by receive time draws a backwards line that exits the park and then jumps back inside, while a naive geofence state machine processes the delayed fix as current truth and fires a spurious re-entry alert moments after an exit alert.
Separating Event Time from Receive Time
Preventing those glitches starts with keeping two timestamps distinct across storage and business logic:
- Event time (
recorded_at): when the device actually sampled the coordinate. Use this to order tracks, segment trips, and check whether an incoming fix is newer than the device’s current geofence state. - Receive time (
received_at): when the server accepted the record. Use this to observe ingestion lag, measure backfill behavior, and support operational audits.
When updating live geofence state, only a fix whose recorded_at is newer than last_event_at should advance the current INSIDE / OUTSIDE status. Late historical fixes still enter the track table so the route stays complete, but they do not rewind live alerts. Because device clocks can drift, ingestion still needs sanity checks to flag implausibly future-dated timestamps rather than trusting every clock unconditionally.
Boundary Semantics: ST_Covers, ST_Contains, and ST_DWithin
Spatial predicates have equally concrete differences. For a point-in-polygon check, ST_Contains(polygon, point) returns false when the point lies directly on the polygon’s perimeter or vertex, whereas ST_Covers(polygon, point) returns true whenever no point of the second object lies outside the first—so a point resting on the polygon boundary still counts as inside.
It is also important not to conflate topological coverage with distance testing. ST_Covers is strictly a boolean coverage predicate with no distance parameter; it supports both geometry and geography inputs without performing meter-threshold calculations. When a geofence needs a radius or outer buffer measured in meters, ST_DWithin(geography, geography, distance_meters, use_spheroid = true) is the dedicated predicate, testing distance in meters on the WGS 84 spheroid by default. The table below summarizes these choices in the illustrative design:
| Dimension | Option A | Option B | Illustrative design choice |
|---|---|---|---|
| Time axis | recorded_at (event time) |
received_at (receive time) |
Order tracks and advance live state by event time; measure lag with receive time |
| Point on polygon edge | ST_Contains(geom, geom) |
ST_Covers(geog/geom, ...) |
Prefer ST_Covers for geofences so a point on the perimeter is not treated as an exit |
| Distance / buffer threshold | Planar degree threshold | ST_DWithin(geog, geog, meters, true) |
Evaluate radii and buffers in meters on geography to avoid latitude distortion |
Handling Edge Jitter with Hysteresis
Even with ST_Covers, real-world fixes near walls or trees can oscillate a few meters across a boundary. Alerting on every single crossing produces noisy notifications. Separating the spatial check from the state transition allows adding hysteresis—for example, switching from INSIDE to OUTSIDE only once a fix clears an outer buffer margin evaluated by ST_DWithin:
// Pseudocode: geofence transition with event-time guard and outer buffer hysteresis
function evaluateGeofence(state, fence, fix):
if fix.recordedAt <= state.lastEventAt:
return state // Backfill tracks without rewinding live fence state
inside = ST_Covers(fence.areaGeog, fix.pointGeog)
farOutside = not ST_DWithin(fence.areaGeog, fix.pointGeog, BUFFER_METERS, true)
if state.status == INSIDE and (not inside) and farOutside:
return nextState(OUTSIDE, fix.recordedAt, emitExitAlert = true)
if state.status == OUTSIDE and inside:
return nextState(INSIDE, fix.recordedAt, emitEnterAlert = true)
return state.withLastEventAt(fix.recordedAt)
The tradeoff is a modest delay before an exit alert fires, which is usually preferable to repeated false alarms. Any buffer distance should be chosen alongside reported horizontal accuracy rather than treated as a universal constant.
Verification Ideas
Focused boundary tests catch most regressions before field validation:
- Exact perimeter points: test coordinates strictly inside, directly on a polygon edge, and one meter outside to confirm
ST_CoversandST_Containsdiffer as expected on the boundary. - Out-of-order replay: feed a newer outside fix followed by older inside fixes, verifying that the track ordered by
recorded_atstays smooth while live fence state does not revert. - Multi-latitude meter checks: validate circular fences and buffers with
ST_DWithin(..., use_spheroid = true)at low and high latitudes to confirm meter thresholds hold consistently.