I'm implementing a messaging system, but experiencing the following two errors on the dev server:
- "Application instance <...> took too long to shut down and was killed."
- The database connections get increased on every
new EventSourcethat is created, despite it being closed on the frontend.
Here is my code:
Backend:
@transaction.non_atomic_requests
async def stream_chat_messages(request: HttpRequest) -> StreamingHttpResponse:
async def event_stream():
SLEEP_INTERVAL = 0.3
"""
We use this function to send a continuous stream of data
to the connected clients.
"""
async for message in get_existing_messages():
yield message
last_id = await get_last_message_id()
# Continuously check for new messages
while True:
new_messages = _get_messages().filter(id__gt=last_id)
async for message in new_messages:
yield f"data: {json.dumps(message)}\n\n"
last_id = message["id"]
await asyncio.sleep(SLEEP_INTERVAL)
return StreamingHttpResponse(event_stream(), content_type="text/event-stream")
Frontend (React):
const [currentChatroom, setCurrentChatroom] = useState<ChatroomProps | null>(
null,
);
useEffect(() => {
setMessages([]);
if (!currentChatroom) return;
let sse = new EventSource(
`.../stream-chat-messages/?chatroom=${currentChatroom.id}`,
);
sse.onmessage = (event) => {
// ...
};
sse.onerror = () => {
sse.close();
};
return () => {
sse.close();
};
}, [currentChatroom?.id]);
What am I doing wrong here? Every time the page is loaded, a new database connection is created, but it keeps persisting.
Thanks!