This sample pairs FastAPI with PostgreSQL LISTEN/NOTIFY
to demonstrate real-time updates between two application containers. A minimal chat UI sends messages with a REST request, and both FastAPI instances broadcast the new message over WebSockets after Postgres notifies them.
- Download Defang CLI
- (Optional) If you are using Defang BYOC authenticate with your cloud provider account
- (Optional for local development) Docker CLI
To run the application locally, you can use the following command:
docker compose -f compose.dev.yaml up --build
Once everything is running:
- Visit http://localhost:8000 for the first FastAPI service.
- Visit http://localhost:8001 for the second service.
- Send a chat message in either window. Both pages should update immediately, proving Postgres
LISTEN/NOTIFY
fans the event across containers.
Stop the stack with Ctrl+C
, then run docker compose -f compose.dev.yaml down
.
For this sample, you can rely on the defaults. Override them with environment variables if needed:
Note that if you are using the 1-click deploy option, you can set these values as secrets in your GitHub repository and the action will automatically deploy them for you.
Database password (default chat_password
).
defang config set POSTGRES_PASSWORD --random
Postgres SSL mode (default disable
, should set to require
in production).
defang config set SSL_MODE=require
Note
Download Defang CLI
Deploy your application to the Defang Playground by opening up your terminal and typing:
defang compose up
If you want to deploy to your own cloud account, you can use Defang BYOC.
Title: FastAPI Postgres Pub/Sub
Short Description: FastAPI sample that stores messages in Postgres and streams them to two app instances via LISTEN/NOTIFY.
Tags: FastAPI, PostgreSQL, WebSockets, PubSub
Languages: Python, SQL