xiaohongshu
xiaohongshu
moai-baas-convex-ext
Enterprise Convex Real-Time Backend with AI-powered reactive database architecture, Context7 integration, and intelligent synchronization orchestration for collaborative applications
Full skill instructions
| Field | Value |
|---|---|
| Skill Name | moai-baas-convex-ext |
| Version | 4.0.0 (2025-11-13) |
| Tier | Enterprise Real-Time Backend Expert |
| AI-Powered | ✅ Context7 Integration, Intelligent Architecture |
| Auto-load | On demand when Convex keywords detected |
Enterprise Convex Real-Time Backend expert with AI-powered reactive database architecture, Context7 integration, and intelligent synchronization orchestration for collaborative applications.
Revolutionary v4.0.0 capabilities:
Automatic triggers:
Manual invocation:
# AI-powered Convex architecture optimization with Context7
class ConvexArchitectOptimizer:
def __init__(self):
self.context7_client = Context7Client()
self.typescript_analyzer = TypeScriptAnalyzer()
self.realtime_optimizer = RealtimeOptimizer()
async def design_optimal_convex_architecture(self,
requirements: ApplicationRequirements) -> ConvexArchitecture:
"""Design optimal Convex architecture using AI analysis."""
# Get latest Convex and TypeScript documentation via Context7
convex_docs = await self.context7_client.get_library_docs(
context7_library_id='/convex/docs',
topic="real-time backend reactive database typescript optimization 2025",
tokens=3000
)
typescript_docs = await self.context7_client.get_library_docs(
context7_library_id='/typescript/docs',
topic="advanced types optimization performance 2025",
tokens=2000
)
# Optimize real-time architecture
realtime_design = self.realtime_optimizer.design_reactive_system(
requirements.realtime_needs,
convex_docs
)
# Optimize TypeScript configuration
typescript_optimization = self.typescript_analyzer.optimize_configuration(
requirements.typescript_features,
typescript_docs
)
return ConvexArchitecture(
schema_design=self._design_schema(requirements),
function_architecture=self._design_functions(requirements),
realtime_system=realtime_design,
typescript_configuration=typescript_optimization,
authentication_setup=self._integrate_authentication(requirements),
deployment_strategy=self._plan_deployment(requirements),
performance_predictions=realtime_design.predictions
)
// Convex schema definition with TypeScript
import { defineSchema, defineTable } from "convex/server";
import { v } from "convex/values";
export default defineSchema({
// User management with real-time presence
users: defineTable({
name: v.string(),
email: v.string(),
avatar: v.optional(v.string()),
status: v.union(v.literal("online"), v.literal("offline"), v.literal("away")),
lastSeen: v.number(),
presence: v.optional(v.object({
currentRoom: v.id("rooms"),
lastActivity: v.number(),
cursor: v.optional(v.object({
x: v.number(),
y: v.number(),
})),
})),
})
.index("by_email", ["email"])
.index("by_status", ["status"]),
// Collaborative rooms with real-time state
rooms: defineTable({
name: v.string(),
description: v.optional(v.string()),
type: v.union(v.literal("document"), v.literal("whiteboard"), v.literal("chat")),
createdBy: v.id("users"),
createdAt: v.number(),
isPublic: v.boolean(),
maxParticipants: v.optional(v.number()),
})
.index("by_created_by", ["createdBy"])
.index("by_type", ["type"]),
// Real-time documents with collaborative editing
documents: defineTable({
title: v.string(),
content: v.optional(v.string()),
roomId: v.id("rooms"),
createdBy: v.id("users"),
createdAt: v.number(),
updatedAt: v.number(),
version: v.number(),
isLocked: v.boolean(),
lockedBy: v.optional(v.id("users")),
})
.index("by_room", ["roomId"])
.index("by_updated_at", ["updatedAt"]),
// Real-time messages and activities
messages: defineTable({
content: v.string(),
author: v.id("users"),
roomId: v.id("rooms"),
timestamp: v.number(),
type: v.union(v.literal("text"), v.literal("system"), v.literal("file")),
metadata: v.optional(v.any()),
})
.index("by_room_timestamp", ["roomId", "timestamp"])
.index("by_author", ["author"]),
});
// Convex functions with real-time capabilities
import { mutation, query, action } from "./_generated/server";
import { v } from "convex/values";
// Real-time presence updates
export const updatePresence = mutation({
args: {
status: v.union(v.literal("online"), v.literal("offline"), v.literal("away")),
currentRoom: v.optional(v.id("rooms")),
cursor: v.optional(v.object({ x: v.number(), y: v.number() })),
},
handler: async (ctx, args) => {
const identity = await ctx.auth.getUserIdentity();
if (!identity) throw new Error("Unauthorized");
const user = await ctx.db
.query("users")
.withIndex("by_email", (q) => q.eq("email", identity.email!))
.unique();
if (!user) throw new Error("User not found");
const updateData: any = {
status: args.status,
lastSeen: Date.now(),
};
if (args.currentRoom || args.cursor) {
updateData.presence = {
currentRoom: args.currentRoom,
lastActivity: Date.now(),
cursor: args.cursor,
};
}
await ctx.db.patch(user._id, updateData);
return user._id;
},
});
// Real-time document collaboration
export const updateDocument = mutation({
args: {
documentId: v.id("documents"),
content: v.string(),
version: v.number(),
},
handler: async (ctx, args) => {
const identity = await ctx.auth.getUserIdentity();
if (!identity) throw new Error("Unauthorized");
const document = await ctx.db.get(args.documentId);
if (!document) throw new Error("Document not found");
// Check if document is locked by another user
if (document.isLocked && document.lockedBy !== document.createdBy) {
throw new Error("Document is locked by another user");
}
// Version conflict detection
if (document.version !== args.version) {
throw new Error("Version conflict - document was modified");
}
const updatedDocument = await ctx.db.patch(args.documentId, {
content: args.content,
updatedAt: Date.now(),
version: args.version + 1,
});
// Trigger real-time update notification
await ctx.scheduler.runAfter(0, internal.notifications.notifyDocumentUpdate, {
documentId: args.documentId,
roomId: document.roomId,
updatedBy: document.createdBy,
});
return updatedDocument;
},
});
// Real-time room activity monitoring
export const getRoomActivity = query({
args: { roomId: v.id("rooms") },
handler: async (ctx, args) => {
const room = await ctx.db.get(args.roomId);
if (!room || !room.isPublic) throw new Error("Room not accessible");
const [messages, activeUsers] = await Promise.all([
// Get recent messages
ctx.db
.query("messages")
.withIndex("by_room_timestamp", (q) =>
q.eq("roomId", args.roomId).order("desc").take(50)
),
// Get active users in room
ctx.db
.query("users")
.withIndex("by_status", (q) => q.eq("status", "online"))
.collect()
.then(users => users.filter(user =>
user.presence?.currentRoom === args.roomId
)),
]);
return {
messages,
activeUsers: activeUsers.map(user => ({
id: user._id,
name: user.name,
avatar: user.avatar,
presence: user.presence,
})),
};
},
});
// Collaborative editing with operational transformation
export const applyEdit = mutation({
args: {
documentId: v.id("documents"),
operation: v.object({
type: v.union(v.literal("insert"), v.literal("delete"), v.literal("replace")),
position: v.number(),
content: v.optional(v.string()),
length: v.optional(v.number()),
}),
clientVersion: v.number(),
},
handler: async (ctx, args) => {
const document = await ctx.db.get(args.documentId);
if (!document) throw new Error("Document not found");
// Apply operational transformation
const transformedOp = await transformOperation(
args.operation,
document.pendingOperations || []
);
// Apply transformed operation to document
const newContent = applyOperation(document.content || "", transformedOp);
// Update document with new content and clear pending operations
await ctx.db.patch(args.documentId, {
content: newContent,
updatedAt: Date.now(),
version: document.version + 1,
pendingOperations: [],
});
// Broadcast operation to other clients
await ctx.scheduler.runAfter(0, internal.realtime.broadcastOperation, {
documentId: args.documentId,
operation: transformedOp,
author: args.operation.author,
});
return { success: true, newVersion: document.version + 1 };
},
});
// Real-time cursor tracking for collaborative cursors
export const updateCursor = mutation({
args: {
roomId: v.id("rooms"),
cursor: v.object({ x: v.number(), y: v.number() }),
},
handler: async (ctx, args) => {
const identity = await ctx.auth.getUserIdentity();
if (!identity) throw new Error("Unauthorized");
const user = await ctx.db
.query("users")
.withIndex("by_email", (q) => q.eq("email", identity.email!))
.unique();
if (!user) throw new Error("User not found");
// Update user's cursor position
await ctx.db.patch(user._id, {
presence: {
currentRoom: args.roomId,
lastActivity: Date.now(),
cursor: args.cursor,
},
});
// Broadcast cursor position to other users in the room
await ctx.scheduler.runAfter(0, internal.realtime.broadcastCursor, {
roomId: args.roomId,
userId: user._id,
cursor: args.cursor,
});
return { success: true };
},
});
// Self-hosted Convex configuration with PostgreSQL
import { ConvexHttpClient } from "convex/browser";
export class SelfHostedConvex {
private client: ConvexHttpClient;
private postgresConfig: PostgresConfig;
constructor(config: SelfHostedConfig) {
this.client = new ConvexHttpClient(config.convexUrl);
this.postgresConfig = config.postgres;
}
// Initialize self-hosted Convex with PostgreSQL
async initialize(): Promise<void> {
// Configure PostgreSQL persistence
await this.configurePostgresPersistence();
// Set up replication for high availability
await this.configureReplication();
// Initialize monitoring and metrics
await this.setupMonitoring();
}
private async configurePostgresPersistence(): Promise<void> {
const persistenceConfig = {
host: this.postgresConfig.host,
port: this.postgresConfig.port,
database: this.postgresConfig.database,
username: this.postgresConfig.username,
password: this.postgresConfig.password,
ssl: this.postgresConfig.ssl,
// Optimization settings for Convex
poolSize: 20,
connectionTimeout: 5000,
statementTimeout: 10000,
// Replication settings
replicationMode: "streaming",
walLevel: "logical",
maxWalSenders: 5,
};
await this.client.action(internal.persistence.configure, persistenceConfig);
}
// Configure multi-region deployment
async configureMultiRegion(deploymentConfig: MultiRegionConfig): Promise<void> {
const regions = [
{ name: "us-east-1", primary: true },
{ name: "eu-west-1", primary: false },
{ name: "ap-southeast-1", primary: false },
];
for (const region of regions) {
await this.deployRegion(region, deploymentConfig);
}
// Configure cross-region replication
await this.setupCrossRegionReplication(regions);
}
}
// Real-time performance optimization strategies
export class ConvexPerformanceOptimizer {
// Optimize function execution with batching
static async batchUpdates<T>(
updates: Array<{ id: Id<any>; data: Partial<T> }>,
batch: any
): Promise<void> {
const BATCH_SIZE = 100;
for (let i = 0; i < updates.length; i += BATCH_SIZE) {
const batchUpdates = updates.slice(i, i + BATCH_SIZE);
await batch.run(async (ctx) => {
const promises = batchUpdates.map(({ id, data }) =>
ctx.db.patch(id, data)
);
await Promise.all(promises);
});
}
}
// Optimize real-time subscriptions with smart filtering
static optimizeRealtimeSubscriptions(
roomId: Id<"rooms">,
userId: Id<"users">,
subscriptionFilters: SubscriptionFilters
) {
return {
// Only subscribe to relevant data
messages: subscriptionFilters.includeMessages
? q => q.eq("roomId", roomId).gte("timestamp", subscriptionFilters.since)
: null,
// Only track presence for active users
users: subscriptionFilters.trackPresence
? q => q.eq("status", "online").eq("presence.currentRoom", roomId)
: null,
// Optimize document updates for collaboration
documents: subscriptionFilters.trackDocumentChanges
? q => q.eq("roomId", roomId).gt("updatedAt", subscriptionFilters.lastSeen)
: null,
};
}
}
defineSchema(schemaDefinition) - Define database schemamutation({...}) - Define data mutation functionquery({...}) - Define data query functionaction({...}) - Define server action functionscheduler.runAfter(delay, function, args) - Schedule delayed executionget_latest_convex_documentation() - Official Convex docs via Context7analyze_realtime_patterns() - Real-time architecture via Context7optimize_typescript_configuration() - TypeScript optimization via Context7moai-baas-foundation (Enterprise BaaS architecture patterns)moai-domain-backend (Backend development patterns)moai-domain-frontend (Frontend integration with Convex)moai-essentials-perf (Performance optimization)moai-foundation-trust (Security and authentication)moai-baas-supabase-ext (PostgreSQL alternative comparison)moai-baas-firebase-ext (Real-time alternative comparison)moai-domain-ml (Real-time ML integration)End of Skill | Updated 2025-11-13
End of Enterprise Convex Real-Time Backend Expert v4.0.0
xiaohongshu
technical spec
product ux expert
database patterns
Conduct multi-agent task orchestration and workflow coordination.
Initialize project with Conductor artifacts (product definition,
Expert in web animations, transitions, and motion design using Framer Motion and CSS
Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...
PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.
Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...
Display project status, active tracks, and next actions
Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.
Generate, edit, and beat-sync AI video with leading models in one workspace.
The world's fastest calendar for remote work
Transform Your Design with AI Designer by ImgCreator.ai
Revolutionizing Video Production with AI-Powered Creativity
Extend an image past the frame and let AI fill the new aspect ratio.
Discover your celebrity doppelgänger with StarByFace!
ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.
Opus.ai: Revolutionize Your Web Experience