# Scaling (https://sockudo.io/docs/server/scaling) > Design multi-node Sockudo deployments with shared adapters, cache, queues, recovery, and push fanout. This page explains how Sockudo runs as a cluster: how a publish on one node reaches sockets on another, which dependencies every node must share, and how to deploy, drain, and load-test without dropping messages. You need it as soon as you run more than one Sockudo process, including two replicas behind a load balancer for availability. Sockudo scales horizontally when every node shares the dependencies that carry cross-node state: adapter, cache, queue, app manager, and optional history store. AI Transport has a stricter horizontal matrix because streaming recovery depends on durable history, versioned-message state, and shared orphan ownership. For horizontal adapters (`redis`, `redis-cluster`, `nats`, `pulsar`, `rabbitmq`, `google-pubsub`, `kafka`, `iggy`, or `omq`), configure shared non-memory history and version-store backends plus Redis or Redis Cluster cache. Startup rejects AI Transport with process-local memory history, version stores, or cache on horizontal adapters. ## Architecture Each WebSocket lives on exactly one node, but a publish can arrive at any node: over HTTP through the load balancer, or as a client event from a socket on another node. The adapter closes that gap. The receiving node delivers to its own subscribers and publishes the message to the adapter bus; every other node receives it and delivers to its own subscribers. Cluster-wide questions, such as channel occupancy or presence membership, are answered by asking peers over the same bus or from gossiped counts. At minimum, a production cluster has: - a load balancer with WebSocket upgrade support - multiple Sockudo nodes - a shared adapter for cross-node fanout - shared cache for rate limits, idempotency, and coordination - shared queue for webhooks and push delivery - shared app manager for dynamic app credentials - metrics and logs from every node ### What breaks if a dependency is node-local | Dependency | If left on `memory` or `local` in a cluster | | --- | --- | | Adapter | Subscribers on other nodes never receive the publish. | | Cache | Idempotent retries that land on another node publish twice; token revocations do not propagate. | | Rate limiter | Each node enforces its own bucket, so the effective limit grows with node count. | | Queue | Webhook and push jobs are lost when the node that holds them exits. | | History and version store | Recovery and history reads on another node cannot prove continuity and fail closed. | | App manager | App changes must be redeployed to every node. | ## Adapter choices | Adapter | Driver | Strength | | --- | --- | --- | | Redis | `redis` | Simple, common, low-latency local and regional deployments. | | Redis Cluster | `redis-cluster` | Higher Redis scale and shard-aware deployments. | | NATS | `nats` | Lightweight pub/sub with strong operational ergonomics. | | Kafka | `kafka` | Durable stream backbone and high-volume integration pipelines. | | RabbitMQ | `rabbitmq` | Enterprise messaging and routing patterns. | | Pulsar | `pulsar` | Multi-tenant stream workloads. | | Google Pub/Sub | `google-pubsub` | Managed GCP fanout. | | Apache Iggy | `iggy` | High-throughput persistent log workloads, with replicated VSR clusters. | | OMQ | `omq` | Brokerless PUB/SUB between nodes; messages in flight are not retained. | If you have no strong preference, start with Redis: it is also the natural choice for the shared cache, queue, and rate limiter, so one dependency covers four roles. ### NATS notes NATS is a good fit for lightweight cross-node fanout, but Sockudo clusters should avoid turning every client subscribe or unsubscribe into a distributed request/reply round trip. Keep room-switch churn on local channel state where possible, and reserve cluster-wide socket counts for post-ack meta events, webhooks, HTTP inspection, and operator views. For subscription-churn or room-switch benchmarks, prefer gossiped aggregate counts so count reads stay local on each node: ```bash ADAPTER_ENABLE_SOCKET_COUNTING=false ADAPTER_AGGREGATE_COUNTS=true ``` Presence first-join and last-leave checks remain strict by default because they drive member webhooks and presence history. For workloads that prefer maximum churn throughput over immediate transition consistency, opt into the replicated presence-registry fast path: ```bash ADAPTER_FAST_PRESENCE_TRANSITIONS=true ``` For Kubernetes NATS clusters, prefer explicit StatefulSet pod DNS entries over a single headless service URL when you want better initial client spread: ```json { "adapter": { "driver": "nats", "nats": { "servers": [ "nats://sockudo-nats-0.sockudo-nats-headless:4222", "nats://sockudo-nats-1.sockudo-nats-headless:4222", "nats://sockudo-nats-2.sockudo-nats-headless:4222" ], "request_timeout_ms": 5000, "connection_timeout_ms": 5000, "subscription_capacity": 131072, "client_capacity": 131072, "max_reconnects": 60, "no_echo": true } } } ``` If `nodes_number` is set, it means expected Sockudo nodes, not NATS server replicas. Use it only when the Sockudo replica count is fixed or injected from deployment automation; otherwise leave discovery enabled. ### Apache Iggy cluster notes Sockudo supports Apache Iggy 0.9 VSR clusters for both the adapter and the queue. Run at least three Iggy replicas: three tolerate one failed replica, five tolerate two. A two-replica cluster cannot make progress after either fails. Point Sockudo at one replica and list the others as seeds, so a node that is down at startup does not block bootstrap: ```bash ADAPTER_DRIVER=iggy QUEUE_DRIVER=iggy IGGY_CONNECTION_STRING=iggy://iggy:secret@iggy-1.internal:8090 IGGY_CLUSTER_SEEDS=iggy-2.internal:8090,iggy-3.internal:8090 QUEUE_IGGY_DURABILITY=persisted ``` After it connects, the Iggy SDK learns the full roster from cluster metadata, reconnects to the leader, fails over to the surviving replicas when its node disappears, and rejoins queue consumer groups. Losing the Iggy leader pauses writes until the surviving replicas elect a new one. A crashed or partitioned leader is noticed only after Iggy's `cluster.heartbeat_timeout` (5 s by default, 2 s minimum), so expect roughly 6 to 9 seconds without cross-node fanout. Publishes wait through that window for up to `failover_timeout_ms` (15 s by default) and then complete; local subscribers on the publishing node are served immediately as always. `/up` on every Sockudo node can return 503 for the same window, so keep readiness probes tolerant of about 10 seconds of failures; the Kubernetes defaults are. Lowering `heartbeat_timeout` shortens the pause at the cost of spurious elections on loaded hosts. Each replica must advertise an address Sockudo can reach: the Iggy roster (`cluster.nodes[*].ip` or `advertised_address`) is what the SDK dials during failover, not the seed hostnames. `IGGY_NODES_NUMBER` counts Sockudo nodes, not Iggy replicas. See [configuration](/docs/reference/configuration#apache-iggy-adapter-and-queue) for durability and reconnection tuning, and `docker-compose.iggy-cluster.yml` for a local three-replica stack. ## Load balancing Sockudo does not require sticky sessions for basic pub/sub when the adapter is shared. Sticky sessions can still reduce reconnect churn and preserve local buffers during rolling updates. Use: - WebSocket upgrade headers - idle timeouts longer than heartbeat intervals - health and readiness checks - draining before pod termination - disruption budgets for production clusters For Kubernetes probes, use `/live` for liveness and startup probes. `/up` checks configured apps and shared dependencies, so it is appropriate for readiness but too expensive for liveness under backend pressure. A slow app manager, cache, queue, or adapter should make the pod unready, not restart it. ```yaml livenessProbe: httpGet: path: /live port: http startupProbe: httpGet: path: /live port: http readinessProbe: httpGet: path: /up/ port: http ``` If a shared dependency such as Redis slows down, every pod fails `/up` at once. As a liveness probe that restarts the whole fleet together; as a readiness probe it only stops routing new traffic. ## Duplicate delivery Distributed realtime systems must tolerate retries and duplicate delivery. Sockudo features that help: - HTTP `idempotency_key` - V2 `message_id` - client-side message deduplication in native SDKs - adapter-level duplicate suppression visibility - recovery continuity checks Consumers should treat application event IDs as stable and idempotent. ## Recovery across nodes V2 recovery uses stream continuity. A reconnect to a different node can recover only if the required replay state is available through the configured shared backend or still present in a valid buffer. The hot replay buffer lives in each node's memory and holds messages published through that node, so a reconnect to a different node usually cannot prove continuity from it. Recovery then falls through to durable history: with a shared history backend the gap is replayed; with `memory` history it cannot be proven and the resume fails. Fail closed if continuity cannot be proven. Do not display a recovered state unless the server returns a successful resume. ## Push fanout at scale Push notification fanout is queue-oriented. A realtime publish and a push publish may target the same logical event, but they have different latency, retry, and delivery semantics. Operational recommendations: - keep push `sync` false in production - use a stable `publishId` for publish retries - partition high-volume channel pushes by tenant or campaign - set publish status retention high enough for support workflows - alert on provider error rates and queue backlog - store provider credentials in secrets, not config maps - use capacity planning before large campaigns ## Rolling deploys On SIGTERM or SIGINT, Sockudo: 1. Reports not ready: `/up` and `/ready` return 503 `DRAINING` and new WebSocket upgrades are rejected with 503. The listener stays open and HTTP API requests are still served, except publishes (`/events`, `/batch_events`) on a node without a horizontal adapter: those return 503 `draining` with `Retry-After`, because no subscriber can receive them there any more. Publishers can retry them against a healthy instance. 2. Closes existing connections with code 4200 so clients reconnect right away instead of waiting for the grace period or a load-balancer cutoff. By default every connection closes at once. `shutdown_close_delay_ms` waits that long first, so the load balancer can see `/ready` return 503 before anyone reconnects. `shutdown_close_spread_ms` spreads the closes evenly over that window, so a node's clients do not all reconnect onto the remaining nodes in the same instant. A second signal closes any remaining connections at once. 3. Keeps the listener open until `shutdown_grace_period` seconds after the signal so load balancers finish deregistration without connection-refused errors. The close delay and spread run inside this window; together they must not exceed it. 4. Waits for connection cleanup, pending presence leases, and delayed lifecycle webhook producers, then flushes the remaining webhook batch. This phase has a separate budget of `queue.reliability.shutdown_timeout_ms` (30 seconds by default). Presence leases and reconnect checks retain their normal timing; shutdown does not force an early departure. 5. Drains local memory-queue work before disconnecting the queue and other backends. Broker queues retain their enqueued jobs and apply their normal worker shutdown budget. Allow the process supervisor enough time for the listener grace, lifecycle drain, queue worker shutdown, and connection/backend teardown. The two drain phases can each use `queue.reliability.shutdown_timeout_ms`. An exhausted lifecycle budget logs a warning that pending events may be lost; a forced process kill cannot flush in-memory events. See [shutdown webhook delivery](/docs/server/webhooks#shutdown-delivery). Set `shutdown_grace_period` to cover your load balancer's deregistration time (for a readiness probe, roughly `periodSeconds × failureThreshold` plus endpoint propagation). Keep it well below the load balancer's connection-draining timeout, otherwise the balancer cuts idle WebSocket connections before Sockudo finishes deregistering. For large nodes, spread the reconnect load. For example, with a load balancer that marks a node down after about two seconds: ```toml title="config.toml" shutdown_grace_period = 20 shutdown_close_delay_ms = 3000 shutdown_close_spread_ms = 15000 ``` Clients can add their own spread too. For example, `@sockudo/client` has `retryJitterMs`. Set `terminationGracePeriodSeconds` above `shutdown_grace_period` plus the lifecycle and queue drain budgets, or the kubelet kills the process before in-memory webhook events are flushed. Then: 1. Keep adapter and cache dependencies available. 2. Watch reconnect, resume, and missed-message metrics. 3. Roll nodes in small batches. ## Metrics to watch Metric names below assume the default `sockudo_` prefix. Full tables and alert suggestions are in [Observability](/docs/server/observability). | Signal | Metrics | | --- | --- | | Active connections by node | `sockudo_connected`, by `instance` | | Connection churn | `sockudo_new_connections_total`, `sockudo_new_disconnections_total` | | Subscriptions by channel class | `sockudo_channel_subscriptions_total`, `sockudo_active_channels` (label `channel_type`) | | Publish volume | `sockudo_http_calls_received_total`, `sockudo_ws_messages_sent_total` | | Fanout latency | `sockudo_broadcast_latency_ms` | | Cross-node requests and adapter health | `sockudo_horizontal_adapter_resolve_time`, `sockudo_horizontal_adapter_uncomplete_promises`, `sockudo_horizontal_transport_reconnections_total`, `sockudo_horizontal_transport_messages_dropped_total` | | Recovery | `sockudo_history_recovery_success_total{source}`, `sockudo_history_recovery_failures_total{code}` | | Durable state | `sockudo_history_degraded_channels`, `sockudo_history_reset_required_channels`, `sockudo_history_queue_depth` | | AI stream orphans | `sockudo_ai_active_streams`, plus `ai_stream_orphaned` webhook delivery | | Webhook and job queues | `sockudo_queue_depth`, `sockudo_queue_settled_total{outcome}` | | Push | `sockudo_push_publish_accepted_total`, `sockudo_push_dispatched_total`, `sockudo_push_provider_failures_total`, `sockudo_push_dispatch_duration_seconds` | ## Capacity checklist Before increasing traffic, follow [Capacity planning and benchmarks](/docs/deployment/capacity-planning) and run a scenario that covers: - peak connected clients - high-frequency channel fanout - private and presence auth throughput - durable history writes - recovery after node restart - AI stream orphan closure after node death - pause/unpause partition checks with `scripts/ai-transport-jepsen-lite.sh` - push burst admission - push provider throttling - webhook retry behavior For room-switch workloads, `benches/subscription-churn.js` models connected sockets that periodically unsubscribe and subscribe to a new room. Churn rate is approximately `VUS / (ROOM_SWITCH_INTERVAL_MS / 1000)`. For example, 10,000 users switching every 20 seconds produces about 500 unsubscribe+subscribe cycles per second: ```bash k6 run \ -e WS_HOSTS=wss://example.com/app/app-key \ -e VUS=10000 \ -e CHANNEL_COUNT=4000 \ -e ROOM_SWITCH_INTERVAL_MS=20000 \ -e SOCKET_LIFETIME_MS=600000 \ -e DURATION=10m \ benches/subscription-churn.js ``` ## Next steps - [Kubernetes](/docs/deployment/kubernetes): Probes, disruption budgets, and Helm values for a cluster. - [Capacity planning](/docs/deployment/capacity-planning): Benchmarks and sizing before a traffic increase. - [Observability](/docs/server/observability): Metric tables and alerts for every subsystem. - [History and recovery](/docs/server/history-recovery): Why cross-node recovery needs a shared history backend.