Articles

How to deploy FastAPI WebSockets that recover after a restart

Save FastAPI job progress in PostgreSQL and replay missed WebSocket events after a disconnect or redeploy, with a two-release test.

Updated

A FastAPI WebSocket can disconnect during a deploy even if the HTTP health check stays green. To recover, save each important event outside the process and reconnect with the ID of the last event the client applied. The new server reads the missing events from PostgreSQL and continues with live updates. A heartbeat can detect a dead connection, but it cannot recover a missing message.

Gregale publishes this guide. The example is a small FastAPI job-progress screen with no Redis, JavaScript framework, or hosted pub/sub dependency.

Keep progress independent of the socket

The worker writes progress to PostgreSQL, not to a WebSocket handler or an in-memory list. Opening a socket is how the browser reads updates; it does not start the job, and closing it does not stop the job. FastAPI's WebSocket guide points out that its in-memory connection list only works in one process.

Each write takes a row lock for its job, checks the producer's event UUID, then assigns the next sequence and commits in the same transaction. That order matters. A plain database sequence can be allocated before commit: a client can see event 43, advance its cursor, and silently skip event 42 when that transaction commits later. The per-job lock prevents that case in this example. Reusing an event UUID with the same payload returns the original sequence; reusing it with different progress returns 409.

Reconnect from the last event applied

The browser opens /jobs/<job-id>/stream?after=1. The server reads sequence > 1 from PostgreSQL in order, then checks the same stream for new rows. The browser applies each increasing event once and advances the cursor only after updating the screen. On close it reconnects with backoff. Both the old and new app revisions read the same event history.

For a real app, authorize the user for the specific job before accepting the socket. Persist the cursor if you want to resume after page reloads, and provide a snapshot if old events have expired. Polling the database on every socket keeps this sample simple; for many clients, use a shared notification to wake subscribers and keep durable replay in the database.

Try the redeploy drill

Download the example source. The README includes two releases, a browser screen and a command-line probe. On Gregale the app runs as a normal HTTP app with --websocket-enabled. Attach managed PostgreSQL with separate runtime and migration bindings, then keep both releases on the same database.

  1. Connect to v1 and receive event 1 at 10%.
  2. Close the socket. Write event 2 at 30% and event 3 at 60%. Repeat the 30% write with the same UUID and check it still returns sequence 2.
  3. Deploy v2, reconnect to the stable URL with after=1, and check that the reply identifies v2 and sends only events 2 and 3, in order.
  4. Write event 4 at 90% and confirm reconnecting from after=3 returns only event 4.

What we verified

In Chromium with local PostgreSQL, the screen caught up after a manual disconnect and reconnected automatically when v1 was stopped and v2 started. Four simultaneous writes of the same event produced one sequence. The screen showed exactly four ordered progress updates.

On a private Gregale Scale app with managed PostgreSQL, the probe received event 1 on v1, closed its socket, and committed events 2 and 3. An identical repeat of event 2 kept the original sequence. After v2 reached 100% traffic, the same stable URL replayed exactly events 2 and 3. A later reconnect from cursor 3 received only event 4. This confirms replay across a real deploy, not that an existing socket stays open.

One open socket keeps its Gregale app instance running. If you mainly send occasional notifications and need your backend to park, see managed WebSockets and SSE.

Questions

How do I reconnect a FastAPI WebSocket without missing events?

Save events in a durable store and reconnect with the last event ID the client applied. Replay newer events in sequence and make repeated writes safe with a stable event ID.

Does a WebSocket stay open during a redeploy?

A release can terminate existing sockets. Test whether the browser reconnects through the stable URL and resumes from its last event, rather than assuming the same connection stays open.