> ## Content Index
> Fetch the complete content index at: https://sparsh.blog/llms.txt
> Use this file to discover other available public pages before exploring further.

# Build a password manager that survives losing a server
- URL: https://sparsh.blog/highly-available-vaultwarden/
- Published: 2026-11-28T18:44:16.000Z
- Updated: 2026-11-28T20:49:01.000Z
- Description: A step-by-step guide to self-hosting Vaultwarden with automatic failover, using Patroni, etcd, HAProxy and Tailscale across two home servers and Oracle's free tier.
- Author: Sparsh Gupta
- Tags: Homelab

Build a password manager that survives losing a server

This is the setup I run, written up so you can build your own. Vaultwarden on Postgres, with automatic failover between two machines at home and a free Oracle VM as the tie-breaker. Every config below comes from my servers, with the secrets swapped out.

By **Sparsh Gupta**29 November 202623 min read

The vault cluster Your devices reach one private address. It points at whichever of the two home servers holds the database leader key. The leader streams every change to the standby, and all three machines exchange etcd heartbeats so they can agree on who leads. 

Leader **Lucknow** Simulated time **0 s** 

Take Lucknow offline 

This is what you're building. Press the button to watch it fail over, sped up about 30 times. Blue dots are devices talking to the vault, green is data being copied to the standby, grey is etcd checking that everyone is still there.

The guide

