Kubernetes and Helm
Deploy Sockudo with production Helm values, safe probes, disruption controls, ingress, and node tuning.
This guide deploys Sockudo to Kubernetes with the official Helm chart, then covers the settings that matter for long-lived connections: probes, drain timing, autoscaling, ingress, and node tuning. It is for platform teams running several replicas who want repeatable rollouts and failure-domain placement.
Kubernetes is a good Sockudo platform when you need repeatable rollouts, failure-domain placement, secret injection, metrics discovery, and several replicas. It does not remove the state model: pods still need shared adapters and stores, and scale-down still disconnects their clients.
Install the chart
The chart is published as an OCI artifact at oci://ghcr.io/sockudo/charts/sockudo. The release
pipeline packages it with the same version as the Sockudo release, so chart 5.3.0 deploys image
5.3.0 by default.
-
Create the namespace and the Secrets that the production values reference. Write each value to a file first so it never appears in shell history or a manifest:
Terminal window kubectl create namespace sockudokubectl create secret generic sockudo-app -n sockudo \--from-file=default-app-id=./secrets/app-id \--from-file=default-app-key=./secrets/app-key \--from-file=default-app-secret=./secrets/app-secretkubectl create secret generic sockudo-redis -n sockudo \--from-file=redis-password=./secrets/redis-password--from-filestores the exact bytes, including a trailing newline. Create the files without one, for exampleopenssl rand -hex 32 | tr -d '\n' > secrets/app-secret.Verify with
kubectl get secret sockudo-app -n sockudo -o jsonpath='{.data}' | jq 'keys', which listsdefault-app-id,default-app-key, anddefault-app-secret. -
Save the production values as
values-production.yamland adapt hosts, Redis address, and limits. -
Install or upgrade the release:
Terminal window helm upgrade --install sockudo oci://ghcr.io/sockudo/charts/sockudo \--version 5.3.0 \--namespace sockudo \--create-namespace \--values values-production.yaml -
Wait for the rollout:
Terminal window kubectl rollout status deploy/sockudo -n sockudoExpect
deployment "sockudo" successfully rolled out. Then run the checks in Verify the deployed state.
Pin the chart and image version in GitOps or release automation. Do not deploy latest.
To work on the chart itself, install from a checkout instead: helm upgrade --install sockudo ./charts/sockudo.
ArgoCD
The chart is published as an OCI artifact, so ArgoCD consumes it directly without cloning this repository:
apiVersion: argoproj.io/v1alpha1kind: Applicationmetadata: name: sockudo namespace: argocdspec: project: default source: repoURL: ghcr.io/sockudo/charts chart: sockudo targetRevision: 5.3.0 helm: valuesObject: replicaCount: 3 destination: server: https://kubernetes.default.svc namespace: sockudo syncPolicy: syncOptions: - CreateNamespace=trueNote repoURL carries no oci:// prefix: for a Helm chart source, ArgoCD takes the bare
registry path and infers the OCI protocol from chart being set.
Configuration from a Secret
By default the chart renders the config.* values into a ConfigMap and mounts it at
/app/config/config.json. Under GitOps that ConfigMap is generated from values held in a
repository, so it can only carry configuration that is safe to commit.
Per-app webhooks are the case where it is not. Webhooks are expressible only in the config file,
never through environment variables, so an app that has them must carry its secret in the same
file. defaultApp.existingSecret does not help: it configures the environment-defined default
app, which has no webhook support.
Point config.existingSecret at a Secret to supply the whole file instead:
config: existingSecret: sockudo-config existingSecretKey: config.jsonThe ConfigMap is then not rendered, and the config volume is backed by the Secret. Combining
config.existingSecret with configJson fails the render rather than silently ignoring one of
them. The config.* keys that the chart also emits as environment variables, such as the driver
selections and shutdownGracePeriod, still apply and override the file.
The content must be JSON: it is mounted as config.json and Sockudo selects its parser from the
file extension, even though the annotated reference configuration is TOML.
Helm never sees the Secret’s content, so the checksum/config pod annotation is not emitted in
this mode. Rotating the Secret updates the mounted file but does not restart the pods, and Sockudo
reads its configuration only at startup - use a reloader controller or restart the Deployment.
This is the shape that pairs with a secret operator. With External Secrets Operator, an
ExternalSecret pulls the config file out of the backing store and the chart mounts the Secret it
produces:
apiVersion: external-secrets.io/v1kind: ExternalSecretmetadata: name: sockudo-config namespace: sockudospec: refreshInterval: 5m secretStoreRef: kind: ClusterSecretStore name: my-secret-store target: name: sockudo-config creationPolicy: Owner template: engineVersion: v2 data: config.json: "{{ .sockudoConfig }}" data: - secretKey: sockudoConfig remoteRef: key: SOCKUDO_CONFIG_FILEProduction values example
The following is a regional three-pod baseline with one immutable app sourced from a Kubernetes Secret and Redis used for fanout, cache, queue, and rate limits:
replicaCount: 3
image: repository: ghcr.io/sockudo/sockudo tag: "5.3.0" pullPolicy: IfNotPresent
strategy: type: RollingUpdate rollingUpdate: maxUnavailable: 0 maxSurge: 25%
config: mode: production debug: false logOutputFormat: json rustLog: "info,sockudo=info" shutdownGracePeriod: 40 adapterDriver: redis appManagerDriver: memory cacheDriver: redis queueDriver: redis rateLimiterDriver: redis rateLimiter: enabled: true apiMaxRequests: 1000 apiWindowSeconds: 60 apiTrustHops: 1 wsMaxRequests: 100 wsWindowSeconds: 60 wsTrustHops: 1 metrics: enabled: true
defaultApp: enabled: true existingSecret: sockudo-app maxConnections: 50000 enableClientMessages: false enableUserAuthentication: true
redis: host: redis.internal port: 6379 existingSecret: sockudo-redis
extraEnv: # Chart default allocator tuning; keep it, because setting extraEnv replaces the list. - name: _RJEM_MALLOC_CONF value: "background_thread:true,dirty_decay_ms:2000,muzzy_decay_ms:0,tcache_max:4096,abort_conf:true" - name: SOCKUDO_MAX_CONNECTIONS value: "50000" - name: ADAPTER_FALLBACK_TO_LOCAL value: "false" - name: SOCKUDO_DEFAULT_APP_ALLOWED_ORIGINS value: "https://app.example.com" - name: INSTANCE_PROCESS_ID valueFrom: fieldRef: fieldPath: metadata.name
resources: requests: cpu: "1" memory: 1Gi limits: memory: 2Gi
readinessProbe: httpGet: path: /up/production port: http periodSeconds: 10 timeoutSeconds: 3 failureThreshold: 3
livenessProbe: httpGet: path: /live port: http periodSeconds: 20 timeoutSeconds: 3 failureThreshold: 3
startupProbe: httpGet: path: /live port: http periodSeconds: 5 timeoutSeconds: 3 failureThreshold: 30
terminationGracePeriodSeconds: 120
pdb: enabled: true minAvailable: 2
topologySpreadConstraints: - maxSkew: 1 topologyKey: topology.kubernetes.io/zone whenUnsatisfiable: DoNotSchedule labelSelector: matchLabels: app.kubernetes.io/name: sockudo
serviceMonitor: enabled: true interval: 30s scrapeTimeout: 10s
ingress: enabled: true className: nginx annotations: nginx.ingress.kubernetes.io/proxy-read-timeout: "180" nginx.ingress.kubernetes.io/proxy-send-timeout: "180" nginx.ingress.kubernetes.io/proxy-buffering: "off" hosts: - host: ws.example.com paths: - path: / pathType: Prefix tls: - secretName: sockudo-tls hosts: - ws.example.comWhat the less obvious values do:
defaultApp.existingSecretreads the keysdefault-app-id,default-app-key, anddefault-app-secret. If the ID or key is missing, the app is not registered.redis.existingSecretmust containredis-password;redis-usernameis optional.defaultApp.maxConnectionsbecomesSOCKUDO_DEFAULT_APP_MAX_CONNECTIONS, the per-app quota.SOCKUDO_MAX_CONNECTIONSis the separate per-pod cap across all apps.ADAPTER_FALLBACK_TO_LOCAL=falsemakes a pod that cannot reach Redis at startup fail instead of running as an isolated node. The default istrue.INSTANCE_PROCESS_IDfrom the pod name gives each pod a unique, readable identity. The chart sets the same variable itself whencluster.enabledis true; do not define it twice in that case.strategysurges new pods before removing old ones; see Rollouts and disruptions.
Adapt the topology label selector when the release name or chart labels differ. If application
records must change dynamically, select a durable app manager instead of memory and configure its
database credentials from a Secret.
For advanced nested configuration, use the chart’s configJson value or mount your own static
file. Keep secret values out of configJson; combine it with extraEnvFrom, ${VAR}
placeholders, or file-backed Secrets.
Probes
Use different endpoints for different decisions:
| Probe | Endpoint | Meaning |
|---|---|---|
| Startup | /live | The process has started. |
| Liveness | /live | The process runtime is alive. |
| Readiness | /up or /up/<app-id> | At least one app is configured and shared dependencies are available. On the public port /up/<app-id> answers like /up; use the metrics port (9601) /up/<app-id> to require that specific app. |
| Capacity-aware readiness | /ready | Same dependency checks as /up, plus 503 CAPACITY when the pod nears SOCKUDO_MAX_CONNECTIONS. |
| New-connection admission | /accept-traffic | The pod is not draining or shedding new connections under memory pressure. |
/ready goes unavailable at the high watermark (default 95% of SOCKUDO_MAX_CONNECTIONS) and
recovers at the low watermark (default 85%), so a full pod stops receiving new clients without
flapping. Tune it with config.httpApi.readiness.highWatermark and lowWatermark, which the chart
writes to its generated ConfigMap; with configJson or config.existingSecret, set
http_api.readiness in your file instead. With a zero
connection limit the capacity gate is disabled. Use /ready for readiness when you want full pods
taken out of rotation; keep /up when rollout health must succeed even on a full pod.
Set probe timeout below its period and above normal dependency-check latency. Sockudo’s
health_check_timeout_ms (default 2000) bounds each dependency check separately.
The standalone Redis and Redis Cluster adapter checks use redis_health_check_attempts (default 2)
within that budget. Set 1 to give a single attempt the full budget. With retries enabled, Sockudo
requires at least 250 ms per attempt and 100 ms between attempts. For example, five attempts require
at least 1,650 ms. An insufficient timeout fails startup with an error that reports the required
minimum. Earlier attempts reserve time for retries, and the last can use the remaining time.
Redis Cluster requires a successful PING from every primary.
Resources and connection admission
Persistent connections do not map cleanly onto CPU-only autoscaling:
- memory rises with sockets, subscriptions, pending writes, and per-connection feature state
- CPU rises with handshake, auth, messages, fanout, compression, filtering, and reconnect bursts
- a pod can have low CPU while holding too many quiet sockets to remove safely
Set SOCKUDO_MAX_CONNECTIONS on every pod so a single replica cannot absorb more connections than
its measured memory and file-descriptor budget. Keep minimum replicas high enough for the peak
quiet-socket count even when CPU is low.
For a second guard based on actual memory use, enable the chart’s memory-pressure admission control:
config: httpApi: acceptTraffic: enabled: true memoryThreshold: 0.9 sampleIntervalMs: 500With memoryLimitBytes: null (the default), Sockudo discovers the pod’s finite cgroup memory limit.
When process RSS reaches the configured fraction, the pod rejects only new native and Ably
WebSocket connections with 503/retry guidance while established sessions continue. It resumes
admission after a later sample falls below the threshold. The sampler is independent of metrics
scrapes and fails open if Linux RSS or cgroup data is unavailable.
For example (illustrative): with limits.memory: 2Gi and memoryThreshold: 0.9, new connections
are refused once RSS reaches about 1.8 GiB, leaving roughly 200 MiB for established sessions to
absorb a fanout burst before the OOM killer would disconnect all of them.
Keep /up as Kubernetes readiness so dependency failures remain visible. If the ingress or external
load balancer supports a separate backend-admission or network-watcher probe, point that probe at
/accept-traffic. Direct admission enforcement remains active even without such a probe.
CPU limits can throttle a pod during the exact reconnect or fanout burst it needs to process. Requests plus a memory limit are a reasonable starting point on a dedicated node pool. Add a CPU limit only when isolation requires it and benchmark with the same quota.
Autoscaling
The chart can configure an HPA:
autoscaling: enabled: true minReplicas: 3 maxReplicas: 12 targetCPUUtilizationPercentage: 65 targetMemoryUtilizationPercentage: 75 behavior: scaleUp: stabilizationWindowSeconds: 30 scaleDown: stabilizationWindowSeconds: 600 policies: - type: Pods value: 1 periodSeconds: 120When autoscaling.enabled is true, the chart omits replicas from the Deployment and the HPA owns
the replica count.
CPU and memory are fallback signals, not a complete realtime scaling policy. A stronger setup also uses active connections per pod, connection admission rejections, event-loop or fanout latency, adapter backlog, and reconnect rate through an external/custom metrics adapter.
autoscaling.metrics is passed through to the HPA verbatim and accepts any autoscaling/v2 metric
type, so those signals can be expressed directly. sockudo_connected is the connection gauge:
autoscaling: enabled: true minReplicas: 3 maxReplicas: 12 metrics: - type: External external: metric: name: sockudo_connected target: type: AverageValue averageValue: "40000"An External metric requires a metrics adapter, such as Prometheus Adapter or KEDA, that exposes
sockudo_connected to the Kubernetes external metrics API.
For example (illustrative): with SOCKUDO_MAX_CONNECTIONS=50000, a target of 40000 adds pods at
80% connection utilization, before /ready reports CAPACITY at 47,500 and well before admission
rejects at 50,000.
Setting it replaces the CPU and memory metrics generated from
targetCPUUtilizationPercentage and targetMemoryUtilizationPercentage rather than adding to
them. That is deliberate: an HPA acts on the highest recommendation from any metric, so leaving
CPU in place would keep overriding a connection-based policy. Put CPU back in the list explicitly
if you want both.
Scale up early. Scale down slowly and one pod at a time. Every removed pod makes its clients reconnect, so an aggressive HPA can oscillate and manufacture load.
Rollouts and disruptions
Set:
- a PodDisruptionBudget that leaves enough connection capacity online
- zone or host topology spread
- a termination grace period covering listener grace, webhook drain, queue worker shutdown, and teardown
- a rollout
maxUnavailablecompatible with the PDB and remaining socket capacity - load-balancer deregistration or endpoint propagation time inside the drain budget
On SIGTERM, Sockudo rejects new WebSocket upgrades, closes existing connections with code 4200 so
clients reconnect right away, and keeps the listener open for SHUTDOWN_GRACE_PERIOD seconds
while /up and /ready return 503 DRAINING:
sequenceDiagram participant K as Kubelet participant P as Old pod participant L as Load balancer participant C as Clients participant N as Other pods K->>P: SIGTERM P-->>L: /ready returns 503 DRAINING Note over P,L: wait shutdown_close_delay_ms P->>C: Close frame 4200 C->>L: Reconnect L->>N: Route to ready pods Note over K,P: listener open until grace ends, then webhook and queue drain
By default the close happens immediately and to every connection at once.
SHUTDOWN_CLOSE_DELAY_MS waits first, so the load balancer can observe the 503 before anyone
reconnects, and SHUTDOWN_CLOSE_SPREAD_MS spreads the closes over a window so the remaining pods
are not hit by one simultaneous reconnect wave. Delay plus spread must fit inside
SHUTDOWN_GRACE_PERIOD; set them through extraEnv. See
rolling deploys for the full sequence.
Set SHUTDOWN_GRACE_PERIOD (chart value config.shutdownGracePeriod) above the readiness probe’s
periodSeconds × failureThreshold plus endpoint propagation time, and keep
terminationGracePeriodSeconds above SHUTDOWN_GRACE_PERIOD plus twice
QUEUE_SHUTDOWN_TIMEOUT_MS / 1000, with additional time for connection and backend teardown.
The two budgets cover webhook draining and queue worker
shutdown. An early SIGKILL can lose buffered lifecycle events.
For example (illustrative), with the production values above:
readiness detection = periodSeconds 10 × failureThreshold 3 = 30 sSHUTDOWN_GRACE_PERIOD > 30 s + ~10 s endpoint propagation → 40 sdrain budget = 40 s + 2 × (QUEUE_SHUTDOWN_TIMEOUT_MS 30000 / 1000) = 100 sterminationGracePeriodSeconds = 100 s + 20 s teardown margin → 120 sThe chart defaults (shutdownGracePeriod: 10, terminationGracePeriodSeconds: 30) are sized for
development; raise both for production.
strategy is passed through to the Deployment. Left unset, Kubernetes applies its default of
maxUnavailable: 25% / maxSurge: 25%, which takes a quarter of the connection capacity offline
during a rollout - exactly while the clients from the replaced pods are reconnecting. Surging
instead keeps capacity flat:
strategy: type: RollingUpdate rollingUpdate: maxUnavailable: 0 maxSurge: 25%During a rollout, watch connection count by pod. Kubernetes considers replica count, not how many sockets each replica owns. One terminating pod may hold a disproportionate share after a long uptime.
If strict connection drain is required, remove readiness first, wait for endpoint and load-balancer propagation, then terminate. Test this behavior with the actual ingress controller; it is not identical across controllers.
Ingress and load balancers
The production example’s apiTrustHops: 1 and wsTrustHops: 1 assume an ingress such as NGINX
that appends one client address to X-Forwarded-For. These values select the client’s position
from the right, not a universal proxy count. A Google external Application Load Balancer directly
in front of Sockudo appends two addresses and needs 2. Restrict pod access to trusted ingress
sources before enabling either value. The default 0 ignores both X-Forwarded-For and
X-Real-IP; see client IP extraction.
Confirm all layers:
- accept HTTP/1.1 WebSocket upgrades
- preserve
UpgradeandConnectionsemantics - have idle timeouts above the heartbeat interval with margin
- do not buffer WebSocket traffic
- expose a dependency-aware readiness path
- drain targets during pod termination
The ingress annotation example above is specific to ingress-nginx. Use the equivalent settings for
AWS Load Balancer Controller, Google Cloud Load Balancing, Azure Application Gateway, Traefik,
Envoy, HAProxy, or a service mesh. The chart also has a separate wsIngress block for controllers
that need different annotations for WebSocket traffic.
Sticky sessions are not required for basic pub/sub with a shared adapter. They can reduce reconnect-to-new-node churn, but must not substitute for shared state.
When preserving client IPs with externalTrafficPolicy: Local or proxy-protocol features, retest
load distribution and health checks. Source-IP preservation can reduce the set of eligible nodes.
Pod and node sysctls
First deploy with provider defaults and inspect counters. Managed Kubernetes node images already ship with non-trivial tuning, and an unnecessary override can reduce stability.
Kubernetes classifies sysctls as safe or unsafe. Safe, namespaced values can be applied in the pod security context when the cluster version and admission policy allow them:
podSecurityContext: runAsNonRoot: true runAsUser: 1000 runAsGroup: 1000 fsGroup: 1000 sysctls: - name: net.ipv4.tcp_keepalive_time value: "600" - name: net.ipv4.tcp_keepalive_intvl value: "60" - name: net.ipv4.tcp_keepalive_probes value: "5"net.core.somaxconn is commonly treated as unsafe. A pod-level value requires both:
- an exact kubelet
allowedUnsafeSysctlsentry on every eligible node - the matching
podSecurityContext.sysctlsvalue and an admission policy that permits it
See Kubernetes’ sysctl documentation
and the provider-specific node-pool guide before enabling it. Do not grant a privileged container
or broad net.* permission to set one value.
Node-level sysctl configuration and pod network namespaces are distinct. Verify the effective value inside the scheduled pod:
kubectl exec -n sockudo deploy/sockudo -- cat /proc/sys/net/core/somaxconnkubectl exec -n sockudo deploy/sockudo -- sh -c 'ulimit -n; cat /proc/1/limits'Kubernetes has no portable pod field for POSIX rlimit values. The effective nofile comes from
the container runtime and node image. If it is too low, change the runtime/node configuration or
use a provider-supported node image customization, then verify again inside the pod.
Provider examples are in Cloud platforms.
Network capacity
High socket counts can hit infrastructure before the pod:
- load-balancer connection and target limits
- node vNIC packets-per-second or bandwidth limits
- CNI IP allocation and conntrack tables
- NAT gateway state for outbound dependencies or load generators
- cross-zone traffic and broker latency
Inbound WebSockets do not consume a Sockudo pod’s local ephemeral port range. Avoid “fixing”
ip_local_port_range unless evidence points to an outbound connection or NAT bottleneck.
Verify the deployed state
-
Confirm the values Helm applied and where the pods landed:
Terminal window helm get values sockudo -n sockudokubectl get pods -n sockudo -o widekubectl get pdb -n sockudoEvery pod is
RunningandREADY 1/1, spread across zones, and the PDB showsMIN AVAILABLE 2. -
Check the file limit inside a pod:
Terminal window kubectl exec -n sockudo deploy/sockudo -- sh -c 'ulimit -n'The value must exceed
SOCKUDO_MAX_CONNECTIONSplus reserve. -
Check health through the Service:
Terminal window kubectl port-forward -n sockudo svc/sockudo 6001:6001curl -fsS -o /dev/null -w '%{http_code}\n' http://127.0.0.1:6001/livecurl -fsS http://127.0.0.1:6001/up/production/liveprints200and/up/productionprintsOK. -
Check metrics through the metrics Service:
Terminal window kubectl port-forward -n sockudo svc/sockudo-metrics 9601:9601curl -fsS http://127.0.0.1:9601/metrics | grep '^sockudo_connected'The output contains
sockudo_connectedsamples. -
Run a node drain and a rolling restart under load, and watch reconnects and recovery. A manifest that renders successfully is not yet a tested realtime deployment.