SevyDevy

Geofencing System Design: Matching Moving Phones Against Millions of Fences

, Last updated , 22 min read

Summary

  • Geofencing system design answers one question at scale: which fences is this moving phone inside now, and did that just change? A fence is a boundary drawn on a map.
  • Never compare a location ping with every fence. A spatial index, a lookup structure for places, cuts millions of fences to a few candidates. Examples: H3, a grid of hexagon cells, and an R-tree, a tree of boxes.
  • Then run an exact point-in-polygon test, which checks whether a point lies inside a shape, on those few candidates. Cells and boxes only approximate the real fence.
  • A small record per phone and fence turns yes-or-no answers into enter, exit and dwell events. Flapping is the answer flickering near an edge. Hysteresis, separate lines for entering and leaving, plus a time rule stops it.
  • Beginners can stop after the battery section. Engineers get two measured runs: a real fence that got zero H3 cells under the centre-point rule, and a margin-plus-time rule cutting about 20 events per walk to two.

What goes wrong when you check moving phones against millions of fences?

Three things go wrong at once: the checks cost too much, the answers flicker, and the phones run out of battery. Geofencing system design is the work of fixing all three without missing a real arrival.

Picture a common setup. A grocery delivery app in a big Indian city has 2 lakh (200,000) riders, and each rider's phone sends its location every 5 seconds. The app has 30 lakh (3 million) fences: dark stores, which are small warehouses, customer apartment complexes and no-parking zones. The numbers are made up, but the problems are real.

The product wants three messages. When a rider enters a customer's complex, tell the customer the rider is at the gate. When a rider waits two minutes at a dark store, mark the order as waiting for pickup. When the rider leaves the store, mark it picked up.

The first version checks every ping against every fence. That is 40,000 pings a second times 3 million fences, or 120 billion checks a second. No sensible cluster does that.

The second problem shows up even with one fence. GPS readings jump around by several metres. A rider parked near a gate looks inside, then outside, then inside again. This flicker is called flapping, and the customer gets five gate alerts in a minute.

The third problem is the phone. Asking for a precise location every few seconds drains the battery. Android and iOS both offer built-in geofencing that the system runs for you, but each caps how many fences one app may register.

Which words do you need before designing a geofencing system?

You need seven words. Each one appears again in the rest of the guide, always with the delivery app in mind.

  • Geofence: a boundary on a map, stored as a circle or a polygon, which is a shape made of straight edges. Example: the outline of one apartment complex.
  • Ping: one location report from a phone, with latitude, longitude, a timestamp and an accuracy estimate in metres.
  • Point-in-polygon test: an exact check of whether a point lies inside a polygon. It is precise but too slow to run against every fence.
  • Spatial index: a lookup structure that finds the few fences near a point without scanning all of them. It works like the index at the back of a book.
  • Cell: one tile in a grid laid over the whole Earth, with an ID number. Geohash, S2 and H3 are three such grids.
  • R-tree: a tree of bounding boxes. A bounding box is the smallest upright rectangle that holds a shape.
  • Hysteresis: using a different line to switch on than to switch off, so small wobbles near the edge do not flip the answer.

What is geofencing system design, and how does it work end to end?

Geofencing system design is a pipeline with four steps: find candidate fences with an index, confirm them with an exact test, compare with the last known state, and publish events. Each step makes the next one cheap.

The index step turns 3 million fences into a few. The exact test turns those few into a true answer, such as inside fences 812 and 4031. The state step compares that answer with the previous ping and finds what changed.

Only a change becomes an event. Most pings change nothing, so most pings end quietly. That is why the event stream is tiny compared with the ping stream.

Where one rider ping goes in the delivery app

Notice that the fence index lives in memory beside the matchers. The database is the source of truth, but no ping waits on it.

Diagram connections:

  • Rider phone to Ingest gateway (ping)
  • Ingest gateway to Ping stream (append)
  • Ping stream to Matcher workers (consume in order)
  • Fence store to Fence index in memory (build and refresh)
  • Fence index in memory to Matcher workers (candidate fences)
  • Matcher workers to Rider-fence state (read and update)
  • Matcher workers to Event stream (only on change)
  • Event stream to Notifier (send message)
  • Rider phone: Sends a ping every 5 seconds
  • Ingest gateway: Checks the token, drops bad pings
  • Ping stream: Partitioned by rider ID to keep order
  • Matcher workers: Index lookup, exact test, state check
  • Fence index in memory: Cell map or R-tree, rebuilt on fence edits
  • Fence store: PostGIS table, the source of truth
  • Rider-fence state: Inside or outside, since when, streak
  • Event stream: ENTER, EXIT and DWELL only
  • Notifier: Tells the customer the rider is at the gate

