Console Login

Hybrid cloud and a local database: WireGuard link, latency and GDPR

The problem

A common hybrid layout has the application tier in a hyperscaler region (for example Frankfurt) while the users, and sometimes the legal requirements, sit in Norway. Two things go wrong at the same time:

  • Slow pages. Each database round trip crosses a national border. Pages that issue many sequential queries, or microservice chains with many internal calls, multiply that delay.
  • Unclear placement of personal data. Tables with personal data end up in whatever region the first deployment used, and nobody decided that on purpose.

A frequent response is to move the database to a local VPS and connect it to the cloud workload with a VPN. That works, but popular write-ups of this pattern contain several mistakes: a serverless function is said to reach a tunnel address directly, forwarding is enabled in a way that does not survive a reboot, an I/O scheduler is changed on the wrong device, and a tunnel is presented as if it removed latency. The sections below separate what holds from what does not.

Why it happens

Distance, not bandwidth

Round-trip time between two sites is bounded by the signal speed in fibre and by the routing path. Bandwidth does not change it. A query that needs one round trip pays that cost once; an application that issues dozens of sequential queries per request pays it dozens of times. Moving only the database away from the application, or only the application away from the users, makes the cost visible.

Accidental placement

Multi-cloud setups are often the result of independent decisions (a SaaS tool, a test cluster, a legacy rack), not of a design. Without an explicit rule such as "the database lives next to the application that queries it, and personal data lives where policy says", components drift apart.

Data location is a legal input, not a guarantee

Norway applies the GDPR through the EEA Agreement. After the Schrems II ruling (CJEU, C-311/18, 2020), transfers of personal data to providers subject to third-country access laws need a valid transfer tool and, where necessary, supplementary measures. Storing the data with a local provider reduces exposure, but it does not settle the question by itself: who controls the provider, who holds the encryption keys and who can access the data all matter. Only truly anonymous data falls outside the GDPR; pseudonymised data is still personal data.

Source of truth

The tunnel part of the fix relies on the WireGuard project's own documentation: the WireGuard Quick Start. It confirms the following:

  • Keys are base64-encoded and are created with wg genkey; the public key is derived from the private key with wg pubkey.
  • The key files should be created under a restrictive umask 077, and key generation can be done in one pipeline with tee.
  • The wg-quick tool automates the routine bring-up and tear-down that would otherwise need manual wg and ip commands.

For the remaining details, consult the primary references by name: the wg-quick(8) manual page (what SaveConfig, PostUp and the route handling of AllowedIPs do), the PostgreSQL manual chapters on listen_addresses and pg_hba.conf, the Linux kernel documentation for BBR and block-layer I/O schedulers, and the EDPB Recommendations 01/2020 on supplementary measures for the legal side. Those pages were not re-checked for this article, so verify them against the version in use.

Fix options

OptionWhat it doesMain drawback
Colocate application and databaseBoth tiers in the same region or site, no cross-border queriesThe tier that stays far from users still pays distance on each user request
WireGuard tunnel between a gateway in the cloud network and a local database hostEncrypted private path over the public internet, small configuration, kernel-level implementationDoes not reduce distance; the gateway is an extra component to run and monitor
Managed IPsec site-to-site VPNProvider-operated tunnel endpoint with its own routing integrationMore configuration, provider-specific billing and limits
Direct TLS to the database over the internetNo tunnel at all; the database is reachable on a public addressPublic attack surface; needs strict firewalling and certificate management
Read replica or cache near the applicationReads stay local, writes go to the primaryReplication lag; personal data is copied into the other location

Why this fix

The first rule is to colocate chatty components. Whatever talks to the database many times per request belongs next to it. The tunnel is then used for the remaining paths: less frequent calls, batch jobs, or a small number of services in the cloud that must read or write the data that has to stay local.

For that remaining path, a WireGuard tunnel with a single gateway is the smallest solution that keeps the database off the public internet. The database listens only on the tunnel address, so nothing else can reach it. Authentication is by key pair, and the configuration is a few lines per side.

Two corrections apply to many published examples:

  • Serverless functions do not run WireGuard. A function cannot hold a tunnel interface. It is attached to the cloud network (VPC) and reaches the database through a routed path to a WireGuard gateway instance inside that network. The database address is then reached via a route, not as a tunnel peer of the function.
  • NAT and forwarding on the database host are not needed. The database host terminates the tunnel and is the destination. Masquerading rules and forwarding there only widen what the host will route. Forwarding belongs on the gateway.

Applying the fix

The commands below are a procedure to apply; no output is reproduced here. Addresses in 10.100.0.0/24 are the tunnel, 10.20.0.0/16 stands for the cloud network CIDR and 203.0.113.10 for the public address of the database host. Replace all of them, and make sure the cloud CIDR does not overlap the tunnel range.

1. Install and create keys on both hosts

sudo apt install wireguard
umask 077
wg genkey | tee privatekey | wg pubkey > publickey

2. Database host: /etc/wireguard/wg0.conf

No SaveConfig is used. With it enabled, the running state is written back to the file on shutdown and hand edits can be overwritten.

[Interface]
Address = 10.100.0.1/24
ListenPort = 51820
PrivateKey = <DB_HOST_PRIVATE_KEY>

