November's monitoring graphs showed a strange staircase: our geofence service's CPU usage jumped up a step with every big customer that came on board. It was 34 percent in September, 52 in October and 85 by the end of November. The new customer arriving in December had 4,000 vehicles and 900 geofence definitions. Simple multiplication said this service would hit the wall in January. Nobody got woken up by a midnight alert; this time we saw the disaster coming on the graph, and that's a rare luxury.
On paper, geofencing is simple: the customer draws a polygon on the map and says, "let me know when my vehicle enters or leaves this area." The engine's job is to know the answer to that question for every location that streams in. Our stream averaged 1,200 locations per second, and 21,000 active geofence definitions had piled up in the system.
Anatomy of a Naive Engine
The first version, to be honest, was what anyone would write first: whenever a location arrives, run a point-in-polygon test against every geofence belonging to that vehicle's customer. The average customer had 40 geofences, so that's 1,200 × 40 = 48,000 polygon tests per second. The cost per test wasn't trivial either: the ray casting algorithm does an intersection calculation for every edge of the polygon. Customers loved drawing detailed shapes on the map, like provincial borders, and polygons with 200-400 vertices were commonplace. A rough calculation: 48,000 tests per second × an average of 250 edges = 12 million intersection calculations. It was obvious where the CPU was going.
The Art of Saying No Cheaply
The first rule of optimization: if the answer to an expensive question is mostly no, find a cheap way to say no. The overwhelming majority of locations aren't even near any geofence. A bounding box (the smallest rectangle enclosing the polygon), computed once and stored for each geofence, can say "this point isn't even in this geofence's neighborhood" with four comparisons. This pre-filter alone eliminated 97 percent of ray casting calls, and CPU dropped from 85 to 31.
One subtlety of the bounding box is the buffer margin: to account for GPS error, we expanded the rectangle by 20 meters in every direction. That way, points very close to the boundary don't get thrown out by the pre-filter before they reach the real test. A cheap no must never be a wrong no.
But as scale grew, the bounding box scan was still linear: for a customer with 900 geofences, that's 900 rectangle checks for every location. As a second layer, we built a grid index that divides the world into cells. Each geofence is registered in the cells it covers; when a location arrives, the point's cell is computed first (two division operations), and only the geofences registered in that cell go onto the candidate list. The average number of candidates dropped from 40 to 1.3. We tried an R-tree as well. Query performance was similar, but the grid's code can be written and understood in half a day, and updating it when geofences are added or removed is much simpler. We chose debuggability over a shiny library.
We also tackled vertex counts separately. Most of the 400-vertex polygons users drew were shapes that didn't deserve that much detail; the map tool was turning every mouse movement directly into vertices. We added Douglas-Peucker simplification at save time: with a 5-meter tolerance, it cuts the vertex count to a quarter on average without breaking the shape's visual integrity. We show the user a preview of the simplified version and ask them to approve it, so there's no "the shape I drew has changed" surprise. We also stopped converting circular geofences to polygons. For a circle stored as a center and a radius, the inside-or-not test is a single distance comparison, and circles make up 30 percent of the total. Accepting input as-is is courtesy; processing it as-is is waste.

We Sharpened Ray Casting Itself, Too
Once the candidate count dropped, the cost per test came to the fore. We made two fixes. Instead of recomputing polygon edges on every test, we extracted the edge list in advance when the geofence was saved and kept it in memory. And we converted coordinates from double-precision degrees to integers multiplied by 1e7, which both sped up the intersection arithmetic and put an end to floating-point precision surprises. With these two changes, the average time for a single test dropped from 4.1 microseconds to 0.9. The overall picture: the old engine ate 85 percent CPU at 48,000 tests per second; the new engine handles the same load with 6 percent of a single core and, in a synthetic test, processes 50,000 point-in-polygon tests per second with a p99 latency of 4 milliseconds.
How we rolled the new engine out to production is also an important part of the story, because geofence alerts are tied to our customers' operational processes, and a false alert and a missed alert both cost real money. We ran the new engine in shadow mode for three weeks: every location went through both the old and the new engine, only the old engine's result went to users, and the differences between the two were logged. In the first week, those differences caught two real bugs. One was lurking in points on the boundary: the old engine counted a point exactly on the boundary as inside, and the new one counted it as outside. We set the rule "the boundary counts as inside" and aligned both. The other wasn't as exotic as the equator, but it mattered to us: on badly drawn, self-intersecting polygons, the two engines were singing different tunes. The permanent fix for this wasn't in the engine but at the front door; we now validate the geometry when a geofence is saved and immediately flag a self-intersecting polygon back to the user.

The Really Hard Part: Jittery GPS and Flapping Alerts
Once the engine got faster, a sneakier problem surfaced: accuracy. GPS points wander by 5-15 meters, so a vehicle parked on a geofence boundary could produce "entered/exited" three times a minute from consecutive points. One customer had received 74 SMS messages in a single night. The solution is hysteresis: we declare a state change not on a single point but on two consecutive consistent points, or on a single point that lands at least 25 meters inside or outside the boundary. Alert counts went back to normal, nobody missed a real entry, and our relationship with that customer was saved.

The memory side was also worth thinking through. The precomputed edge lists, bounding boxes and grid cell registrations for 21,000 geofences take up 380 MB in total, and all of it lives in process memory. There are no trips to the database; when geofences are added or deleted, a small change stream updates the in-memory copy. Early on, out of unnecessary engineering enthusiasm, we had debated putting it all in Redis. The math turned out to be simple: a query that makes a round trip over the network, however fast, can't compete with local memory access measured in a few hundred nanoseconds, and 380 MB is nothing for a server. Every data structure has a place where it naturally lives; for this engine, that place was process memory.
Capacity planning now works on paper, too: since the engine handles 50,000 tests per second on a single core and, thanks to the grid, the number of tests per vehicle is close to constant, our customer projection for the next two years stays within a single server's comfort zone. That staircase graph is now a flat line. I check it once a month looking for a step, and I don't find one.
The takeaway I've kept from these three months of work is this: in performance problems, scaling up hardware is a legitimate tool, but even when it seems to be its turn, there are usually still 10-50x gains on the table at the algorithm layer. Without adding a single server, just by changing data structures, we gained 14x capacity. If you're working with spatial data and want to dig into the guts of your engine together, you can write to me here. I never get tired of hearing polygon stories.