discord.js Client and Discord Gateway: session resumption behavior during zero-downtime deployments
0 reputation · 12 Aug 2022, 22:42 UTC
0 reputation · 12 Aug 2022, 22:42 UTC
Achieve a deployment process for a small discord.js bot that avoids any gap in event delivery when replacing the running process.
The Discord Gateway permits session resumption via RESUME using a stored session ID and sequence number, and discord.js handles this automatically for transient disconnects. However, a full process replacement invalidates the in-memory session state unless the new process can resume the same session. The library does not provide a built-in mechanism to hand off a Gateway session between processes. Discord also enforces IDENTIFY rate limits per 24-hour window, which restricts how frequently a new process can establish a fresh connection. For a small single-shard bot, sharding adds complexity without eliminating the restart gap.
33775 reputation · 13 Aug 2022, 01:18 UTC
A new discord.js process cannot natively resume a Gateway session from a previous process because the required session_id and sequence number are stored in-memory. To achieve zero-downtime event delivery, you must either implement an external state handoff (complex and unsupported by the high-level API) or migrate to an Interactions Endpoint URL for slash commands, which removes the Gateway dependency for those specific events.
While the Discord Gateway allows a RESUME payload to recover a session, discord.js manages this state internally. For a new process to resume a session, it would need the exact session_id and the last received sequence number. Because the library does not provide a public API to manually inject these values into a new Client instance upon startup, a process restart effectively forces a new IDENTIFY call.
Rolling restarts are constrained by two primary factors:
IDENTIFY is required.Moving to an Interactions Endpoint URL (Webhooks) eliminates the Gateway session dependency for slash commands, context menus, and component interactions. Instead of a persistent WebSocket, Discord sends a POST request to your server. This allows for true zero-downtime deployments via a load balancer or rolling update, as the HTTP endpoint remains reachable regardless of the internal process state.
POST requests.PONG for the initial verification or a JSON response for the command).Note: HTTP endpoints only support Interaction events. If your bot relies on MESSAGE_CREATE or other Gateway-only events, you will still experience a delivery gap during process replacement.
To determine if the Identify rate limit is your primary bottleneck, please provide the specific HTTP status codes or Gateway close codes (e.g., 4014) observed in your logs during deployment failures.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.