Nov 23, 20267 min read

Geofencing Backend for Logistics: Enter and Exit Events from GPS Pings

How to turn a stream of vehicle GPS positions into reliable geofence enter and exit events for depots, customer sites and restricted zones, with PostGIS, hysteresis against GPS drift, out-of-order pings and a TypeScript example on Encore.

Illustration for Geofencing Backend for Logistics: Enter and Exit Events from GPS Pings

Logistics platforms care most about vehicle positions at the moment a vehicle crosses a line: a truck reaching a depot starts the dock clock, and a van leaving a customer site closes the stop. Geofencing turns raw GPS pings into those events.

This guide covers the parts beyond the point-in-polygon check, GPS drift at the boundary, late pings and parallel processing, and builds the backend in TypeScript with PostGIS.

Where should geofence checks run?

Phones can register geofences with the operating system, which saves battery, but each platform caps the number of active regions per app and the rules end up spread across mobile builds. Fleets also mix sources: driver apps, telematics boxes in trucks and partner carrier feeds. Running the check on the server, against every position you receive, handles all of them with one set of zones and one set of rules, and the events it produces can feed the rest of the backend directly.

How do you store zones and check a position?

Store each zone as a polygon in a PostGIS geography column with a GiST index. Depots and customer sites are usually drawn on a map tool and saved as GeoJSON, which ST_GeomFromGeoJSON reads directly. For each ping, ST_Covers returns the zones that contain the point, including points exactly on the edge, and the index keeps this fast with thousands of zones. Geography works in meters on the earth's surface, so distances in later checks need no projection math.

How do you stop events from flapping?

A GPS-enabled smartphone is typically accurate to within about 5 meters under open sky, according to GPS.gov, and noticeably worse between buildings or under a loading dock roof. A truck parked at the gate of a depot jumps in and out of the polygon, and a naive check emits enter and exit every few seconds.

Add hysteresis: enter a zone only when the position is inside the polygon, and treat the vehicle as still inside while it is within a buffer of the polygon, for example 50 meters, using ST_DWithin. It exits only once it is further out than the buffer. Pick the buffer per zone type: a large depot tolerates 100 meters, a customer door in a dense street needs less.

How do you handle late and duplicate pings?

Mobile clients buffer positions when they lose signal and send them in bursts, and HTTP retries create duplicates. Store the timestamp of the last position you applied per vehicle and ignore anything older, or a late ping from inside the depot would re-enter a truck that has already left. Process each vehicle's pings one at a time by locking its state row in the transaction, which keeps two concurrent requests from both seeing "outside" and both emitting an enter event.

Which events should you emit?

Emit enter and exit with the vehicle, the zone, the time from the device and the position. Dwell time falls out of the pair. Consumers then do the business work: arrival notifications to customers, dock check-in, detention billing when a truck stays past its window, or alerts for restricted zones. Keeping these in subscribers means a slow notification provider never delays position ingestion.

Geofencing with Encore

Encore

Encore is a backend framework with built-in infrastructure, and the zone table, the vehicle state and the event topic in this design are declared in the TypeScript service itself. An Encore Postgres database stores zones and state with PostGIS, which is available in Encore's Postgres both locally and in the cloud, and enter and exit events go to a Pub/Sub topic that other services subscribe to. Deployed, Encore provisions the database and topic in your own AWS or GCP account. See How Pallet built an event-driven AI logistics platform on GCP without touching Terraform.

Set up the app

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