The ping stream is split by rider ID on purpose. All pings from one rider then reach the same matcher in order, so that matcher can safely compare each ping with the last one.

How do you find candidate fences fast for each location ping?

You precompute which fences touch each cell or box, then look up only the cell or box the ping falls in. Two families do this well: cell grids and R-trees.

Cell grids turn a location into a key

A cell grid gives every patch of the Earth an ID. You store a map from cell ID to the fences that touch it. For a ping, you compute its cell ID and read one entry.

Geohash interleaves latitude and longitude bits into one number, often written as a short text string. Redis docs say strings with a shared prefix are nearby, but nearby places can have different prefixes.

S2 projects the six faces of a cube onto the Earth and splits each cell into four children, through levels 0 to 30. H3 uses hexagons, plus 12 pentagons at every resolution. Each hexagon has seven children, called aperture 7, and resolutions run from 0 to 15. At resolution 10 the average hexagon is about 0.015 square kilometres, with an edge of about 76 metres.

R-trees group fences by their boxes

An R-tree stores each fence's bounding box and groups nearby boxes into bigger boxes. A query walks down only the branches whose boxes hold the point. It works for any fence shape and needs no cell size choice.

PostGIS, the spatial extension for PostgreSQL, builds its GiST index (a general-purpose index framework in PostgreSQL) as an R-tree. Its docs say spatial indexes store only bounding boxes. The Python library Shapely offers an in-memory R-tree called STRtree.

Ways to find candidate fences (checked against official docs as of 30 October 2026)
OptionWhat it storesGood atWatch out for
Geohash cellsGrid cells named by text stringsSimple keys in any key-value storeNeighbours can have different prefixes
S2 cellsQuadtree cells on six cube faces, 64-bit IDsCovering any shape with mixed cell sizesCell areas at one level vary about twofold
H3 cellsHexagons with 64-bit IDs, 16 resolutionsSimple maps and fast parent lookupsChildren only roughly fill their parent
R-treeBounding boxes in a treeAny shape, any size, no cell size to pickA long diagonal fence gets a big, mostly empty box
Redis GEOPoints in a sorted setCircle or box searches around a pointNo polygon search on the GEOSEARCH page

We tested both families on 20,000 made-up polygon fences with radii of 80 to 300 metres, spread over a 30 kilometre square. With H3 at resolution 10, each fence touched 10.5 cells on average. A ping found 3.6 candidates.

Shapely's STRtree found 2.4 candidates per ping from bounding boxes. Both methods agreed on all 20,000 test pings, and matched a brute-force check of every fence on 500 pings. Our fences overlap a lot, so your counts will differ.

Why does a cell covering still need a point-in-polygon test?

Because hexagons and boxes never line up exactly with a real fence edge. A cell on the edge is partly inside and partly outside, so only an exact test on the real polygon can answer.

A covering is the set of cells you store for one fence. H3 can build it three useful ways. Centre mode keeps cells whose centre point lies inside the fence. Full mode keeps cells entirely inside. Overlap mode keeps every cell that touches the fence.

We ran this on one made-up apartment complex fence of 5.7 hectares (57,000 square metres) using h3 4.5.0 and Shapely 2.2.0. The code below is the exact script we ran. Pause and predict: one resolution 9 hexagon averages about 10.5 hectares. How many centre-mode cells will this smaller fence get?

python
import h3
from shapely.geometry import Point, Polygon

# A made-up fence around an apartment complex, as (lat, lng) pairs
fence = [(12.97160, 77.59460), (12.97175, 77.59720), (12.97010, 77.59745),
         (12.96960, 77.59600), (12.97040, 77.59470)]
shape = h3.LatLngPoly(fence)

for res in (9, 10, 11):
    centre = h3.h3shape_to_cells(shape, res)
    overlap = h3.h3shape_to_cells_experimental(shape, res, contain="overlap")
    full = h3.h3shape_to_cells_experimental(shape, res, contain="full")
    print(res, len(centre), len(overlap), len(full))

# Exact test: Shapely wants (x, y), which is (lng, lat)
exact = Polygon([(lng, lat) for lat, lng in fence])
corner = Point(77.59460, 12.97160)
print(exact.covers(Point(77.5960, 12.9707)), exact.contains(corner), exact.covers(corner))

