Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions example/convex/_generated/api.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
* @module
*/

import type * as batchedWrites from "../batchedWrites.js";
import type * as btree from "../btree.js";
import type * as crons from "../crons.js";
import type * as leaderboard from "../leaderboard.js";
Expand All @@ -23,6 +24,7 @@ import type {
} from "convex/server";

declare const fullApi: ApiFromModules<{
batchedWrites: typeof batchedWrites;
btree: typeof btree;
crons: typeof crons;
leaderboard: typeof leaderboard;
Expand Down Expand Up @@ -65,5 +67,6 @@ export declare const components: {
photos: import("@convex-dev/aggregate/_generated/component.js").ComponentApi<"photos">;
stats: import("@convex-dev/aggregate/_generated/component.js").ComponentApi<"stats">;
btreeAggregate: import("@convex-dev/aggregate/_generated/component.js").ComponentApi<"btreeAggregate">;
batchedWrites: import("@convex-dev/aggregate/_generated/component.js").ComponentApi<"batchedWrites">;
migrations: import("@convex-dev/migrations/_generated/component.js").ComponentApi<"migrations">;
};
321 changes: 321 additions & 0 deletions example/convex/batchedWrites.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,321 @@
/**
* Example of using the batch API for efficient writes.
*
* This demonstrates how to use the `.buffer()` method to queue write
* operations and flush them in a batch, reducing the number of mutations
* and improving performance.
*/

import { DirectAggregate } from "@convex-dev/aggregate";
import { mutation } from "./_generated/server";
import { components } from "./_generated/api.js";
import { v } from "convex/values";
import { customMutation } from "convex-helpers/server/customFunctions";

const aggregate = new DirectAggregate<{
Key: number;
Id: string;
}>(components.batchedWrites);

/**
* Basic example: Enable buffering, queue operations, then flush manually.
*/
export const basicBatchedWrites = mutation({
args: {
count: v.number(),
},
handler: async (ctx, { count }) => {
// Enable buffering mode - modifies the aggregate instance in place
aggregate.buffer(true);

// Queue multiple insert operations
for (let i = 0; i < count; i++) {
await aggregate.insert(ctx, {
key: i,
id: `item-${i}`,
sumValue: i * 10,
});
}

// Disable buffering after we're done
aggregate.buffer(false);
// Flush all buffered operations in a single batch
await aggregate.flush(ctx);

// Read operations work normally (and auto-flush if needed)
const total = await aggregate.count(ctx);

return { inserted: count, total };
},
});

/**
* Advanced example: Use custom functions with onSuccess callback.
*
* This pattern is useful when you are also using triggers, to avoid all
* triggered writes calling the component individually.
*/

// Create a custom mutation that uses buffered aggregate
const mutationWithBuffering = customMutation(mutation, {
args: {},
input: async () => {
aggregate.buffer(true);
return {
ctx: {},
args: {},
onSuccess: async ({ ctx }) => {
await aggregate.flush(ctx);
},
};
},
});
Comment on lines +60 to +72
Copy link

@coderabbitai coderabbitai bot Dec 5, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Buffering not disabled on handler error.

If the handler throws before onSuccess runs, aggregate.buffer(true) remains set on the shared instance. Subsequent mutations using this aggregate may unintentionally inherit buffering mode. Consider wrapping in try/finally or resetting state defensively.

 const mutationWithBuffering = customMutation(mutation, {
   args: {},
   input: async () => {
     aggregate.buffer(true);
     return {
       ctx: {},
       args: {},
       onSuccess: async ({ ctx }) => {
         await aggregate.flush(ctx);
+        aggregate.buffer(false);
       },
     };
   },
 });

Note: This still doesn't handle the error case. A more robust approach would be to use a local aggregate instance per invocation or ensure cleanup on error paths.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const mutationWithBuffering = customMutation(mutation, {
args: {},
input: async () => {
aggregate.buffer(true);
return {
ctx: {},
args: {},
onSuccess: async ({ ctx }) => {
await aggregate.flush(ctx);
},
};
},
});
const mutationWithBuffering = customMutation(mutation, {
args: {},
input: async () => {
aggregate.buffer(true);
return {
ctx: {},
args: {},
onSuccess: async ({ ctx }) => {
await aggregate.flush(ctx);
aggregate.buffer(false);
},
};
},
});
🤖 Prompt for AI Agents
In example/convex/batchedWrites.ts around lines 60 to 72, calling
aggregate.buffer(true) in input may leave the shared aggregate stuck in
buffering mode if the handler throws; wrap the buffering lifecycle so it is
always disabled on exit (use try/finally to call aggregate.buffer(false) or
aggregate.flush/cleanup in the finally block), or better yet create and use a
local aggregate instance per invocation so state isn't shared across handlers;
ensure any early-throw paths perform the same cleanup to avoid leaking buffering
state to subsequent mutations.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mutations are all run in isolated environments - globals are not shared across them

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ianmacartney Thank you for the clarification! I misunderstood the Convex execution model. If each mutation runs in an isolated environment where globals aren't shared across invocations, then my concern about state leaking between mutations is indeed invalid. The buffering state would be fresh for each mutation call, so there's no risk of one mutation affecting another.

