---
title: "Keep counts and sums"
description: "Counts and sums over a table that stay fast at any size, from Convex's aggregate component kept in step by triggers, and sharded counters for numbers many people change at once."
canonical_url: "https://nuxt-backend.dev/docs/build/data/read-write/aggregates"
---
# Keep counts and sums

> Counts and sums over a table that stay fast at any size, from Convex's aggregate component kept in step by triggers, and sharded counters for numbers many people change at once.

Version: nuxt-backend 0.6.x · Tab: Build · Kind: recipe · Status: stable

Every page: [llms.txt](https://nuxt-backend.dev/llms.txt) · Skill for coding agents: [nuxt-backend](https://nuxt-backend.dev/.well-known/skills/nuxt-backend/SKILL.md)

Commands use npm; use your project's package manager.

Show how many strips a workspace has without reading every row, and keep a like count that hundreds of readers change at once. Convex has no count operator: reading every row gets slower as the table grows, and the query re-runs on every change. Two official Convex components keep the number for you, and your app imports them directly:

- **@convex-dev/aggregate** keeps counts, sums and ranks over a table's rows, updated in the same transaction as each write. A read costs the logarithm of the rows.
- **@convex-dev/sharded-counter** keeps a number that is not a count of rows, such as views or likes, spread over several documents so concurrent writes do not conflict.

The package adds nothing of its own here. It accepts your trigger-wrapped `mutation` in `createFunctions`, so every write through an access tier keeps the aggregate in step.

## Count a workspace's strips

Install the component and the helpers its triggers use:

```bash
npm install @convex-dev/aggregate convex-helpers
```

Then mount it, define the aggregate, wrap the tiers' `mutation` in its trigger, and read the count:

<code-tree default-value="backend/aggregates.ts">

```ts [backend/convex.config.ts]
import aggregate from '@convex-dev/aggregate/convex.config'

// …after the package's components, before `export default app`
app.use(aggregate)
```

```ts [backend/aggregates.ts]
import { TableAggregate } from '@convex-dev/aggregate'
import { Triggers } from 'convex-helpers/server/triggers'
import { components } from './_generated/api'
import type { DataModel } from './_generated/dataModel'

// One count per workspace: the namespace is the row's workspace.
export const stripsPerWorkspace = new TableAggregate<{
  Namespace: string
  Key: null
  DataModel: DataModel
  TableName: 'strips'
}>(components.aggregate, {
  namespace: strip => strip.workspaceId,
  sortKey: () => null,
})

export const triggers = new Triggers<DataModel>()
triggers.register('strips', stripsPerWorkspace.trigger())
```

```ts [backend/functions.ts]
import { customCtx, customMutation } from 'convex-helpers/server/customFunctions'
import { createFunctions } from 'nuxt-backend/functions'
import { triggers } from './aggregates'
import { billing } from './billing'
import { rateLimiter } from './rateLimiter'
import { components } from './_generated/api'
import { action, mutation as rawMutation, query } from './_generated/server'

// Every write through a tier now keeps the aggregate in step.
const mutation = customMutation(rawMutation, customCtx(triggers.wrapDB))

export const { authed, workspace, admin, withRole, withFeature, setUserRole } = createFunctions(
  { query, mutation, action },
  { components, billing, rateLimiter },
)
```

```ts [backend/strips.ts]
import { stripsPerWorkspace } from './aggregates'
import { workspace } from './functions'

export const count = workspace.query({
  args: {},
  handler: ctx => stripsPerWorkspace.count(ctx, { namespace: ctx.workspace.id }),
})
```

```vue [app/components/StripCount.vue]
<script setup lang="ts">
import { api } from '#backend/api'

const count = useQuery(api.strips.count, {})
</script>

<template>
  <p>{{ count ?? '…' }} strips</p>
</template>
```

</code-tree>

`useQuery` returns `undefined` until the first read lands, so the page never shows a `0` that is not an answer. A query that fails throws: [Query and update data](https://nuxt-backend.dev/docs/build/data/read-write) shows the forms that keep an error in the result.

A trigger sees only writes made through the wrapped `mutation`. A job that writes `strips` from an `internalMutation` needs the same wrapper: `customMutation(rawInternalMutation, customCtx(triggers.wrapDB))`.

## Sums, ranks and a second aggregate

A sum is the same aggregate with a `sumValue`, such as `sumValue: strip => strip.panelCount`, read with `.sum(ctx, { namespace })`. A `sortKey` other than `null` orders the rows, for ranks and offsets (`.indexOf`, `.at`).

Every `TableAggregate` on one mount shares its storage, one tree per namespace. Two aggregates over the same table with the same namespace write the same entries, and the second insert fails with "key already exists". Give each its own place:

- **A namespace of its own** on the same mount, such as `namespace: strip => 'pages:' + strip.workspaceId`.
- **A second mount**, `app.use(aggregate, { name: 'stripPanels' })`, passed as `components.stripPanels`. Use it when you want to clear or rebuild one aggregate on its own.

## Backfill rows that predate the trigger

A trigger only sees writes made after you register it, and `trigger()` throws on an update or a delete of a row the aggregate never saw. On a table that already has rows:

1. Register `stripsPerWorkspace.idempotentTrigger()` in place of `trigger()`, and deploy.
2. Fill the aggregate with a [migration](https://nuxt-backend.dev/docs/build/data/jobs/migrations) whose `migrateOne` calls `stripsPerWorkspace.insertIfDoesNotExist(ctx, doc)`. It is idempotent, so running it again changes nothing.
3. Once the migration has finished, switch back to `trigger()`.

## Counts with many writers

A like count is one number that many people change at once, and many writes to one document conflict and retry. The sharded counter spreads each count over 16 documents by default, so concurrent increments land on different ones.

```bash
npm install @convex-dev/sharded-counter
```

<code-tree default-value="backend/likes.ts">

```ts [backend/convex.config.ts]
import shardedCounter from '@convex-dev/sharded-counter/convex.config'

app.use(shardedCounter)
```

```ts [backend/likes.ts]
import { ShardedCounter } from '@convex-dev/sharded-counter'
import { v } from 'convex/values'
import { components } from './_generated/api'
import { query } from './_generated/server'
import { authed } from './functions'

const likes = new ShardedCounter(components.shardedCounter)

// One like per person also needs a row per reader and strip, or a rate limit.
export const like = authed.mutation({
  args: { stripId: v.id('strips') },
  handler: (ctx, { stripId }) => likes.inc(ctx, stripId),
})

export const count = query({
  args: { stripId: v.id('strips') },
  handler: (ctx, { stripId }) => likes.count(ctx, stripId),
})
```

</code-tree>

`add`, `subtract`, `inc`, `dec` and `reset` change a count from a mutation or an action, and `count` reads it from any function. A count that was never written reads `0`. More shards take more writers at once, fewer make a read cheaper: `{ defaultShards: 4 }` changes it for every key, `{ shards: { featured: 64 } }` for the keys it names.

A read of `count` touches every shard, so a mutation that reads a count it also writes contends with every writer. `estimateCount(ctx, key)` reads one shard and scales the answer up.

When a workspace is deleted, clear its namespace in the same source that deletes its rows: `stripsPerWorkspace.clear(ctx, { namespace: workspaceId })`.

Pick an aggregate when the count follows a table's rows, or you need sums, ranges or ranks. Pick the counter when the number is the data and many people change it at once.

## Related

- [Migrate data](https://nuxt-backend.dev/docs/build/data/jobs/migrations): backfill an aggregate over rows that predate its trigger.
- [Scope tables to a workspace](https://nuxt-backend.dev/docs/build/data/read-write/workspace-scoped): the `workspaceId` the count is namespaced by.
- [Plan quotas](https://nuxt-backend.dev/docs/build/billing/subscriptions/quotas): the package's own counts of what a plan allows.
- [Convex](https://nuxt-backend.dev/docs/services/convex): components and what each costs in function calls.
- The [aggregate](https://www.convex.dev/components/aggregate) and [sharded counter](https://www.convex.dev/components/sharded-counter) components: every method.


## Sitemap

See the full [sitemap](https://nuxt-backend.dev/sitemap.md) for all pages.
