# Stream close codes

When the server closes a stream connection, it sends a code explaining why. The table below lists the action for each code. The server checks the connection's key again once a minute.

| Code | Reason | What to do |
|---|---|---|
| `4501` | `invalid_token`: the connection header has no valid Bearer app key, the key is unknown or deleted, or its owner is blocked | check the key; automatic reconnection has stopped |
| `4502` | `token_expired`: the key has expired | do not reconnect, get a new key |
| `4504` | `insufficient_scope`: a valid public key, a secret key with no stream scope, or no scope for a requested channel | use a secret key with the required scopes; automatic reconnection has stopped |
| `4505` | `bad_request`: extra fields in the connection data, such as a key | do not reconnect, fix the request |
| `4290` | `rate_limited`: the [limit on new connections](https://developers.donatty.com/en/rate-limits.md#stream-connections) is exceeded | the library reconnects by itself |
| `3005` | the once-a-minute check found that the key no longer works | the library reconnects and gets the exact code |
| `3011` | you deleted one of the keys | the library reconnects: a valid key allows the connection to reopen |
| `3504` | the channel already has as many open connections as the [limit](https://developers.donatty.com/en/rate-limits.md#stream-connections) allows | do not reconnect, close an extra connection |

Code `4504` applies to a valid public key. An unknown or deleted public key gets `4501`; an expired one gets `4502`. Connection data is checked before the key: invalid `data` gets `4505`.

Code `4503` (`access_revoked`) is reserved and is not sent yet. An unknown code from 3500 to 3999 or from 4500 to 4999 stops reconnection. For other codes, the library retries automatically.

For creating a key and replacing it in an open stream, see [Keys and scopes](https://developers.donatty.com/en/tokens.md#replace-a-key-in-an-open-stream); for the scope required by each channel, see [Stream channels](https://developers.donatty.com/en/realtime/channels.md). REST response codes are on the [HTTP error codes](https://developers.donatty.com/en/errors.md) page.
