Benchdog guide

This guide covers the TypeScript packages, the Ember addon and the dashboard. The Rails and Django packages come later, and they follow the same spec. The TypeScript packages are on npm. The versions are below 1.0, so an API can change before 1.0.

Install

pnpm add @benchdog-ts/core @benchdog-ts/prisma @benchdog-ts/express @benchdog-ts/dashboard
pnpm add @benchdog-ts/ember        # an Ember app
pnpm add @benchdog-ts/redis ioredis # more than one process

Node 22.12 or later. The core also runs in browsers and edge runtimes.

Flags

Declare the flags in code. Then a wrong key, or a default of the wrong type, is a compile error.

import { defineFlags } from '@benchdog-ts/core'

export const flags = defineFlags({
  'new-checkout': { type: 'boolean' },
  theme: { type: 'string', variations: ['classic', 'ocean'] },
  price: { type: 'number' },
})

A flag in the store has gates, rules and a fallthrough. A boolean flag needs only a key: { "key": "new-checkout" } is off for everyone.

Gate On when
boolean Always.
actors The actor id is in the list.
groups A group that your code registers is true for the actor.
expression A Flipper expression is true, for example {"Equal": [{"Property": "plan"}, "pro"]}.
percentageOfActors The actor's bucket is below the percentage. The same actor always gets the same answer.
percentageOfTime A random number is below the percentage.

Evaluation

The order is: the kill switch (enabled: false), prerequisites, the boolean, actor, group and expression gates, the rules, the percentage gates, and then the fallthrough. The first step that decides gives the result. The result has the value, the variation, an OpenFeature reason and the step that decided.

flagsClient.details('new-checkout', { id: 'user:42' })
// { value: true, variation: 'on', reason: 'SPLIT', gate: 'percentageOfActors' }

The full rules are in spec/SPEC.md. Evaluation does no I/O: the client keeps a snapshot of the environment in memory.

Express

Mount the admin API and the dashboard. You give the sign-in (authenticate) and the role in each environment (roleFor).

import express from 'express'
import { dashboardDir } from '@benchdog-ts/dashboard'
import { benchdog } from '@benchdog-ts/express'

app.use(
  '/benchdog/api',
  benchdog({
    store,
    environments: [{ name: 'staging', promotesTo: 'production' }, { name: 'production' }],
    authenticate: request => currentUser(request),
    roleFor: (user, environment) => (user.isAdmin ? 'admin' : 'viewer'),
    actorFor: (request, user) => (user ? { id: `user:${user.id}` } : undefined),
  }),
)
app.use('/benchdog', express.static(dashboardDir))

The roles are viewer, editor, approver and admin. Each write needs a reason. Send the ETag from a read as If-Match, so a write does not undo a change by another user.

Prisma

Copy node_modules/@benchdog-ts/prisma/prisma/benchdog.prisma (or benchdog.mysql.prisma) into your Prisma schema folder, make a migration, and give your client to the store.

import { PrismaStore } from '@benchdog-ts/prisma'

const store = new PrismaStore(prisma)

Each write is one transaction: the change and its audit entry. PostgreSQL, MySQL and SQLite pass the same store contract.

Redis

With more than one process, put Redis in front of the store and use its pub/sub as the change feed.

import { Redis } from 'ioredis'
import { RedisChangeFeed, cachedStore, fromIoredis, ioredisSubscriber } from '@benchdog-ts/redis'

const redis = new Redis(process.env.REDIS_URL)
const feed = new RedisChangeFeed(fromIoredis(redis), ioredisSubscriber(redis.duplicate()))
const store = cachedStore(new PrismaStore(prisma), fromIoredis(redis), { feed })
const flagsClient = createBenchdog({ store, environment: 'production', flags, feed })

In serverless functions with no long connection, use pollIntervalMs in place of a feed.

Ember

The benchdog service reads ENV.benchdog and the payload in the page. Templates render again when a value changes.

