Backend Architecture
Relevant source files
The following files were used as context for generating this wiki page:
The backend of OpenChat is powered by Convex, a real-time serverless platform that integrates a database, authentication, file storage, and server-side logic. It functions as a centralized hub for managing application state, executing AI workflows, and coordinating third-party service integrations. The architecture is designed to support real-time updates across clients, secure data isolation, and scalable background task execution.
The backend infrastructure provides the foundation for several core capabilities: a real-time relational database for chat history and user preferences, serverless functions (Queries, Mutations, and Actions) for business logic, and integrated scheduling for autonomous background agents.
Sources: CLAUDE.md:82-95, src/routes/security.tsx:55-65
Core Components and Function Types
The Convex backend is organized into four distinct types of functions, each serving a specific role in the data flow and execution lifecycle.
| Function Type | Description | Access to Database | External API Access |
|---|---|---|---|
| Query | Deterministic, reactive functions used to read data from the database. | Read-only | No |
| Mutation | Deterministic functions used to modify data in the database. | Read/Write | No |
| Action | Non-deterministic functions used for side effects and calling external APIs (e.g., AI models). | Via Query/Mutation | Yes |
| Internal | Private versions of the above (internalQuery, etc.) accessible only by other backend functions. | Depends on type | Depends on type |
Sources: agent_rules/convex_rules.md:80-90, CLAUDE.md:89-94
Data Access and Safety
All database operations are transactional within Mutations and Queries, ensuring data consistency. Actions, however, do not have direct ctx.db access and must use ctx.runQuery or ctx.runMutation to interact with the database. This separation enforces a clean boundary between non-deterministic external calls (like AI streaming) and state management.
Sources: agent_rules/convex_rules.md:255-260, convex/scheduled_ai.ts:25-30
Database Schema and Data Modeling
The system uses a modular schema definition to manage entities such as users, chats, messages, and scheduled tasks. The schema is defined with explicit indexes to optimize performance and avoid slow table scans.
The diagram above illustrates the relationships between the core data entities managed by Convex.
Sources: convex/schema.ts:16-47, agent_rules/convex_rules.md:315-320
Key Data Tables
| Table | Primary Purpose | Key Indexes |
|---|---|---|
users | Stores user profiles and preference data. | email |
chats | Groups messages into distinct sessions. | by_user |
messages | Stores individual message content and AI metadata. | by_chat_and_created, by_user_content (Search) |
scheduled_tasks | Defines parameters for recurring AI background jobs. | by_next_execution, by_user |
connectors | Manages third-party service connections (Gmail, etc.). | by_user_and_type |
Sources: convex/schema.ts:18-46
Background Agent Execution Flow
OpenChat features a sophisticated background execution system for autonomous tasks. These tasks are managed via scheduled_tasks and executed through actions in convex/scheduled_ai.ts.
The flow represents the lifecycle of a background agent execution from trigger to completion.
Sources: convex/scheduled_ai.ts:33-280
Execution Logic
- Validation: The system verifies the user and task status.
- Context Loading: It retrieves user preferences and working memory from Upstash Redis to provide continuity across task runs.
- Tool Integration: Connectors (e.g., GMAIL, NOTION) are loaded based on the user's connected services.
- AI Generation: The
createScheduledAgentuses the AI SDK to process the prompt autonomously without user intervention. - Completion: The system saves the result to a specific chat history, increments usage credits, and triggers email notifications via the Resend integration.
Sources: convex/scheduled_ai.ts:50-80, convex/scheduled_ai.ts:180-210
External Integrations and Infrastructure
OpenChat leverages specialized providers for specific backend capabilities, ensuring security and performance.
AI Integration and Gateway
The backend acts as a gateway for multiple AI providers (OpenAI, Anthropic, Google, etc.). It manages model-specific preferences and performs secure encryption for user-provided API keys using AES-GCM 256-bit encryption.
Sources: src/routes/security.tsx:28-35, CLAUDE.md:100-110
Email and Storage System
- Email: Task summaries are generated by converting markdown to safe HTML and sent via Resend. The
email.tsmodule includes sanitization logic to remove scripts and hazardous tags for email safety. - Storage: While Convex provides built-in file storage, the project integrates Cloudflare R2 via
@convex-dev/r2for object storage of chat attachments.
Sources: convex/email.ts:20-60, CLAUDE.md:79, convex/schema.ts:32-36
Summary
The Backend Architecture of OpenChat is a robust, serverless implementation that prioritizes real-time reactivity and autonomous task execution. By utilizing Convex as the central orchestration layer, the system maintains strict data isolation and security while facilitating complex AI workflows that span multiple models and third-party integrations. This architecture allows for seamless scaling from simple chat interactions to sophisticated, scheduled background agents.