Backend Engineer Guide: Sub-Millisecond IP-to-Country Geolocation in Python & PostgreSQL Without Paid Third-Party APIs
Calling an external HTTP IP-geolocation API on every incoming request adds 50ms–200ms of network latency, creates a single point of failure during checkout or localization routing, and racks up per-request SaaS fees. As a Senior Backend Engineer, I resolve client IPv4 and IPv6 addresses to ISO country codes in under 0.3 milliseconds using native PostgreSQL `inet`/`cidr` GiST indexes or memory-mapped binary radix trees (`maxminddb` / GeoLite2 MMDB).
1. Sub-Millisecond CIDR Containment Lookups in PostgreSQL (`inet_ops` GiST)
A naive `WHERE ip_int BETWEEN start_ip AND end_ip` query on a B-Tree index forces PostgreSQL to scan half the index because B-Trees cannot efficiently bound two independent range endpoints simultaneously. Instead, store IP blocks using PostgreSQL's native `cidr` type indexed with a GiST `inet_ops` index and query with the `>>=` (contains or equals) operator:
-- Create table of CIDR blocks mapped to ISO-3166-1 alpha-2 country codes
CREATE TABLE geoip_country_blocks (
network_cidr cidr PRIMARY KEY,
country_code char(2) NOT NULL
);
-- GiST index with inet_ops enables O(log N) prefix containment lookups
CREATE INDEX CONCURRENTLY idx_geoip_cidr_gist
ON geoip_country_blocks USING GIST (network_cidr inet_ops);
-- Lookup client IP in < 0.3ms
SELECT country_code
FROM geoip_country_blocks
WHERE network_cidr >>= '203.0.113.42'::inet
LIMIT 1;
2. Extracting Verified Client IPs Behind Cloud Run, Cloudflare & AWS ALB
Never trust the raw `X-Forwarded-For` header blindly if a client can spoof leading entries. In production behind Google Cloud Load Balancing / Cloud Run or Cloudflare, read `CF-Connecting-IP` (when authenticated via origin rules) or the right-most untrusted hop in `X-Forwarded-For`.
3. Related Backend Engineering Guides
- Hire a Senior Backend Engineer: Python, Django, FastAPI, Golang & PostgreSQL Pillar Guide
- Backend & Full Stack Engineer Guide: Fixing Slow PostgreSQL Queries & APIs
⚡ Hire Aldian Fazrihady — Senior Cloud, GCP, Backend, AI Application & Full Stack Engineer
Need production cloud architecture, GCP/AWS infrastructure, high-throughput backend systems, AI agents, or full stack web engineering? Book a 1-Day Programming Sprint for $100 USD (International Card / Apple Pay) or Rp 1,000,000 (Indonesian QRIS / Bank Virtual Account), or hire directly on Upwork:
Book $100 / Rp 1M 1-Day Sprint → Hire on Upwork (100% Job Success) →