Skip to main content

Rate limits, audit log and call events

Limit how often an action runs, keep a record of who changed which rows, and send one event per call to your log service.

Both are written in the policy, next to the roles. There is no second place to configure them.

convex/policy.ts
export const policy = definePolicy({
  actions: [
    'invites.send',
    'reports.generate',
    'contact.send',
    'projects.archive',
    'members.remove',
  ],
  roles: { owner: ['*'] },
  scopes: {},
  public: ['contact.send'],
  limits: {
    'invites.send': { max: 10, every: 'minute' },
    'reports.generate': { max: 30, every: 'hour', per: 'tenant' },
    'contact.send': { max: 60, every: 'minute', per: 'everyone' },
  },
  audit: ['projects.archive', 'members.*'],
})

Rate limits

max is how many calls the bucket holds. It refills max per every ('second', 'minute', 'hour' or 'day'), continuously: ten calls a minute gives back one call every six seconds. max is a whole number of at least 1.

per says whose calls share a bucket:

perBucket
'user' (default)The person. For an agent: the person and the client or in-app agent.
'tenant'The call's tenant. A call without a tenant counts per user.
'everyone'One bucket for the whole action.

The call's tenant is the deepest tenant it names. With tenants inside tenants (clients in an organization), each client has its own bucket, so a person who may create clients can spread calls across them. Add a per: 'user' limit on another action of the same request when that matters.

A visitor who is not signed in has no user, so a public action uses the everyone bucket whatever per says. everyone is one document that every call writes: use it for low-volume public actions such as a contact form, not for busy ones.

A call over the limit fails with RATE_LIMITED and the message Too many requests. Try again in N seconds.

What counts:

  • The policy decides first. A call it denies (NOT_SIGNED_IN, FORBIDDEN, NOT_FOUND) never takes a token.
  • The token is taken in the transaction of the call, before the handler. A mutation that fails gives its token back, so it does not count. A public action takes its token in its check (authorizeAction), before its handler runs; when the handler fails, the token stays spent: an action has no transaction.
  • Every mutation built with fns is limited, public or internal, and so is every public action.
  • Work that a call runs or schedules is part of that call. A mutation that the call runs with ctx.runMutation, or schedules with ctx.scheduler, takes no second token from a bucket that the call already took one from. The same is true for a mutation that an internal action runs, when the call scheduled or ran that internal action. A mutation with another bucket (another action, or another tenant) takes its own token.
  • So a request that schedules "call a service, then save" with the same action pays once. Limit the request, not the save after the outside call: a save that the limit refuses throws away the outside call's result.
  • A chain that schedules itself again pays once per request, not once per step. It keeps running after an agent's turn ends, until it stops itself or the agent's grant ends, so count its steps in the operation and stop at a bound.
  • Jobs and other system calls are never limited.
  • An agent's call is limited like a person's, with one exception: a request that waits for approval takes no token, and neither does the run after the person approves it. The person is the limit there. The request still counts against the agent's 60 writes a minute.
  • Wrong definitions throw when the policy is defined: an action that is not in actions, max below 1 or not whole, an unknown every or per.

Convex actions

A public action built with action takes its token in its check, before the handler runs. A mutation that the handler runs with ctx.runMutation takes no second token from the same bucket. An action has no transaction, so a call that fails after the check keeps its token spent.

An internal action has no check of its own. Limit the action of the call that schedules it. A mutation that the internal action runs with ctx.runMutation takes no second token from a bucket that call already took one from, and takes its own token from any other bucket.

A query cannot take a token. A limits entry for an action that only a query uses throws when the query is defined: "is limited, but no mutation uses it".

Storage

Buckets live in the library table rateLimits: one small document per limited key. Their number is bounded by users times limited actions, plus the tenants and actions with per: 'tenant'. If you use agents, housekeeping deletes buckets idle for more than a day. Without agents nothing deletes them; a full bucket costs one row.

Audit log

The log follows the action, whichever door the call came in by. After an audited mutation succeeds, the library writes one row to the auditLog table, in the same transaction. Every audited operation writes its own row: a public mutation, an agent's tool call (also when a person approved it), or an internal mutation that was scheduled or run for a person or an agent. The one exception is an operation that an audited call runs with ctx.runMutation: its ids join the outer call's row. Under a call that is not audited, it writes its own row.

FieldContent
actorWho: the same record as in activity. For an agent: door mcp or app, with clientId or agent.
actionThe policy action of the outer call.
tenantIdThe call's tenant, when it has one.
rowsThe ids the call inserted, patched, replaced or deleted, at most 50.
moreHow many ids there were beyond the 50.

The time is the row's _creationTime. The log holds no values, no arguments and no results: only ids. A call that fails writes nothing, because the whole transaction rolls back. System actors (jobs) and signed-out visitors have no row. activity stays as it is: it is the agents' replay and history, not the audit log.

A call with no tenant of its own writes a row without tenantId: a crossTenant call, such as a move of a row from one tenant to another, and a call whose input names no tenant. auditTrail(ctx, { tenantId }) does not show these rows, so neither tenant's trail lists the move. Find them by the person who acted, in the by_user index of auditLog (actor.userId). Operations cannot read library tables: read the index in the Convex dashboard, or in a function built with trusted.

audit takes the same patterns as roles: 'projects.archive', 'members.*' or '*'. A pattern that matches no action throws when the policy is defined.

Reading the log

The library does not decide who may read it. Write an operation with its own action and call auditTrail:

ts
import { auditTrail } from '@lupinum/better-convex-functions'

export const trail = query({
  action: 'audit.read',
  args: { orgId: v.id('orgs'), paginationOpts: paginationOptsValidator },
  returns: v.any(),
  handler: (ctx, { orgId, paginationOpts }) => auditTrail(ctx, { tenantId: orgId, paginationOpts }),
})

It returns one page of the tenant's rows, newest first. No retention is applied: the log is meant to last. When a person deletes their account, erasure removes their id from the rows and keeps the rows themselves.

Call events

Turn on observe to write one line on the console for each call. A Convex log stream (Convex Pro plan) sends the lines to your log service. Log streams and PostHog shows how to connect one and find a call.

convex/functions.ts
export const fns = defineFunctions({
  auth,
  policy,
  user,
  roleOf,
  rules,
  observe: true,
})

Each call that reaches your function writes one JSON line:

json
{
  "type": "better-convex.call",
  "action": "projects.archive",
  "kind": "mutation",
  "actor": { "key": "person:k57…", "kind": "person", "door": "web", "userId": "k57…" },
  "tenant": "j97…",
  "outcome": "error",
  "code": "FORBIDDEN"
}
FieldContent
actionThe policy action. A job writes job.<name>. An internal action has none. The agents package's own functions write agents.<name>.
kindquery, mutation or action.
actorThe same record as in auditLog, or { "kind": "visitor" }. An internal action shows only the kind it acts for, such as { "kind": "person" }, without key. Missing when the call failed before it knew the caller.
agentThe key of the agent whose request a person approved or declined. actor is that person.
tenantThe call's tenant, when it has one.
outcomeok or error. For an agent's request: pending while it waits for a person, declined when a person declined it.
codeThe data.code of the ConvexError: a library code or your app's own. A crash has none.
writtenHow many rows a call that succeeded inserted, patched, replaced or deleted. Missing for work that runs as the system, such as a job: its writes are not counted.
approvalThe approval request an agent's call made, or the one its work runs under.
traceThe ID of the chain of calls this call belongs to (see below). Missing on a call that starts no other work.
fieldsWhat the handler added with ctx.log.set. A value JSON cannot hold, such as a BigInt, is left out.

A query writes a line only when it fails, because Convex runs a query again each time the rows it read change. A mutation that fails also writes its line: its writes roll back, but the console line stays.

One transaction writes one line. An internal operation that a query or mutation runs with ctx.runQuery or ctx.runMutation is part of the caller's transaction, so it writes no line of its own. The caller's line counts its rows in written and shows its ctx.log.set fields. Calls from an action and scheduled work run on their own and write their own lines. A job argument cannot be named inner.

When the caller catches the failure of such an inner call, its line shows only its own outcome: ok, without the inner call's code.

ok means that your handler finished. Convex can still fail the call after that, when the result does not match returns. Convex also refuses arguments that do not match args before your handler runs, and then no line is written. Convex's own event for the same request ID has the final status.

A public action that its policy check refuses also writes a line, with the actor and the tenant of the call.

Agents

With the agents package, each tool call writes a line with the agent as actor, except a query tool that succeeds, like any query. A call the library refuses before your function runs writes one too: a revoked connection (AGENT_DISABLED), a connection over its limit (RATE_LIMITED) or input that does not fit (INVALID_INPUT).

A tool call that needs a person's approval writes outcome: "pending" and the request in approval. The person's decision writes the next line for the same request, with the request's action:

json
{
  "type": "better-convex.call",
  "action": "projects.archive",
  "kind": "mutation",
  "actor": { "key": "person:k57…", "kind": "person", "door": "web", "userId": "k57…" },
  "agent": "mcp:k57…:claude-desktop",
  "tenant": "j97…",
  "outcome": "ok",
  "written": 1,
  "approval": "jd7…"
}

The approved work runs inside approve and writes no line of its own. The line of approve shows the outcome of the work: ok with its rows, or error with its code, for example STALE when a row changed after the agent asked. A decline writes outcome: "declined".

housekeeping, the upload route, and the steps of in-app agents write no line. The tool calls those steps make do.

What the line holds

The line holds IDs and codes, never arguments, results or messages. You can add your own IDs with ctx.log.set. Do not add values that a person typed, such as names, amounts or email addresses: the log stream copies every line to another service.

ts
handler: async (ctx, { documentId }) => {
  ctx.log.set({ document: { id: documentId } })
  // …
}

Without observe, ctx.log.set does nothing.

Convex writes its own event for each call, with the function path, the duration, the final status and the request ID. Find both events by the request ID that error.requestId shows the user. observe reads and writes no table and changes no query subscription.

Convex gives scheduled work a new request ID, and its event does not name the call that scheduled it. So a call that starts other work (ctx.scheduler, ctx.runQuery, ctx.runMutation or ctx.runAction) gets a trace ID and passes it on. Each internal operation, internal action and job in the chain writes the same trace, also when it runs hours later. Search for one trace to see everything that one call started. A job argument cannot be named trace.

The audit log and call events answer different questions. The audit log stays in your database and records who changed which rows. Call events leave Convex and also record refused and failed calls.