The output is four lines: "9 0 3 0", "10 3 9 0", "11 25 40 14" and "True False True". Read each of the first three as resolution, then centre, overlap and full cell counts. What just happened? The fence is smaller than one hexagon, so no cell centre landed inside it.

  • At resolution 9, centre mode returns zero cells. If you indexed this fence that way, no rider could ever enter it.
  • At resolution 11, centre mode still missed 1,338 of 15,339 random points that were truly inside. Overlap mode missed none.
  • Full cells are a fast path: a ping in one is inside without an exact test. Only the 26 edge cells at resolution 11 need the polygon check.
  • The corner point is not contained but is covered. A point on the edge counts as outside for contains and inside for covers.

So index with overlap mode, mark full cells, and run the exact test only for edge cells. Choose covers or contains on purpose, and use the same one everywhere.

How do you turn inside-or-outside answers into enter, exit and dwell events?

You keep a tiny record for each rider and fence pair, and emit an event only when that record changes. The record holds the state, the time it began and a streak counter.

ENTER fires when the state goes from outside to inside. EXIT fires on the way back. DWELL fires once when the rider has stayed inside for a set time, such as two minutes at the dark store.

Android uses the same three names. Its docs suggest DWELL instead of ENTER when you get too many alerts from people driving past. The wait before DWELL fires is called the loitering delay.

  • Key the state by rider ID and fence ID, and keep it near the matcher, for example in Redis or in the matcher's own memory with snapshots.
  • Drop pings older than the last one you used. A phone that lost signal may upload a backlog, so old pings can arrive late.
  • Give every event an ID built from rider, fence, type and time. The notifier can then skip duplicates if the stream delivers twice.
  • When a fence is deleted, emit EXIT for riders still inside it, or clear their records. Otherwise their state stays stuck.

How do you stop boundary flapping with hysteresis?

Use two lines instead of one, and ask for a few pings in a row before you believe a change. Enter only when the rider is well inside, and exit only when well outside. Waiting for a change to hold steady is called debouncing.

Think of an air conditioner thermostat that switches on at 26 degrees and off at 24. Temperature is the rider's distance from the fence edge. The two set points are the inner and outer lines, and the gap between them stops constant clicking.

Where the picture breaks: a thermostat reads temperature accurately, but GPS readings jump at random. One wild ping can cross both lines, so you also need the time rule.

One ping through the debounce for one fence

Notice that a single noisy ping can only grow or reset the streak. It can never emit an event on its own.

Diagram connections:

  • New ping arrives to Read rider-fence state (look up)
  • Read rider-fence state to Past the far line? (compare)
  • Past the far line? to Reset streak to 0 (No)
  • Past the far line? to Add 1 to streak (Yes)
  • Add 1 to streak to Streak reached 3? (check)
  • Streak reached 3? to Emit ENTER or EXIT (Yes)
  • Streak reached 3? to Save and wait (No)
  • Reset streak to 0 to Save and wait (store)
  • New ping arrives: Already confirmed as a candidate fence
  • Read rider-fence state: Currently OUT or IN, plus streak
  • Past the far line?: OUT needs inner line, IN needs outer line
  • Reset streak to 0: Wobble near the edge, nothing to report
  • Add 1 to streak: Count pings in a row on the new side
  • Streak reached 3?: About 15 seconds at one ping per 5 s
  • Emit ENTER or EXIT: Flip the state, clear the streak
  • Save and wait: Store the streak for the next ping

Here is the rule as a small function, with a 200 metre square fence on a local metre grid. The inner line is 25 metres inside, the outer line 25 metres outside.

python
from shapely.geometry import Point, box

fence = box(0, 0, 200, 200)  # a 200 m square on a local metre grid
inner, outer = fence.buffer(-25), fence.buffer(25)


def step(state, streak, x, y, need=3):
    p = Point(x, y)
    if state == "OUT":
        streak = streak + 1 if inner.covers(p) else 0
        if streak == need:
            return "IN", 0, "ENTER"
    else:
        streak = streak + 1 if not outer.covers(p) else 0
        if streak == need:
            return "OUT", 0, "EXIT"
    return state, streak, None


state, streak = "OUT", 0
for x in [10, 30, 5, 30, 31, 33, 40, 210, 230, 228, 235]:
    state, streak, event = step(state, streak, x, 100)
    if event:
        print(x, event)

It prints "33 ENTER" and "235 EXIT". The ping at 5 metres resets the entry streak. The ping at 210 metres is outside the fence but inside the outer line, so it never counts towards an exit.

What the simulation showed

We simulated a rider who stands 8 metres inside the edge for three minutes, walks in, then leaves. Each ping had made-up GPS noise with a standard deviation of 15 metres on each axis. We ran 200 random walks.