-- geofence/migrations/1_create_geofence.up.sql CREATE EXTENSION IF NOT EXISTS postgis; CREATE TABLE zones ( id BIGSERIAL PRIMARY KEY, name TEXT NOT NULL, kind TEXT NOT NULL, exit_buffer_m DOUBLE PRECISION NOT NULL DEFAULT 50, area GEOGRAPHY(POLYGON, 4326) NOT NULL ); CREATE INDEX zones_area ON zones USING gist (area); CREATE TABLE vehicles ( id TEXT PRIMARY KEY, last_ping_at TIMESTAMPTZ ); CREATE TABLE vehicle_zones ( vehicle_id TEXT NOT NULL REFERENCES vehicles (id), zone_id BIGINT NOT NULL REFERENCES zones (id) ON DELETE CASCADE, entered_at TIMESTAMPTZ NOT NULL, PRIMARY KEY (vehicle_id, zone_id) );
// geofence/encore.service.ts import { Service } from "encore.dev/service"; export default new Service("geofence");
// geofence/geofence.ts import { api } from "encore.dev/api"; import { SQLDatabase } from "encore.dev/storage/sqldb"; import { Topic } from "encore.dev/pubsub"; const db = new SQLDatabase("geofence", { migrations: "./migrations" }); export interface ZoneEvent { type: "enter" | "exit"; vehicleId: string; zoneId: number; at: string; lat: number; lng: number; } export const zoneEvents = new Topic<ZoneEvent>("zone-events", { deliveryGuarantee: "at-least-once", }); interface CreateZoneParams { name: string; kind: string; exitBufferM?: number; // GeoJSON Polygon geometry, as drawn in your map tool. polygon: { type: "Polygon"; coordinates: number[][][] }; } // Only signed-in dispatchers may manage zones. export const createZone = api( { expose: true, auth: true, method: "POST", path: "/zones" }, async (p: CreateZoneParams): Promise<{ id: number }> => { const row = await db.queryRow<{ id: number }>` INSERT INTO zones (name, kind, exit_buffer_m, area) VALUES (${p.name}, ${p.kind}, ${p.exitBufferM ?? 50}, ST_GeomFromGeoJSON(${JSON.stringify(p.polygon)})::geography) RETURNING id`; return { id: row!.id }; }, ); interface PingParams { vehicleId: string; lat: number; lng: number; recordedAt: string; // device time, ISO 8601 } // Devices sign in too; check that the caller is the device registered to vehicleId. export const ping = api( { expose: true, auth: true, method: "POST", path: "/vehicles/:vehicleId/ping" }, async ({ vehicleId, lat, lng, recordedAt }: PingParams): Promise<{ events: number }> => { const events: ZoneEvent[] = []; { await using tx = await db.begin(); await tx.exec` INSERT INTO vehicles (id) VALUES (${vehicleId}) ON CONFLICT (id) DO NOTHING`; // Lock the vehicle so its pings are applied one at a time, and drop late ones. const v = await tx.queryRow<{ stale: boolean }>` SELECT coalesce(last_ping_at >= ${recordedAt}::timestamptz, false) AS stale FROM vehicles WHERE id = ${vehicleId} FOR UPDATE`; if (v?.stale) return { events: 0 }; const point = `SRID=4326;POINT(${lng} ${lat})`; // Inside now: covered by the polygon, or still within the exit buffer of a zone we were in. const rows = tx.query<{ zone_id: number; was_inside: boolean; is_inside: boolean }>` WITH pt AS (SELECT ${point}::geography AS g) SELECT z.id AS zone_id, (vz.zone_id IS NOT NULL) AS was_inside, CASE WHEN vz.zone_id IS NULL THEN ST_Covers(z.area, pt.g) ELSE ST_DWithin(z.area, pt.g, z.exit_buffer_m) END AS is_inside FROM zones z CROSS JOIN pt LEFT JOIN vehicle_zones vz ON vz.zone_id = z.id AND vz.vehicle_id = ${vehicleId} WHERE vz.zone_id IS NOT NULL OR ST_DWithin(z.area, pt.g, z.exit_buffer_m)`; for await (const r of rows) { if (r.is_inside && !r.was_inside) { events.push({ type: "enter", vehicleId, zoneId: r.zone_id, at: recordedAt, lat, lng }); } else if (!r.is_inside && r.was_inside) { events.push({ type: "exit", vehicleId, zoneId: r.zone_id, at: recordedAt, lat, lng }); } } for (const e of events) { if (e.type === "enter") { await tx.exec` INSERT INTO vehicle_zones (vehicle_id, zone_id, entered_at) VALUES (${vehicleId}, ${e.zoneId}, ${recordedAt}::timestamptz)`; } else { await tx.exec` DELETE FROM vehicle_zones WHERE vehicle_id = ${vehicleId} AND zone_id = ${e.zoneId}`; } } await tx.exec` UPDATE vehicles SET last_ping_at = ${recordedAt}::timestamptz WHERE id = ${vehicleId}`; await tx.commit(); } for (const e of events) await zoneEvents.publish(e); return { events: events.length }; }, );

The candidate query uses ST_DWithin with the zone's buffer, which the GiST index serves, and only then decides per zone: a zone the vehicle was not in needs ST_Covers to enter, a zone it was in only needs to be within the buffer to stay. Events are published after the commit, so a rolled back transaction never announces a crossing. A crash between commit and publish loses that event, and when every crossing must be delivered, write events to an outbox table in the same transaction and publish from there.

Consumers subscribe to zoneEvents from their own services, for example a dock check-in service that opens a visit on enter at a depot zone, or a notification service that tells a customer their delivery is arriving. Each subscription retries on its own, which keeps ingestion fast when a downstream provider is slow.

encore run starts Postgres with PostGIS, so you can draw a depot polygon, post a few pings that cross its edge and confirm that drift within 50 meters of the boundary produces no extra events, with every query visible in the local trace. An agent tuning the buffer or adding a dwell rule changes the query and reruns the same pings locally, with the database and the topic already there.

Best fit: Logistics and delivery teams that need dependable arrival and departure events from mixed GPS sources, feeding dock, billing and customer notification workflows.

Frequently asked questions

How does server-side geofencing work?

Each GPS position from a vehicle or device is checked against stored zone polygons with a point-in-polygon query. The backend keeps the set of zones each vehicle is currently inside, compares the new result to that set and emits an enter event for new zones and an exit event for zones it left.

How do you stop geofence events from flapping at the boundary?

Use hysteresis: a vehicle enters a zone only when its position is inside the polygon, but it exits only when it is further than a buffer, such as 50 meters, outside the polygon. GPS noise near the edge then stops producing enter and exit pairs every few seconds.

Should geofencing run on the device or the server?

Device geofencing saves battery and works offline, but every business rule then lives in the app and each platform limits how many zones you can register. Server-side geofencing works for any number of zones, any GPS source including telematics boxes, and keeps the rules in one place.

How do I build a geofencing backend with Encore?

Store zones as PostGIS geography polygons in an Encore Postgres database, check each ping in a transaction that locks the vehicle row, and publish enter and exit events to an Encore Pub/Sub topic that arrival notifications and billing subscribe to.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders