MCPInstall

convex-best-practices

Production patterns for Convex apps and the rules the @convex-dev/eslint-plugin enforces: validators, indexes, idempotent mutations, avoiding OCC conflicts, thin function wrappers, error handling. Use when reviewing Convex code, asking whether a pattern is right, setting up ESLint, or fixing write conflicts and slow queries.

Installs
3.9K
Last 24h
—
Trending rank
—
Security
Warn

Install

Works with every agent the skills CLI supports.

npx skills add https://github.com/waynesutton/builder-skills --skill convex-best-practices
  1. 01

    Install

    Run the command in your project. The CLI asks which agents to install for.

  2. 02

    Describe the task

    Ask your agent for something this skill covers. It loads convex-best-practices automatically when relevant.

  3. 03

    Review the result

    The agent follows the SKILL.md steps, scripts and references bundled with the skill.

Security audits

Independent scans of the skill's instructions and bundled files.

Gen Agent Trust Hub PassSAFE ·This skill provides production-grade best practices and configuration guides for building Convex applications. It includes standard instructions for installing official Convex developer tools and setting up ESLint to enforce performance and correctness rules. No malicious patterns were detected.
Socket PassNo alerts
Snyk WarnMEDIUM ·Risk: MEDIUM · 1 issue

SKILL.md

The instructions your agent reads when the skill is triggered.

Convex best practices

The patterns that keep a Convex app fast and correct in production. The rule that matters most: read as little as possible before you write, and read through an index.

Rules that matter most

  1. Validators on every function. args and returns, with returns: v.null() when nothing comes back.
  2. Indexes, not filters. Every table read goes through withIndex against an index in convex/schema.ts.
  3. Idempotent mutations. Return early when the document is already in the target state so retries are safe.
  4. Patch without reading first. ctx.db.patch(id, fields) throws if the doc is missing; you rarely need the old value.
  5. Promise.all for independent writes. Do not await them one at a time.
  6. Schedule internal.* only. Crons and ctx.scheduler run without a client, so public targets skip auth.
  7. Thin wrappers. Auth and business logic live in plain helpers that take ctx.
  8. ConvexError for anything a client should read. Plain Error messages are redacted in production.
// convex/tasks.ts
import { query, mutation } from "./_generated/server";
import { v, ConvexError } from "convex/values";

const taskValidator = v.object({
  _id: v.id("tasks"),
  _creationTime: v.number(),
  userId: v.id("users"),
  title: v.string(),
  status: v.union(v.literal("open"), v.literal("done")),
});

export const listOpen = query({
  args: { userId: v.id("users") },
  returns: v.array(taskValidator),
  handler: async (ctx, args) => {
    return await ctx.db
      .query("tasks")
      .withIndex("by_user_and_status", (q) =>
        q.eq("userId", args.userId).eq("status", "open"),
      )
      .order("desc")
      .take(100);
  },
});

export const rename = mutation({
  args: { taskId: v.id("tasks"), title: v.string() },
  returns: v.null(),
  handler: async (ctx, args) => {
    if (args.title.trim().length === 0) {
      throw new ConvexError("Title cannot be empty");
    }
    await ctx.db.patch(args.taskId, { title: args.title.trim() });
    return null;
  },
});

The schema behind that index:

tasks: defineTable({
  userId: v.id("users"),
  title: v.string(),
  status: v.union(v.literal("open"), v.literal("done")),
})
  .index("by_user", ["userId"])
  .index("by_user_and_status", ["userId", "status"]),

Name indexes after their fields in order, and query fields in that same order.

OCC and write conflicts

Convex runs mutations under optimistic concurrency control. A mutation records what it read. If another mutation commits a change to any of that data first, Convex retries it. After enough retries it fails and the client sees a write conflict error.

Conflicts come from three places:

  • Two mutations writing the same document at once: counters, "last seen" fields, a shared settings doc
  • A mutation that reads a wide range, such as .collect() on a whole table, so any change in that range conflicts with it
  • A client calling the same mutation faster than it can commit: typing, dragging, polling

Idempotent and patch first

export const complete = mutation({
  args: { taskId: v.id("tasks") },
  returns: v.null(),
  handler: async (ctx, args) => {
    const task = await ctx.db.get(args.taskId);
    if (!task || task.status === "done") {
      return null;
    }
    await ctx.db.patch(args.taskId, { status: "done" });
    return null;
  },
});

export const reorder = mutation({
  args: { itemIds: v.array(v.id("items")) },
  returns: v.null(),
  handler: async (ctx, args) => {
    await Promise.all(
      args.itemIds.map((id, index) => ctx.db.patch(id, { order: index })),
    );
    return null;
  },
});

