---
title: "The WebSocket stream"
description: "Events pushed over a WebSocket the moment they commit: connecting, the frames in both directions, replay with last_event_id, the limits and the close codes."
url: https://doorman.fyi/docs/stream
markdown: https://doorman.fyi/docs/stream.md
area: "Guides"
section: "Being told about mail"
---

# The WebSocket stream

Events pushed over a WebSocket the moment they commit: connecting, the frames in both directions, replay with last_event_id, the limits and the close codes.

Source: https://doorman.fyi/docs/stream

## Connecting

[`GET /v1/ws`](https://doorman.fyi/docs/reference/stream.md#stream) upgrades to a WebSocket. Authenticate with the `Authorization: Bearer dm_...` header, or with `?token=dm_...` on the URL for a client that cannot set headers, such as a browser. Console sessions are not accepted on the stream. An app token for the REST resource needs `events:read` and `mail:read`; the default agent permissions do not include the first. An account key sees every inbox; an inbox key sees its own and cannot subscribe to others.

Idle connections cost nothing on the server and sleep at the edge; the inbound pipeline pushes each event to the subscribers right after it is stored, before the webhook queue, so the stream is the earliest an agent can learn about mail.

TypeScript:
```ts
import WebSocket from "ws";

const socket = new WebSocket("wss://api.doorman.fyi/v1/ws", { headers: { authorization: `Bearer ${process.env.DOORMAN_API_KEY}` } });
// A client that cannot set headers (a browser) passes the key as ?token=dm_... instead.
socket.addEventListener("open", () => socket.send(JSON.stringify({"type":"subscribe","inbox_ids":["inb_01jc4q7w9k2m5n8p3r6t1v4x7z"]})));
socket.addEventListener("message", (message) => {
  const frame = JSON.parse(String(message.data));
  if (frame.type === "subscribed") console.log("subscribed", frame.inbox_ids);
  if (frame.event === "message.received") console.log(frame.event_id, frame.message.subject);
});
```

Python:
```python
import asyncio, json, os
import websockets

async def main():
    headers = {"authorization": f"Bearer {os.environ['DOORMAN_API_KEY']}"}
    async with websockets.connect("wss://api.doorman.fyi/v1/ws", additional_headers=headers) as socket:
        await socket.send(json.dumps({"type": "subscribe", "inbox_ids": ["inb_01jc4q7w9k2m5n8p3r6t1v4x7z"]}))
        async for raw in socket:
            frame = json.loads(raw)
            if frame.get("event") == "message.received":
                print(frame["event_id"], frame["message"]["subject"])

asyncio.run(main())
```

## Frames

Both sides send JSON text frames. The client's frames are the [`StreamClientFrame`](https://doorman.fyi/docs/reference/schemas.md#StreamClientFrame) schema:

- `subscribe`: Start receiving events: everything the key can see, or a narrower set with `inbox_ids` (up to 32, all of them the key's) and `event_types`. Subscriptions accumulate. Add `last_event_id` to replay what was missed, below.
- `unsubscribe`: Stop receiving: everything, or the inboxes named in `inbox_ids`.
- `ping`: A keepalive the edge answers with `pong` without waking the stream. Send one every 30 to 60 seconds through idle proxies.

The server's frames are the [`StreamServerFrame`](https://doorman.fyi/docs/reference/schemas.md#StreamServerFrame) schema:

- `subscribed`: The subscription in force after a subscribe frame, with the inbox ids and event types; empty arrays mean all.
- `unsubscribed`: The answer to an unsubscribe frame, echoing the inboxes it named.
- `pong`: The answer to a ping.
- `error`: A frame that could not be honoured, with a message. The connection stays open.
- An event: The webhook payload plus `delivered_at` and `attempt`, the [`StreamEvent`](https://doorman.fyi/docs/reference/schemas.md#StreamEvent) schema. `attempt` is always 1 on the stream.

The client subscribes:
```json
{
  "type": "subscribe",
  "inbox_ids": [
    "inb_01jc4q7w9k2m5n8p3r6t1v4x7z"
  ]
}
```

The server confirms:
```json
{
  "type": "subscribed",
  "inbox_ids": [
    "inb_01jc4q7w9k2m5n8p3r6t1v4x7z"
  ],
  "event_types": []
}
```

An event arrives:
```json
{
  "event": "message.received",
  "event_id": "evt_01jc5e5f6g7h8j9k0m1n2p3q4r",
  "occurred_at": "2026-11-05T10:05:00.000Z",
  "inbox_id": "inb_01jc4q7w9k2m5n8p3r6t1v4x7z",
  "thread_id": "thr_01jc5a1b2c3d4e5f6g7h8j9k0m",
  "message": {
    "id": "msg_01jc5a6g7h8j9k0m1n2p3q4r5s",
    "rfc_message_id": "<a1b2c3@example.com>",
    "from": "sam@example.com",
    "to": "concierge@doorman.example",
    "header_to": "concierge@doorman.example",
    "delivery_role": "to",
    "cc": [],
    "address_names": {
      "sam@example.com": "Sam Rivera"
    },
    "subject": "Invoice 2847",
    "body_text": "Hi, invoice 2847 is attached.",
    "attachments": [
      {
        "filename": "invoice.pdf",
        "contentType": "application/pdf",
        "sizeBytes": 45000,
        "url": "https://api.doorman.example/v1/attachments/msg_01jc5a6g7h8j9k0m1n2p3q4r5s/invoice.pdf",
        "parsedText": "Invoice 2847. Line 3: Setup fee, billed twice. Total 1,480.",
        "extractionMethod": "pdf"
      }
    ],
    "raw_url": "https://api.doorman.example/v1/messages/msg_01jc5a6g7h8j9k0m1n2p3q4r5s/raw",
    "received_at": "2026-11-05T10:05:00.000Z",
    "category": "personal",
    "auto_replyable": true,
    "verdict": "clean",
    "spam_score": null
  },
  "delivered_at": "2026-11-05T10:05:00.000Z",
  "attempt": 1
}
```

## Replay after a disconnect

A push that fails is not retried over the socket. Keep the `event_id` of the last event you handled and, on reconnect, subscribe with it as `last_event_id`: the server replays every event after it, up to 100 and filtered by the subscription, before the live ones. An id the account does not know answers an `error` frame; a client that was away for longer than 100 events catches up through [the event log](https://doorman.fyi/docs/events.md) instead.

Subscribe and replay:
```json
{
  "type": "subscribe",
  "inbox_ids": [
    "inb_01jc4q7w9k2m5n8p3r6t1v4x7z"
  ],
  "last_event_id": "evt_01jc5e5f6g7h8j9k0m1n2p3q4r"
}
```

> Note: Replay and the live feed can overlap at the boundary. The `event_id` is the same in both, so deduplicate on it, as a webhook receiver does.

## Limits and close codes

- 10 open connections per account; the next one is closed with `4008`.
- 30 frames per 10 seconds per connection; more closes it with `4029`.
- A client frame may be 16 KiB at most, and a subscribe frame may name 32 inboxes.
- A revoked key, a deleted inbox or a suspended account closes its connections with `4001`.

| Close code | Meaning | What to do |
| --- | --- | --- |
| `4001` | The key was revoked, the inbox deleted or the account suspended. | Do not reconnect with the same key. |
| `4008` | The account already has 10 connections open. | Close one, or share a connection between workers. |
| `4029` | The connection sent frames too fast. | Reconnect with a slower sender; one subscribe and a ping a minute is plenty. |

Any other close, including a network drop, is ordinary: reconnect with a short backoff and `last_event_id`.