I appreciate you taking the time to explain this!


✏️ Learnings added
Learnt from: ianmacartney
Repo: get-convex/aggregate PR: 167
File: example/convex/batchedWrites.ts:60-72
Timestamp: 2025-12-05T03:45:23.412Z
Learning: In Convex, mutations are run in isolated environments where globals are not shared across mutation invocations. A global variable set in one mutation invocation will not affect subsequent mutation invocations.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


🧠 Learnings used
Learnt from: CR
Repo: get-convex/aggregate PR: 0
File: example/.cursor/rules/convex_rules.mdc:0-0
Timestamp: 2025-12-03T18:51:23.434Z
Learning: Applies to example/convex/**/*.{ts,tsx} : Use `ctx.runMutation` to call a mutation from a mutation or action

Learnt from: CR
Repo: get-convex/aggregate PR: 0
File: example/.cursor/rules/convex_rules.mdc:0-0
Timestamp: 2025-12-03T18:51:23.434Z
Learning: Applies to example/convex/**/*.{ts,tsx} : Use `for await (const row of query)` syntax for async iteration; do not use `.collect()` or `.take(n)` on query results

Learnt from: CR
Repo: get-convex/aggregate PR: 0
File: example/.cursor/rules/convex_rules.mdc:0-0
Timestamp: 2025-12-03T18:51:23.434Z
Learning: Applies to example/convex/**/*.{ts,tsx} : Convex queries do NOT support `.delete()`; instead `.collect()` the results and call `ctx.db.delete(row._id)` on each result

Learnt from: CR
Repo: get-convex/aggregate PR: 0
File: example/.cursor/rules/convex_rules.mdc:0-0
Timestamp: 2025-12-03T18:51:23.434Z
Learning: Applies to example/convex/**/*.{ts,tsx} : Use `internalQuery`, `internalMutation`, and `internalAction` to register private functions that are only callable by other Convex functions

Learnt from: CR
Repo: get-convex/aggregate PR: 0
File: example/.cursor/rules/convex_rules.mdc:0-0
Timestamp: 2025-12-03T18:51:23.434Z
Learning: Applies to example/convex/**/*.{ts,tsx} : Organize files with public query, mutation, or action functions thoughtfully within the `convex/` directory using file-based routing

Learnt from: CR
Repo: get-convex/aggregate PR: 0
File: example/.cursor/rules/convex_rules.mdc:0-0
Timestamp: 2025-12-03T18:51:23.434Z
Learning: Applies to example/convex/**/*.{ts,tsx} : When using `ctx.runQuery`, `ctx.runMutation`, or `ctx.runAction` to call a function in the same file, specify a type annotation on the return value


/**
* Example using custom function with onSuccess callback.
*
* This demonstrates the recommended pattern for batching:
* - Enable buffering at the start (in customCtx)
* - Queue operations throughout the function using the global aggregate
* - Flush in the onSuccess callback
*/
export const batchedWritesWithOnSuccess = mutationWithBuffering({
args: {
items: v.array(
v.object({
key: v.number(),
id: v.string(),
value: v.number(),
}),
),
},
handler: async (ctx, { items }) => {
// Queue all operations - they're stored in memory, not sent yet
// We use the global 'aggregate' instance which has buffering enabled
for (const item of items) {
await aggregate.insert(ctx, {
key: item.key,
id: item.id,
sumValue: item.value,
});
}

return {
queued: items.length,
};
},
});

