Headscale Cluster Architecture for Large-Scale Device Onboarding
Standard headscale is designed as a single-node control plane backed by SQLite or PostgreSQL. That architecture is simple to self-host, but when device counts grow into the thousands across many independent users, a single Headscale instance hits hard ceilings in concurrent long-lived map streams, database write contention, and full netmap recalculations.
This article outlines the architecture used to evolve headscale from a single monolith into a horizontally scalable cluster: cluster_id logical sharding, shared PostgreSQL storage, an Admission and Control Service (ACS), mandatory query isolation, and incremental netmap rebuilds.
Why Single-Node Headscale Hits a Ceiling
Every online Tailscale/Larktun client maintains a persistent control stream to its Headscale server. Even when the data plane runs peer-to-peer, the control plane still handles:
- Persistent HTTP/2 / Noise polling connections for every active device
- Database reads and writes for heartbeats, endpoint updates, and route changes
- ACL evaluation and netmap serialization whenever peer state changes
On a single process, scaling vertically eventually runs into lock contention, elevated GC pauses, and blast-radius risk during maintenance restarts. Splitting users horizontally across multiple stateless-ish shard nodes solves both capacity and reliability.
Five Core Building Blocks
Moving Headscale toward a SaaS-grade multi-node control plane relies on five coordinated design pieces:
cluster_idlogical sharding: Partition control-plane ownership cleanly across independent Headscale worker nodes, each pinned to a uniquecluster_id.- Shared PostgreSQL / PG cluster: Keep durable metadata in a centralized relational database while isolating every worker's working set by
cluster_id. - Admission and Control Service (ACS): Act as the front-door coordinator for first-time tenant placement, quota enforcement, region affinity, and sticky routing.
- Mandatory DAO/ORM query scoping: Enforce
WHERE cluster_id = ?at the data-access layer so one cluster node can never accidentally read, mutate, or broadcast another shard's nodes. - Incremental netmap calculation: Replace global netmap rebuilds with event-driven, scoped recomputation and caching.
Cluster Architecture Overview
In a clustered deployment:
- Multiple
headscalenodes run side by side, each launched with a distinctCLUSTER_ID(for exampleA,B, or numeric shard IDs). - A dynamic edge router (such as Traefik) maps each tenant or user endpoint to its assigned Headscale shard based on ACS placement records.
- All nodes connect to the same PostgreSQL cluster, which simplifies cross-shard operational tooling and tenant migration without requiring separate database instances per worker.
- PostgreSQL
LISTEN/NOTIFYpaired with short debounce windows triggers netmap recalculation strictly for the affectedcluster_idand scope key.
Node Startup Configuration
Each Headscale shard node declares its shard identity, shared PostgreSQL DSN, and DERP map endpoint at startup:
CLUSTER_ID=A \
PG_DSN="postgres://headscale:secret@pg-cluster.internal:5432/headscale?sslmode=require" \
DERP_MAP_URL="https://derp.example.com/map.json" \
./headscale --config ./config.yaml
Keeping shard identity injected via environment variables allows all nodes to share the same container image and base configuration template.
Enforcing Data and Query Isolation
Logical sharding only works if database queries are both indexed and impossible to forget. First, extend core tables (users, nodes, pre_auth_keys, routes, policies) with a non-null cluster_id column and supporting indexes:
ALTER TABLE nodes ADD COLUMN cluster_id TEXT NOT NULL DEFAULT 'default';
CREATE INDEX idx_nodes_cluster_id ON nodes(cluster_id);
Second, wrap database access in a scoped helper inside the DAO/ORM layer so every read and write automatically injects the shard predicate:
func (c *ClusterDB) Scoped() *gorm.DB {
return c.db.Where("cluster_id = ?", c.clusterID)
}
By routing all repository methods through Scoped(), cross-shard leaks are caught structurally rather than relying on individual handler authors to remember manual WHERE clauses.
Moving from Full to Incremental Netmap Rebuilds
Rebuilding the entire netmap across all nodes on every endpoint change wastes CPU and amplifies reconnect storms. An incremental pipeline avoids unnecessary work:
- When a node endpoint, route, or ACL changes, emit a lightweight notification such as
NOTIFY netmap_dirty(cluster_id, scope_key). - Only the Headscale worker owning that
cluster_idconsumes the event; other shards ignore it immediately. - Combine rapid bursts of changes with a short debounce window (e.g., 100–300 ms) so rapid client flapping coalesces into a single rebuild.
- Recompute and push updates strictly for the affected
scope_key(tenant/user, tag group, or route domain), backed by an in-memory versioned cache.
Multi-Shard Verification Screenshots
The screenshots below demonstrate two isolated shards (cluster_id = 1 and cluster_id = 2) sharing the same PostgreSQL schema while maintaining separate node lists, users, and pre-auth keys:





Operational Benefits
With cluster_id sharding in place, adding capacity becomes an operational routine instead of a risky vertical upgrade: launch a new Headscale shard with a new CLUSTER_ID, register it in ACS, and assign new tenants (or seamlessly migrate busy tenants) without interrupting existing shards.
Open-Source Project and Next Steps
- Reference implementation: OwnDing/headscale-saas
- Next in series: Headscale SaaS Seamless User Switching
- Multi-tenant isolation details: Headscale Multi-Tenant Isolation for ACL, Routes, and MagicDNS
- See how Larktun productizes this architecture: Larktun Product Architecture