Convex Components & Architecture Patterns
Convex is a backend-as-a-service (BaaS) platform designed to make it easy to build full-stack reactive applications with minimal setup. It combines a real-time database, serverless functions, and authentication, all managed within a TypeScript-first developer experience.
-
Reactive Database
- Document-based (like Firebase or MongoDB)
- All queries are reactive: clients auto-update on data change
- Queries written in TypeScript, securely executed from client
-
Serverless Functions
- Write logic with
query()andmutation()in TypeScript - Fully managed environment, async and npm-ready
- Write logic with
-
Authentication
- Built-in support for GitHub, Google, JWT, etc.
- Access control via roles and TypeScript logic
-
Real-time React Integration
- Use hooks like
useQuery()anduseMutation() - Automatic reactivity without polling
- Use hooks like
-
File Storage
- Upload and serve files via Convex's native file API
- Full-stack in one repo — unified client + server code
- Type safety everywhere — auto-inferred TypeScript types
- Live collaboration — perfect for reactive shared UIs
- Zero backend ops — no infrastructure to manage
- Collaborative tools (whiteboards, CRMs)
- Real-time dashboards
- AI assistants and agents with UIs
- Internal tools
- MVPs and fast-moving startups
- CLI:
npx convex dev,convex deploy - File-based routing in
convex/functions/ - Hot reload and codegen
- Frontend: React (with Tailwind, ShadCN)
- Backend: Convex (queries, mutations, auth)
- DB: Convex Reactive DB
- Hosting: Vercel / Netlify
- AI: OpenAI / Langchain / OpenRouter APIs
- Store text chunks in Convex.
- Use external embedding (e.g., OpenAI) for vector search.
- Query relevant data to enrich LLM prompts.
- Agents persist state and memory in Convex.
- Store thoughts, actions, decisions, or queued tasks.
- Useful for multi-agent orchestration.
- Track user or system state across steps.
- Implement UI wizards, multi-step processes, or backend orchestration.
- Use
action()to send transactional emails via Resend. - Templates and metadata stored in Convex DB.
- Log actions per user/IP in a
rate_limit_logtable. - Throttle usage based on time windows.
- Store online status and activity with periodic
heartbeatmutations. - Clean stale users via CRON or TTL.
- Distribute counter writes across documents.
- Reduce write contention for high-frequency actions.
- Pre-compute totals or metrics on write or via CRON.
- Store in
aggregatestable for fast retrieval.
- Store lat/lng coordinates.
- Filter using bounding box or Haversine formula in
query().
- Real-time data syncing between clients using
useQuery(). - Ideal for shared editors, dashboards, or Kanban boards.
- Implement collaborative editors.
- Use patching or CRDT integration (e.g., Y.js, Automerge).
- Use
action()to trigger SMS, voice, or calls. - Store Twilio credentials in Convex secrets.
- Cache expensive results (e.g., LLM outputs or API calls).
- Store and reuse if recent.
| Component | Type | Native or Pattern | Convex Usage |
|---|---|---|---|
| RAG | Pattern | External support | Store + query chunks, external embeddings |
| AGENT | Pattern | Custom | Stateful logic via mutation() + orchestration |
| Workflow | Pattern | Native + Custom | Multi-step flow via state tracking in DB |
| RESEND | Integration | External API | Send emails via action() using Resend |
| RateLimiter | Pattern | Custom | Track usage in DB, check on each request |
| Presence | Pattern | Custom | Heartbeat + user state updates |
| CRON | Feature | Native | Schedule tasks like cleanup, reminders |
| Shard Counter | Pattern | Custom | Split counter writes across multiple docs |
| Aggregates | Pattern | Custom | Precompute and store stats via mutation or CRON |
| Geo Spatial | Pattern | Custom | Manual bounding box or Haversine checks |
| Collaborative | Pattern | Built-in friendly | Real-time synced state via useQuery() |
| Text Sync | Pattern | External + Custom | CRDT/OT integration or patch model |
| Twilio | Integration | External API | SMS/call API via action() |
| Action Cache | Pattern | Custom | Store API result in DB to prevent redundant calls |
- Keep functions modular: Extract logic into helpers to reuse across queries/mutations.
- Use
action()only for side effects: Never access Convex DB fromaction()—usemutation()instead. - Cache external calls: Store expensive API/LLM results to reduce latency and cost.
- Enable real-time debugging: Use admin-only logs or metadata capture for audit/debug workflows.
- Pair with AI tools: Store prompts, outputs, and feedback for fine-tuning and diagnostics.
- Simulate queues and delays: Combine CRON + timestamps for task scheduling without true queues.
- Extend session objects with onboarding or billing metadata.
- Schedule tasks via CRON and timestamps.
- Simulate delays or expiry windows.
- Handle external webhooks via
action(). - Persist events and trigger downstream flows.
- Store per-user or global flags in a settings table.
- Toggle features dynamically.
- Handle Stripe webhooks and store subscription data.
- Sync feature access with Convex roles/fields.
- Store jobs in DB and process with CRON.
- Mark status:
pending,processing,done,failed.
- Track system and user actions.
- Include metadata for compliance or debugging.
- Store and serve real-time in-app alerts.
- Extend with Resend or Twilio for multi-channel support.
- Store messages and participants.
- Support real-time threaded conversations.
- Structured memory (facts, chat logs, serialized context).
- Used to reconstruct prompts or plan next actions.
- Use JSON blobs for flexible schema needs.
- Good for dynamic forms or user-generated config.
- Protect sensitive data with role-based access.
- Mask or encrypt fields based on context.
| Tool | Use Case |
|---|---|
| Convex DevTools | Live inspect DB, queries, and mutations |
| Convex Playground | Test backend functions interactively |
| CLI Codegen | Generate type-safe hooks and definitions |
| Convex + Vercel/Fly | Full-stack hosting integrations |
| Convex Secrets | Store API keys securely |
| Convex on Fly.io | Run your own edge-based infra (optional) |
This document serves as a flexible blueprint for designing high-performance, real-time applications using Convex. Whether building solo tools, collaborative systems, or AI agents, these patterns offer a scalable starting point.