Convex Mutations Skill
This skill provides specialized guidance for implementing Convex mutation functions, including best practices for function definition, registration, database operations, and scheduling patterns.
When to Use This Skill
Use this skill when:
- Defining new mutation functions to write or modify data in the Convex database
- Performing database operations (
insert, patch, replace, delete)
- Calling mutations from other Convex functions
- Scheduling future mutations with
ctx.scheduler.runAfter
- Handling transactional operations
- Coordinating mutations with actions for background processing
Skill Resources
This skill includes comprehensive reference documentation in references/mutation-guidelines.md that covers:
Core Mutation Development
- Function definition syntax using the new function syntax
- Mutation registration (
mutation and internalMutation)
- Argument validators and their usage
- Function calling patterns (
ctx.runQuery and ctx.runMutation)
- Function references (
api and internal objects)
- File-based routing for mutation paths
Database Operations
ctx.db.insert() - Create new documents
ctx.db.patch() - Shallow merge updates into existing documents
ctx.db.replace() - Fully replace existing documents
- Error handling for missing documents
- Transaction semantics and consistency guarantees
Advanced Mutation Features
- Scheduling: Using
ctx.scheduler.runAfter() to queue background jobs
- Scheduling mutations and actions for future execution
- Understanding that auth state does NOT propagate to scheduled jobs
- Using internal functions for scheduled jobs that need privileges
- Avoiding tight loops and respecting 10-second minimum intervals
- Transactional Behavior: Understanding mutation transactions
- Enqueuing scheduler jobs is transactional within mutations
- Race condition prevention through transaction boundaries
Function Composition
- Calling queries within mutations for validation
- Calling mutations from mutations
- Using return type annotations for same-file mutation calls
How to Use This Skill
- Read the reference documentation at
references/mutation-guidelines.md to understand the complete mutation patterns
- Follow the syntax examples for defining mutation functions with proper validators
- Use appropriate database operations (
insert, patch, replace) based on your needs
- Schedule background work using
ctx.scheduler.runAfter for long-running operations
- Remember auth state does NOT propagate to scheduled jobs; use internal functions for privileged operations
- Leverage transactions for consistency across multiple operations
Key Mutation Guidelines
- ALWAYS include argument validators for all mutation functions
- Use
ctx.db.patch() for partial updates and ctx.db.replace() for full replacements
- Use
ctx.scheduler.runAfter() to schedule actions (e.g., AI responses, notifications)
- Remember that scheduled jobs have
null auth state; use internal functions instead
- Mutations execute for at most 1 second and can write up to 8192 documents
- Return
null implicitly if your mutation doesn't have an explicit return value
- Use return type annotations when calling mutations in the same file (TypeScript circularity workaround)
Example: Mutation with Database Operation and Scheduling
import { mutation, internalAction } from "./_generated/server";
import { v } from "convex/values";
import { internal } from "./_generated/api";
export const sendMessage = mutation({
args: {
channelId: v.id("channels"),
authorId: v.id("users"),
content: v.string(),
},
handler: async (ctx, args) => {
// Validate channel and user exist
const channel = await ctx.db.get(args.channelId);
if (!channel) {
throw new Error("Channel not found");
}
// Insert message into database
await ctx.db.insert("messages", {
channelId: args.channelId,
authorId: args.authorId,
content: args.content,
});
// Schedule AI response generation (transactional)
await ctx.scheduler.runAfter(0, internal.functions.generateResponse, {
channelId: args.channelId,
});
return null;
},
});
export const updateUserStatus = mutation({
args: {
userId: v.id("users"),
status: v.string(),
},
handler: async (ctx, args) => {
// Patch updates an existing document with shallow merge
await ctx.db.patch(args.userId, {
status: args.status,
lastUpdated: Date.now(),
});
return null;
},
});
For more detailed information and additional patterns, refer to the complete reference documentation.
1---2name: convex-mutations3description: This skill should be used when implementing Convex mutation functions. It provides comprehensive guidelines for defining, registering, calling, and scheduling mutations, including database operations, transactions, and scheduled job patterns.4---5
6# Convex Mutations Skill
7
8This skill provides specialized guidance for implementing Convex mutation functions, including best practices for function definition, registration, database operations, and scheduling patterns.
9
10## When to Use This Skill
11
12Use this skill when:
13- Defining new mutation functions to write or modify data in the Convex database
14- Performing database operations (`insert`, `patch`, `replace`, `delete`)
15- Calling mutations from other Convex functions
16- Scheduling future mutations with `ctx.scheduler.runAfter`
17- Handling transactional operations
18- Coordinating mutations with actions for background processing
19
20## Skill Resources
21
22This skill includes comprehensive reference documentation in `references/mutation-guidelines.md` that covers:
23
24### Core Mutation Development
25- Function definition syntax using the new function syntax
26- Mutation registration (`mutation` and `internalMutation`)
27- Argument validators and their usage
28- Function calling patterns (`ctx.runQuery` and `ctx.runMutation`)
29- Function references (`api` and `internal` objects)
30- File-based routing for mutation paths
31
32### Database Operations
33- `ctx.db.insert()` - Create new documents
34- `ctx.db.patch()` - Shallow merge updates into existing documents
35- `ctx.db.replace()` - Fully replace existing documents
36- Error handling for missing documents
37- Transaction semantics and consistency guarantees
38
39### Advanced Mutation Features
40- **Scheduling**: Using `ctx.scheduler.runAfter()` to queue background jobs
41 - Scheduling mutations and actions for future execution
42 - Understanding that auth state does NOT propagate to scheduled jobs
43 - Using internal functions for scheduled jobs that need privileges
44 - Avoiding tight loops and respecting 10-second minimum intervals
45- **Transactional Behavior**: Understanding mutation transactions
46 - Enqueuing scheduler jobs is transactional within mutations
47 - Race condition prevention through transaction boundaries
48
49### Function Composition
50- Calling queries within mutations for validation
51- Calling mutations from mutations
52- Using return type annotations for same-file mutation calls
53
54## How to Use This Skill
55
561. **Read the reference documentation** at `references/mutation-guidelines.md` to understand the complete mutation patterns
572. **Follow the syntax examples** for defining mutation functions with proper validators
583. **Use appropriate database operations** (`insert`, `patch`, `replace`) based on your needs
594. **Schedule background work** using `ctx.scheduler.runAfter` for long-running operations
605. **Remember auth state does NOT propagate** to scheduled jobs; use internal functions for privileged operations
616. **Leverage transactions** for consistency across multiple operations
62
63## Key Mutation Guidelines
64
65- ALWAYS include argument validators for all mutation functions
66- Use `ctx.db.patch()` for partial updates and `ctx.db.replace()` for full replacements
67- Use `ctx.scheduler.runAfter()` to schedule actions (e.g., AI responses, notifications)
68- Remember that scheduled jobs have `null` auth state; use internal functions instead
69- Mutations execute for at most 1 second and can write up to 8192 documents
70- Return `null` implicitly if your mutation doesn't have an explicit return value
71- Use return type annotations when calling mutations in the same file (TypeScript circularity workaround)
72
73## Example: Mutation with Database Operation and Scheduling
74
75```ts
76import { mutation, internalAction } from "./_generated/server";
77import { v } from "convex/values";
78import { internal } from "./_generated/api";
79
80export const sendMessage = mutation({
81 args: {
82 channelId: v.id("channels"),
83 authorId: v.id("users"),
84 content: v.string(),
85 },
86 handler: async (ctx, args) => {
87 // Validate channel and user exist
88 const channel = await ctx.db.get(args.channelId);
89 if (!channel) {
90 throw new Error("Channel not found");
91 }
92
93 // Insert message into database
94 await ctx.db.insert("messages", {
95 channelId: args.channelId,
96 authorId: args.authorId,
97 content: args.content,
98 });
99
100 // Schedule AI response generation (transactional)
101 await ctx.scheduler.runAfter(0, internal.functions.generateResponse, {
102 channelId: args.channelId,
103 });
104
105 return null;
106 },
107});
108
109export const updateUserStatus = mutation({
110 args: {
111 userId: v.id("users"),
112 status: v.string(),
113 },
114 handler: async (ctx, args) => {
115 // Patch updates an existing document with shallow merge
116 await ctx.db.patch(args.userId, {
117 status: args.status,
118 lastUpdated: Date.now(),
119 });
120 return null;
121 },
122});
123```
124
125For more detailed information and additional patterns, refer to the complete reference documentation.