# Location-aware ranking without a geolocation API: a local IP database in about 100 lines

Some of the listings on our site get a promoted slot above the regular results. Showing that slot to everybody turned out to be a bad idea.

A remote role written in one language is noise for a visitor browsing in another. An on-site role in one country is noise for someone who is clearly somewhere else.

Language we already knew from the page and the filters. Country we did not. Nothing in front of the app was adding a country header at the time, and the browser geolocation prompt is far too heavy for deciding the order of a list.

That left the IP address, and two ways to turn it into a country.

## Why not a hosted API

The quick version is an HTTP call to a geolocation service. It is also a network round trip inside the request that renders your listing page.

You then own a timeout, a retry policy, a rate limit, a cache and an outage mode. You also send every visitor's IP address to a third party, which has to be explained in your privacy policy.

For a country code, none of that is necessary. We use the free IP to Country Lite database from DB-IP, in MaxMind's `.mmdb` format, read with the `maxminddb` package. No key, no sign-up. The licence is CC BY 4.0, so attribution is required.

The file is about 8 MB. It changes monthly. The address never leaves the process.

## The lookup

The public function returns a two-letter code or an empty string. It never raises.

```python
def country(ip: str) -> str:
    try:
        addr = ipaddress.ip_address((ip or "").strip())
    except ValueError:
        return ""
    if not addr.is_global:
        return ""
    reader = get_reader()
    if reader is None:
        return ""
    try:
        row = reader.get(str(addr)) or {}
    except Exception:
        return ""
    return str((row.get("country") or {}).get("iso_code") or "").upper()
```

Every early return is a real case. Test clients send a hostname instead of an address. Local development sends loopback. Health checks come from private ranges.

A missing file or a missing library is also just "unknown". Ranking is a nicety, and a nicety must not be able to take down the page.

## Measuring it, with one surprise

I ran 100,000 random global IPv4 addresses against the current file on an Apple Silicon laptop with Python 3.13. About 93% of them resolved to a country.

- With the C extension (the default mode when it is available): about **3.1 µs per lookup**.
- With the pure Python reader over mmap: about **27 µs per lookup**.
- Parsing the string with `ipaddress` and checking `is_global`: about **3.8 µs**.

So with the extension loaded, the input guard costs more than the database lookup. We kept it anyway. A few microseconds on a page that renders a template is nothing, and the guard keeps junk out of the reader.

The practical advice is to check which reader you actually got. `type(reader).__module__` tells you. A build without the extension still works, just roughly nine times slower in this test, and nothing will warn you.

## Hot reload without a restart

In our setup a background worker downloads new releases, while web processes only read. They need to notice a new file without being restarted.

The reader is held in module state. At most once a minute, a request checks the file's modification time and reopens it if it changed.

```python
def get_reader():
    now = time.time()
    if now - state["checked"] < 60:
        return state["reader"]
    with lock:
        state["checked"] = now
        try:
            mtime = os.path.getmtime(DB_PATH)
        except OSError:
            return state["reader"]
        if state["reader"] is None or mtime != state["mtime"]:
            try:
                state["reader"] = maxminddb.open_database(DB_PATH)
                state["mtime"] = mtime
            except Exception as exc:
                log.warning("geo database did not open: %s", exc)
        return state["reader"]
```

We deliberately do not close the old reader. Another thread may be in the middle of a lookup on it. Dropping the reference and letting the garbage collector clean up is simpler than reference counting by hand.

If the file disappears or the new one fails to open, the old reader keeps serving. Month-old country data beats none.

One trade-off hides in there. `checked` is set before the open finishes, so on a cold start a concurrent request can see "recently checked" with no reader yet. It gets an empty country once. For ranking that is acceptable. If the answer gated anything important, it would not be.

## Refreshing the file safely

The refresh job runs daily and does nothing unless the file is missing or older than 35 days. Downloading is where the sharp edges are.

New releases are published per month, but not necessarily at midnight on the first. So the job tries the current month and falls back to the previous one.

```python
for month in (first_of_month, first_of_month - timedelta(days=1)):
    tmp = tempfile.NamedTemporaryFile(dir=folder, suffix=".tmp", delete=False)
    try:
        with urlopen(url_for(month), timeout=120) as resp:
            with gzip.GzipFile(fileobj=resp) as gz:
                shutil.copyfileobj(gz, tmp)
        tmp.close()
        probe = maxminddb.open_database(tmp.name)
        ok = (probe.get("1.1.1.1") or {}).get("country")
        probe.close()
        if not ok:
            raise ValueError("no country field")
        os.chmod(tmp.name, 0o644)
        os.replace(tmp.name, DB_PATH)
        return True
    finally:
        tmp.close()
        if os.path.exists(tmp.name):
            os.remove(tmp.name)
```

(The real loop also catches and logs the error, so a failed month moves on to the next one.)

Four details are worth copying.

**The temp file lives in the target directory.** `os.replace` is atomic only within one filesystem. A file in the system temp directory may be on another one.

**Probe before you swap.** A truncated download or an unexpected schema should fail in the job, not in a visitor's request. Opening the file and asking for one well-known address is cheap.

**Fix the permissions.** `NamedTemporaryFile` creates files with mode `0600`. If the reader runs as a different user from the writer, the atomic swap succeeds and the site silently loses its country data.

**Always clean up.** After a successful replace the temp name no longer exists, so the `finally` block only removes leftovers from failures.

## Deciding with an uncertain signal

IP geolocation is a hint. VPNs, mobile carriers and corporate proxies all move people around on the map. The ranking rule has to be written with that in mind.

We combine two sources of countries: the one from the IP, and the one the visitor picked in the location filter. Both go into a set, and empty values are discarded.

```python
def promoted_for(item, viewer):
    iso = "" if item.is_remote else iso_code(item.location)
    if iso and viewer["countries"]:
        return iso in viewer["countries"]
    codes = set(item.languages)
    return "en" in codes or bool(codes & viewer["langs"])
```

Remote listings are judged by language. On-site listings with a recognisable country are judged by country. If we cannot tell where the viewer is, we fall back to language instead of hiding things.

An explicit filter adds to the guess rather than competing with it. Someone abroad who is researching another country gets what they asked for.

Nothing is ever removed from the results. A listing that fails the rule still appears as a normal card in normal order. The worst outcome of a wrong guess is a missing highlight.

## Testing it

The rule is a pure function of a listing and a small viewer dictionary, so most tests need no database file at all.

Page-level tests patch the `country` function to return a chosen code and assert which cards carry the promoted class. Separately, one test feeds the real function an empty string, a hostname, a private address and loopback, and expects empty results.

## Caveats

Behind a proxy, the client address comes from a header, and headers can be forged. Accept it only from a proxy you control, and never use a guessed country for access control.

Lite databases are less precise than paid ones, and we have not measured their error rate ourselves. Country level is enough for ordering a list. We would not use it for tax, legal or fraud decisions.

## Takeaways

- A local database removes a network dependency from the request path.
- Make "unknown" a first-class answer and give it a sensible behaviour.
- Reload by modification time, swap files atomically, and validate before swapping.
- Treat location as a ranking signal, not as a gate.

We use this at [SpinHire](https://spinhire.io), a job board for the iGaming industry.