Our simulation, 200 walks, one ping every 5 seconds (Shapely 2.2.0)
RuleResultCost
Plain inside or outsideAbout 20 ENTER and EXIT events per walk instead of 2None
25 m lines onlyNot exactly one ENTER then one EXIT in 86 of 200 walksNone
25 m lines plus 2 pings in a rowClean pair in 199 of 200 walksEXIT about 25 seconds late
25 m lines plus 3 pings in a rowClean pair in 199 of 200 walksEXIT about 32 seconds late

Lines alone were not enough, because the noise sometimes pushed a ping 33 metres out, past the outer line. The time rule fixed that. Together, the outer line and the time rule delayed EXIT by 25 to 32 seconds. A rider who stands right at the edge may never count as entered, so keep the margin well below the fence size.

Phones do something similar. Apple's archived 2016 region monitoring guide says a crossing is reported only after the device moves a minimum distance past the boundary and stays there at least 20 seconds.

How do phones run geofences without draining the battery?

You hand a short list of fences to the operating system and let it watch them. The system decides how to check location, and wakes your app only on a crossing.

Android's docs say geofencing on most devices uses only network location for triggering, not satellite GPS. They add that turning Wi-Fi on greatly improves accuracy. Both platforms cap how many fences one app may watch.

Built-in phone geofencing, from official docs as of 30 October 2026
QuestionAndroidiOS
Fences per app100 per app, per device user20 conditions of any type
EventsENTER, EXIT and DWELL with a loitering delayCondition becomes satisfied or unsatisfied
Typical delayUsually under 2 minutes, up to 6 if the phone was stillArchived guide: at least 20 seconds past the line
Size adviceRadius of 100 to 150 metres for best resultsArchived guide: for testing, assume a crossing needs about 200 metres past the line
After a rebootYour app must register the fences againMonitoring stops at a reboot and can occur again only after the user unlocks the phone

Android also lets you set notification responsiveness. Its docs say a five minute value means the app checks for entry or exit only once every five minutes, which saves power. The same docs warn that alerts may never arrive with Wi-Fi turned off.

A delivery app has far more than 100 fences, so the phone cannot hold them all. One pattern that fits the limits keeps the full list on the server and sends each phone only the nearest few.

Rotating the nearest fences onto a phone

Notice the big refresh fence: leaving it is the signal to fetch the next set, so the app wakes only when the nearby list goes stale.

