High-Speed IP-to-Country Geolocation in Python & PostgreSQL Without Paid APIs
Calling an external third-party HTTP GeoIP API on every incoming web request adds 50–150ms of network latency, introduces an external point of failure, and quickly racks up usage bills. By syncing CIDR IP allocation blocks locally via an automated cron job and indexing them with PostgreSQL's native inet / cidr GiST index (or MaxMind GeoLite2 MMDB), you can resolve any IPv4/IPv6 address to a country code in under 0.2 milliseconds.
1. Indexing CIDR Blocks with PostgreSQL GiST (`inet_ops`)
PostgreSQL includes first-class network address types (inet and cidr). Creating a GiST index with inet_ops enables lightning-fast subnet containment queries (>>=):
CREATE TABLE ip_country_blocks (
network cidr PRIMARY KEY,
country_code char(2) NOT NULL
);
CREATE INDEX idx_ip_country_network_gist
ON ip_country_blocks USING gist (network inet_ops);
-- Sub-millisecond lookup for any client IP:
SELECT country_code
FROM ip_country_blocks
WHERE network >>= '203.0.113.42'::inet
LIMIT 1;
2. Automated Weekly Cron Refresh
A lightweight weekly Python cron script downloads updated RIR/GeoLite CIDR tables, loads them into a staging table via COPY FROM STDIN, and swaps the table inside a single atomic transaction so production traffic never experiences lock contention.