# Add WebSockets to an aiohttp App

Yes. An agent adds a WebSocket endpoint to your aiohttp app that pushes live results to open pages, closes sockets cleanly on shutdown, tests it, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-websockets/aiohttp/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads the request path it is about to extend before it adds a socket beside it. In an app laid out like the `polls` demo in aio-libs/aiohttp-demos, `aiohttpdemo_polls/main.py` builds the `web.Application` in `init_app`: it stores the YAML config under `config_key`, sets up `aiohttp_jinja2` with a `PackageLoader`, appends `pg_context` to `app.cleanup_ctx` so a SQLAlchemy `create_async_engine` is created on startup and disposed on cleanup, then calls `setup_routes`, `setup_static_routes` and `setup_middlewares`. `routes.py` registers `/`, `/poll/{question_id}` as `poll`, `/poll/{question_id}/results` as `results` and `POST /poll/{question_id}/vote` as `vote`. `views.py` has `vote` read `choice` from the form, call `db.vote(request.app, question_id, choice_id)`, and redirect to the `results` route, whose template `results.html` prints each choice as `choice_text -- votes vote(s)`. `typedefs.py` already types the application keys with `web.AppKey`, and `requirements-dev.txt` pins `aiohttp==3.13.5`, `SQLAlchemy==2.0.54`, `asyncpg==0.32.0`, `pytest==9.1.1` and `pytest-aiohttp==1.1.1`. The repository's own `chat` demo shows the house style: `web.WebSocketResponse`, a `ws_key` AppKey, an Origin check, and an `on_shutdown` handler that closes every socket.

The agent adds `GET /poll/{question_id}/results/ws`, named `results_ws`, to `routes.py` and a `results_ws` handler to `views.py`. The handler prepares a `web.WebSocketResponse`, refuses an `Origin` that does not match `request.host` with `HTTPForbidden` as the chat demo does, adds the socket to a `weakref.WeakSet` kept per question under a new `ws_key` AppKey in `typedefs.py`, sends the current counts as one JSON message, and then loops on `receive()` until the client closes. A `broadcast(app, question_id)` helper in `views.py` reads the choices again through `db.get_question` and sends `{"question_id": …, "choices": [{"id", "text", "votes"}]}` to every socket in that question's set, discarding a socket whose send raises. `vote` calls it once after `db.vote` and before the redirect, so the page that voted and every other open results page receive the same message.

The template changes are small. `results.html` gains a `data-choice-id` attribute on each `<li>` and a script that opens `new WebSocket` against `location.host` with `ws:` or `wss:` chosen from `location.protocol`, updates the count in place on each message, and reconnects with a short backoff when the socket closes. In `main.py` the agent appends an `on_shutdown` handler that closes each tracked socket with `WSCloseCode.GOING_AWAY`, which the aiohttp docs ask for because `run_app` does not know how to close a WebSocket handler on its own. While reading `db.vote` the agent sees that `result.votes += 1` runs before the `if not result` check, so an unknown choice id raises `AttributeError` rather than `RecordNotFound`; it moves the check up one line and lists that as a separate item in the pull request.

Tests follow the existing `tests/conftest.py`: the `cli` fixture builds the app from `config/polls_test.yaml` with `aiohttp_client`, and `tables_and_data` creates and seeds the tables through `init_db.py`. A new `tests/test_results_ws.py` opens `cli.ws_connect('/poll/1/results/ws')`, reads the first message and checks it matches the seeded choices, posts `choice` to `/poll/1/vote` with `allow_redirects=False`, and asserts the next message carries the incremented count; a second test opens two sockets and checks both receive it; a third sends a wrong `Origin` header and expects 403. `pytest.ini` sets `filterwarnings = error` and `asyncio_mode = auto`, so an unawaited coroutine or an unclosed socket fails the suite rather than printing a warning, and the agent runs `pytest tests` from `demos/polls` against a Postgres it starts in its sandbox the way the root `ci.yml` does with a `postgres` service.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add a WebSocket endpoint to this aiohttp polls app so an open results page updates live when someone votes. Read aiohttpdemo_polls/main.py, routes.py, views.py, db.py, typedefs.py, middlewares.py, the templates, tests/conftest.py, tests/test_integration.py, pytest.ini, requirements-dev.txt and init_db.py first, and read how the chat demo in this repository handles WebSocketResponse, Origin and on_shutdown. Add GET /poll/{question_id}/results/ws that sends the current counts on connect, keep the sockets per question in a WeakSet under a web.AppKey, broadcast the new counts from the vote view after db.vote, close every socket with WSCloseCode.GOING_AWAY in an on_shutdown handler, and update results.html to apply each message in place and reconnect on close. Write tests with aiohttp_client and ws_connect that vote and assert the pushed count, and one that rejects a foreign Origin. Run flake8 and pytest and quote the output. Open a pull request.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

