Skip to content

An AI-powered search engine with a generative UI

perf: optimize DB operations with transactions

Yoshiki Miura852177c7ddcd
diff --git a/lib/actions/chat.ts b/lib/actions/chat.ts
index 7ed10bfc..8fef099e 100644
--- a/lib/actions/chat.ts
+++ b/lib/actions/chat.ts
@@ -128,26 +128,22 @@ export async function createChatWithFirstMessage(
const messageId = message.id || generateId()
const chatTitle = title || DEFAULT_CHAT_TITLE
- // Create chat
- const chat = await dbActions.createChat({
- id: chatId,
- title: chatTitle.substring(0, 255),
+ // Use transaction for atomic operation
+ const result = await dbActions.createChatWithFirstMessageTransaction({
+ chatId,
+ chatTitle,
userId,
- visibility: 'private'
- })
-
- // Save message
- const dbMessage = await dbActions.upsertMessage({
- ...message,
- id: messageId,
- chatId
+ message: {
+ ...message,
+ id: messageId
+ }
})
// Revalidate cache
revalidateTag(`chat-${chatId}`)
revalidateTag('chat')
- return { chat, message: dbMessage }
+ return result
}
diff --git a/lib/db/actions.ts b/lib/db/actions.ts
index 45a86036..edc831d4 100644
--- a/lib/db/actions.ts
+++ b/lib/db/actions.ts
@@ -336,3 +336,47 @@ export async function updateChatTitle(
return updatedChat || null
}
+
+/**
+ * Create a chat with the first message in a single transaction
+ * Optimized for new chat creation
+ */
+export async function createChatWithFirstMessageTransaction({
+ chatId,
+ chatTitle,
+ userId,
+ message
+}: {
+ chatId: string
+ chatTitle: string
+ userId: string
+ message: PersistableUIMessage
+}): Promise<{ chat: Chat; message: Message }> {
+ return await db.transaction(async tx => {
+ // 1. Create chat
+ const [chat] = await tx
+ .insert(chats)
+ .values({
+ id: chatId,
+ title: chatTitle.substring(0, 255),
+ userId,
+ visibility: 'private',
+ createdAt: new Date()
+ })
+ .returning()
+
+ // 2. Save message
+ const dbMessage = mapUIMessageToDBMessage({ ...message, chatId })
+ const [savedMessage] = await tx.insert(messages).values(dbMessage).returning()
+
+ // 3. Save parts if they exist
+ if (message.parts && message.parts.length > 0) {
+ const partsData = mapUIMessagePartsToDBParts(message.parts, savedMessage.id)
+ if (partsData.length > 0) {
+ await tx.insert(parts).values(partsData)
+ }
+ }
+
+ return { chat, message: savedMessage }
+ })
+}
diff --git a/lib/streaming/create-chat-stream-response.ts b/lib/streaming/create-chat-stream-response.ts
index abb5a7f8..b2b2c657 100644
--- a/lib/streaming/create-chat-stream-response.ts
+++ b/lib/streaming/create-chat-stream-response.ts
@@ -45,15 +45,19 @@ export async function createChatStreamResponse(
})
}
- // Fetch chat data for authorization check and cache it
- let initialChat = await loadChat(chatId, userId)
-
- // Authorization check: if chat exists, it must belong to the user
- if (initialChat && initialChat.userId !== userId) {
- return new Response('You are not allowed to access this chat', {
- status: 403,
- statusText: 'Forbidden'
- })
+ // Skip loading chat for new chats optimization
+ let initialChat = null
+ if (!isNewChat) {
+ // Fetch chat data for authorization check and cache it
+ initialChat = await loadChat(chatId, userId)
+
+ // Authorization check: if chat exists, it must belong to the user
+ if (initialChat && initialChat.userId !== userId) {
+ return new Response('You are not allowed to access this chat', {
+ status: 403,
+ statusText: 'Forbidden'
+ })
+ }
}
// Create parent trace ID for grouping all operations