Skip to content

High Availability ​

BatleHub is a stateless HTTP server — all durable state lives in PostgreSQL and an object store, not in the process. Running multiple replicas safely requires swapping two single-instance defaults for shared backends: the in-memory cache store and the local filesystem storage.


Architecture overview ​

                 ┌───────────────┐
                 │  Load balancer │
                 └──────┬────────┘
          ┌─────────────┼─────────────┐
          ▼             ▼             ▼
   ┌────────────┐ ┌────────────┐ ┌────────────┐
   │ BatleHub 1 │ │ BatleHub 2 │ │ BatleHub 3 │
   └─────┬──────┘ └─────┬──────┘ └─────┬──────┘
         │               │               │
         └───────────────┼───────────────┘
                         │
           ┌─────────────┼─────────────┐
           ▼             ▼             ▼
     ┌──────────┐  ┌──────────┐  ┌──────────┐
     │PostgreSQL│  │  Redis   │  │    S3    │
     │(primary) │  │ (cache)  │  │(storage) │
     └──────────┘  └──────────┘  └──────────┘

All state is shared externally. No sticky sessions are needed — any replica can serve any request, a cold artifact included: the replicas share one fill per artifact (Cold fills).

What changes between single-instance and HA ​

ComponentSingle-instance defaultMulti-instance requirement
Metadata cacheInMemoryCacheStore (per-process)PostgreSQL or Redis ([cache])
Rate limitingInMemoryRateLimitStore (per-process)Same [cache] backend — automatic
IP blockingInMemoryIpBlockStore (per-process)Same [cache] backend — automatic
Global bannerInMemoryBannerStore (per-process)Same [cache] backend — automatic
Cold-fill leaseIn the processPostgreSQL row, whenever [cache] is shared — automatic
Artifact storageFilesystem (/var/cache/batlehub)S3-compatible object store
Canonical dataPostgreSQLPostgreSQL — already shared

The [cache] section controls all four in-memory stores, and who fills a cold artifact, with a single setting. Switching it also fixes rate limiting, IP blocking, the global admin banner and duplicate upstream fetches without any additional config.


Prerequisites ​

Before scaling beyond one replica:

  • PostgreSQL 14+ — already required; no change needed.
  • S3-compatible object store — AWS S3 or RustFS (MinIO is no longer officially supported). Filesystem storage is single-node only.
  • Shared cache backend — either the same PostgreSQL instance (simplest) or a Redis 7+ instance.
  • Load balancer / ingress — anything that does round-robin HTTP (nginx, Traefik, Kubernetes Ingress). No session affinity required.

Configuration changes ​

These are the only config changes needed to go from single-instance to multi-instance. Everything else stays the same.

Cache backend ​

Replace the default in-memory cache with a shared backend. This single change covers metadata cache, rate limiting, IP blocking and the cold-fill lease. More than one replica needs it: with memory, every pod fills, rate-limits and bans on its own. The Helm chart refuses to render replicaCount > 1 without config.cache.type set to postgres or redis, unless the config comes from somewhere it cannot read (an externalManifest entry with mount.asConfig, or credentials.existingSecret) — then it is yours to get right.

Option A — PostgreSQL (uses your existing database, no extra service):

toml
[cache]
type = "postgres"
# url defaults to database.url — omit it unless you want a separate connection string

Option B — Redis (lower latency, recommended for high request volume):

toml
[cache]
type  = "redis"
url   = "redis://redis:6379"

Artifact storage ​

Switch from filesystem to S3. All replicas read and write to the same bucket.

toml
[storage]
type   = "s3"
bucket = "batlehub-artifacts"
region = "us-east-1"

# For self-hosted S3 (RustFS):
# endpoint_url     = "http://rustfs:9000"
# force_path_style = true

There is no credential field here: the block takes bucket, region, prefix, endpoint_url and force_path_style, and nothing else. Keys are not rejected, they are ignored — an access_key_id written here looks like a bucket policy problem at the first cache miss. Credentials come from the standard AWS SDK chain: the instance or pod role, or AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY in the process environment.

Database connection pool ​

Each replica opens its own connection pool. Lower max_connections per replica when running behind PgBouncer, or leave it at the default (20) when connecting directly — see sizing max_connections.

toml
[database]
type            = "postgresql"
url             = "postgresql://batlehub:changeme@postgres:5432/batlehub"
max_connections = 5   # recommended per replica when using a connection pooler

The read cache and LISTEN ​

Each replica keeps the reads every download repeats — the package's block, its flags, its visibility, the presented token, the caller's user block, where the artifact is stored — in memory, and Postgres tells every replica when one of them changes (LISTEN/NOTIFY, fed by triggers). A block or a revoked token therefore applies on every replica within a notification round trip, not after a timeout.