The read in complete is fine: one document, early exit. reorder never reads at all.

Event records instead of counters

A counter field on one document is the most common conflict source. Insert one row per event and count in a query.

export const trackView = mutation({
  args: { pageId: v.id("pages") },
  returns: v.null(),
  handler: async (ctx, args) => {
    await ctx.db.insert("pageViews", { pageId: args.pageId });
    return null;
  },
});

export const viewCount = query({
  args: { pageId: v.id("pages") },
  returns: v.number(),
  handler: async (ctx, args) => {
    const views = await ctx.db
      .query("pageViews")
      .withIndex("by_page", (q) => q.eq("pageId", args.pageId))
      .collect();
    return views.length;
  },
});

Once the event table gets large, move the count to the @convex-dev/sharded-counter or @convex-dev/aggregate component instead of collecting rows.

Dedup windows

For heartbeats and presence, skip the write when the last one was recent. Pair it with a client side debounce: 300 to 500 ms for typing, a few seconds for heartbeats.

const DEDUP_MS = 10_000;

export const heartbeat = mutation({
  args: { sessionId: v.string(), path: v.string() },
  returns: v.null(),
  handler: async (ctx, args) => {
    const now = Date.now();
    const existing = await ctx.db
      .query("sessions")
      .withIndex("by_session", (q) => q.eq("sessionId", args.sessionId))
      .unique();
    if (!existing) {
      await ctx.db.insert("sessions", { ...args, lastSeen: now });
      return null;
    }
    if (existing.path === args.path && now - existing.lastSeen < DEDUP_MS) {
      return null;
    }
    await ctx.db.patch(existing._id, { path: args.path, lastSeen: now });
    return null;
  },
});

Put hot fields such as lastSeen in their own table so those writes do not conflict with reads of the stable document.

Pagination over collect

.collect() on an unbounded table gets slower every day and eventually hits read limits. Paginate anything a user can grow. postValidator below is a hoisted document validator like taskValidator above.

import { paginationOptsValidator } from "convex/server";

export const feed = query({
  args: { userId: v.id("users"), paginationOpts: paginationOptsValidator },
  returns: v.object({
    page: v.array(postValidator),
    isDone: v.boolean(),
    continueCursor: v.string(),
    splitCursor: v.optional(v.union(v.string(), v.null())),
    pageStatus: v.optional(
      v.union(v.literal("SplitRecommended"), v.literal("SplitRequired"), v.null()),
    ),
  }),
  handler: async (ctx, args) => {
    return await ctx.db
      .query("posts")
      .withIndex("by_user", (q) => q.eq("userId", args.userId))
      .order("desc")
      .paginate(args.paginationOpts);
  },
});

On the client, usePaginatedQuery from convex/react drives loadMore.

No Date.now() in queries

Queries must be deterministic so Convex can cache them and rerun them when data changes. Pass time from the client, or store a status field that a scheduled mutation updates.

export const dueBefore = query({
  args: { userId: v.id("users"), now: v.number() },
  returns: v.array(taskValidator),
  handler: async (ctx, args) => {
    return await ctx.db
      .query("tasks")
      .withIndex("by_user_and_due", (q) =>
        q.eq("userId", args.userId).lt("dueAt", args.now),
      )
      .take(100);
  },
});

Mutations and actions may call Date.now().

ESLint plugin

@convex-dev/eslint-plugin catches the old function syntax, missing arg validators, .filter() in queries, and top of the hour crons at lint time. Install it in every Convex project.

npm i --save-dev @convex-dev/eslint-plugin
// eslint.config.js
import { defineConfig } from "eslint/config";
import convexPlugin from "@convex-dev/eslint-plugin";

export default defineConfig([...convexPlugin.configs.recommended]);

Open references/eslint-setup.md when you need the full rule list, the TypeScript aware config, package scripts, or a custom convex/ directory.

Common mistakes

MistakeWhy it breaksDo instead
.filter() on a table queryReads every row, then drops mostAdd an index, use withIndex
.collect() on an unbounded tableSlower every day, hits read limits, wide OCC footprint.paginate() or .take(n)
Read, compute, then patch a shared docTwo clients read the same version and both writePatch directly, or split into event rows
Counter field incremented per eventEvery increment conflicts with every otherEvent records or a sharded counter component
Mutation without an early returnRetries and double clicks apply the change twiceCheck state, return null if already done
Sequential await on independent writesSlow, and each read widens the conflict windowPromise.all
Date.now() in a queryResult changes every ms, cache and subscriptions breakPass now as an arg
Scheduling api.*Public function runs with no client authSchedule internal.*
Plain Error for user messagesRedacted to "Server Error" in productionConvexError
Business logic inside the handlerUntestable, duplicated across functionsPlain helper that takes ctx

