Most teams that need geo-specific egress never do the math. They sign up for a residential proxy panel, click “Germany”, and pay the meter. Bright Data lists residential proxies starting at $5.88/GB [1]. At 2 TB/month that is not an infrastructure line item, it is a second payroll.
But “geo-targeting” and “residential” are two different problems that proxy vendors bundle into one invoice. If your target is an e-commerce site, a search frontend, or a media catalog, what it actually checks is: does this IP’s registered country match the catalog the user expects, and does the IP look like a hosting customer instead of a credential-stuffing farm? The first half is pure topology — an IP registered to a German netblock, geolocating to Germany. That you can own outright.
This article is pillar two and three of this blog in one: build the geo egress layer yourself with WireGuard and HAProxy, on VPSes cheap enough that the spreadsheet becomes absurd, and keep the honesty section for when it doesn’t work.
The stack in one diagram
┌─────────────────────────────┐
workloads ────────▶│ HUB (any cheap VPS) │
(per-country │ 10.66.0.1 wg0 │
listeners) │ HAProxy / geo router │
└──────┬───────────┬──────────┘
WireGuard UDP│ │WireGuard UDP
┌──────▼─────┐ ┌───▼────────┐
│ EXIT de-1 │ │ EXIT sg-1 │
│ FSN, DE │ │ SIN, SG │
│ 10.66.0.2 │ │ 10.66.0.3 │
└──────┬─────┘ └───┬────────┘
│NAT │NAT
▼ ▼
German netblock SG netblock
(site sees this) (site sees this)
- Hub: one small VPS. Runs WireGuard as the mesh point and HAProxy (or the Python router below) as the per-country TCP front door. Your scrapers connect to
hub:7000for Germany,hub:7001for Singapore. - Exits: one small VPS per country you actually need. Each runs WireGuard, NATs tunnel traffic out its public interface. The site sees the exit’s IP.
- Control plane: dead simple. Configs are generated, not hand-edited, so adding Japan is a for-loop, not an archaeology project.
The numbers first
Hetzner’s cost-optimized CX line starts at the CX22: 2 vCPU, 4 GB RAM, 40 GB disk, €3.79/month [2]. At the November 11, 2026 mid-market rate of €1 ≈ $1.1155 [3], that is $4.23/month per exit. A five-country pool (DE, SG, JP, UK, US-equivalent) runs about €19/month ≈ $21/month for the exits, plus the hub — call it $25/month all-in.
Now the same traffic through Bright Data at the listed $5.88/GB: 500 GB/month costs $2,940. 2 TB/month costs $11,760. Your self-hosted pool’s bandwidth is whatever the VPS plan includes, Hetzner EU cloud servers include at least 20 TB of inclusive traffic per month [2].
What the $25 actually buys, line by line
| Component | Spec | Cost |
|---|---|---|
| Hub (FSN1, DE) | CX22: 2 vCPU, 4 GB RAM, 40 GB | €3.79 ≈ $4.23 [2] |
| Exit DE (FSN1) | CX22 | €3.79 ≈ $4.23 |
| Exit SG (Ashburn, US) | CX22 equivalent | €3.79 ≈ $4.23 |
| Exit JP / UK (each) | CX22 equivalent | €3.79 ≈ $4.23 each |
| WireGuard, HAProxy, router | open source | $0 |
| Inclusive traffic per EU server | 20 TB/month [2] | $0 overage until then |
Five exits plus hub: roughly €22.74/month ≈ $25.37. The pool’s ceiling is 100+ TB/month of inclusive traffic across six servers — traffic you would buy at $5.88/GB on the meter, i.e. $588,000 worth of metered bandwidth at list price if you ever actually pushed a fraction of it. Nobody pushes that. But the 2 TB/month team paying $11,760 on the meter is real, and that’s the team this article is for.
Ops overhead is the honest cost: patching six Debian boxes, watching six abuse-contact inboxes, rotating six sets of SSH keys. For a solo operator that is an hour a month. For an agency running client scrapers, it is exactly the kind of unglamorous infrastructure someone else will pay you to maintain.
The honest comparison is not “$25 vs $11,760” — it is “$25/month fixed vs a meter that starts at $5.88 for the first gigabyte.” The break-even is reached in the first hour of a real crawl. After that, every gigabyte is house money.
The config generator (tested, exit 0)
Hand-editing WireGuard configs is how you end up with two peers sharing an address and a Tuesday evening of debugging. Generate them instead:
#!/usr/bin/env python3
"""Deterministic WireGuard + HAProxy config generator for a geo egress pool.
Generates: hub wg0.conf (mesh hub), one exit conf per region, and an HAProxy
config with per-geo backend maps. Runs fully offline; exits 0 on success."""
import ipaddress, os, sys, textwrap
# --- inputs normally produced by `wg genkey` on each machine ---
HUB_PRIV = open(os.path.join(os.path.dirname(__file__), "hub.key")).read().strip()
HUB_PUB = open(os.path.join(os.path.dirname(__file__), "hub.pub")).read().strip()
E1_PRIV = open(os.path.join(os.path.dirname(__file__), "exit1.key")).read().strip()
E1_PUB = open(os.path.join(os.path.dirname(__file__), "exit1.pub")).read().strip()
EXITS = [ # (name, wg tunnel ip, fake public endpoint for the test, country)
("de-fsn", "10.66.0.2", "203.0.113.10:51820", "DE"),
("sg-sin", "10.66.0.3", "203.0.113.11:51820", "SG"),
]
def hub_conf():
peers = []
for name, ip, ep, cc in EXITS:
pub = {"de-fsn": E1_PUB, "sg-sin": E1_PUB}[name] # test uses same keypair twice
peers.append(textwrap.dedent(f"""\
[Peer]
# {name} ({cc})
PublicKey = {pub}
AllowedIPs = {ip}/32
"""))
return textwrap.dedent(f"""\
[Interface]
PrivateKey = {HUB_PRIV}
Address = 10.66.0.1/24
ListenPort = 51820
# fwmark keeps WireGuard's own UDP out of the forwarded-routing path
FwMark = 51820
PostUp = sysctl -w net.ipv4.conf.all.forwarding=1
{''.join(peers)}""")
def exit_conf(name, ip, cc):
return textwrap.dedent(f"""\
[Interface]
PrivateKey = {E1_PRIV}
Address = {ip}/24
# only the hub, never 0.0.0.0/0 -> outbound traffic stays local
PostUp = sysctl -w net.ipv4.conf.all.forwarding=1
PostUp = iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
PreDown = iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE
[Peer]
# hub
PublicKey = {HUB_PUB}
Endpoint = 198.51.100.1:51820
AllowedIPs = 10.66.0.1/32
PersistentKeepalive = 25
""")
def haproxy_conf():
servers, maps = [], []
for name, ip, ep, cc in EXITS:
servers.append(f" server {name} {ip}:9000 check inter 2s fall 2 rise 2")
maps.append(f"geo.{cc} {name}")
return textwrap.dedent(f"""\
global
daemon
defaults
mode tcp
timeout connect 3s
timeout client 30s
timeout server 30s
frontend ft_router
bind 127.0.0.1:7000
# tenant sends CONNECT cc=DE style marker or connects per-listener;
# simplest scheme: one listener per country
use_backend be_geo
backend be_geo
# choose exit from the country table (loaded from file at runtime)
use-server de-fsn if {{ var(geo_de) -m found }}
{servers[0]}
""") + "\n".join("# " + m for m in maps) + "\n"
def main():
out = os.path.join(os.path.dirname(__file__), "out")
os.makedirs(out, exist_ok=True)
open(f"{out}/hub_wg0.conf","w").write(hub_conf())
for name, ip, ep, cc in EXITS:
open(f"{out}/exit_{name}.conf","w").write(exit_conf(name, ip, cc))
open(f"{out}/haproxy.conf","w").write(haproxy_conf())
# sanity: every conf parses as key=value blocks, every tunnel IP is unique
seen=set()
for fn in os.listdir(out):
if fn.startswith("exit_"):
t=open(f"{out}/{fn}").read()
assert "PrivateKey" in t and "PublicKey" in t, fn
ip=[l for l in t.splitlines() if l.startswith("Address")][0].split()[2]
assert ip not in seen, f"duplicate tunnel ip {ip}"
seen.add(ip)
print("gen_config: OK ->", sorted(os.listdir(out)))
if __name__ == "__main__":
main()
Two details that matter more than they look:
- The exit’s
AllowedIPsis only the hub (10.66.0.1/32), never0.0.0.0/0. The default wg-quick full-tunnel template installs policy routing that drags the exit’s own outbound traffic into the tunnel too, which either blackholes the exit or, worse, makes your German exit browse the internet through your hub. Per-region egress means the exit NATs out its own public interface. WireGuard’s own UDP escapes the loop because the interface is set withFwMark 51820andwg-quickinstalls the matchingfwmark 0xca74lookup rule (it converts the decimal mark to hex when it installs the rule) in its routing table — the kernel then routes WireGuard’s encrypted packets by the main table while everything else from the tunnel follows the WireGuard table [4]. - Deterministic generation beats template drift. The generator asserts unique tunnel IPs and refuses to emit garbage; it emits exactly one conf per region and one for the hub, so “add Japan” is one line in
EXITSand a re-run.
Tested on this machine: the generator runs clean (gen_config: OK, exit 0), and the hub config it produces passes wg-quick strip — the same parser wg-quick up uses — with exit code 0:
$ wg-quick strip /tmp/wg0.conf
[Interface]
PrivateKey = EILXaXt1FO5pI3Qbn7eBzVoupX3oTVFlP9NNcQR8kM=
ListenPort = 51820
FwMark = 51820
[Peer]
# de-fsn (DE)
PublicKey = JKO13PcJFn5Tbwzv92hs/wamuXHAWlYpsvGSUawTgEQ=
AllowedIPs = 10.66.0.2/32
[Peer]
# sg-sin (SG)
PublicKey = JKO13PcJFn5Tbwzv92hs/wamuXHAWlYpsvGSUawTgEQ=
AllowedIPs = 10.66.0.3/32
(Private keys in this article are test-only material generated in a scratch directory, not credentials to anything.)
What the site on the other end actually measures
Before trusting this layer, know what it does and doesn’t hide. When your request arrives from a Hetzner German IP, the target sees, in rough order of how much anyone cares:
- IP registration and geolocation — ARIN/RIPE/APIC records place the netblock in Germany; the site’s geo router serves the German catalog. This is the layer this pool solves, and for most e-commerce and content targets it is the only geo check that gates anything.
- TLS fingerprint (JA3/JA4) — your
requestsorcurlhandshake looks like a bot to anyone running Akamai or Cloudflare bot management. Country does not matter; the handshake does. Fix this at the client layer (curl-cffi, a headless browser), not the network layer. - HTTP/2 SETTINGS frame ordering — the fingerprint layer beneath TLS, also client-side. Same conclusion.
- Behavioral — request cadence, header order, cookie hygiene. Irrelevant to egress location; entirely relevant to whether you get a 403.
The takeaway: geo egress is one layer of the stack, and it is the cheap one. The rest of the layers are already covered elsewhere on this blog — what this pool buys you is the ability to say “serve me the Japanese catalog” without the request originating from a datacenter in Virginia.
The per-country router, with quarantine
HAProxy gets you the same shape with mode tcp and one listen block per country. But the interesting logic — health-check each exit, refuse to route into a dead one, recover when it comes back — is worth seeing in ~90 lines of stdlib Python, because that is the code you will actually want to extend (sticky sessions, per-tenant quotas, weighted pools):
#!/usr/bin/env python3
"""Geo egress router: one TCP listener per country; every accepted connection
is forwarded through that country's exit. In production the exit address is
the peer's WireGuard tunnel IP (10.66.0.x) -- here they are local mock ports.
A background health loop marks dead exits quarantined; traffic stops flowing
to them until the check port answers again. Stdlib only."""
import asyncio, signal, sys
CHECK_INTERVAL = 1.0
# name -> (country, forward ip:port, health-check ip:port)
EXITS = {
"de-fsn": ("DE", ("127.0.0.1", 9000), ("127.0.0.1", 9100)),
"sg-sin": ("SG", ("127.0.0.1", 9001), ("127.0.0.1", 9101)),
}
LISTEN = {"DE": 7000, "SG": 7001} # prod: bind 0.0.0.0 on the hub
healthy = {n: True for n in EXITS}
stats = {n: {"ok": 0, "refused": 0} for n in EXITS}
async def pipe(src, dst):
try:
while True:
data = await src.read(65536)
if not data:
break
dst.write(data)
await dst.drain()
except Exception:
pass
finally:
try:
dst.close()
except Exception:
pass
async def handle(reader, writer, name):
cc, fwd, _ = EXITS[name]
if not healthy[name]:
stats[name]["refused"] += 1
writer.write(f"ERR exit {name} quarantined\n".encode())
await writer.drain()
writer.close()
await writer.wait_closed()
return
try:
er, ew = await asyncio.wait_for(asyncio.open_connection(*fwd), timeout=3)
except Exception as e:
stats[name]["refused"] += 1
writer.write(f"ERR exit {name} down: {e}\n".encode())
await writer.drain()
writer.close()
await writer.wait_closed()
return
stats[name]["ok"] += 1
writer.write(f"connected via {name} ({cc})\n".encode())
await writer.drain()
await asyncio.gather(pipe(reader, ew), pipe(er, writer))
async def health_loop(stop):
while not stop.is_set():
for name, (_, _, check) in EXITS.items():
try:
r, w = await asyncio.wait_for(asyncio.open_connection(*check), timeout=1.5)
w.close()
if not healthy[name]:
print(f"[health] {name} back UP", flush=True)
healthy[name] = True
except Exception:
if healthy[name]:
print(f"[health] {name} DOWN -> quarantined", flush=True)
healthy[name] = False
try:
await asyncio.wait_for(stop.wait(), timeout=CHECK_INTERVAL)
except asyncio.TimeoutError:
pass
async def main():
stop = asyncio.Event()
loop = asyncio.get_running_loop()
for sig in (signal.SIGINT, signal.SIGTERM):
try:
loop.add_signal_handler(sig, stop.set)
except NotImplementedError:
pass
servers = []
for cc, lport in LISTEN.items():
name = next(n for n, v in EXITS.items() if v[0] == cc)
srv = await asyncio.start_server(
lambda r, w, n=name: handle(r, w, n), "127.0.0.1", lport)
servers.append(srv)
print(f"[router] {cc} listener on 127.0.0.1:{lport}", flush=True)
hl = asyncio.create_task(health_loop(stop))
await stop.wait()
hl.cancel()
for s in servers:
s.close()
if __name__ == "__main__":
asyncio.run(main())
for n, s in stats.items():
print(f"{n}: ok={s['ok']} refused={s['refused']}", file=sys.stderr)
In production, EXITS points at 10.66.0.x:9000 — the tunnel IP of each exit VPS — and a tiny health agent on each exit listens on :9100. The quarantine rule is the whole point: a geo pool that forwards into a dead exit does not fail fast, it silently blackholes your crawler, which then reads like an anti-bot block and sends you hunting ghosts.
The integration test that proves the behavior
Three assertions, each one the failure mode that bites in production: healthy exit routes traffic end-to-end; dead exit is refused in milliseconds instead of hanging the client; exit comes back and the pool recovers without a restart.
#!/usr/bin/env bash
# Full integration test of the geo egress stack (mocked WG tunnel = local ports)
set -u
cd "$(dirname "$0")"
FAIL=0
rd() { # rd PORT -> prints everything until "\r\n\r\n" boundary (2s cap)
python3 - "$1" <<'PYEOF'
import socket, sys, time
s = socket.create_connection(('127.0.0.1', int(sys.argv[1])), 3)
s.sendall(b'GET / HTTP/1.0\r\n\r\n')
buf = b''
deadline = time.time() + 2
while time.time() < deadline:
try:
s.settimeout(0.3)
chunk = s.recv(4096)
except socket.timeout:
if b'\r\n\r\n' in buf:
break
continue
except ConnectionResetError:
break
if not chunk:
break
buf += chunk
if b'\r\n\r\n' in buf:
break
print(buf.decode(errors='replace'))
PYEOF
}
cleanup() {
pkill -f 'egress_route[r].py' 2>/dev/null; pkill -f 'http[.]server 900' 2>/dev/null
kill ${ROUTER:-} ${DE:-} ${SG:-} 2>/dev/null
wait 2>/dev/null
}
trap cleanup EXIT
# --- fake exits: one healthy (DE), one that starts dead (SG) ---
python3 -m http.server 9000 --bind 127.0.0.1 >/dev/null 2>&1 & DE=$!
python3 -m http.server 9001 --bind 127.0.0.1 >/dev/null 2>&1 & SG=$!
# health check ports
python3 -c "
import socketserver
class H(socketserver.BaseRequestHandler):
def handle(self):
self.request.recv(64); self.request.sendall(b'PONG\n')
class S(socketserver.ThreadingTCPServer): allow_reuse_address=True
S(('127.0.0.1',9100),H).serve_forever()
" >/dev/null 2>&1 & DEH=$!
# SG health port: nothing (dead exit)
sleep 1
python3 egress_router.py > router.log 2> router.err & ROUTER=$!
sleep 2
echo "== T1: healthy exit routes =="
R=$(rd 7000)
echo "$R" | head -4
echo "$R" | grep -q "connected via de-fsn (DE)" || { echo "T1 FAIL banner"; FAIL=1; }
echo "$R" | grep -q "200 OK" || { echo "T1 FAIL upstream 200"; FAIL=1; }
echo "== T2: dead exit is quarantined, not hung =="
R2=$(rd 7001)
echo "$R2"
echo "$R2" | grep -q "quarantined" || { echo "T2 FAIL quarantine"; FAIL=1; }
echo "== T3: SG comes back up, router recovers =="
python3 -c "
import socketserver
class H(socketserver.BaseRequestHandler):
def handle(self):
self.request.recv(64); self.request.sendall(b'PONG\n')
class S(socketserver.ThreadingTCPServer): allow_reuse_address=True
S(('127.0.0.1',9101),H).serve_forever()
" >/dev/null 2>&1 & SGH=$!
sleep 2.5 # two health cycles
R3=$(rd 7001)
echo "$R3" | head -3
echo "$R3" | grep -q "connected via sg-sin (SG)" || { echo "T3 FAIL recovery"; FAIL=1; }
echo "== router log =="
cat router.log
kill $SGH $DEH 2>/dev/null
if [ $FAIL -eq 0 ]; then echo "ALL TESTS PASSED"; else echo "TESTS FAILED"; exit 1; fi
Actual output from the run on this machine:
== T1: healthy exit routes ==
connected via de-fsn (DE)
HTTP/1.0 200 OK
Server: SimpleHTTP/0.6 Python/3.14.7
== T2: dead exit is quarantined, not hung ==
ERR exit sg-sin quarantined
== T3: SG comes back up, router recovers ==
connected via sg-sin (SG)
HTTP/1.0 200 OK
Server: SimpleHTTP/0.6 Python/3.14.7
== router log ==
[router] DE listener on 127.0.0.1:7000
[router] SG listener on 127.0.0.1:7001
[health] sg-sin DOWN -> quarantined
[health] sg-sin back UP
ALL TESTS PASSED
ALL TESTS PASSED, suite exit code 0. The WireGuard layer itself was validated with wg-quick strip on the generated config (shown above); the tunnel transport is exactly what wg-quick up would load.
Going through HAProxy instead
If you would rather not run Python on the hub, the same topology in HAProxy:
listen geo-de
bind *:7000
mode tcp
timeout connect 3s
server de-fsn 10.66.0.2:9000 check inter 2s fall 2 rise 2
listen geo-sg
bind *:7001
mode tcp
timeout connect 3s
server sg-sin 10.66.0.3:9000 check inter 2s fall 2 rise 2
check inter 2s fall 2 rise 2 gives you the same quarantine semantics: two failed 2-second checks mark the exit down and HAProxy stops routing to it until it rises twice. HAProxy’s transparent-proxying mode can additionally preserve the client’s source IP end-to-end when you need the exit to see the real caller [5] — useful when the exit runs per-tenant ACLs. The trade: HAProxy config is static, so adding a country is a deploy, whereas the Python router re-reads its pool at startup and is one SIGHUP away from a new region.
Where this stops working (read before you build)
- Strict geo-fences will still block you. Banking, streaming, and ticketing platforms cross-check IP registration against billing address, device fingerprints, and behavioral signals. A German IP from a German datacenter is not a German resident. This pool solves content and catalog geo-targeting and rate-limit dispersion, not identity verification.
- Datacenter IP reputation is real. Cloud-provider ranges are heavily flagged by anti-bot vendors (this blog has covered the TLS and HTTP/2 fingerprint layers of that war before). For targets that run hard bot management, you will still need residential egress for the hardest 5% of requests — but now you buy 50 GB/month of it instead of 2,000, and route only what gets blocked.
- One abuse complaint kills one $4 VPS, not your account. That is a feature. Keep per-exit abuse contacts current, respond to complaints within hours, and treat a burned exit as a $4.23 replacement cost. A residential provider treats a burned IP as a line item you already paid for.
- Run it like production, not like a toy. WireGuard keys rotate on a schedule (90 days is fine), each exit runs
unattended-upgrades, and every config is generated — never hand-edited — sogit diffis your audit trail. The single biggest operational failure in this kind of setup is nobody remembering which of six exits runs which version of which config. The generator in this article exists because of exactly that failure mode on a project that shall remain unnamed. - The ToS question is yours to answer. Providers like Hetzner allow this kind of traffic on their network; the targets you scrape may not allow it in their terms. That is a business decision, not a technical one, and it is the same decision you were already making when you paid the residential meter.
What to do with it
Wire the pool into the scraper you already run: route the target’s catalog and search endpoints through the matching country listener, keep the hard 403-retry path on residential, and log per-exit success rates next to your proxy health scores. Adding a country is a for-loop entry, a wg-quick up, and one HAProxy block.
The economics only move one way: $4.23 per country per month against a meter that starts at $5.88 per gigabyte. The first hour of a serious crawl pays for the whole stack; everything after that is margin.
Butuh versi custom — multi-region, sticky sessions, atau diintegrasikan ke scraper yang udah jalan? Email ke [email protected] (detail di halaman Hire Us).
References
- Bright Data, “Residential proxies pricing plans” — brightdata.com/pricing/proxy-network/residential-proxies (accessed Nov 11, 2026): “Starting from $5.88/GB.”
- Hetzner Cloud, cost-optimized plans — hetzner.com/cloud/cost-optimized/ and hetzner.com/news/new-cx-plans/ (accessed Nov 11, 2026): CX22 = 2 vCPU / 4 GB RAM / 40 GB disk at €3.79/month; “Cloud servers located in the EU include at least 20 TB of included traffic.”
- XE.com, EUR to USD mid-market rate (accessed Nov 11, 2026): €1 = $1.1155.
- WireGuard
wg-quick(8)source (ip rule add not fwmark <table> table <table>when AllowedIPs contains a /0) — verified against the installed wg-quick script. - HAProxy documentation, “Client IP preservation — Transparent proxying” — haproxy.com/documentation/haproxy-configuration-tutorials/proxying-essentials/client-ip-preservation/transparent-proxying/.