/**
* Complex example: Mix different operation types in a batch.
*/
export const complexBatchedOperations = mutation({
args: {
inserts: v.array(
v.object({
key: v.number(),
id: v.string(),
value: v.number(),
}),
),
deletes: v.array(
v.object({
key: v.number(),
id: v.string(),
}),
),
updates: v.array(
v.object({
oldKey: v.number(),
newKey: v.number(),
id: v.string(),
value: v.number(),
}),
),
},
handler: async (ctx, { inserts, deletes, updates }) => {
// Enable buffering
aggregate.buffer(true);

// Queue inserts
for (const item of inserts) {
await aggregate.insert(ctx, {
key: item.key,
id: item.id,
sumValue: item.value,
});
}

// Queue deletes
for (const item of deletes) {
await aggregate.deleteIfExists(ctx, {
key: item.key,
id: item.id,
});
}

// Queue updates (replace operations)
for (const item of updates) {
await aggregate.replaceOrInsert(
ctx,
{ key: item.oldKey, id: item.id },
{ key: item.newKey, sumValue: item.value },
);
}

// Flush all operations at once
await aggregate.flush(ctx);

// Disable buffering
aggregate.buffer(false);

return {
operations: {
inserts: inserts.length,
deletes: deletes.length,
updates: updates.length,
},
};
},
});

/**
* Performance comparison: Batched vs unbatched writes.
*/
export const comparePerformance = mutation({
args: {
count: v.number(),
useBatching: v.boolean(),
},
handler: async (ctx, { count, useBatching }) => {
const start = Date.now();

if (useBatching) {
// Batched approach
aggregate.buffer(true);

for (let i = 0; i < count; i++) {
await aggregate.insert(ctx, {
key: 1000000 + i,
id: `perf-test-${i}`,
sumValue: i,
});
}

await aggregate.flush(ctx);
aggregate.buffer(false);
} else {
// Unbatched approach
for (let i = 0; i < count; i++) {
await aggregate.insert(ctx, {
key: 1000000 + i,
id: `perf-test-${i}`,
sumValue: i,
});
}
}

const duration = Date.now() - start;

return {
method: useBatching ? "batched" : "unbatched",
count,
durationMs: duration,
};
},
});

/**
* Example showing automatic flush on read operations.
*/
export const autoFlushOnRead = mutation({
args: {
count: v.number(),
},
handler: async (ctx, { count }) => {
// Enable buffering
aggregate.buffer(true);

// Queue some operations
for (let i = 0; i < count; i++) {
await aggregate.insert(ctx, {
key: 2000000 + i,
id: `auto-flush-${i}`,
sumValue: i,
});
}

// This read operation automatically flushes the buffer first
// So we'll see the correct count including the queued operations
const total = await aggregate.count(ctx, {
bounds: {
lower: { key: 2000000, inclusive: true },
},
});

// Disable buffering
aggregate.buffer(false);

return {
queued: count,
totalInRange: total,
};
},
});

/**
* Example: Batch operations with namespace grouping.
*
* When you have operations across multiple namespaces,
* the batch mutation automatically groups them and fetches
* each namespace's tree only once.
*/
export const batchedWritesWithNamespaces = mutation({
args: {
operations: v.array(
v.object({
namespace: v.string(),
key: v.number(),
id: v.string(),
value: v.number(),
}),
),
},
handler: async (ctx, { operations }) => {
// Create a namespaced aggregate
const namespacedAggregate = new DirectAggregate<{
Key: number;
Id: string;
Namespace: string;
}>(components.batchedWrites);

// Enable buffering
namespacedAggregate.buffer(true);

// Queue operations - they'll be grouped by namespace internally
for (const op of operations) {
await namespacedAggregate.insert(ctx, {
namespace: op.namespace,
key: op.key,
id: op.id,
sumValue: op.value,
});
}

// Flush all operations
// The batch mutation will group by namespace automatically
await namespacedAggregate.flush(ctx);

// Disable buffering
namespacedAggregate.buffer(false);

// Count unique namespaces
const namespaces = new Set(operations.map((op) => op.namespace));

return {
operations: operations.length,
namespaces: namespaces.size,
message: `Processed ${operations.length} operations across ${namespaces.size} namespaces in a single batch`,
};
},
});
1 change: 1 addition & 0 deletions example/convex/convex.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ app.use(aggregate, { name: "music" });
app.use(aggregate, { name: "photos" });
app.use(aggregate, { name: "stats" });
app.use(aggregate, { name: "btreeAggregate" });
app.use(aggregate, { name: "batchedWrites" });

app.use(migrations);

Expand Down
Loading
Loading