- [Before you start](#start)
- [1Connect the machines](#tailscale)
- [2etcd, the referee](#etcd)
- [3Postgres and Patroni](#patroni)
- [4HAProxy finds the primary](#haproxy)
- [5Vaultwarden and Traefik](#app)
- [6One address that follows](#front-door)
- [7Backups you've restored](#backups)
- [8Break it on purpose](#drills)
- [Things that will bite you](#gotchas)
- [What it can't do](#limits)
- [It's Kubernetes, by hand](#kubernetes)

The guide 
- [Before you start](#start)
- [1Connect the machines](#tailscale)
- [2etcd, the referee](#etcd)
- [3Postgres and Patroni](#patroni)
- [4HAProxy finds the primary](#haproxy)
- [5Vaultwarden and Traefik](#app)
- [6One address that follows](#front-door)
- [7Backups you've restored](#backups)
- [8Break it on purpose](#drills)
- [Things that will bite you](#gotchas)
- [What it can't do](#limits)
- [It's Kubernetes, by hand](#kubernetes)

**The idea** Both home servers run the whole stack. Patroni keeps one Postgres primary and one synchronous copy, etcd on three machines decides which is which, and a Tailscale Service gives your devices one private address that always lands on the primary. Nothing is open to the internet, and it costs me nothing a month.

## [Before you start](#start)

I wanted a password manager I control, that works properly with AutoFill and passkeys on an iPhone, iPad and Mac, and that keeps working when one of my home servers dies. [Vaultwarden](https://github.com/dani-garcia/vaultwarden?ref=sparsh.blog) covers the first part. It's a community-written server in Rust that speaks the same API as Bitwarden, so you use the official Bitwarden apps. It's unofficial and hasn't been through Bitwarden's security audits, so know that going in. The apps encrypt everything on the device, and the server only ever stores encrypted blobs.

Running one Vaultwarden is a 15 minute job. This guide is about the second part: surviving a dead machine without losing a single save. Here's what you need.

| You need                                               | What I used                                                                                                                                                                                     |
| ------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Two machines that stay on, ideally in different places | A Dell Latitude 5430 in Lucknow and an HP Pavilion from 2013 in Hyderabad, each running one VM under Proxmox                                                                                    |
| A third, tiny machine somewhere else                   | Oracle Cloud's [Always Free](https://docs.oracle.com/en-us/iaas/Content/FreeTier/freetier%5Ftopic-Always%5FFree%5FResources.htm?ref=sparsh.blog) E2.1.Micro: an eighth of a CPU and 1 GB of RAM |
| A private network between them                         | A [Tailscale](https://tailscale.com/?ref=sparsh.blog) account                                                                                                                                   |
| A domain whose DNS you can edit by API                 | A domain on Cloudflare, DNS only, nothing proxied                                                                                                                                               |
| Somewhere off-site for backups                         | A Backblaze B2 bucket                                                                                                                                                                           |

Why three machines? Because two can't make a decision. If Lucknow and Hyderabad stop hearing each other, each one just sees the other vanish. Neither can tell whether the other box died or the internet between them did. If both decide to take over, you get two databases accepting writes and quietly drifting apart, which for a password manager is about the worst thing that can happen. The third machine breaks the tie. It never holds a password. It only votes.

All three of my VMs run Ubuntu 26.04 with SSH keys only. In the configs below, `vault-athena`, `vault-hermes` and `vault-oracle` are the machine names, `ATHENA_TS`, `HERMES_TS` and `ORACLE_TS` stand for each one's Tailscale IP, and `vault.example.com` is your domain. Anything that says `CHANGE_ME` is a secret you generate yourself, and `openssl rand -base64 32` is a good way to make one.

### Use your own values

Reset 

Fill these in and every command and config below updates, so Copy gives you something you can paste straight in. They stay in this browser and are never sent anywhere.

Your domain Email for Let's Encrypt Tailscale IP of vault-athena Tailscale IP of vault-hermes Tailscale IP of vault-oracle Backblaze B2 bucket 

## [1Connect the machines](#tailscale)

Everything in the cluster talks over Tailscale addresses, and only over Tailscale. That way it doesn't matter that one machine sits behind a home router, one behind two layers of NAT, and one in a data centre. Install Tailscale on all three, then bring each one up with tags. Both home servers get `tag:vault-host` as well, because they're the ones allowed to serve the vault later.

install and joinon each VM

```
curl -fsSL https://tailscale.com/install.sh | sh

# on vault-athena (and vault-hermes, with its own hostname)
sudo tailscale up --hostname=vault-athena \
  --advertise-tags=tag:vault-node,tag:vault-host --accept-dns=false

# on vault-oracle
sudo tailscale up --hostname=vault-oracle \
  --advertise-tags=tag:vault-node --accept-dns=false
```

Then lock each VM's own firewall down to SSH plus anything arriving over Tailscale. etcd and Patroni's API don't use TLS between members here, so this is what keeps them private.

firewallon both home VMs

```
sudo ufw allow OpenSSH
sudo ufw allow in on tailscale0
sudo ufw enable
```

Oracle's Ubuntu image doesn't use ufw. It ships with iptables rules that reject nearly everything, and they will silently eat your etcd traffic even over Tailscale. Allow the Tailscale interface and save the rules so they survive a reboot. While you're in Oracle's console, open UDP 41641 in the subnet's security list too. Without it, Tailscale can't make a direct connection to the VM and relays everything instead.

firewallon vault-oracle

```
sudo iptables -I INPUT -i tailscale0 -j ACCEPT
sudo netfilter-persistent save
```

In the Tailscale admin console, the tailnet policy needs three things. The nodes need to reach each other on the cluster ports. Your own devices need to reach the vault service. And the home servers need to be allowed to serve it without you clicking approve each time. A minimal version looks like this:

tailnet policy file (excerpt)admin console

```
"tagOwners": {
  "tag:vault-node": ["autogroup:admin"],
  "tag:vault-host": ["autogroup:admin"]
},
"grants": [
  { "src": ["tag:vault-node"],   "dst": ["tag:vault-node"], "ip": ["tcp:2379", "tcp:2380", "tcp:5432", "tcp:8008"] },
  { "src": ["autogroup:member"], "dst": ["tag:vault-node"], "ip": ["tcp:22"] },
  { "src": ["autogroup:member"], "dst": ["svc:vault"],      "ip": ["tcp:443"] }
],
"autoApprovers": {
  "services": { "svc:vault": ["tag:vault-host"] }
}
```

**Check:** run `tailscale ping vault-hermes` from each machine to each other one, and note whether it goes "via DERP" (relayed) or straight to an address. Then send a big packet with `ping -M do -s 1200 HERMES_TS`. Small pings can work fine on a path that drops big ones, and Postgres replication is mostly big packets.

Here's what I ended up with. The relay between my two homes is fine: 47 ms with no loss beats "direct" with loss.

| Between               | Path                                      | Round trip  |
| --------------------- | ----------------------------------------- | ----------- |
| Hyderabad and Oracle  | Direct                                    | 3 to 4 ms   |
| Lucknow and Oracle    | Direct, once UDP 41641 was open on Oracle | about 41 ms |
| Lucknow and Hyderabad | Tailscale's relay in Mumbai               | about 47 ms |

### If your Proxmox hosts are also subnet routers

This one cost me an evening. My first check between the two homes said "direct", which felt too good to be true for a box behind double NAT. Small pings were fine. The 1200 byte ones lost two out of every three packets.

Both of my Proxmox hosts were already running Tailscale as [subnet routers](https://tailscale.com/kb/1019/subnets?ref=sparsh.blog), so each could reach the other city's home network. When the Hyderabad VM sent anything to Athena's home LAN address, the Hermes host quietly grabbed the packet and pushed it through its own tunnel. My cluster traffic was WireGuard inside WireGuard, through both hosts, and the big packets didn't fit.

Before: two tunnels, through both hosts

vault-hermes Hermes host *tunnel in a tunnel* Athena host vault-athena 

After: one tunnel, VM to VM

vault-hermes *one WireGuard tunnel, no loss* vault-athena 

The fix is one routing rule on the host. Tailscale's own rules sit at priority 5270, so a rule at 5200 gets checked first and keeps the VM's traffic out of the host's tunnel. Swap in your VM's address and the other home's LAN range. I saved mine under the bridge in `/etc/network/interfaces` so it comes back after a reboot.

/etc/network/interfaces, under vmbr1on the Hermes Proxmox host

```
post-up ip rule add from 10.10.10.203 to 192.168.68.0/22 lookup main priority 5200
```

I'd do this even without the packet loss. On the old path, restarting Tailscale on either Proxmox host would have cut the two vault VMs off from each other while both were perfectly healthy. That's a great way to trigger a failover for no reason.

## [2etcd, the referee](#etcd)

[etcd](https://etcd.io/?ref=sparsh.blog) is a small key-value store built on the Raft consensus algorithm. One member leads, every write needs a majority to agree, and if the leader goes quiet the others elect a new one. Patroni uses it to store the one thing that matters most here: who the database leader is. It's also where Kubernetes keeps all its state, if you've ever wondered what's in there.

Install it on all three machines. Ubuntu's package reads its settings from `/etc/default/etcd`.

installon all three

```
sudo apt install -y etcd-server etcd-client
```

The defaults assume servers in the same rack. Mine are 40-odd milliseconds apart, so I made it more patient: a heartbeat every 250 ms, and an election only after 2.5 seconds of silence. This is Athena's file. On the other two, change `ETCD_NAME` and the two advertise URLs to that machine's own name and address.

/etc/default/etcdon all three

```
ETCD_NAME="vault-athena"
ETCD_DATA_DIR="/var/lib/etcd/default"
ETCD_LISTEN_PEER_URLS="http://0.0.0.0:2380"
ETCD_LISTEN_CLIENT_URLS="http://0.0.0.0:2379"
ETCD_INITIAL_ADVERTISE_PEER_URLS="http://ATHENA_TS:2380"
ETCD_ADVERTISE_CLIENT_URLS="http://ATHENA_TS:2379"
ETCD_INITIAL_CLUSTER="vault-athena=http://ATHENA_TS:2380,vault-hermes=http://HERMES_TS:2380,vault-oracle=http://ORACLE_TS:2380"
ETCD_INITIAL_CLUSTER_TOKEN="vault-etcd"
ETCD_INITIAL_CLUSTER_STATE="new"      # change to "existing" once the cluster has formed
ETCD_HEARTBEAT_INTERVAL="250"
ETCD_ELECTION_TIMEOUT="2500"
ETCD_AUTO_COMPACTION_RETENTION="1"
```

Restart etcd on all three within a minute or so of each other, so they find each other while forming. Once they have, set `ETCD_INITIAL_CLUSTER_STATE` to `"existing"` everywhere, so a member that restarts later rejoins instead of trying to found a new cluster.

**Check:** add `export ETCDCTL_ENDPOINTS=http://ATHENA_TS:2379,http://HERMES_TS:2379,http://ORACLE_TS:2379` to your `~/.bashrc`. Then `etcdctl endpoint status -w table` should list three members, one of them the leader.

Then break it on purpose. Stop one member and writes keep working. Stop two, and the last one standing says `etcdserver: no leader` and refuses to answer even a read, because it can't prove its data is still current. The first time I saw that I thought I'd broken something. That refusal is the whole point: a machine that has lost the majority must not make decisions.

Everything up Lucknow loses power Hyderabad goes dark Lose the witness 

 Add a fourth etcd member in Lucknow 

Press a machine to switch it off or on. etcd only acts when more than half its members agree, so what matters is how many are up, not which ones.

## [3Postgres and Patroni](#patroni)

[Patroni](https://patroni.readthedocs.io/?ref=sparsh.blog) sits next to Postgres on both home servers. Every ten seconds it reads the cluster state from etcd, looks at what its own Postgres is doing, and fixes whatever doesn't match. Whoever holds the leader key in etcd runs as the primary, and the other follows it as a replica. If you've ever written a Kubernetes controller, it's the same loop.

Install Postgres 18, Patroni, and the etcd library Patroni needs. Ubuntu's Patroni package doesn't pull that library in by itself, and without it Patroni refuses to start with a confusing list of the stores it does support. Then remove the default Postgres cluster, because Patroni creates and runs its own.

installon both home VMs

```
sudo apt install -y postgresql-18 patroni python3-etcd
sudo systemctl disable --now postgresql
sudo pg_dropcluster --stop 18 main
```

Here's my whole config. On Hermes, change `name` and the two `connect_address` lines. The passwords must match on both machines.

/etc/patroni/config.ymlon both home VMs

```
scope: vault
namespace: /service/
name: vault-athena

restapi:
  listen: 0.0.0.0:8008
  connect_address: ATHENA_TS:8008
  authentication:               # protects the endpoints that change things
    username: patroni
    password: CHANGE_ME

etcd3:
  hosts: ATHENA_TS:2379,HERMES_TS:2379,ORACLE_TS:2379

bootstrap:
  dcs:
    ttl: 30                     # how long the leader key lives
    loop_wait: 10
    retry_timeout: 10
    maximum_lag_on_failover: 1048576
    synchronous_mode: true      # the standby confirms every commit
    postgresql:
      use_pg_rewind: true       # lets an old primary rejoin after a failover
      use_slots: true
      parameters:
        wal_level: replica
        hot_standby: "on"
        wal_log_hints: "on"
        max_wal_senders: 10
        max_replication_slots: 10
        wal_keep_size: 512MB
        password_encryption: scram-sha-256
  initdb:
    - encoding: UTF8
    - locale: C.UTF-8           # systemd gives Postgres no locale to inherit
    - data-checksums

postgresql:
  listen: 0.0.0.0:5432
  connect_address: ATHENA_TS:5432
  data_dir: /var/lib/postgresql/18/patroni
  bin_dir: /usr/lib/postgresql/18/bin
  authentication:
    superuser:   { username: postgres,    password: CHANGE_ME }
    replication: { username: replicator,  password: CHANGE_ME }
    rewind:      { username: rewind_user, password: CHANGE_ME }
  pg_hba:
    - local all all peer
    - host all all 127.0.0.1/32 scram-sha-256
    - host replication replicator 127.0.0.1/32 scram-sha-256
    - host replication replicator ATHENA_TS/32 scram-sha-256
    - host replication replicator HERMES_TS/32 scram-sha-256
    - host all all ATHENA_TS/32 scram-sha-256
    - host all all HERMES_TS/32 scram-sha-256
```

Two settings carry the safety. The leader key expires after 30 seconds unless the leader keeps renewing it. If Athena loses touch with the etcd majority it can't renew, so it steps down by itself before anyone else is allowed to take over. You can't end up with two primaries.

The other is `synchronous_mode`. When you save something, the primary waits for the standby to confirm it has the change before telling your phone it's saved. Across my two cities that's one extra round trip, around 45 ms, which you will never notice in a password manager. In return, a failover never loses a save. If the standby is down, Patroni stops waiting for it rather than blocking every write, so saves keep working on one machine.

I allow my whole tailnet range in `pg_hba`, and listing the two servers, as above, is tighter. The line that's easy to miss is replication from `127.0.0.1`. Patroni makes a replication connection to its own Postgres, and without that line you get `no pg_hba.conf entry for replication`.

start itAthena first, then Hermes

```
sudo chown postgres:postgres /etc/patroni/config.yml
sudo chmod 600 /etc/patroni/config.yml
sudo systemctl enable --now patroni

# a shortcut worth having on both
alias pctl='sudo -u postgres patronictl -c /etc/patroni/config.yml'
```

Wait for Athena to come up as the leader before starting Hermes. Hermes then copies the whole database from Athena and starts streaming.

**Check:** `pctl list` on either machine. Same timeline on both sides, zero lag:

pctl listoutput

```
| Member       | Role         | State     | TL | Receive LSN | Lag |
| vault-athena | Leader       | running   |  1 |             |     |
| vault-hermes | Sync Standby | streaming |  1 |   0/3000088 |   0 |
```

Last, make a database for Vaultwarden. Run this on whichever machine is the leader.

create the app databaseon the leader

```
sudo -u postgres psql -c "CREATE ROLE vaultwarden LOGIN PASSWORD 'CHANGE_ME'"
sudo -u postgres createdb -O vaultwarden vaultwarden
```

## [4HAProxy finds the primary](#haproxy)

Vaultwarden wants one database address and has no idea any of this is happening. So each server runs [HAProxy](https://www.haproxy.org/?ref=sparsh.blog) on `127.0.0.1:5000`, and every 3 seconds it asks both Patroni nodes "are you the primary?". Only the leader answers `/primary` with a 200, so only the leader gets connections. When leadership moves, `shutdown-sessions` kills the old connections, so Vaultwarden reconnects instead of sitting there stuck.

/etc/haproxy/haproxy.cfg, after the stock global sectionon both home VMs

```
defaults
    log global
    mode tcp
    option tcplog
    retries 2
    timeout connect 4s
    timeout client 30m
    timeout server 30m
    timeout check 5s

listen stats
    mode http
    bind 127.0.0.1:7000
    stats enable
    stats uri /

listen postgres_primary
    bind 127.0.0.1:5000
    option httpchk
    http-check send meth GET uri /primary
    http-check expect status 200
    default-server inter 3s fall 3 rise 2 on-marked-down shutdown-sessions
    server vault-athena ATHENA_TS:5432 maxconn 50 check port 8008
    server vault-hermes HERMES_TS:5432 maxconn 50 check port 8008
```

Test the file with `sudo haproxy -c -f /etc/haproxy/haproxy.cfg` before restarting. It prints nothing at all when the file is fine, which confused me the first time, so check `echo $?` for a 0.

**Check:** on both machines, `psql "host=127.0.0.1 port=5000 user=vaultwarden dbname=vaultwarden" -c "select pg_is_in_recovery()"` should print `f`. Hermes is the interesting one, because its local HAProxy has sent you across to the primary on Athena.

## [5Vaultwarden and Traefik](#app)

Vaultwarden and [Traefik](https://doc.traefik.io/traefik/?ref=sparsh.blog) run in Docker on both home servers, from identical files in `/opt/vault`. Both containers use host networking and listen only on loopback. Tailscale is the only way in, and that's the next step. I installed Docker from [Docker's own repository](https://docs.docker.com/engine/install/ubuntu/?ref=sparsh.blog).

/opt/vault/compose.yamlon both home VMs

```
services:
  vaultwarden:
    image: vaultwarden/server:1.37.5   # pin a release
    container_name: vaultwarden
    restart: unless-stopped
    network_mode: host
    env_file: vaultwarden.env
    volumes:
      - ./vw-data:/data

  traefik:
    image: traefik:v3.8.0
    container_name: traefik
    restart: unless-stopped
    network_mode: host
    env_file: traefik.env
    volumes:
      - ./traefik/traefik.yml:/etc/traefik/traefik.yml:ro
      - ./traefik/dynamic.yml:/etc/traefik/dynamic.yml:ro
      - ./letsencrypt:/letsencrypt
```

Vaultwarden points at HAProxy, not at Postgres directly, so it always reaches whichever machine is primary. For `ADMIN_TOKEN`, store a hash rather than the token itself. `docker run --rm -it vaultwarden/server:1.37.5 /vaultwarden hash` makes one. If you want push notifications in the official apps, get the two push values from [bitwarden.com/host](https://bitwarden.com/host/?ref=sparsh.blog).

/opt/vault/vaultwarden.env (chmod 600)on both home VMs

```
DOMAIN=https://vault.example.com
DATABASE_URL=postgresql://vaultwarden:CHANGE_ME@127.0.0.1:5000/vaultwarden
DATABASE_MAX_CONNS=10
ROCKET_ADDRESS=127.0.0.1
ROCKET_PORT=8080
IP_HEADER=X-Forwarded-For
SIGNUPS_ALLOWED=true          # set to false once your accounts exist
INVITATIONS_ALLOWED=false
SHOW_PASSWORD_HINT=false
ADMIN_TOKEN='$argon2id$...'   # the hash, in single quotes
PUSH_ENABLED=true
PUSH_INSTALLATION_ID=CHANGE_ME
PUSH_INSTALLATION_KEY=CHANGE_ME
```

Traefik gets a real Let's Encrypt certificate with a DNS challenge. It proves you own the domain by writing a TXT record through Cloudflare's API, so you never open a port to the internet. Make a Cloudflare API token that can edit DNS for that one zone and put it in `/opt/vault/traefik.env` as `CF_DNS_API_TOKEN=`.

/opt/vault/traefik/traefik.ymlon both home VMs

```
entryPoints:
  websecure:
    address: "127.0.0.1:443"   # loopback only: Tailscale delivers traffic here
  traefik:
    address: "127.0.0.1:8081"  # dashboard, reachable only through an SSH tunnel

providers:
  file:
    filename: /etc/traefik/dynamic.yml
    watch: true

certificatesResolvers:
  cloudflare:
    acme:
      email: you@example.com
      storage: /letsencrypt/acme.json
      dnsChallenge:
        provider: cloudflare
        resolvers:
          - "1.1.1.1:53"
          - "1.0.0.1:53"

api:
  dashboard: true
  insecure: true   # only on the loopback 'traefik' entrypoint

log:
  level: INFO
```

/opt/vault/traefik/dynamic.ymlon both home VMs

```
http:
  routers:
    vaultwarden:
      rule: "Host(`vault.example.com`)"
      entryPoints:
        - websecure
      service: vaultwarden
      tls:
        certResolver: cloudflare

  services:
    vaultwarden:
      loadBalancer:
        servers:
          - url: "http://127.0.0.1:8080"
```

Start it on Athena first, with `docker compose up -d` in `/opt/vault`. On first start, Vaultwarden writes `vw-data/rsa_key.pem`, the key it signs your login sessions with. **Copy that file to Hermes before Hermes starts Vaultwarden for the first time.** If each server makes its own key, every failover signs you out on every device. With a shared key, my iPhone stayed logged in straight through a switchover.

Create your account, then set `SIGNUPS_ALLOWED=false` on both machines. After any change to an env file, use `docker compose up -d`, not `docker compose restart`. Restart keeps the old environment, and I lost a while to a password change that "didn't work" because of it.

**Check:** `curl --resolve vault.example.com:443:127.0.0.1 https://vault.example.com/alive` on each machine. A timestamp means Traefik has its certificate and Vaultwarden can reach the database.

## [6One address that follows the primary](#front-door)

Now the part I like best. Your devices use a [Tailscale Service](https://tailscale.com/docs/features/tailscale-services?ref=sparsh.blog), a virtual IP on your tailnet that doesn't belong to any one machine. Any host can advertise that it serves it, or drain itself to stop. If only the primary ever advertises, the front door always lands on the same machine as the primary database, and Vaultwarden never talks to Postgres across the country.

In the admin console, open Services, define `svc:vault` with the endpoint `tcp:443`, and note the TailVIP it gives you. Then tell both servers what the service maps to:

register as a service hoston both home VMs

```
sudo tailscale serve --service=svc:vault --tcp=443 tcp://127.0.0.1:443
```

Then a small watchdog decides, every 5 seconds, whether this machine should advertise or drain. It advertises only if it's the Patroni primary and Vaultwarden answers. It needs two failed checks in a row before draining, so a single slow answer doesn't move the vault.

/usr/local/sbin/vault-watchdog (chmod 755)on both home VMs

```
#!/usr/bin/env bash
# Advertise svc:vault only while this node is the Patroni primary and the app answers.
set -u
SVC="svc:vault"
STATE=/run/vault-watchdog.state     # last action taken: advertise or drain
FAILS=/run/vault-watchdog.fails     # consecutive failed checks

is_primary() {
  [ "$(curl -s -o /dev/null -w '%{http_code}' --max-time 3 http://127.0.0.1:8008/primary)" = "200" ]
}
app_ok() {
  curl -sf --max-time 3 --resolve vault.example.com:443:127.0.0.1 https://vault.example.com/alive >/dev/null
}

if is_primary && app_ok; then
  want=advertise; echo 0 > "$FAILS"
else
  n=$(( $(cat "$FAILS" 2>/dev/null || echo 0) + 1 )); echo "$n" > "$FAILS"
  [ "$n" -ge 2 ] && want=drain || exit 0   # ignore a single blip
fi

have=$(cat "$STATE" 2>/dev/null || echo none)
if [ "$want" != "$have" ]; then
  tailscale serve "$want" "$SVC" && echo "$want" > "$STATE"
  logger -t vault-watchdog "$SVC -> $want"
fi
```

/etc/systemd/system/vault-watchdog.service and .timeron both home VMs

```
# vault-watchdog.service
[Unit]
Description=Advertise or drain svc:vault based on Patroni role
After=tailscaled.service patroni.service docker.service

[Service]
Type=oneshot
ExecStart=/usr/local/sbin/vault-watchdog

# vault-watchdog.timer
[Unit]
Description=Run vault-watchdog every 5 seconds

[Timer]
OnBootSec=30s
OnUnitActiveSec=5s
AccuracySec=1s

[Install]
WantedBy=timers.target
```

Enable it with `sudo systemctl enable --now vault-watchdog.timer`. Last, in Cloudflare, add an A record for `vault.example.com` pointing at the TailVIP, with the proxy turned off. It's a private address, so the name only works for devices on your tailnet. Here's the whole path a request takes from your phone:

1. **iPhone**Bitwarden appAsks for vault.example.com
2. **Tailscale**svc:vault :443Only exists on your tailnet, nobody else can even see it
3. **Traefik**:443Handles TLS with the certificate it got over DNS
4. **Vaultwarden**:8080The actual password server
5. **HAProxy**:5000Sends it to whichever Postgres is the leader right now
6. **Postgres primary**:5432Which, thanks to the watchdog, is on the same machine

**Check:** `journalctl -t vault-watchdog` should show `advertise` on the leader and `drain` on the standby. Then, in the Bitwarden app, choose a self-hosted server, enter `https://vault.example.com` and log in.

**The catch:** because the vault only exists on your tailnet, every device needs Tailscale on to sync. With it off, the Bitwarden apps still unlock and autofill from their local copy, passkeys too. They just can't save anything new until they reconnect.

## [7Backups you've actually restored](#backups)

High availability is not a backup. If you delete something by accident, the deletion is copied to the standby within milliseconds. So every night the primary sends an encrypted backup to Backblaze B2 with [restic](https://restic.net/?ref=sparsh.blog). Both servers run the job, and the one that isn't primary just skips it, so there's exactly one backup a night whichever machine is in charge.

Create a B2 bucket and an application key limited to that bucket. Then on both machines, make an env file and a restic password file, both `root:root` and mode 600, with the same values on each. Generate the restic password with `openssl rand -base64 32` and keep a copy somewhere offline. Without it, the backups are useless.

/etc/vault-backup.env (chmod 600)on both home VMs

```
RESTIC_REPOSITORY=b2:YOUR_BUCKET:vault
RESTIC_PASSWORD_FILE=/root/.restic-vault-pass
B2_ACCOUNT_ID=CHANGE_ME
B2_ACCOUNT_KEY=CHANGE_ME
PGPASSWORD=CHANGE_ME          # the vaultwarden database user's password
```

Run `restic init` once, from one machine, to create the repository. Then the script:

/usr/local/sbin/vault-backup (chmod 755)on both home VMs

```
#!/usr/bin/env bash
set -euo pipefail
# Only the current Patroni primary backs up, so there is exactly one backup per night.
[ "$(curl -s -o /dev/null -w '%{http_code}' --max-time 3 http://127.0.0.1:8008/primary)" = "200" ] || { echo "not primary, skipping"; exit 0; }

set -a; . /etc/vault-backup.env; set +a

# restic runs pg_dump itself; if pg_dump exits non-zero the snapshot is discarded
# (a pipe would have saved a truncated dump as a valid snapshot).
restic backup --tag db --stdin-filename vaultwarden.dump --stdin-from-command -- \
  pg_dump -h 127.0.0.1 -p 5000 -U vaultwarden -d vaultwarden -Fc

restic backup --tag files \
  --exclude /opt/vault/vw-data/icon_cache \
  /opt/vault/vw-data /opt/vault/vaultwarden.env /opt/vault/traefik.env \
  /opt/vault/compose.yaml /opt/vault/traefik \
  /etc/patroni/config.yml /etc/haproxy/haproxy.cfg /usr/local/sbin/vault-watchdog

restic forget --keep-daily 14 --keep-weekly 8 --keep-monthly 12 --prune
```

The obvious way to back up a database is `pg_dump | restic backup --stdin`. Don't. If pg\_dump dies halfway, during a failover for example, restic never finds out and saves the truncated dump as your newest snapshot. With `--stdin-from-command`, restic runs pg\_dump itself and throws the snapshot away if it fails.

/etc/systemd/system/vault-backup.service and .timeron both home VMs

```
# vault-backup.service
[Unit]
Description=Encrypted Vaultwarden backup to Backblaze B2 (primary only)
Wants=network-online.target
After=network-online.target

[Service]
Type=oneshot
Environment=LC_ALL=C.UTF-8 RESTIC_CACHE_DIR=/var/cache/restic
CacheDirectory=restic
ExecStart=/usr/local/sbin/vault-backup

# vault-backup.timer
[Unit]
Description=Nightly Vaultwarden backup

[Timer]
OnCalendar=*-*-* 02:30:00
Persistent=true

[Install]
WantedBy=timers.target
```

The cache lines matter. systemd services have no home directory, so without them restic can't keep a cache and downloads the repository index from B2 on every run. Enable the timer on both, then run the service once by hand on each. One should log `not primary, skipping` and the other should upload two snapshots. Mine has already worked both ways round: the first nightly run happened while Hermes was primary, and Hermes took it.

### Now restore it somewhere else

A backup you haven't restored is a guess. I restored mine onto my Mac: `restic restore latest --tag db` and `--tag files`, then the dump into a throwaway `postgres:18` container with `pg_restore --no-owner --no-privileges`, then Vaultwarden 1.37.5 on top of the restored data folder. I logged in and all 184 items were there. `restic check --read-data`, which downloads and verifies every pack, came back clean too.

Two things to know if you try it. Put both containers on a private Docker network and don't publish the database port, or you've just put a copy of your vault on your LAN with the password `test`. And the web vault refuses plain HTTP, even on localhost. It says "Insecure URL not allowed", so serve the test copy with a throwaway self-signed certificate. Delete the whole restore folder afterwards, because it holds your B2 key and env files.

## [8Break it on purpose](#drills)

Until you've watched it fail over, you don't know that it does. Put a few test items in the vault, start a monitor on a laptop that hits the vault once a second, and break one thing at a time.

downtime monitoron your laptop

```
caffeinate -dims &   # macOS: a sleeping laptop logs fake outages
while true; do
  printf '%s %s\n' "$(date -u +%T)" \
    "$(curl -s -m 2 -o /dev/null -w '%{http_code}' https://vault.example.com/alive)"
  sleep 1
done >> ~/vault-drills.log
```

Start with the gentlest one, a planned switchover. Patroni moves the leader key on purpose, the same way it would during maintenance.

planned switchoveron either home VM

```
pctl switchover --leader vault-athena --candidate vault-hermes --force
```

Here's what my monitor saw when I ran it.

Replay it 22:34:03 UTC Each tick is one probe from my monitor. 

22:34:03 UTC22:34:31

1. About 6 sPostgres moves to Hermes. Athena's `/alive` can't get a database connection while HAProxy waits for the new primary.
2. 2 sAthena serves fine again, because HAProxy has found the new primary on Hermes.
3. About 12 sThe watchdogs swap. Athena drains, Hermes advertises, and Tailscale moves the address to Hyderabad.
4. From 22:34:28Served from Hyderabad, on the same address.

My planned switchover from Athena to Hermes, drawn from the monitor log. Each failed probe takes about 3 seconds, so the edges are approximate.

About 20 seconds in total, and the iPhone stayed logged in with every test item there. An item I saved right after, with Hermes as primary, landed fine. The interesting bit is the split. The database moved in about 6 seconds. The other 12 were the front door moving, at a moment when Athena was already serving correctly again through HAProxy. A watchdog that kept advertising on the old primary until the new one answered would cut that down. I haven't changed it yet.

The harder drills are next for me: a hard power cut on the leader, cutting the leader off the network, losing the witness, and losing the standby. The unplanned ones have to wait out the 30 second leader key, so expect longer outages than this. I'll post the real numbers once I've run them.

## [Things that will bite you](#gotchas)

Roughly in the order I hit them. Most are in the steps above too, but here they all are in one place, listed by what you'll actually see.

- Available implementations: consul, kubernetesPatroni can't find the etcd library. `sudo apt install python3-etcd`.
- initdb: invalid locale settingssystemd starts Postgres with almost no environment, so it has no locale to inherit. Set `locale: C.UTF-8` in Patroni's `initdb` section.
- no pg\_hba.conf entry for replication ... 127.0.0.1Patroni makes a replication connection to its own Postgres. Allow replication from `127.0.0.1`.
- candidate name does not match with sync\_standbyA second switchover gets refused with a 412 while the old leader is still rejoining. Wait until `pctl list` shows it as Sync Standby again. Patroni won't promote a copy it isn't sure is complete, which is what you want.
- etcdctl complains that a flag is shadowedOnce `ETCDCTL_ENDPOINTS` is set, don't also pass `--endpoints`.
- Oracle VM ignores etcd, even over TailscaleOracle's Ubuntu image ships iptables rules that reject nearly everything. Allow `tailscale0` and run `netfilter-persistent save`.
- "Direct" path, but big packets vanishYour Proxmox hosts are subnet routers and the traffic is tunnelling twice. See the routing rule in step 1.
- A new VM knocks the host offlineMy Hermes host falls back to Wi-Fi when its cable is out, and a VM on the main bridge made the bridge look connected. VMs on that host now live on a separate NAT bridge.
- Vaultwarden keeps an old setting`docker compose restart` reuses the old environment. `docker compose up -d` recreates the container.
- unable to open cache: neither $XDG\_CACHE\_HOME nor $HOME are definedrestic inside systemd. Add `CacheDirectory=restic` and `RESTIC_CACHE_DIR` to the unit.
- Insecure URL not allowed. All URLs must use HTTPS.The web vault of a restored test copy, served over plain HTTP. Use a self-signed certificate.
- pg\_restore complains about role vaultwardenThe dump's grants name a role your test database doesn't have. Use `--no-owner --no-privileges`.
- nc: Unknown host HERMES\_TSI pasted a command with the placeholder still in it. nc was right.
- SSH hardening, on the wrong machineI once ran my SSH lockdown snippet on the Proxmox host instead of the VM. Check your prompt before you paste.

## [What it can't do](#limits)

It's not perfect, and you should know where the edges are before you trust it with real passwords.

If Vaultwarden itself breaks on the primary while Postgres is fine, that's an outage. The front door follows the database, not the app, so the standby won't step in. Docker restarts actual crashes, and for anything weirder you'd switch the leader by hand.

Where the witness lives matters. My standby and my Oracle VM are both in Hyderabad. If Hyderabad drops off the internet completely, Lucknow is left alone without a majority and stops accepting saves. That's the correct behaviour, but it's still downtime. A fourth etcd member wouldn't fix it, because four members need three for a majority. The fix is a witness in a third place, and moving mine out of Hyderabad is on my list.

Vaultwarden keeps attachments and file Sends on disk in its data folder, not in Postgres. This setup copies the database between machines, not that folder, so don't expect attachments to be there after a failover unless you add something to sync them.

And iOS only runs one VPN at a time. Turn on another one and Tailscale goes off, so the phone can't sync until you switch back.

## [It's Kubernetes, by hand](#kubernetes)

Half the reason I built it this way is that almost every piece maps onto something in Kubernetes. Doing it by hand first made the Kubernetes versions make a lot more sense to me, and if you're learning, this table is the payoff.

| What you built                     | The Kubernetes version                       |
| ---------------------------------- | -------------------------------------------- |
| etcd on three machines             | The control plane's etcd                     |
| Patroni's loop                     | A controller or operator, like CloudNativePG |
| Leader key with a TTL              | A Lease object                               |
| HAProxy checking /primary          | A Service with a readiness probe             |
| Tailscale Service and the watchdog | A Service IP and its EndpointSlice           |
| Traefik with a DNS challenge       | An Ingress controller with cert-manager      |
| Tailscale grants                   | NetworkPolicy                                |

If you build something like this, or you spot something I got wrong, I'd really like to hear about it.

Thanks for reading. Built with Vaultwarden, PostgreSQL, Patroni, etcd, HAProxy, Traefik, Tailscale and restic, on two laptops and one free VM.