43 Million Locations a Day: Answering 'Is the Vehicle in the Zone?' in a Split Second

It's 7:55 a.m. A parent glances at their phone: "The shuttle has arrived at school." In the same minute, a line pops up on a logistics company's screen: "34 ABC 123 has left the depot," and a courier gets a new order because they just entered a delivery zone. Three different businesses, but the question behind them is the same: which zone is this vehicle in right now?

For one vehicle and one zone, that question takes a glance. The difficulty starts with how often it gets asked. Picture a fleet of 5,000 vehicles, each sending its location every 10 seconds. That's 500 locations per second, 43.2 million per day. If the system has 2,000 zones defined and every location is compared against every zone one by one, that means 86.4 billion comparisons a day. This post explains how that work gets more than a thousand times faster, and what actually breaks things in the field.

The Same 100,000 Locations, Three Different Methods

We ran the numbers ourselves and kept the setup simple enough for anyone to reproduce. We placed 2,000 zones across a 40 x 40 km area, about the size of a large city. The zones have radii between 50 and 600 meters and between 6 and 16 vertices; in other words, they are the size of a schoolyard, a depot, a residential complex, or a small delivery zone. We then dropped 100,000 random locations onto this area and, for each one, answered the question "which zones is it inside?" with three different methods. The sample data is synthetic.

MethodZones checked per locationTotal boundary testsTime (100,000 locations)
Ask every zone one by one2,000200,000,000about 98 s
Check the zone's box first2,000 boxes24,12810.2 s
Check the cell first, then the box1.024,1280.05 s

All three methods give the same answer: 15,284 of the 100,000 locations are inside at least one zone, and 1,206 are inside more than one overlapping zone. The only difference is how much effort it takes to get there.

The first row is the most honest but most exhausting approach: for every location, ask all 2,000 zones "am I inside you?" Rather than running this method on all 100,000 locations, we measured it on 2,000 (1.96 seconds) and multiplied by 50.

The second row adds a small trick. Around each zone we draw a rectangle that fully encloses it. If a location falls outside that rectangle, it can't possibly be inside the zone. Checking the rectangle takes four simple comparisons; checking the zone boundary is a much longer job. The number of heavy tests drops from 200 million to 24,128. But all 2,000 rectangles are still being checked one by one.

The third row divides the map into 500-meter squares and registers each zone, ahead of time, in every square it touches. When a location comes in, the first question is "which square are you in?", and then only the zones registered to that square are checked. For an average location, that works out to exactly 1.0 zone. The time drops from 98 seconds to 0.05 seconds.

The times were measured on an ordinary laptop, on a single core, without any acceleration libraries, and are only meant to give a rough idea. The number that really matters is the machine-independent count of boundary tests: 24,128 instead of 200 million, or roughly eight thousand times less work.

Two counters for every location that lands on the map: the method that asks every zone checks thousands of zones, while the grid method checks only the zones in the square where the location falls
A 10 x 10 km section of the synthetic map. The number of zones each method checks for each location comes from the actual calculation.

Why Is It Hard? Because "Is It Inside?" Costs More Than You'd Think

A zone is a polygon drawn on the map: a boundary with corners, indentations, and protrusions. A computer can't "see" whether a point is inside that boundary; it has to calculate it. The best-known way to do that is a childishly simple idea.

Draw a straight line from the point out to the right and count how many times it crosses the zone boundary. Imagine walking out of a building from somewhere inside: every time you pass through a wall, you go from inside to outside or from outside to inside. If you end up outside and you passed through an odd number of walls, you must have started inside. That's the whole rule: an odd number of crossings means inside, an even number means outside. Computer scientists call this "ray casting."

Lines are drawn to the right from three points in an indented school zone; one and three crossings mean inside, two crossings mean outside
An illustrative zone. Point B, inside the indentation, is outside the zone even though it seems to sit in its "lap."

The idea is simple, but it isn't free. Every time, the computer checks every edge of the boundary one by one. The zones in our example have 11 vertices on average. Real zones, drawn by hand on a map or taken from municipal boundaries, can have hundreds of vertices, and the work grows accordingly.

