fix: handle duplicate room creation race condition

Merged
SI
10mo ago
+1-1

Problem

Intermittent 500 errors on new chat due to duplicate key value violates unique constraint "rooms_pkey".

Root Cause

Frontend and backend both try to create the same room:

  1. Recoup-Chat/app/api/chat/create/route.ts → Creates room for optimistic UI
  2. Recoup-API/lib/chat/handleChatCompletion.ts → Also creates room (for API clients)

Race condition: backend's selectRoom() returns null before frontend's insert is visible → duplicate key error.

Solution

Catch the 23505 (unique constraint violation) error in handleChatCompletion. If room already exists, skip notification and continue - the frontend already created it.

Changes

  • Wrap insertRoom in try/catch
  • Catch 23505 error → continue without throwing
  • Only send notification if we successfully created the room

Related

  • Recoup-Chat PR: adds refetchConversations() to onFinish to sync title updates