Diagram connections:

  • Fence server to Pick nearest fences (phone's last area)
  • Pick nearest fences to Phone OS geofencing (register list)
  • Pick nearest fences to Big refresh fence (also register)
  • Big refresh fence to App wakes up (EXIT means refresh)
  • Phone OS geofencing to App wakes up (crossing)
  • App wakes up to Event API (send event)
  • Event API to Fence server (ask for next set)
  • Fence server: Holds all 30 lakh fences and the index
  • Pick nearest fences: Stay under 100 on Android, 20 on iOS
  • Phone OS geofencing: Watches the fences using cheap signals
  • Big refresh fence: One wide circle around today's area
  • App wakes up: Handles ENTER, EXIT or DWELL
  • Event API: Server confirms and runs the debounce

Riders on shift are a different case. The app already streams their pings for live tracking, so matching on the server adds no new work on the phone. Use phone geofencing for occasional users, such as a customer near a store.

For engineers

Beginners can stop here. You now know the full pipeline: index, exact test, state, debounce and phone limits. The rest covers scaling, PostGIS and Redis, and the interview frame.

How do you scale geofence matching to millions of fences and pings?

Keep the fence index in memory on every matcher, split the pings by rider, and shrink the index with mixed cell sizes. Pings are the hard load, and fences change slowly.

Estimate the index before you build it

Our run gave 10.5 cells per fence at resolution 10 for fences with radii of 80 to 300 metres. For 3 million fences that is about 31.5 million map entries. Measure your own fences, because big zones touch far more cells.

H3's compact step replaces seven sibling cells with their parent. Our 5.7 hectare fence had 149 full cells at resolution 12. After compacting, 71 cells remained, from resolutions 11 and 12.

Walk up the parents, not across the map

H3 docs say geographic containment between levels is approximate, while containment in the ID is exact. We tested it: 7.3 percent of points inside a resolution 9 hexagon had a resolution 10 cell with a different parent.

So never test a ping against a parent hexagon's shape. Compute the ping's cell at your finest resolution, then look up that cell and each of its parent IDs in the map. The ID chain matches how compact built the index.

Split work by rider, update fences in the background

  • Partition the ping stream by rider ID, so one matcher owns each rider's state and sees pings in order.
  • Give every matcher the full read-only index if it fits in memory. If not, shard fences by a coarse cell and route each ping to its shard.
  • When a fence changes, write it to the fence store, rebuild its cells, and publish the change so every matcher swaps it in.
  • Watch two numbers: candidates per ping and exact tests per ping. In our run they were 3.6 and 3.1. A sudden jump means a huge fence or a bad cell size.

Where do PostGIS and Redis fit in a geofencing system?

PostGIS is a good source of truth for fences and for batch checks. Redis GEO is good for circle searches around a point, but not for polygon fences.

In PostGIS, ST_Contains checks that a point is inside a polygon. Its docs say it automatically uses a bounding box test that can use spatial indexes. We ran it on PostgreSQL 16.15 with PostGIS 3.4.2 and 20,000 made-up fences.

The query plan showed an index scan on the GiST index first, then a filter running the exact test. That is the same two steps as before: boxes find candidates, the polygon test decides.

The edge rule matters here too. A point exactly on a fence edge gave false for ST_Contains and true for ST_Covers. The PostGIS docs say polygons do not contain points lying only on their boundary.

Redis stores geo points in a sorted set, using a 52-bit geohash score. As of 30 October 2026, its GEOSEARCH page lists only a circle (BYRADIUS) or an upright box (BYBOX).

You can still use it as a first filter. Store each fence's centre, search a radius as large as the farthest any fence reaches from its centre, then run the exact test. For circle fences, that test is a distance check against each fence's own radius.

In the interview

How do you explain geofencing system design in a system design interview?

Walk the pipeline in order, put numbers on each step, and name the trade-off you chose. Two ideas carry most of the answer: filter then confirm, and stop flapping.

  1. Pin down the load

    Ask how many devices, how often they ping and how many fences exist. Work out pings per second and why checking every fence is impossible.

  2. Name the events

    Define ENTER, EXIT and DWELL, and who consumes them. Ask how late an alert may be, because that sets your debounce.

  3. Choose the index

    Pick H3 or S2 cells for a key-value or stream design, or an R-tree for PostGIS. Say you index by overlap and mark full cells.

  4. Confirm exactly

    Run point-in-polygon only on edge-cell candidates. State whether a point on the edge counts as inside, and keep that choice everywhere.

  5. Keep state per pair

    Store rider and fence state, partition pings by rider for ordering, and drop stale pings. Give events IDs so retries do not duplicate alerts.

  6. Debounce

    Use inner and outer lines plus a few pings in a row. Say the cost out loud: fewer false alerts, a few seconds of delay.

  7. Cover the phone

    Mention the platform limits of 100 fences on Android and 20 on iOS. Rotate the nearest fences onto the phone with a refresh fence.

Questions people ask

What is the difference between geofencing and a proximity service?

Geofencing pushes an event when a moving point crosses a boundary, while a proximity service answers a pull query for nearby places. Proximity asks what is near me now. Geofencing remembers the last answer and reports only changes, such as a rider entering a complex. Both use spatial indexes, but geofencing adds per-device state and debouncing.

Should I use H3, S2 or geohash for geofencing?

Any of them works if you index by overlap and confirm with an exact test. H3 gives simple cell maps and fast parent lookups. S2 covers odd shapes well with mixed cell sizes. Geohash is easy to store as text prefixes. Choose by your tooling, then measure candidates per ping on your real fences.

Why not just use PostGIS for every ping?

You can at small scale, and it is correct, because the GiST index filters by boxes and ST_Contains confirms. At tens of thousands of pings a second, every ping becomes a database query. A better split keeps PostGIS as the source of truth and copies the fences into an in-memory index for the live path.

How big should a geofence be?

Big enough to beat location error. Android's docs recommend a minimum radius of 100 to 150 metres for best results. Your debounce margin must also fit inside the fence, or people standing near the edge never count as entered. For small targets such as one shop door, prefer DWELL with a longer wait.

What is a dwell event in geofencing?

A dwell event fires once when a device has stayed inside a fence for a set time. Android calls that time the loitering delay. Dwell filters out people who only drive past, so it suits pickup points and stores better than a plain enter event.

Why do geofence alerts arrive late on phones?

Because the operating system checks location less often to save battery. Android's docs say latency is usually under 2 minutes and can reach about 6 minutes if the phone was still. Apple's archived guide says the device must stay past the boundary at least 20 seconds before a crossing is reported.

Is a point on the fence edge inside or outside?

It depends on the function you call, so decide once and use it everywhere. In PostGIS and Shapely, contains returns false for a point exactly on the edge, while covers returns true. We checked an edge point on PostGIS 3.4.2 and a corner point on Shapely 2.2.0.