The pull request changes `routes.py` (one route), `views.py` (the `results_ws` handler and `broadcast`), `typedefs.py` (the `ws_key` AppKey), `main.py` (the `on_shutdown` handler), `db.py` (the reordered check in `vote`) and `templates/results.html` (the attributes and the script), and adds `tests/test_results_ws.py`. Its description quotes the `flake8` and `pytest` output, shows the JSON a page receives, and names the one behavior change outside the feature, the `RecordNotFound` fix.

A reviewer opens two tabs on a poll's results page from the branch, votes in a third tab, and watches both counts move. In the code they look for the two mistakes WebSocket code usually has: a send to a socket that is already closed, which the discard-on-error loop handles, and a socket left in the set after its handler returned, which the `WeakSet` handles. They also decide whether the Origin check should accept a configured list of hosts rather than `request.host` alone.

The broadcast is per process. `web.run_app` in `main.py` runs one process, so this is complete for the demo; the pull request says that an app served by several workers would need a shared channel, such as Postgres `LISTEN`/`NOTIFY` or Redis, to fan a vote out across them.

## Run it on every Linear issue labelled realtime

A product team that keeps its live-update requests in Linear starts one run per issue from a handler on its own server: when an issue gains the `realtime` label, the handler sends this body to `POST /o/{org}/sessions` with the repository in `resources` and the issue's `https://linear.app/<workspace>/issue/<ID>` URL as a second resource, so the issue text is in front of the agent, with a `request_id` that is a UUID v5 of the issue id so a redelivery returns the run already started. The prompt tells the agent to reuse the `ws_key` set and the `broadcast` helper once they exist instead of opening a second socket per feature.

A Rush automation with a `linear` trigger on `linear.issue.labeled` can watch the same label, but its runs are read-only: they read the repository and comment, and do not push. That fits a plan step, where the run comments on the issue with which views and templates it would change, and the handler above starts the run that opens the pull request.

## Why run it on Rush?

Socket code is short and its bugs are timing bugs: a write to a closed connection, a set that keeps dead sockets, a shutdown that hangs because a handler is still blocked on `receive()`. The agent runs the real server in its own sandbox with Postgres beside it, drives it with the `aiohttp_client` socket client, runs the suite with warnings turned into errors, and keeps the output with the pull request, so the reviewer starts from a passing test rather than from a video of a browser.

A reviewer reads a handler, a helper and a test instead of a tutorial, and the demo's own conventions, `AppKey`, `cleanup_ctx`, `on_shutdown`, are the ones used. A team with several aiohttp services starts the same request across all of them at once, and each pull request is specific to the views that service has.

## Frequently asked questions

### Does aiohttp need an extra package for WebSockets?

No. `web.WebSocketResponse` on the server and `ws_connect` on the test client are part of `aiohttp` itself, pinned at 3.13.5 in `requirements-dev.txt`. The only new import is `weakref` from the standard library and `WSCloseCode` from `aiohttp`.

### Why a WeakSet and an on_shutdown handler?

The aiohttp docs recommend keeping open sockets in a `weakref.WeakSet` under an `AppKey` and closing them from an `Application.on_shutdown` signal, because `run_app`'s graceful shutdown cannot close a WebSocket handler by itself. The repository's `chat` demo does the same with a dict, so the pattern is already familiar to the codebase.

### What happens to a page whose socket drops?

The script in `results.html` reconnects with a short backoff, and the handler sends the current counts on every connect, so a page that was offline for a moment catches up on its first message rather than waiting for the next vote.

### Will the form-based vote still work without JavaScript?

Yes. `POST /poll/{question_id}/vote` still answers with the redirect to the results page, which renders the counts server-side as before. The socket only keeps an already open page current.

### Why does the pull request touch db.vote?

Because `result.votes += 1` runs before `if not result`, a vote for a choice id that does not exist raises `AttributeError` instead of the `RecordNotFound` the view expects, and the broadcast would never run. Moving the check above the increment is one line, and the description lists it separately so the reviewer can accept or drop it.

## More aiohttp jobs

- [Turn Sentry Errors Into Fix Pull Requests for an aiohttp App](https://getrush.ai/run/fix-sentry-errors/aiohttp/)
- [Add Cookie Sessions to an aiohttp App](https://getrush.ai/run/add-cookie-sessions/aiohttp/)
- [Add CORS to an aiohttp App](https://getrush.ai/run/add-cors/aiohttp/)

## The same job on other stacks

- [Add WebSockets to a Cloudflare Worker with Durable Objects](https://getrush.ai/run/add-websockets/cloudflare-workers/)
- [Add WebSockets to a Fastify App](https://getrush.ai/run/add-websockets/fastify/)
- [Add WebSockets to a Fiber App](https://getrush.ai/run/add-websockets/fiber/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