The cache turns on only once the replica has seen a notification it sent itself come back, and turns off as soon as one does not. Behind a transaction-mode pooler (PgBouncer's pool_mode = transaction), notifications never reach the listener: the cache stays off, every read goes to the database as before, and the log says why once. To keep the cache, give the listener a direct or session-mode connection:

toml
[database]
url        = "postgresql://batlehub:changeme@pgbouncer:6432/batlehub"
listen_url = "postgresql://batlehub:changeme@postgres:5432/batlehub"  # direct, for LISTEN only

Without listen_url the listener holds one connection of the pool. batlehub_read_cache_live (1 or 0) says whether the cache is on; batlehub_read_cache_invalidations_total counts the notifications received.

A listener whose connection dies without a reset (a network partition) is noticed by its heartbeat, sent every 10 s: an answer can be stale for at most 20 s in that case, and every entry is dropped after 5 minutes regardless. A write made through a replica clears that replica's own copy at commit, without waiting for the notification.

The cache is on by default, also with a single replica: the scan worker (--roles worker), another replica or an operator's SQL writes the same rows, and only the notification tells this process. To turn it off — every read goes to the database, and no listener is started:

toml
[database]
read_cache = false

CORS ​

Since 1.1.0 an unset cors_allowed_origins means same-origin only. If BatleHub serves the SPA itself — the default, and what the Helm chart does — you need nothing here: same-origin requests never consult CORS.

Set it when a browser client is served from a different origin than the API:

toml
[server]
host                 = "0.0.0.0"
port                 = 8080
cors_allowed_origins = ["https://batlehub.example.com"]

Breaking change in 1.1.0

An empty or absent list previously allowed every origin. Setting cors_allowed_origins = ["*"] restores that behaviour and raises a cors.any-origin config warning.

Complete multi-instance config example ​

toml
[server]
host                 = "0.0.0.0"
port                 = 8080
static_dir           = "/app/ui/dist"
cors_allowed_origins = ["https://batlehub.example.com"]

[database]
type            = "postgresql"
url             = "postgresql://batlehub:changeme@postgres:5432/batlehub"
max_connections = 5

[cache]
type = "redis"
url  = "redis://redis:6379"

[storage]
type   = "s3"
bucket = "batlehub-artifacts"
region = "us-east-1"

[[auth]]
type = "token"

[[auth.tokens]]
value   = "change-me-admin-token"
role    = "admin"
user_id = "admin"

[[registries]]
type = "npm"
name = "npm"

[registries.rbac]
anonymous = ["releases:read", "source:read"]
user      = ["releases:read", "source:read"]
admin     = ["*"]

Cold fills ​

A cold miss is one fill per artifact across every replica that shares the database, the [cache] and the bucket — how a single fill streams, verifies and stores the bytes is in A cold miss.

  • Who fills is a lease. With [cache] set to postgres or redis it is a PostgreSQL row (fill_leases; PostgreSQL even with a Redis cache). With memory — one replica — it stays in the process and costs no statement.
  • The other replicas follow the fill instead of fetching. A replica that gets a request for an artifact another one is filling reads the committed 8 MiB segments back from storage and makes no upstream request. It is woken by a NOTIFY on the LISTEN connection it already holds, or polls the lease once a second while that connection is down. Its first byte comes at most one segment's transfer after the filler's: 0.84 s at 10 MB/s, 8.4 s at 1 MB/s.
  • A pod that dies mid-fill is a restart, not a resume. The lease lives 30 s and the filler renews it every 10 s on a timer of its own, so a quiet upstream or a long S3 assembly does not let it lapse. When the filler dies, its readers on other replicas are cut once the lease expires (up to ~30–60 s); the client's retry takes the lease over, deletes the dead fill's segments and fetches from zero.
  • Leftovers are swept. Every 5 minutes one replica (elected by a PostgreSQL advisory lock) claims each expired lease, then deletes its segments and row, and deletes staging keys older than 24 h.

Add a bucket lifecycle rule on S3

The sweep does not abort incomplete multipart uploads. Give the bucket a lifecycle rule that aborts incomplete multipart uploads after 1 day and expires objects under the staging: prefix (below your prefix, if set) after 1 day.

What a fill costs in storage, memory, S3 requests and statements is in Capacity planning.


Docker Compose — single-host redundancy ​

Docker Compose can run multiple server replicas on a single host. This protects against process crashes but not host failure. Use it for staging environments or when you want process-level redundancy without a full Kubernetes cluster.

yaml
# docker-compose.ha.yml
services:
  postgres:
    image: postgres:17-alpine
    environment:
      POSTGRES_DB:       batlehub
      POSTGRES_USER:     batlehub
      POSTGRES_PASSWORD: changeme
    volumes:
      - postgres_data:/var/lib/postgresql/data

  redis:
    image: redis:7-alpine
    command: redis-server --save "" --appendonly no

  batlehub:
    image: ghcr.io/batlehub/batlehub:1.7.0
    deploy:
      replicas: 2
      restart_policy:
        condition: on-failure
    depends_on: [postgres, redis]
    volumes:
      - ./config.toml:/etc/batlehub/config.toml:ro
    # No cache volume needed — storage is S3.

  proxy:
    image: nginx:alpine
    ports:
      - "8080:80"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf:ro
    depends_on: [batlehub]

volumes:
  postgres_data:

Minimal nginx.conf:

nginx
events {}
http {
  upstream batlehub {
    server batlehub:8080;   # Docker's internal DNS round-robins across replicas
  }
  server {
    listen 80;
    location / {
      proxy_pass http://batlehub;
      proxy_set_header Host              $host;
      proxy_set_header X-Real-IP         $remote_addr;
      proxy_set_header X-Forwarded-For   $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto $scheme;
    }
  }
}

IP blocking behind a proxy

If [ip_blocking] is enabled, BatleHub reads the client IP from X-Real-IP or X-Forwarded-For. Ensure your load balancer sets these headers; otherwise all requests appear to come from the proxy's IP.


Kubernetes / Helm — production HA ​

The bundled Helm chart supports multi-replica deployments out of the box once S3 and a shared cache backend are configured.

HA values file ​

yaml
# ha-values.yaml
replicaCount: 3

image:
  repository: ghcr.io/batlehub/batlehub
  tag: "1.1.0"    # pin to a specific version

# The application config: the chart serialises `config` to config.toml.
config:
  database:
    type: "postgresql"
    url:  "postgresql://batlehub:changeme@postgres-svc:5432/batlehub"
  storage:
    type:   "s3"
    bucket: "batlehub-artifacts"
    region: "us-east-1"
    path:   null             # drop the chart's filesystem default
  # Required above one replica — the chart refuses to render without it.
  cache:
    type: "redis"            # or "postgres" (url defaults to database.url)
    url:  "redis://redis-svc:6379"

# S3 credentials come from the AWS SDK chain: a pod role, or these variables.
envFrom:
  - secretRef:
      name: batlehub-s3      # AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY

# PVC not needed — all artifacts go to S3.
persistence:
  enabled: false

ingress:
  enabled: true
  className: nginx
  host: batlehub.example.com
  annotations:
    cert-manager.io/cluster-issuer: letsencrypt-prod
  tls:
    - secretName: batlehub-tls
      hosts:
        - batlehub.example.com

# Spread replicas across nodes.
affinity:
  podAntiAffinity:
    preferredDuringSchedulingIgnoredDuringExecution:
      - weight: 100
        podAffinityTerm:
          topologyKey: kubernetes.io/hostname
          labelSelector:
            matchLabels:
              app.kubernetes.io/name: batlehub

resources:
  requests:
    cpu:    200m
    memory: 256Mi
  limits:
    cpu:    1000m
    memory: 512Mi
sh
helm install batlehub ./helm/batlehub \
  --namespace batlehub \
  --create-namespace \
  -f ha-values.yaml

Horizontal Pod Autoscaler ​

Scale replicas automatically based on CPU load:

yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: batlehub
  namespace: batlehub
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: batlehub
  minReplicas: 2
  maxReplicas: 10
  metrics:
    - type: Resource
      resource:
        name: cpu
        target:
          type: Utilization
          averageUtilization: 70

Rolling updates and zero-downtime deploys ​

BatleHub applies database migrations automatically on startup. Migrations are designed to be additive — they never drop columns or tables that the previous version still reads. This means a rolling deploy is safe:

  1. New pods start, run migrations, and become ready.
  2. Old pods continue serving requests while new ones apply migrations.
  3. Old pods are terminated once new ones pass their readiness probe.

Configure the Deployment strategy to guarantee zero downtime:

yaml
# The Deployment's strategy — not a chart value; apply it with the patch below:
strategy:
  type: RollingUpdate
  rollingUpdate:
    maxUnavailable: 0
    maxSurge: 1

To apply this to the chart's Deployment directly (the chart does not expose this as a top-level value), patch it after installation:

sh
kubectl patch deployment batlehub \
  -n batlehub \
  --type=json \
  -p='[{"op":"add","path":"/spec/strategy","value":{"type":"RollingUpdate","rollingUpdate":{"maxUnavailable":0,"maxSurge":1}}}]'

Health probes ​

The Helm chart configures liveness and readiness probes automatically:

ProbeEndpointInitial delayPeriod
ReadinessGET /api/v1/admin/health5 s10 s
LivenessGET /api/v1/admin/health10 s30 s

The health endpoint does not require an Authorization header. Kubernetes can reach it directly from the kubelet.

Traffic is only routed to a pod once its readiness probe passes — so clients are never sent to a replica that is still applying migrations or warming its cache.


Observability ​

Distributed tracing works across replicas without any extra configuration. Each span carries the same trace ID regardless of which replica handles a request. Point all replicas at the same OpenTelemetry collector:

toml
[otel]
endpoint     = "http://otel-collector:4317"
service_name = "batlehub"

In Helm:

yaml
config:
  otel:
    endpoint:     "http://otel-collector:4317"
    service_name: "batlehub"

Each replica emits its own spans; the collector stitches them into complete traces by trace ID. See the Administration guide for the Jaeger quickstart.

Cold-fill metrics ​

MetricWhat it says
batlehub_proxy_fill_activeFills running on this replica
batlehub_proxy_fill_joined_total{registry,scope}Requests that joined a fill, on this replica (local) or another one (remote)
batlehub_proxy_fill_first_byte_seconds{scope}Time to a joiner's first byte
batlehub_proxy_fill_segments_total{registry}Segments committed to storage
batlehub_proxy_fill_assembly_secondsTime to turn the segments into the blob
batlehub_proxy_fill_follow_polls_totalLease polls by a follower whose LISTEN connection is down
batlehub_proxy_fill_takeovers_total{registry}Fills taken over from an expired lease
batlehub_proxy_fill_lease_lost_total{registry}Fills that lost their lease
batlehub_proxy_fill_lease_errors_totalLease store failures — the replica then fills on its own, as one replica would
batlehub_proxy_fill_orphans_deleted_totalLeftovers deleted by the sweep

Two alerts are worth having, and neither should page — both degrade cost (upstream traffic, a client retry), not correctness:

promql
increase(batlehub_proxy_fill_takeovers_total[1h]) > 0     # outside a rollout: pods dying mid-fill
increase(batlehub_proxy_fill_lease_errors_total[15m]) > 0 # replicas filling on their own

Known limitations ​

These are accepted trade-offs documented in docs/contributing/contributing.md §9:

  • Quota TOCTOU race — publish quota enforcement reads the current usage and then increments it in two separate DB operations. Under concurrent publishes across replicas the quota can be exceeded by at most one upload per concurrent writer. Enforcement is eventually consistent, not strict.

  • Cache warm-up duplicates — each replica runs its own warm-up pass on startup. Multiple replicas starting simultaneously will each independently fetch the same upstream packages. The downloads are idempotent (last writer wins in S3) but generate duplicate upstream traffic.

  • Async quota rollback — if a publish fails after storage but before the DB commit, the quota counter is decremented asynchronously. A short window exists where the counter is overcounted.

  • A config reload reaches one replica — the config editor and an approved file change are applied by the replica that handles the request, and by no other: the pending reload is in that process's memory and the file is on that pod's mount. Apply a change on every replica, or roll them out from the same files (helm upgrade). While the replicas that reported in the last minute do not all serve the same configuration, the Config Reload page shows a config.replica-drift warning naming each one and the configuration it serves; each replica reports a fingerprint of its merged config to PostgreSQL (system_kv) every fifteen seconds, so a reformatted but identical file does not count as a difference. Accepting it with [console] accepted = ["warning:config.replica-drift"] takes effect only once every reporting replica's configuration says so, so the answer does not depend on which replica serves the page.

  • The catalogue follows within fifteen seconds — a package one replica publishes, deletes or caches for the first time clears that registry's cached listings on every replica at its next poll of PostgreSQL, every fifteen seconds.

    Both run only when [cache] is shared (redis or postgres), which more than one replica requires anyway: a single server with type = "memory" has no replica to agree with, and does not pay the statement every fifteen seconds.

  • In-memory stores if misconfigured — if [cache] is left at the default type = "memory", each replica maintains its own independent rate-limit and IP-block state. Rate limits will be N times more permissive than configured (where N is the replica count), and IP blocks set on one replica will not propagate to others, and each replica fills a cold artifact on its own. Always set a shared cache backend for multi-replica deployments — the Helm chart refuses to render without one when it can read the config (Cache backend).

Released under the Apache 2.0 License. Made with care and too much coffee.