Horizontal scaling
This page explains why OpenWA runs as a single instance, which parts of it you can scale out, and how to grow capacity safely within that model. Read it before you reach for replicas: 3.
OpenWA ships as a single-process application, and the safe default is still exactly one API instance per session-data volume (replicas: 1). Two instances sharing the same session storage corrupt WhatsApp authentication and can get the linked account logged out or banned. Sticky sessions and shared storage do not fix this on their own.
Multi-node operation is now possible opt-in as of v0.14.0, but only when every node opts into the session-ownership layer (NODE_URL on every node, a stable NODE_ID, one PostgreSQL data database shared by every node, Redis for the event fan-out, and synchronized clocks). Without that layer, the corruption risk below is unchanged. The prerequisites and the gaps that remain are explained in Multi-node operation (experimental).
The core constraint: engine state lives in memory
Every running session is a live, stateful connection to WhatsApp:
- a Chromium browser, on the default
whatsapp-web.jsengine, or - a WebSocket client, on the
baileysengine (setENGINE_TYPE=baileys).
OpenWA holds that connection — plus its reconnect, error, and status state — in in-memory maps inside the API process. By default there is no shared registry of which instance owns which session, so two processes can race to start the same session; the opt-in claim and lease added in v0.14.0 (Multi-node operation (experimental)) closes that race only when you enable it. When the process stops, the live connections stop with it; another process cannot pick them up.
That single fact drives the entire scaling model. A second instance has no way to know a session is already live elsewhere, so it tries to bring that session online too.
Two instances writing the same on-disk auth directory for one session corrupts it. WhatsApp's linked-device auth is not designed for concurrent writers, so you get a forced logout, a re-scan loop, or — worst case — a banned account. The danger peaks with AUTO_START_SESSIONS=true, where every instance tries to bring every session online the moment it boots.
Cookie or IP affinity at the load balancer reduces the windows where two instances touch the same session, but it does not close them — failover, a rolling deploy, or a brief overlap still produces two writers. Affinity is not a substitute for an enabled claim/lease. Without the opt-in ownership layer, keep one instance.
What you can share, and what you can't
OpenWA already supports shared external datastores. That is what lets one instance grow, and it is the foundation a future multi-instance design would build on. What it does not have is a way to share live engine state.
| State | Where it lives | Shareable today? |
|---|---|---|
| Persistent data (session metadata, messages, webhooks, templates) | SQLite, or PostgreSQL with DATABASE_TYPE=postgres | Yes — point the instance at a managed PostgreSQL |
| Cache and queue | No cache, in-process rate-limit counters and inline webhook dispatch by default; Redis with REDIS_ENABLED=true (cache connection, rate-limit counters, WebSocket fan-out) and QUEUE_ENABLED=true (webhook and ingress job queue) | Yes — external Redis is supported |
| Media files | Local disk, or S3 / MinIO with STORAGE_TYPE=s3 | Yes — S3-compatible storage is shareable |
| Live WhatsApp engine connection | In-memory map in the API process | No by default; opt-in claim/lease fencing exists since v0.14.0 (experimental — see Multi-node operation) |
The first three rows move state out of the container, onto networked services that survive restarts and could one day back multiple instances. The fourth row cannot move — it is the WebSocket or browser the process is actively holding.
For how to migrate each layer onto its networked counterpart, see the Migration Guide. The environment variables themselves are in Configuration.
Scale up, not out
Because you are capped at one instance, capacity comes from vertical scaling (a bigger host) and engine choice — not more replicas.
- Add CPU and RAM. The default
whatsapp-web.jsengine runs a Chromium instance per session, so memory is usually the first ceiling you hit. More sessions and higher message volume both want more RAM. The bundled Compose files also cap the container at 2048 processes (OPENWA_PIDS_LIMIT), which the repository sizes at about 8 to 10whatsapp-web.jssessions: raise it with the memory cap (see Size the host). - Consider Baileys.
ENGINE_TYPE=baileysis a browser-free WebSocket client with a much smaller per-session footprint, so you fit more sessions on the same hardware. Review the engine trade-offs in Sessions before switching a live deployment. - Move the shared layers off-box. Switch to PostgreSQL and Redis so the database and cache stop competing with the engines for the host's resources under load.
- Run independent instances for isolation. Need more total sessions than one host carries, or hard tenant separation? Run separate OpenWA deployments, each with its own session-data volume and its own routing. They are independent single-instance deployments — they do not share live session state, and that is exactly why this is safe. Deployments that share one Redis must each set their own
QUEUE_PREFIX(v0.26.0+), or one's workers take the other's webhook jobs and complete them without delivering. The prefix covers the BullMQ queues only: withREDIS_ENABLED=truethe rate-limit counters and the WebSocket fan-out stay shared, so events reach the clients of every deployment on that Redis, and such deployments need a Redis each. The nodes of one deployment share one value, and changing it on a live deployment leaves the jobs queued under the old prefix unprocessed. On one Docker daemon the built-in datastores the dashboard starts have fixed container names (openwa-postgres,openwa-redis,openwa-minio), so a second instance that turns on Use Built-in attaches to the first one's container and data: let at most one instance per daemon use them, and point the others at datastores of their own.
These are unbenchmarked starting figures for the default whatsapp-web.js engine, not guarantees. Baileys needs considerably less. Always size from your own monitoring.
| Sessions | RAM | CPU |
|---|---|---|
| 1–5 | 2 GB | 2 cores |
| 5–10 | 4 GB | 4 cores |
| 10–20 | 8 GB | 8 cores |
Know when you are at the ceiling
Watch host memory and CPU, and poll the health endpoints. /api/health returns the basic status; /api/health/ready returns 503 when a required database is unreachable or the instance is draining, which is what your orchestrator should gate traffic on.
The basic check is public: it needs no X-API-Key header. Send a valid key and the response also carries the running version (since v0.19.0); a probe with no key, or with a key that fails validation, gets status and timestamp alone.
curl http://localhost:2785/api/health -H "X-API-Key: YOUR_API_KEY"
{
"status": "ok",
"timestamp": "2026-06-26T10:15:00.000Z",
"version": "0.31.0"
}
The readiness check is also public. It probes the auth/audit (main) and data databases (sharing one in-flight probe across concurrent callers and caching the result for 1 second outside shutdown since v0.28.0) and is what your orchestrator should gate traffic on:
curl -i http://localhost:2785/api/health/ready
When both databases respond, it returns 200 with each dependency marked up:
{
"status": "ok",
"details": {
"mainDatabase": { "status": "up" },
"dataDatabase": { "status": "up" }
}
}
When a required database is unreachable, it returns 503 with the failing dependency marked down — this is the response your probe will hit, so configure it to treat 503 as "not ready":
{
"status": "error",
"details": {
"mainDatabase": { "status": "down" },
"dataDatabase": { "status": "up" }
}
}
While the instance is draining during a graceful shutdown, it returns 503 with a shutdown detail even if the databases are still up, so traffic stops before teardown:
{
"status": "error",
"details": {
"shutdown": { "status": "draining" }
}
}
For media-heavy workloads, set INBOUND_MEDIA_GLOBAL_CONCURRENCY to cap downloads across sessions (default 0 leaves only the per-session cap). PostgreSQL stores each chat in arrival order, so text can wait behind earlier media; a media item is stored omitted only after it has waited twice MEDIA_DOWNLOAD_TIMEOUT_MS for its per-session slot with no slot released in that time. Archive uploads and parked inline webhook deliveries need extra memory beyond the download caps; see host sizing.
Keep at least 75 s termination grace, plus increases to the shutdown delay/drain settings. Once teardown begins, ordinary API calls return 503 with Connection: close; /api/health/live remains the liveness probe. Shutdown settings cover retry and signal-forwarding requirements.
When memory sits high under steady load, you have three levers, in order of effort: switch sessions to Baileys, give the host more RAM, or split sessions across a second independent instance. Adding replicas to the same deployment is not on that list.
The session, message, and other resource endpoints you would call alongside these checks do require an X-API-Key header — see Authentication for how to obtain a key.
Multi-node operation (experimental)
As of v0.14.0, the groundwork for true horizontal scaling ships opt-in and experimental. Single-instance remains the supported default. The multi-node path is something you turn on by setting the right variables, and several gaps (listed at the end of this section) still keep it short of a fully supported topology.
Session ownership: claim and lease
Sessions now carry an owner (nodeId) and a renewed lease (leaseExpiresAt). A process claims a session before starting its engine and refuses when another node holds a live claim, so two replicas can no longer both launch the same session — which is what corrupted the shared LocalAuth directory in the first place. A booting process also reaps only the sessions it may claim, instead of reporting a peer's live sessions as disconnected (and since v0.28.0 the boot reset queries also require leaseExpiresAt IS NULL OR leaseExpiresAt < :now, so a process accidentally started with a duplicate NODE_ID still cannot reset a session whose lease is live). Claims are released on a clean shutdown and expire otherwise, so failover does not depend on a graceful exit. Since v0.28.0, when a transient database error prevents start, stop, or delete from checking or claiming session ownership, the gateway answers 503 Service Unavailable without starting, stopping, or deleting the session.
The owner and the lease are columns of the session row in the data database, so every node must use DATABASE_TYPE=postgres against the same PostgreSQL database. With the default SQLite file (./data/openwa.sqlite) on each node's own data volume, each node reads and writes its own copy of the table and never sees another node's claim, so nothing stops two nodes from starting the same session. Since v0.27.0 the PostgreSQL pool sends statement_timeout, TimeZone='UTC' and search_path as SQL statements on each new connection rather than startup packet options, so PgBouncer in session pooling mode can sit in front of PostgreSQL without ignore_startup_parameters; transaction pooling remains unsupported because boot migrations and background trigram index builds use session-level advisory locks.
NODE_ID names the owning process. It defaults to the hostname and must be stable across restarts — a value that changes makes the restarted process a new node, which has to wait out its own previous lease before it can reclaim.
Give every process a unique NODE_ID, even with host networking or pm2 cluster mode. Since v0.24.0 a shared id logs duplicate_node_id while either process holds sessions. A stable id identifies one process, not the whole cluster.
Failover via the takeover sweep
A periodic takeover sweep (SESSION_TAKEOVER_SWEEP_MS, default 30000) adopts sessions whose holder's lease has lapsed — a crashed peer, or a recreated container whose new identity boots before its old lease expires. Adopting is gated by the same AUTO_START_SESSIONS flag as boot auto-start; since v0.23.5 the sweep itself is not, and runs on every node, because it also carries a job that starts nothing. A row a vanished node left ready, initializing, authenticating or action_required is corrected to disconnected once its lease expired more than two lease TTLs ago, which is three TTLs after the holder's last renewal plus up to one sweep interval. A qr_ready row is corrected only while it has no phone recorded, since the sweep never adopts a row without one; a qr_ready row that has one keeps its status, so the correction never turns a mid-pairing session into an adoptable one. Nothing else revisits such a row, which is why a node with auto-start off used to go on reporting a running engine no process held. Since v0.30.3, with auto-start off, a correction of a linked session that no operator stopped also logs, as the boot does, how many linked sessions stay disconnected and how to start them (action=auto_start_disabled). Only authenticated sessions in a running-or-should-be state are adopted; mid-pairing and operator-failed ones are left alone, and a cleanly stopped session releases its claim so it is never seen as lapsed. Since v0.27.0, when a takeover sweep's engine start fails during adoption, it releases its claim and sets the unowned active session row to disconnected. Adopting a session fails its stuck in-flight bulk batches — there is no auto-resume, because what the dead node already sent is unknowable.
Since v0.24.0 an explicit stop or force-kill persists across restart and takeover, until POST /api/sessions/{sessionId}/start. AUTO_START_SESSIONS=true does not undo an operator stop. Since v0.26.0 a DELETE that failed part-way, or died with its node, leaves the same kind of record: the session stays out of boot auto-start and takeover until an explicit start, or until a repeated DELETE removes it. A stop that arrives during a delete keeps the delete's claim, and when another node takes over an expired claim, each later removal transaction checks the new owner and the older delete stops.
Request routing (opt-in via NODE_URL)
When every node sets its own reachable URL (for example NODE_URL=http://10.0.0.5:2785), a session-scoped request landing on a non-owner is forwarded to the live owner and the owner's response is relayed back (the response carries x-openwa-served-by naming the owner). The forward happens after API-key auth, carries the caller's credentials, which the owner checks against its own key store (see below), is bounded by SESSION_PROXY_TIMEOUT_MS (default 60000; since v0.28.0 that timeout budgets both the response headers and the response body, and responses over 4 MiB stream directly to the caller instead of buffering in memory), and is one hop only — a forwarded request is never forwarded again. Since v0.23.5 a failed forward says whether the owner could have acted on it. A forward that never reached the owner answers 503 (the connection was refused, NODE_URL does not resolve, its host or network is unreachable, or the value is not a usable absolute URL): nothing ran there, so the call is safe to retry. A forward that passes SESSION_PROXY_TIMEOUT_MS answers 504, and any other failure, such as a connection that broke mid-request or a TLS certificate the forwarding node does not trust, answers 502. On those two the owner may already have carried the request out, so do not blindly repeat a non-idempotent call such as a message send. A request that still lands on a live non-owner (stale ownership, or a forged hop marker) is refused with a retryable 409 rather than executed there. A lapsed owner is deliberately not forwarded to: the local node handles the request, which is exactly how a takeover begins. Before v0.26.0 a session whose id is not a UUID, which a data import keeps from the deployment it came from, was never forwarded: the receiving node handled the request itself.
Without NODE_URL the whole routing path is inert, and single-node deployments pay nothing for it.
A path in NODE_URL is kept and put in front of every forwarded /api/... path (v0.23.7+; before, the path was discarded), so give one only for a reverse-proxy prefix: a value ending in /api forwards to /api/api/....
Read engineLoaded on GET /api/sessions and in the MCP session tools as "a live node holds an engine for this session". Since v0.23.7 it is true for a session another live node runs, not only for one the answering node runs. Without routing, only the node that runs a session can act on it: any other node answers 409 to start and stop, and 400 to logout and force-kill.
API keys and the audit log are per node. They live in the main database, which is always a SQLite file local to the node (MAIN_DATABASE_NAME, default ./data/main.sqlite), never in the shared PostgreSQL data database, and nothing replicates it. The node that receives a request checks the key against its own copy, and the owner checks it again against its own, so a forwarded call needs the same key on both: a key the owner does not have is refused there with 401. A key created through the API or the dashboard gets a fresh random value and exists only on the node that created it. The same value can reach several nodes through the API_MASTER_KEY each node is seeded with on its first boot (the seed runs only while no key exists), or through a copy of one node's main.sqlite taken while that node is stopped, which authenticates on another node only if it uses the same API_KEY_PEPPER. Revoking, narrowing or deleting a key on one node does not change the copies on the others.
The forwarded body is the one the receiving node already parsed, re-serialized as JSON. Since v0.23.6 the forward labels it application/json, so a form-encoded request is accepted on the owner. Before, the forward kept the Content-Type the client sent, so the owner's form parser read the JSON text as a single form key and answered 400.
Forwarded requests carry the client address in x-forwarded-for (the inbound chain preserved, the observed peer appended). For an allowedIps-restricted key or the per-IP throttler to see the real client on forwarded calls, list every peer node's address in each node's TRUSTED_PROXIES — otherwise the owner correctly ignores the chain and every forwarded request appears to come from the peer itself.
With routing in effect, start, stop and delete landing on the wrong node are forwarded like any other session-scoped call, and the owner's answer comes back. When a request is not forwarded, because the receiving node has no NODE_URL or the owner runs without one, stop and delete answer 409 while a live peer is running the session (so a request landing on the wrong node never writes disconnected over a peer's engine or deletes its row while the peer keeps running). A lapsed claim still proceeds, since taking over is what the claim rule allows.
WebSocket event fan-out (requires Redis)
When REDIS_ENABLED=true, WebSocket events fan out across replicas through a Redis pub/sub adapter attached to Socket.IO — a client connected to node A receives an event raised on node B. Scope this honestly: it distributes fan-out only. The per-key WebSocket rate-limit buckets and the engine registry stay process-local, and a key change is not broadcast to peers either. Without REDIS_ENABLED the adapter is inert and delivery is single-node, exactly as before.
The fan-out to other replicas is best effort and keeps no replay queue. Since v0.26.0 the publish connection is destroyed when Redis stays silent for 10 s, and a Redis that pauses for less than that answers afterwards, so the events raised meanwhile reach the other replicas late. The events a node raises while that connection is down, plus its reconnect backoff of up to 5 s once Redis is back, are dropped for the clients connected to the other replicas: they are neither delivered late nor twice. What was written to the connection when it was destroyed may be lost with it, or may still arrive late and after newer events. A Redis that keeps answering but slower than events are raised is bounded by count instead: once a node holds 12,000 unanswered events and the backlog has outlived 2 s, it drops further events for the other replicas until fewer than 6,000 are unanswered, with a warning when dropping starts and another, with the count, when it ends. It can hold about 2 s of traffic on top of the 12,000. Before v0.26.0 a stalled Redis made the publish client hold every event in memory. Clients connected to the node that raised an event are served directly, and webhooks do not use this path, so neither is affected.
The connection a replica receives on is pinged every 15 s and replaced when an answer takes more than 30 s, so one that stops answering without closing (a proxy that keeps its side open, a firewall that drops the flow) costs that replica at most about 45 s of the others' events; before v0.26.0 it stayed until it closed. A replaced connection misses what the others published into the gap. Since v0.28.0, when a replica fans a message event out to chat-restricted (allowedChats) WebSocket clients, it caches the session's lid_mappings rows in memory for 5 seconds instead of querying the database per client per event. The other Redis clients carry bounds of their own. The rate-limit store gives each command 2 s and, since v0.26.0, destroys a socket that stays silent for 1.5 s after a write, and its counters fail open, so with a Redis that is connected but not answering only the first request waits out a timeout and the requests behind it pass uncounted while the client reconnects. Since v0.26.0 the cache connection, which only the infrastructure status probe uses, bounds each command at 2 s and does not resend unanswered ones after a reconnect.
Key eviction is local to the node that holds the change. The node that processes a revoke, a delete or a change to a key's role, allowlists or expiry closes that key's sockets in the same request, and nothing is published to its peers. Since v0.23.6 every node also re-validates the keys behind its own live sockets against its own API-key table once a minute, and closes with an UNAUTHORIZED frame the sockets of any key that is gone or inactive, or whose role, allowlists or expiry differ from what the socket connected with, a widening included. The same once-a-minute timer already closed, on every node, the sockets of a key that reached the expiry they connected with. That check sees only what changed in the node's own main database, such as a direct write to it. A change made on another node never reaches it, so the other nodes keep accepting the key, on REST and on their sockets, until the same change is made on each of them. Before, a change written to the node's own database other than through its API reached a socket only at the client's next subscribe: a key that no longer validated (revoked, deleted, expired, or no longer admitting the client's IP) was disconnected there, and a narrowed session scope refused a subscribe outside it, but the rooms the socket had already joined stayed joined. A key's usage counters and a rename evict nobody. REST needs no sweep: a node reads the key's row in its own database on each request, so it refuses a revoked, deleted or expired key, and applies a changed role, allowlist or expiry, from the next call once the change has been made on that node.
Clocks must agree
The lease compares timestamps written by different nodes. Each node writes leaseExpiresAt from its own clock and reads every other node's the same way, so a node whose clock runs more than the lease TTL minus one heartbeat ahead (SESSION_LEASE_TTL_MS minus SESSION_LEASE_HEARTBEAT_MS, so 40 s at the defaults of 60000 and 20000, and 20 s once one renewal is missed) sees healthy peers as lapsed just before each renewal and takes their sessions over. Run NTP (or any time sync) on every node — the default on ordinary server images — and treat a skew approaching that margin as a misconfiguration.
Since v0.23.5 the lapsed-status correction reads the same timestamps, and it runs on every node even with AUTO_START_SESSIONS off. A node whose clock runs more than three lease TTLs minus one heartbeat ahead (SESSION_LEASE_HEARTBEAT_MS, default 20000, so 160 s at the defaults) marks a healthy peer's sessions disconnected, and nothing writes them back until that session's status next changes.
Only the clocks have to agree, not the time zones. Since v0.23.6 the PostgreSQL data connection binds, reads and defaults every timestamp in UTC, so nodes in different zones, or in one zone that observes daylight saving, read each other's leases as the instants they were written at. Up to v0.23.5 the lease columns held the writer's local wall time with no zone, so every node had to run in one time zone without daylight saving, and any offset between nodes dwarfed the 160 s threshold in both directions.
That older behavior returns while a cluster runs mixed versions: a node still on v0.23.5 or earlier writes its leases in its own local time for as long as it keeps renewing them. Run every node in TZ=UTC, which is what the container runs unless you set TZ, until the last node is upgraded. A cluster whose nodes ran outside UTC also has leases to clear before the first start on v0.23.6; see PostgreSQL deployments that ran outside UTC.
The same window leaves chat scopes unenforced on the older nodes. A node on v0.23.5 or earlier does not know allowedChats, so it treats a key restricted to selected chats like any other key of its role and sessions: a request it serves itself reaches every chat on the key's sessions, and every route a chat scope refuses, and its /events handshake accepts the key. A request it forwards is checked again on a v0.23.6 owner. Give a key an allowedChats list only once every node runs v0.23.6.
Deletes have a mixed-version window of their own. A node still on v0.25.0 does not read the record a DELETE leaves on a session (deleting or deleting-stopped): its takeover sweep can adopt such a session, and a POST /start it serves leaves the record in place. Upgrade every node to v0.26.0 before relying on delete holds, removal fences or serialized batch cleanup.
What still does not work
The multi-node path is experimental because real gaps remain:
- Per-key WebSocket rate-limit state is process-local, and API keys are per node. The per-key WS rate limit is counted per replica. A key revoked on node A is refused on A, and A's sockets for it close at once, but every other node keeps accepting it, on REST and on its sockets, until the same revoke is made there. A node's once-a-minute re-validation (v0.23.6+) reads that node's own key table, so it does not carry the change across.
- The liveness watchdog and reconnect timers act on whatever is in the local registry, not on a shared cluster view.
- Bulk send batches cannot be resumed by a takeover. A batch driven by a dead node is failed, not continued, and since v0.24.0 a node that shuts down fails the batches it is still running in the same way.
- MCP tool invocations execute on the node that received them, not on the owning node — so an agent tool call for a session owned by a peer will not reach that peer's engine.
Treat multi-replica examples — a Docker Swarm service with replicas: 3, or a Kubernetes StatefulSet whose pods share one session volume — as experimental until those land. Without the ownership layer enabled (every node setting NODE_URL, a stable NODE_ID, one PostgreSQL data database shared by every node, Redis for the event fan-out, and synchronized clocks), replicas: 1 is still the only correct value, and two instances sharing one session volume will corrupt WhatsApp authentication as described at the top of this page.
Next steps
- Deployment — production Docker setup, health checks, and reverse-proxy TLS.
- Migration Guide — move persistent data to PostgreSQL, cache to Redis, and media to S3 / MinIO.
- Configuration — the
DATABASE_TYPE,REDIS_ENABLED,STORAGE_TYPE, andENGINE_TYPEvariables referenced above.