Now back to scale. In our example, a single boundary test took about half a microsecond. Running the 86.4 billion tests the 5,000-vehicle fleet generates each day at that speed would mean one processor core spending roughly 12 hours a day on this one question alone. With the grid method, the same day's work takes less than half a minute. And this isn't just a cost difference; it's a speed difference. It determines whether the parent's notification arrives seconds after the vehicle reaches the gate, or minutes later because the system couldn't keep up.

The Solution: Ask About the Neighborhood First, Then the Boundary

When you look for an address, you don't walk every street in the city. You find the district first, then the neighborhood, and only then look for the house number. That is exactly the idea behind fast zone checks. The technical name is a "spatial index": essentially, an index for the map.

  • Box: the rectangle drawn around each zone. The cheapest way to say "this location is definitely not in this zone."
  • Grid: dividing the map into equal squares. Finding which square a location is in takes a single division, because the squares' positions are fixed from the start.
  • Exact test: boundary crossing counts are done only for the few zones that pass through both of these filters.

This two-stage approach isn't an invention; it's the industry standard. The documentation for the open-source spatial database PostGIS, for example, explains that the index stores the boxes surrounding the shapes rather than the shapes themselves, and that the exact test runs only on records whose boxes match.

Why Hexagons Instead of Squares?

A square grid has a small flaw: a square has 8 neighbors, and they aren't all the same distance away. The distance to a square that shares an edge differs from the distance to one that shares only a corner. Hexagons, the reason bees build honeycombs, don't have this problem. A hexagon has 6 neighbors, and all of them are the same distance from its center. Movement calculations like "the vehicle moved from this cell to its neighbor" and questions like "everything within 1 km of this point" come out much cleaner with hexagons.

In 2018, Uber released this idea as open source under the name H3. H3 divides the entire world into hexagons at 16 different levels of detail. At each level, a cell is roughly one-seventh the size of a cell at the level above. A few examples:

  • Resolution 7: average edge 1.4 km, area about 5.2 km². The size of a district.
  • Resolution 9: average edge about 201 m, area about 0.1 km². A neighborhood block spanning a few streets.
  • Resolution 10: average edge about 76 m. The scale of a schoolyard or a depot.

A small detail: it's impossible to tile a sphere perfectly with hexagons alone. That is why H3 has exactly 12 pentagon cells alongside the hexagons at every level.

On a map with a hexagonal grid, the hexagon of an incoming location lights up, and only the zones registered to that hexagon turn orange and get checked
Illustrative drawing: not the H3 library, but a simple hexagonal grid we wrote using the same idea. The zones come from synthetic data.

Four Things That Break It in Real Life

Answering fast is half the job. The other half is making sure the answer means the right thing in the field.

1. GPS Jitters, and Notifications Flicker

According to the US government's GPS website, GPS-enabled smartphones are typically accurate to within a 4.9-meter radius under open sky; near buildings, bridges, and trees, that accuracy gets worse. Those few meters make a big difference for a vehicle waiting right next to a boundary.

We calculated this, too. A school shuttle waits 3 meters inside the school zone's boundary for 10 minutes, sending its location every 10 seconds; that's 60 readings. We simulated this wait 2,000 times. For open sky, we assumed an error such that about 95 percent of readings fall within 4.9 meters; between buildings, we assumed twice that error.

  • Under open sky: each reading has a 6.7 percent chance of appearing outside. A system that trusts every reading produces an average of 7.3 "entered" or "exited" notifications per wait, even though the vehicle never moves.
  • Between buildings: that chance rises to 22.7 percent, and false notifications per wait rise to an average of 20.6.

The fix is what the thermostat on a home boiler does. A thermostat doesn't switch the boiler on and off every time the room temperature wobbles by a tenth of a degree; it waits for a certain range. In zone checks, this has two counterparts: accept a change of state only after it has been confirmed for 30 seconds in a row (3 readings), and wait for the vehicle to move 10 meters outside the boundary before saying "exited." The technical term is "hysteresis." The 30-second rule alone cuts false notifications between buildings to 0.98 per wait. With the buffer added, not a single false notification appears in any run of the simulation. The cost is that real entries and exits are also reported about 30 seconds late. That delay is a business decision that should be chosen according to the type of work.

