Skip to content

Discord bot reconnect storm got its token reset: add backoff, a circuit breaker and clean teardown #402

Closed

Description

@mchestr

What happened

Discord reset the bot's token and sent this notice:

It appears your bot, MikeFlixBot, has connected to Discord more than 1000 times within a short time period. Since this kind of behavior is usually a result of a bug we have gone ahead and reset your bot's token.

So something in our lifecycle is logging in (gateway IDENTIFY) over and over. Discord allows about 1000 IDENTIFYs per 24 h per bot. Going over it resets the token, which takes the bot down until an admin pastes a new token in Admin, Settings, Discord.

How the bot is run today

  • lib/instrumentation/node.ts, startDiscordBotPolling(): builds one DiscordBot and a LeasePoller over the discord-bot LeaseLock (30 s lease, 10 s poll, renewed every 10 s). onLockAcquired runs bot.initialize(), and onLockLost runs bot.destroy(). A change to DiscordIntegration.configVersion bounces it: destroy, then initialize.
  • lib/discord/bot.ts: initialize() creates a new discord.js Client and calls client.login() on every call.

Suspected causes (to confirm from logs)

  1. Failed login retries with no backoff. If bot.initialize() throws (invalid or disallowed intents, a bad token, a gateway timeout, a 429), onLockAcquired calls lock.release(). The next poll tick, 10 s later, acquires the lease again and logs in again. That's about 360 IDENTIFY attempts an hour, forever, with no backoff and no point where it gives up. After a token reset, every attempt fails, so this loop keeps going until someone notices.
  2. Clients leak when login fails. initialize() assigns this.client = this.createClient() before login(). If login throws, the client is never destroy()ed. isInitialized stays false, so the next attempt creates another Client. A client that has already opened its websocket and later failed, for example by timing out waiting for READY, can keep reconnecting on its own while new ones pile up.
  3. The bot is torn down whenever the lease changes hands. One failed renewal, from a DB blip or an event-loop stall longer than the 30 s lease, runs onLockLost, which destroys the bot. The bot then logs in again from scratch with a fresh IDENTIFY, instead of letting discord.js resume the session. If two instances or roles swap the lease back and forth, every swap costs two connections.
  4. The config bounce always re-identifies. Every configVersion change destroys the bot and logs in again, even when the token and intents didn't change.
  5. Check that only one process runs the bot. Make sure the bot doesn't start in more than one process role, for example web and worker, or under next dev HMR re-running instrumentation, or that the lease alone can't let two clients run at once.

Proposal

  • Back off between attempts. Use exponential backoff with jitter between login attempts, from about 30 s up to about 30 min, kept in the poller or bot rather than tied to the 10 s tick. Reset it after a stable READY.
  • Stop retrying fatal errors. For close codes such as 4004 (authentication failed) and 4013/4014 (invalid or disallowed intents), and for a token rejected by Discord, stop retrying. Log an error and mark the integration unhealthy so Admin, Settings and /api/metrics show it. Wait for a configVersion change (a new token) before trying again.
  • Cap logins per day. Count IDENTIFYs in a rolling 24 h window, in Redis or the DB, so the count survives restarts. Refuse to log in again above a safe threshold, for example 100 a day, and alert instead.
  • Tear down cleanly. If initialize() fails, destroy() the client it created. Never have two live Clients in one process.
  • Keep the session when possible. A transient renewal failure shouldn't drop a healthy gateway session if this instance can get the lease back right away. Let discord.js handle resumable disconnects itself (ShardReconnecting/ShardResume) rather than destroying the client. Bounce on a configVersion change only when the token or another login-relevant field actually changed.
  • Make it visible. Add a metric for gateway logins and disconnects (count, last close code) and log ShardDisconnect close codes at warn, so a storm shows up long before Discord's limit.

Acceptance criteria

  • A bad or reset token causes a handful of login attempts, then an error state shown to the admin. It never causes an unbounded retry loop.
  • Failed logins never leak a Client. A unit test with a fake client factory whose login rejects shows destroy() is called and no second client stays alive.
  • Backoff is tested. Fake timers show attempt spacing grows and resets after success.
  • One failed lease renewal doesn't cause a re-IDENTIFY when the same instance gets the lease back.
  • A rolling 24 h IDENTIFY counter stops logins above the threshold, and /api/metrics exposes it.
  • docs/discord-bot.md covers the new behaviour and what to do after Discord resets a token (paste the new token in Admin, Settings, Discord).

Operator note

The current token is dead. Generate a new one in the Discord Developer Portal and save it in Admin, Settings, Discord. Until this issue is fixed, consider setting ENABLE_DISCORD_BOT=false, or watching the logs closely after restoring it, so the token doesn't get reset again.

Activity

  1. added
    bug
    discord
    observability
    security
    on Oct 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugdiscordobservabilitysecurity

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions