Skip to content

Add exponential backoff on connection failures #7

@alexknowshtml

Description

@alexknowshtml

Summary

Handle Discord connection failures gracefully with exponential backoff to prevent rapid reconnection loops.

How Andy Does It

In start.ts:

const MAX_RETRIES = 5;
const INITIAL_BACKOFF_MS = 1000;
const MAX_BACKOFF_MS = 30000;
const BACKOFF_MULTIPLIER = 2;

// Fatal error detection
const FATAL_ERROR_CODES = new Set([
    'TokenInvalid',
    'DisallowedIntents',
    'ShardingRequired',
]);

let retryCount = 0;
let backoffMs = INITIAL_BACKOFF_MS;

while (retryCount < MAX_RETRIES) {
    try {
        await startBot({ token });
        // Reset on success
        retryCount = 0;
        backoffMs = INITIAL_BACKOFF_MS;
        // ... run server
    } catch (err) {
        // Don't retry fatal errors
        if (err.code && FATAL_ERROR_CODES.has(err.code)) {
            logError('Fatal error, not retrying');
            process.exit(0);  // Clean exit so PM2 doesn't restart
        }

        retryCount++;
        log(`Attempt ${retryCount}/${MAX_RETRIES} failed`);
        log(`Waiting ${backoffMs}ms before retry...`);

        await sleep(backoffMs);
        backoffMs = Math.min(backoffMs * BACKOFF_MULTIPLIER, MAX_BACKOFF_MS);
    }
}

Current Cord Behavior

No retry logic. If connection fails, process exits.

Implementation

  1. Wrap bot startup in retry loop
  2. Detect fatal errors (bad token, wrong intents) and exit cleanly
  3. Exponential backoff: 1s → 2s → 4s → 8s → 16s → 30s (capped)
  4. Reset backoff on successful connection
  5. Max 5 retries before giving up

Why This Matters

  • Handles temporary Discord outages
  • Prevents rate limiting from rapid reconnects
  • Clean exit on fatal errors (bad config)

Priority

Medium - improves reliability

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions