-
Notifications
You must be signed in to change notification settings - Fork 3
batch writes #167
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ianmacartney
wants to merge
2
commits into
main
Choose a base branch
from
ian/batch-writes
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
batch writes #167
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| }, | ||
| }; | ||
| }, | ||
| }); | ||
|
|
||
| /** | ||
| * 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`, | ||
| }; | ||
| }, | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Buffering not disabled on handler error.
If the handler throws before
onSuccessruns,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
🤖 Prompt for AI Agents
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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
🧠 Learnings used