# Baileys disconnect codes, WAHA and Evolution API session errors

> Baileys DisconnectReason codes, which need a new QR, WAHA session statuses and 463/475 limits, Evolution API states, and a reconnect function.

Published 2026-11-04. Z-API Omni team.

Reconnect with backoff on most Baileys close codes. Stop on `401` (`loggedOut`), which needs a new QR scan, and on `403` (`forbidden`), which Evolution API won't retry. This post also recommends stopping on `440`. A `515` right after a QR scan is expected: reconnect at once. In WAHA, restart a `FAILED` session, then log out and start again if that doesn't help. WAHA's 463 and 475 errors are limits on a working session, not disconnects, so never restart on them.

## Baileys `DisconnectReason`, from the source

Baileys defines the codes in `src/Types/index.ts` on its master branch ([source](https://github.com/WhiskeySockets/Baileys/blob/master/src/Types/index.ts), [baileys.wiki reference](https://baileys.wiki/api-reference/enumerations/DisconnectReason), accessed 2026-11-04). The enum has ten members and no comments:

```typescript
export enum DisconnectReason {
	connectionClosed = 428,
	connectionLost = 408,
	connectionReplaced = 440,
	timedOut = 408,
	loggedOut = 401,
	badSession = 500,
	restartRequired = 515,
	multideviceMismatch = 411,
	forbidden = 403,
	unavailableService = 503
}
```

The codes reach you as `lastDisconnect.error.output.statusCode` in the `connection.update` event, on a Boom error. Where each one comes from in `src/Socket/socket.ts` and `src/Utils/generics.ts`:

| Code | Member | Where Baileys raises it | What to do |
| --- | --- | --- | --- |
| 401 | `loggedOut` | Intentional logout, or a request for the removed mobile API | Stop. Clear auth, scan a new QR |
| 403 | `forbidden` | Not raised by name; probably a failure-node reason | Stop and investigate |
| 408 | `connectionLost` | Keepalive timeout: `'Connection was lost'` | Reconnect with backoff |
| 408 | `timedOut` | QR never scanned: `'QR refs attempts ended'` | Show a new QR when someone can scan it |
| 411 | `multideviceMismatch` | `'Multi-device beta not joined'` | Reconnect with backoff |
| 428 | `connectionClosed` | WebSocket closed, or stream ended by server | Reconnect with backoff |
| 440 | `connectionReplaced` | Stream error `conflict` | Stop (judgement call, below) |
| 500 | `badSession` | Default for an unknown stream error | Reconnect with backoff |
| 503 | `unavailableService` | Not raised by name in `socket.ts` | Reconnect with backoff |
| 515 | `restartRequired` | Stream error renamed `'restart required'` | Reconnect at once |

Baileys also turns WebSocket errors into codes. `getCodeFromWSError` defaults to 500, and it maps timeouts and network errors to 408. When WhatsApp sends a failure node, Baileys uses its numeric `reason` attribute as the status code, defaulting to 500. A code outside the enum can therefore arrive there. Evolution API's source, for example, also handles 402 and 406.

### 515 after a QR scan is normal

The [QR code guide](https://baileys.wiki/authentication/qr-code) says "Once scanned, WhatsApp forcibly disconnects the socket so Baileys can reconnect with full credentials." Handle it "by reconnecting on `DisconnectReason.restartRequired`". A first login therefore always shows a close event. Code that treats every close as a failure will alert on every new pairing.

### 408 means two different things

`connectionLost` and `timedOut` share the value 408, so the code alone can't tell a dropped network from an unscanned QR. Read `error.message` as well. `'QR refs attempts ended'` means nobody scanned the code before the refs ran out. Reconnecting in a loop then generates QR codes nobody sees. Wait until a person is ready to scan.

### 401 means a new QR

Baileys "does not automatically reconnect after a connection is closed", and its [troubleshooting page](https://baileys.wiki/advanced/troubleshooting) calls that intentional. Its docs and README use one check:

```typescript
const shouldReconnect = (lastDisconnect.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut
```

After a 401, reconnecting won't help. The troubleshooting page says to delete the auth folder, restart and scan again. It also names the most common cause of unexpected session expiry: failing to save updated credentials. Register `sock.ev.on('creds.update', saveCreds)` on every socket you create. The [session management page](https://baileys.wiki/authentication/session-management) adds that "The useMultiFileAuthState function is not recommended for deployment in production."

### 440 is a judgement call

The troubleshooting page treats every code other than 401 as safe to retry. For 440, the recommendation here is to stop. Baileys raises it from a `conflict` stream error, which means another client took the session. If two processes hold the same credentials, each reconnect can replace the other in a loop. No Baileys page documents what to do on 440, so treat this as a recommendation, not library behavior.

The Baileys docs don't explain what triggers 403, 411 or 503 on WhatsApp's side.

## A reconnect decision function

No library publishes a full decision table. Baileys has the `!== loggedOut` line above, and Evolution API has its own list of codes it won't retry. The function below combines both with the cases above. It runs with Node 18 or later as a plain `.mjs` file, with no dependencies.

```javascript
// reconnect-decision.mjs  ·  run: node reconnect-decision.mjs
import { pathToFileURL } from 'node:url';

// Values from DisconnectReason in Baileys src/Types/index.ts (master, read 2026-11-04)
export const DisconnectReason = Object.freeze({
  connectionClosed: 428,
  connectionLost: 408,
  connectionReplaced: 440,
  timedOut: 408,
  loggedOut: 401,
  badSession: 500,
  restartRequired: 515,
  multideviceMismatch: 411,
  forbidden: 403,
  unavailableService: 503,
});

const BASE_DELAY_MS = 2_000;
const MAX_DELAY_MS = 60_000;
const MAX_ATTEMPTS = 8;
const NO_RETRY = new Set([DisconnectReason.forbidden, 402, 406]); // as in Evolution API's source

// error: lastDisconnect.error from connection.update. attempt: reconnects since the last 'open'.
export function decideReconnect(error, attempt = 0) {
  const code = error?.output?.statusCode;
  const message = error?.message ?? '';

  if (code === DisconnectReason.loggedOut) {
    return { action: 'new-qr', clearAuth: true, why: '401 logged out: reconnecting will not help' };
  }
  if (NO_RETRY.has(code)) {
    return { action: 'stop', clearAuth: false, why: `${code}: do not retry, investigate` };
  }
  if (code === DisconnectReason.restartRequired) {
    return { action: 'reconnect', delayMs: 0, why: '515 restart required, expected after a QR scan' };
  }
  if (code === DisconnectReason.connectionReplaced) {
    return { action: 'stop', clearAuth: false, why: '440 another client took the session (judgement call)' };
  }
  if (code === 408 && message === 'QR refs attempts ended') {
    return { action: 'new-qr', clearAuth: false, why: '408 QR expired unscanned: wait for a person' };
  }
  if (attempt >= MAX_ATTEMPTS) {
    return { action: 'stop', clearAuth: false, why: `${code ?? 'no code'}: ${attempt} attempts, alert a person` };
  }
  const delayMs = Math.min(MAX_DELAY_MS, BASE_DELAY_MS * 2 ** attempt);
  return { action: 'reconnect', delayMs, why: `${code ?? 'no code'}: retry with backoff` };
}

if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
  const samples = [
    [{ message: 'Intentional Logout', output: { statusCode: 401 } }, 0],
    [{ message: 'restart required', output: { statusCode: 515 } }, 0],
    [{ message: 'QR refs attempts ended', output: { statusCode: 408 } }, 0],
    [{ message: 'Connection was lost', output: { statusCode: 408 } }, 3],
    [{ message: 'Connection Failure', output: { statusCode: 403 } }, 0],
    [{ message: 'Stream Errored (conflict)', output: { statusCode: 440 } }, 0],
    [{ message: 'Connection Terminated', output: { statusCode: 428 } }, 9],
  ];
  for (const [error, attempt] of samples) {
    console.log(error.output.statusCode, JSON.stringify(decideReconnect(error, attempt)));
  }
}
```

The sample errors only mimic the Boom shape; the messages for 440 and 515 are placeholders. Call `decideReconnect(lastDisconnect?.error, attempt)` when `connection === 'close'`, and reset `attempt` to 0 when `connection === 'open'`. The backoff, the attempt cap and the 440 rule are recommendations from this post. Baileys does none of them.

## WAHA session statuses

WAHA reports a status per session on its [sessions page](https://waha.devlike.pro/docs/how-to/sessions/) (no updated date shown, accessed 2026-11-04):

| Status | WAHA's description | What to do |
| --- | --- | --- |
| `STOPPED` | "session is stopped" | Start it |
| `STARTING` | "session is starting" | Wait |
| `SCAN_QR_CODE` | "session is required to scan QR code or login via phone number." | Show the QR or pairing code |
| `PASSKEY_REQUIRED` | "WhatsApp asks for a passkey (WebAuthn) to finish pairing." GOWS engine only | Complete the passkey step |
| `PASSKEY_CONFIRMATION_REQUIRED` | "the user must check a code before the pairing completes." | Have the user confirm the code |
| `WORKING` | "session is working and ready to use" | Nothing |
| `FAILED` | "session is failed due to some error." | Restart; if that fails, Logout and Start |

WAHA says the first QR code expires in 60 seconds. Each later one lasts 20 seconds, up to 6 in total. After that, the session moves to `FAILED` and needs a restart.

The four actions differ in what they keep. Restart stops and starts a running session. Stop "doesn't Log out or Delete anything". Logout "removes session information (authentication info and data), but keeps the session's configuration". Delete removes both.

By default WAHA restarts sessions when their worker restarts; `WAHA_WORKER_RESTART_SESSIONS=False` turns that off.

WAHA's `session.status` webhook sample has trailing commas, so it is not valid JSON. Here it is with the commas removed:

```json
{
  "event": "session.status",
  "session": "default",
  "me": {
    "id": "7911111@c.us",
    "pushName": "~"
  },
  "payload": {
    "status": "WORKING",
    "statuses": [
      { "status": "STOPPED", "timestamp": 1700000001000 },
      { "status": "STARTING", "timestamp": 1700000002000 },
      { "status": "WORKING", "timestamp": 1700000003000 }
    ]
  },
  "engine": "WEBJS",
  "environment": {
    "version": "2023.10.12",
    "engine": "WEBJS",
    "tier": "CORE"
  }
}
```

### 463 and 475 are not disconnects

Both arrive while the session stays `WORKING`. Sends to new contacts fail with `server returned error 463` (Reachout Timelock). `GET /api/sessions/{session}/timelock` returns `enforcementType`, `isActive` and `timeEnforcementEnds`. Capped sends fail with `server returned error 475`, and `GET /api/sessions/{session}/capping` returns a `cappingStatus` of `NONE`, `FIRST_WARNING`, `SECOND_WARNING` or `CAPPED`. For both, WAHA says "Do NOT restart, logout or re-pair the session." Keep these codes out of any reconnect logic. What they say about the number's standing is covered in [can a QR-connected WhatsApp number be banned](/academy/articles/whatsapp-qr-connection-ban-risk-terms-of-service/).

### EOF and 503 in the logs

Logs from WAHA's GOWS engine can show WebSocket EOF lines and stream 503 lines. WAHA's docs and changelog don't document either one. The [changelog](https://waha.devlike.pro/docs/overview/changelog/) has GOWS reconnect entries, such as 2025.7.3, "GOWS - reconnect on session start if any network error happens". Entry 2026.7.1 reads "GOWS - no webhook events after `<stream:error>` while status stays `WORKING`". A session has been able to show `WORKING` while sending no webhook events. Store the time of the last event per session and alert when it goes quiet. Check the changelog against your image version first; the newest listed on 2026-11-04 is 2026.10.1.

## Evolution API connection states

`GET /instance/connectionState/{instanceName}` with an `apikey` header returns `instance.instanceName` and `instance.state`. The documented states are `open`, `close` and `connecting` ([connection state](https://docs.evolutionfoundation.com.br/evolution-api/get-connection-state), accessed 2026-11-04). The page publishes no full response sample. `POST /instance/restart/{instanceName}` restarts an instance ([restart instance](https://docs.evolutionfoundation.com.br/evolution-api/restart-instance)).

The [webhooks page](https://docs.evolutionfoundation.com.br/evolution-api/configuration/webhooks) lists `CONNECTION_UPDATE` for connection status and `QRCODE_UPDATED`, which sends the QR code as base64. With webhook by events turned on, the event name is appended to your URL, as in `/connection-update`. The page has no payload sample.

The [Baileys service source](https://github.com/EvolutionAPI/evolution-api/blob/main/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts) fills in what the docs leave out:

- `const codesToNotReconnect = [DisconnectReason.loggedOut, DisconnectReason.forbidden, 402, 406];`
- The webhook's `statusReason` is the Baileys status code, or 200 when there is none.
- When the QR limit is hit, it sends `state: 'refused'` with `statusReason` 428 and the message `'QR code limit reached, please login again'`. The docs' state list doesn't include `refused`.

If Baileys runs inside another project, that project's `package.json` pins the version. Checking it is covered in [Baileys v7 and keeping a session current](/academy/articles/baileys-v7-lts-2027-keep-session-current/).

If the drops follow a daily pattern, the cause is usually the phone, covered in [why a QR-connected number disconnects every day](/academy/articles/whatsapp-qr-connection-disconnects-every-24-hours/). To stop running sessions yourself, see [Baileys and whatsapp-web.js vs the Cloud API](/academy/articles/baileys-whatsapp-web-js-vs-cloud-api/) and [migrating from Baileys to the Cloud API](/academy/articles/migrate-baileys-whatsapp-web-js-to-cloud-api/).

*Z-API Omni team*