import { Flag, enabled, flagValue, BenchdogToolbar } from '@benchdog-ts/ember'

<template>
  {{#if (enabled "dark-mode")}}...{{/if}}
  <p class={{flagValue "theme" "classic"}}>...</p>
  <Flag @key="new-checkout"><NewCheckout /></Flag>
</template>

In a route: await requireFlag(this, 'new-checkout', 'index'). In development, <BenchdogToolbar /> switches flags with local overrides. For types, add your flags to BenchdogRegistry.

Browser client

The server evaluates the flags that have the client tag, and sends only the results. Rules and other users stay on the server.

import { createClient, readPayload } from '@benchdog-ts/client'

const client = createClient({ flags, payload: readPayload(), live: true })
client.enabled('new-checkout')

Dashboard

The dashboard lists the flags of each environment, edits the gates, kills and promotes flags, and shows the audit log. It uses only the admin API, so it works on every host. Try the demo.

Groups and actors in the dashboard

The audience option of createAdminApi tells the dashboard which groups and actor types exist. It also gives the dashboard a way to find an actor by name. The option does not change how a flag is evaluated.

With the option, the flag page shows a name lookup for actors, a list of the known groups with their meaning, and a panel that says in plain words who gets the flag. An Audience page lists the groups and the actor types. That page is read-only.

A group is still a function that your app registers in code, in groups. The audience.groups list only gives each group a description for the dashboard. A group name that only a flag uses still shows in the dashboard, marked as not registered.

Warning: each signed-in user with a role can search for actors, a viewer included. Benchdog does not filter the result. Your lookupActors function must decide which actors the user can see.

The function gets the query and the signed-in user. The query has q (a text search) or ids (exact actor ids), and never both. If a request has both, ids wins. The query also has an optional type and a limit from 1 to 50. The function returns objects with an id (a full actor id, for example user:42) and an optional name and note.

import { createAdminApi } from '@benchdog-ts/admin-api'

createAdminApi({
  store,
  environments: [{ name: 'staging', promotesTo: 'production' }, { name: 'production' }],
  authenticate: request => currentUser(request),
  roleFor: (user, environment) => (user.isAdmin ? 'admin' : 'viewer'),
  groups: { staff: actor => actor.attributes?.staff === true },
  audience: {
    groups: [{ key: 'staff', description: 'The employees' }],
    actorTypes: [{ type: 'user', label: 'A person' }],
    lookupActors: async ({ q, ids, type, limit }, user) =>
      ids ? usersByActorId(ids, user) : searchUsers(q, { type, limit, user }),
  },
})

Each part of audience is optional. Without lookupActors, the dashboard shows that actors take ids only. In the example, usersByActorId and searchUsers are your own functions.

The actor check in the dashboard answers one question: is the flag on for this actor, and which step decided? It has two limits. First, the check knows only the id of the actor. A gate that reads an attribute, such as an expression or a group function, can give a different answer than in production. Second, the percentage-of-time gate is random, so the answer can change on the next check.

An audience that a user edits in the dashboard and saves is a segment. A segment is not a group. The dashboard does not edit groups, because they come from the code of your app.

Audit log

Each change writes one entry: who, when, the action, the reason, the source, and the flag before and after. Each entry holds the SHA-256 hash of the entry before it, so a change to an old entry breaks the chain. GET /audit/verify and the dashboard check the chain.

Tests

// Node: a store in memory
const store = new MemoryStore()

// Ember
import { setFlag, setupBenchdog } from '@benchdog-ts/ember/test-support'
setupBenchdog(hooks, { 'new-checkout': true })
setFlag('new-checkout', false)

From Flipper

Benchdog uses Flipper's bucket function (crc32(key + id) % 100000) and Flipper's expression format. A 25% rollout in Flipper gives the flag to the same actors in Benchdog. The Flipper backend, the importer and the Flipper API come with the Rails phase.