[Peer]
# gateway inside the cloud network
PublicKey = <GATEWAY_PUBLIC_KEY>
AllowedIPs = 10.100.0.2/32, 10.20.0.0/16

The second AllowedIPs entry makes wg-quick install a route so replies to cloud addresses go back through the tunnel.

3. Gateway in the cloud network: /etc/wireguard/wg0.conf

[Interface]
Address = 10.100.0.2/32
PrivateKey = <GATEWAY_PRIVATE_KEY>

[Peer]
PublicKey = <DB_HOST_PUBLIC_KEY>
Endpoint = 203.0.113.10:51820
AllowedIPs = 10.100.0.1/32
PersistentKeepalive = 25

4. Forwarding on the gateway only, persistent

echo 'net.ipv4.ip_forward = 1' | sudo tee /etc/sysctl.d/90-forward.conf
sudo sysctl --system

Writing to /proc/sys/net/ipv4/ip_forward directly, as some guides do, is lost at reboot.

5. Cloud routing for the gateway (AWS CLI example)

An instance that forwards traffic must have the source/destination check disabled, and the route tables used by the workloads need a route for the tunnel range pointing at the gateway.

aws ec2 modify-instance-attribute --instance-id <GATEWAY_INSTANCE_ID> --no-source-dest-check
aws ec2 create-route --route-table-id <ROUTE_TABLE_ID> --destination-cidr-block 10.100.0.0/24 --instance-id <GATEWAY_INSTANCE_ID>

The security group of the functions or containers must allow outbound TCP 5432, and the gateway must accept traffic from them.

6. Open the UDP port on the database host and start the tunnel

sudo ufw allow 51820/udp
sudo systemctl enable --now wg-quick@wg0

Run the same systemctl command on the gateway.

7. Bind PostgreSQL to the tunnel address only

In postgresql.conf:

listen_addresses = '10.100.0.1'

In pg_hba.conf, allow only the application role from the cloud network, with password hashing by SCRAM:

host    appdb    appuser    10.20.0.0/16    scram-sha-256

Because the address only exists once the tunnel is up, order the services. Create a drop-in for the unit that runs the cluster (on Debian and Ubuntu, for example postgresql@16-main):

sudo systemctl edit postgresql@16-main
[Unit]
[email protected]
[email protected]
sudo systemctl restart postgresql@16-main

8. Verify the tunnel and the query path

sudo wg show
ping -c 3 10.100.0.1
psql "host=10.100.0.1 dbname=appdb user=appuser sslmode=require" -c "select 1"

A working tunnel shows a recent handshake for the peer in wg show. For measurement, use the path the application really uses. Pinging a cloud provider's API hostname says little about a database connection. A TCP probe to the database port is closer:

mtr -rwbc 50 -T -P 5432 10.100.0.1

Inside psql, \timing shows the time of real statements.

9. Optional host tuning

BBR needs a kernel of version 4.9 or later and the fq queueing discipline. It mainly helps throughput on lossy long-distance paths and does not lower the round-trip time. Put the settings in a file under /etc/sysctl.d/:

echo 'net.core.default_qdisc = fq' | sudo tee /etc/sysctl.d/91-bbr.conf
echo 'net.ipv4.tcp_congestion_control = bbr' | sudo tee -a /etc/sysctl.d/91-bbr.conf
sudo sysctl --system
sysctl net.ipv4.tcp_congestion_control

For the I/O scheduler, look at the device that is actually in use. A virtio disk is typically vda, while a directly attached NVMe device is nvme0n1. The kernel picks a sensible default for multi-queue devices, so a change is only needed after measuring. Writing as root through sudo echo ... > fails because the redirect runs unprivileged, and a manual write is lost at reboot. Check first, then persist with a udev rule if required:

cat /sys/block/vda/queue/scheduler
cat /sys/block/nvme0n1/queue/scheduler
# /etc/udev/rules.d/60-io-scheduler.rules
ACTION=="add|change", KERNEL=="nvme[0-9]*n[0-9]*", ATTR{queue/scheduler}="none"

Review

What the approach gives

  • A private, key-authenticated path to a database that is not exposed on a public address.
  • A clear placement rule: personal data stays on the local host, while the cloud side handles stateless or non-personal work.
  • A small configuration surface compared with an IPsec setup.

Limits

  • The tunnel does not remove distance. If the application stays in a distant region and keeps issuing many queries per request, it stays slow. Colocate such components, or cut the number of queries.
  • The gateway is a single point of failure unless it is duplicated, and tunnel throughput is limited by the gateway instance and by the default tunnel MTU, which must be accounted for in the path.
  • Data location is not compliance. Encryption with keys kept outside the provider is one of the supplementary measures discussed by the EDPB, but the legal assessment of a transfer remains a separate task for the data protection officer or counsel.
  • Cost claims need a calculation. Egress pricing, flat versus per-second compute and storage performance differ per provider and plan. Compare current price lists for the real traffic profile.

When to choose another method

Use a managed site-to-site VPN if the organisation requires provider-supported tunnels or already runs IPsec. Use a replica or cache if reads dominate and the data may legally be copied. Run everything in one location if the cross-site design has no clear reason to exist.