Checklist

  • Every function has args and returns
  • Every table read uses withIndex, never .filter()
  • Indexes are named after their fields in order
  • Mutations return early when the doc is already in the target state
  • Mutations patch without a prior read unless the old value is needed
  • Independent writes run under Promise.all
  • High frequency counts use event rows or a counter component
  • Unbounded lists use .paginate()
  • No Date.now() inside a query
  • Scheduled and cron targets are internal.*
  • @convex-dev/eslint-plugin is installed and npm run lint passes

Docs

FAQ

What does the convex-best-practices skill do?

Production patterns for Convex apps and the rules the @convex-dev/eslint-plugin enforces: validators, indexes, idempotent mutations, avoiding OCC conflicts, thin function wrappers, error handling. Use when reviewing Convex code, asking whether a pattern is right, setting up ESLint, or fixing write conflicts and slow queries.

How do I install convex-best-practices?

Run npx skills add https://github.com/waynesutton/builder-skills --skill convex-best-practices in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/convex-best-practices/ (personal) or .claude/skills/convex-best-practices/ (project).

Which AI agents can use convex-best-practices?

Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.

Is convex-best-practices safe to install?

Security partners have reviewed it: Gen Agent Trust Hub passed; Socket passed; Snyk flagged items to review. As with any skill, read the SKILL.md and bundled scripts before installing.

Who maintains convex-best-practices?

It is published by waynesutton in waynesutton/builder-skills. It has 3,894 recorded installs.

More from waynesutton/builder-skills

View all →

convex

waynesutton/builder-skills

Routes Convex work to the right builder skill and covers the handful of rules that apply everywhere: validators on every function, withIndex over filter, idempotent mutations, internal functions for scheduling. Use when a task mentions Convex and no more specific skill matches, or as the first stop before picking one.

convex-functions

waynesutton/builder-skills

Writes Convex queries, mutations, actions, and internal functions in the object form with args and returns validators, correct ctx usage, runtime boundaries, and error handling. Use when adding or changing anything in convex/.ts that exports a function, or when deciding between query, mutation, and action.

3.2K installs

convex-schema-validator

waynesutton/builder-skills

Designs convex/schema.ts tables, validators, indexes, and relationships, and keeps the schema honest as data evolves. Use when creating tables, adding fields, choosing index fields, modeling relationships, or when a validator error appears at deploy time.

DevOps & Cloud3K installs

convex-realtime

waynesutton/builder-skills

Builds reactive UIs on Convex subscriptions: useQuery patterns, optimistic updates, pagination that stays live, presence, and avoiding subscription churn. Use when wiring the frontend to Convex, when data does not update live, or when a page rerenders too much.

Frontend & Design2.9K installs

convex-cron-jobs

waynesutton/builder-skills

Schedules work in Convex: cron jobs in convex/crons.ts, one off scheduled functions with runAfter and runAt, batching large jobs, and cancelling or inspecting the queue. Use when something needs to run on a timer, later, or in the background, or when a cron is not firing.

2.8K installs

convex-http-actions

waynesutton/builder-skills

Adds HTTP endpoints in convex/http.ts: webhook receivers with signature checks, REST style routes, CORS, auth headers, streaming responses, and file uploads over HTTP. Use when integrating Stripe, Clerk, Resend, or any service that calls back into the app, or when a client needs a plain HTTP API.

Backend & APIs2.7K installs

Popular code quality & workflow skills

View category →

grill-me

mattpocock/skills

A relentless interview to sharpen a plan or design.

Scan a codebase for deepening opportunities, present them as a visual HTML report, then grill through whichever one you pick.

handoff

mattpocock/skills

Compact the current conversation into a handoff document for another agent to pick up.

domain-modeling

mattpocock/skills

Build and sharpen a project's domain model. Use when discussing codebase terminology, writing or editing a GLOSSARY.md, or recording or editing an ADR.

codebase-design

mattpocock/skills

Shared vocabulary for designing deep modules. Use when the user wants to design or improve a module's interface, find deepening opportunities, decide where a seam goes, make code more testable or AI-navigable, or when another skill needs the deep-module vocabulary.

diagnosing-bugs

mattpocock/skills

Diagnosis loop for hard bugs and performance regressions. Use when the user says "diagnose"/"debug this", or reports something broken/throwing/failing/slow.