GPS readings from a shuttle waiting 3 meters inside the school zone boundary jump to both sides of the boundary; the method that trusts every reading produces 20 notifications, the 30-second rule 2, and the buffered rule zero
A single 10-minute wait taken from the simulation (between-buildings scenario). The vehicle never moves.

2. Zones Don't Fit Neatly Into Cells

Grid size is a balancing act. In our example, with 500-meter squares, each zone was registered in 3.2 squares on average, and 1.0 zone was checked per location on average. Shrinking the squares to 250 meters raised registrations per zone to 7.0 and lowered zones checked to 0.54. Enlarging them to 5 kilometers dropped registrations to 1.2, but zones checked per location shot up to 35.6. A grid that's too fine means a huge index; a grid that's too coarse means a crowded neighborhood.

The second trap is sneakier: forgetting the edge cells when registering a zone to cells. According to its documentation, H3's function for converting a polygon to cells selects the cells whose centers fall inside the polygon. If cells that touch the zone but have their centers outside it are left off the list, the system will never see a vehicle at the edge of the zone. When registering, these edge cells, and zones smaller than a cell, need to be added separately.

3. Zones and Rules Change

When the operations manager redraws the depot zone in the dashboard, the index has to be updated immediately as well. The harder question is this: if the vehicle is inside the old boundary but outside the new one at that exact moment, should it be reported as "exited"? The answer is a business decision, not a software one, but it has to be made in advance.

Rules usually depend on more than location, too. A "left the depot" alarm matters outside working hours and is noise during them. School shuttle notifications should go quiet on holidays. For trucks crossing borders, which country's clock defines "working hours" also needs to be settled up front. A good system stores time in a single common clock and evaluates the rule in the zone's local time.

4. Locations Don't Arrive in Order

When a vehicle enters a tunnel or loses coverage, the device buffers its locations and sends them all at once when the connection returns. If the system processes them in order of arrival, it may conclude that the vehicle left a zone without ever entering, or entered it twice. The right approach is to sort each location by the time the device recorded it, discard a location if it arrives twice, and flag late arrivals separately. Learning at 8:15 that a vehicle "entered the zone at 8:02 a.m." isn't an error; recording it as having entered at 8:15 is.

Does Every Business Need This?

No. For a fleet of 20 vehicles and 10 zones, even if every vehicle sends its location every 10 seconds, that's only 20 boundary tests per second. Any server handles that load without noticing. Here the real investment isn't speed but the right rules against the four traps above: jitter protection, working-hours rules, and ordering.

A spatial index becomes indispensable once vehicles number in the thousands and zones in the hundreds, when customers draw zones freely, and when notifications need to go out within seconds. In most cases you don't need to write anything from scratch, either; spatial databases like PostGIS and mature libraries like H3 provide most of this out of the box. The engineering effort goes into combining these pieces correctly with the business's rules. On our Vehicle tracking system software page, we describe the general structure of a system like this.

For developers: a zone index with H3

The example below was written with the functions in version 4.x of h3-java, Uber's official Java binding. Each zone is registered to the hexagons whose centers fall inside it and, so that edges aren't missed, to their neighbors as well. When a location comes in, only the zones registered to that hexagon go through the exact test.

H3Core h3 = H3Core.newInstance();
int res = 9;
Map<Long, Set<Zone>> index = new HashMap<>();

for (Zone zone : zones) {
    for (long cell : h3.polygonToCells(zone.border(), List.of(), res)) {
        for (long near : h3.gridDisk(cell, 1)) {
            index.computeIfAbsent(near, k -> new HashSet<>()).add(zone);
        }
    }
}

long cell = h3.latLngToCell(lat, lng, res);
List<Zone> inside = index.getOrDefault(cell, Set.of()).stream()
        .filter(zone -> zone.contains(lat, lng)).toList();

zone.border() returns a List<LatLng>; zone.contains is your own method that performs the ray casting test. Zones smaller than a hexagon may return no cells at all from polygonToCells; for these, the cells of their vertices, found with latLngToCell, should also be added.

Sources

Note: The 2,000 zones, 100,000 locations, and school shuttle wait in this post are synthetic data; the GPS error values are assumptions based on the typical 4.9-meter figure from gps.gov. Times were measured on a single laptop and are only meant to give a rough idea. The hexagon animation and the ray casting drawing are illustrative. The figures do not represent a real customer's operation.