Agora

You're viewing the docs for Flags 0.x. The latest is 1.x (rc). Go to the 1.x (rc) docs

Central Server

One flags server many apps connect to — topologies, tenant tokens with authkit or shared secrets, transports, and OFREP.

With several apps, run flags in one place. The control-plane owns the ruleset, the console, the event log and the sinks. Each app is a tenant: it downloads the ruleset, evaluates locally and sends its events to the control-plane. topology, verifyTenant and tenant take the same shape as in @adonis-agora/durable.

Deployment topologies

RunsNeeds
standalone (default)everything in the appnothing
control-planeruleset, console, events, sinks, OFREPverifyTenant
tenantevaluation in memory, events sent to the control-planetenant: { url, partition, token }

authkit-server, the flags control-plane and the apps can be separate servers. Nothing in flags needs authkit-server in its own process: the helpers come from @adonis-agora/authkit-client, and flags works without authkit at all (shared secrets).

The control-plane

config/flags.ts (flags server)
import env from '#start/env'
import { defineConfig } from '@adonis-agora/flags'
import { authkitTenantVerifier } from '@adonis-agora/authkit-client'

export default defineConfig({
  topology: 'control-plane',
  flags: {},
  verifyTenant: authkitTenantVerifier({
    issuer: env.get('AUTHKIT_ISSUER'),
    resource: 'urn:agora:flags',
  }),
})

verifyTenant takes a function, an object with verify() (a class instance), or a lazy import of a class:

config/flags.ts (flags server)
verifyTenant: () => import('#tenants/flags_verifier'),
app/tenants/flags_verifier.ts
import { AuthkitTenantVerifier } from '@adonis-agora/authkit-client'

export default class FlagsVerifier extends AuthkitTenantVerifier {
  constructor() {
    super({ issuer: process.env.AUTHKIT_ISSUER!, resource: 'urn:agora:flags' })
  }
}

Whatever the form, it answers { partition, environment?, capabilities } for a valid token and null otherwise. The partition (the app), its environment and what it may do all come from the token, never from the request.

controlPlane holds the HTTP options: prefix (default /_flags), ofrep (default true) and corsOrigins for OFREP.

Tenants authenticate with tokens, not cookies: exempt the flags API from @adonisjs/shield's CSRF check on the control-plane, or it refuses their events.

config/shield.ts (flags server)
import { flagsCsrfExceptions } from '@adonis-agora/flags'

csrf: { enabled: true, exceptRoutes: (ctx) => flagsCsrfExceptions(ctx.request.url()) },

It serves, under /_flags, each endpoint requiring one capability in the token:

EndpointCapability
GET /v1/ruleset (with ETag), GET /v1/ruleset/stream (server-sent events)flags:ruleset:read
POST /v1/events, POST /v1/usage, POST /v1/browser-keyflags:events:write
POST /v1/declarationsflags:declarations:write
POST /ofrep/v1/evaluate/flags[/:key]flags:ofrep:evaluate

A token the verifier refuses gets 401; a valid token without the capability gets 403.

A capability can use * wildcards. A * segment matches any one segment, and a trailing * also covers everything under it:

GrantedAllows
flags:*every endpoint above
flags:*:writeflags:events:write and flags:declarations:write
*everything, in every product

Nothing else is implied: flags:events:write does not allow flags:ruleset:read, and flags:* does not allow another product's capabilities.

A tenant

config/flags.ts (an app)
import env from '#start/env'
import { defineConfig, flag } from '@adonis-agora/flags'
import { authkitTenantToken } from '@adonis-agora/authkit-client'

export default defineConfig({
  topology: 'tenant',
  flags: {
    new_player: flag.boolean({ default: false }),
  },
  tenant: {
    url: env.get('FLAGS_URL'),          // https://flags.example.com/_flags
    partition: 'streaming',             // this app's name
    token: authkitTenantToken({
      issuer: env.get('AUTHKIT_ISSUER'),
      clientId: env.get('AGORA_TENANT_CLIENT_ID'),
      clientSecret: env.get('AGORA_TENANT_CLIENT_SECRET'),
      resource: 'urn:agora:flags',
    }),
    snapshotPath: 'storage/flags/ruleset.json',
  },
})

tenant.token takes a string (a shared secret), a function returning a token, or an object with get(). authkitTenantToken finds authkit's token endpoint through discovery, caches the token and refreshes it before it expires.

tenant.url also takes a function resolving the URL, so the app can find the control plane through authkit discovery instead of an env var:

config/flags.ts (an app)
import { controlPlaneUrl } from '@adonis-agora/authkit-client'

tenant: {
  url: controlPlaneUrl({ issuer: env.get('AUTHKIT_ISSUER'), resource: 'urn:agora:flags' }),
  // …
}

It is resolved before the first request and resolved again (its refresh()) when the control plane stops answering or answers 404. node ace agora:doctor --deep reports whether it resolves.

The app reads flags exactly as before (ctx.flags, the service). Changes arrive within milliseconds over the stream; polling is the fallback. snapshotPath keeps the last ruleset on disk, so an app that boots while the server is down still serves real targeting.

A tenant has no store, sinks or console: edit flags on the control-plane. It publishes its declarations at boot, so the console knows its flags.

Set up authkit

Declare the flags resource on authkit-server, next to the other products you run centrally:

config/authkit.ts (authkit server)
serviceTenants: {
  resources: {
    'urn:agora:flags': {},
    'urn:agora:durable': {},
  },
},

Then give each app one service-tenant client (console: Clients → New Client → Service tenant; or node ace authkit:clients:create) with:

  • partition: the app's name, the same as tenant.partition;
  • capabilities: flags:ruleset:read, flags:events:write, flags:declarations:write (add flags:ofrep:evaluate for OFREP callers), or flags:* for all of them, plus whatever the app's other products need;
  • environment (optional): the environment whose ruleset the app reads. Without it, the control-plane's.

The same client gets a token for each resource it names, so the app uses one client id and secret for flags, durable and config. A urn:agora:durable token is refused by the flags control-plane. Disabling the client cuts the app off; open streams close when the token expires.

Because authkit gives a person the same sub in every app, an experiment can span apps: the same user lands in the same variant everywhere.

Without authkit

A secret per app:

config/flags.ts (flags server)
import { sharedSecretVerifier } from '@adonis-agora/flags'

verifyTenant: sharedSecretVerifier({
  partitions: {
    streaming: env.get('FLAGS_SECRET_STREAMING'),
    billing: { secret: env.get('FLAGS_SECRET_BILLING'), environment: 'staging' },
  },
}),
config/flags.ts (an app)
tenant: { url, partition: 'streaming', token: env.get('FLAGS_SECRET_STREAMING') }

The tenant names its partition (from tenant.partition) and the secret proves it. A partition gets every capability unless you list capabilities.

Transports

By default a tenant and the control-plane talk over HTTP. tenant.transport picks another way for server-to-server traffic: the app's events, evaluation counts and declarations, and its ruleset. Configure the same driver on both sides.

Browsers never use it. remoteFlags, browser tokens and OFREP always talk to the control-plane over HTTP, so its HTTP routes stay mounted whatever you choose. One control-plane can serve tenants on Redis, tenants on HTTP and browsers at once.

DriverEvents (push)Ruleset (watch)Needs
tenantTransports.http({ url?, fetch?, timeoutMs? }) (default)POSTETag + server-sent eventsnothing
tenantTransports.queue({ queue?, connection? })✅ jobs— (HTTP)@adonisjs/queue
tenantTransports.bullmq({ connection, prefix? })✅ jobs— (HTTP)bullmq + ioredis
tenantTransports.redis({ connection?, prefix? })✅ stream✅ key + pub/sub@adonisjs/redis
tenantTransports.durable({ controlPlane? })✅ durable runs✅ run + durable's control plane@adonis-agora/durable

The packages are loaded only when you select their driver. tenantTransports is not the top-level transport option (transports.db(), transports.redis()), which is the control-plane's own event log.

Redis

config/flags.ts (flags server)
import { defineConfig, tenantTransports } from '@adonis-agora/flags'

export default defineConfig({
  topology: 'control-plane',
  flags: {},
  verifyTenant,
  controlPlane: {
    transports: [tenantTransports.redis({ connection: 'main' })],
  },
})
config/flags.ts (an app)
import { defineConfig, tenantTransports } from '@adonis-agora/flags'

export default defineConfig({
  topology: 'tenant',
  flags: {},
  tenant: {
    partition: 'shop',
    token,
    transport: tenantTransports.redis({ connection: 'main' }),
    snapshotPath: 'storage/flags/ruleset.json',
  },
})

Both sides need the same Redis and the same prefix (default agora:flags:tenants). The app does not need tenant.url unless it serves a frontend (see below).

Queue and BullMQ

These carry events only; the ruleset still comes over HTTP, so the app keeps tenant.url.

config/flags.ts (flags server)
controlPlane: {
  transports: [tenantTransports.queue()],
},
config/flags.ts (an app)
tenant: {
  url: env.get('FLAGS_URL'),
  partition: 'shop',
  token,
  transport: tenantTransports.queue(),
},

Run the queue worker for agora-flags-tenants on the flags server only: node ace queue:work --queue=agora-flags-tenants.

For BullMQ, use tenantTransports.bullmq({ connection: { host: 'redis', port: 6379 } }) on both sides. The flags server runs the worker itself.

Durable

The app and the flags server run on the same durable cluster. The flags server registers the workflow that applies tenant messages; ruleset changes go out on the controlPlane from config/durable.ts.

config/flags.ts (both sides)
// flags server
controlPlane: { transports: [tenantTransports.durable()] },

// an app
tenant: { partition: 'shop', token, transport: tenantTransports.durable() },

Every tenant message is a durable run, so you see them, with their retries and failures, in the durable console. Fetching the ruleset is slower than over HTTP or Redis, because each fetch is a run.

Mixing drivers

tenant.watch picks where the ruleset comes from when it differs from transport. It takes http, redis or durable:

config/flags.ts (an app)
tenant: {
  partition: 'shop',
  token,
  transport: tenantTransports.bullmq({ connection }),
  watch: tenantTransports.redis(),
},

Apps with a frontend

A tenant on any driver still issues browser tokens. It gets its signing key from the control-plane over HTTP and gives browsers the control-plane's HTTP address, so set tenant.url (or browser.publicUrl):

config/flags.ts (an app)
tenant: {
  url: env.get('FLAGS_URL'),
  partition: 'shop',
  token,
  transport: tenantTransports.redis(),
},
browser: {},

Security and delivery

Every message carries the app's token and an id. The control-plane runs verifyTenant on each message. The partition, environment and capabilities come from the verified token, never from the message or the queue it came from. A shared broker does not let one app write as another.

Delivery is at least once. The control-plane ignores an id it has already applied for that partition. A message it can never apply (an unreadable message, a refused token, a missing capability, one over controlPlane.maxMessageBytes, 1 MiB by default) is dead-lettered instead of retried. So is one that still fails after its retries. Dead letters go to controlPlane.onDeadLetter, which logs them by default:

config/flags.ts (flags server)
import logger from '@adonisjs/core/services/logger'

controlPlane: {
  transports: [tenantTransports.redis()],
  onDeadLetter: (letter) => logger.error(letter, 'flags tenant message dropped'),
},

Redis also keeps them in the <prefix>:dead stream, BullMQ in the queue's failed jobs, and durable as failed runs.

With snapshotPath, a tenant that boots while the control-plane is down still serves the last ruleset, on every driver. On Redis it reads the ruleset key first, which outlives the control-plane.

node ace agora:doctor --deep checks that the broker is reachable from each side.

End to end: authkit, a flags server, two apps

  1. auth.example.com runs authkit-server with serviceTenants.resources['urn:agora:flags'] and two service-tenant clients: shop and blog, each with the three flags capabilities.
  2. flags.example.com runs topology: 'control-plane' with verifyTenant: authkitTenantVerifier({ issuer: 'https://auth.example.com', resource: 'urn:agora:flags' }). It never calls authkit except to fetch its keys.
  3. shop.example.com and blog.example.com run topology: 'tenant', each with authkitTenantToken({ issuer, clientId, clientSecret, resource: 'urn:agora:flags' }) and its own partition.

Each app's events land on the flags server tagged with the partition from its token; the console lists both apps and their declarations.

Seeing one app

The ruleset is one for every app. What the apps send is kept per app: each event, exposure and evaluation count is stored with the partition and environment of the token that sent it, whatever the request says.

On the control-plane's console, the App picker in the header chooses whose numbers every screen shows: experiment results, exposures, unused flags and the connected apps. All apps puts them together. The picker shows up once two apps have called in; a standalone app has none.

The pick travels in the URL (?app=shop), so a link opens on the same app. The console API, the flags_* MCP tools and the experiment recompute take the same app.

Limit who sees which app

authorize can answer the apps a person may see:

config/flags_dashboard.ts (flags server)
import { defineConfig } from '@adonis-agora/flags/dashboard'

export default defineConfig({
  authorize: async (ctx) => {
    const user = ctx.auth.user
    if (!user) return { allowed: false, reason: 'unauthenticated' }
    if (user.isAdmin) return { allowed: true }
    return { allowed: true, apps: user.teamApps } // ['shop']
  },
})

apps: '*' (or no apps) is every app. With a list, the picker offers those apps only, All apps covers those apps only, and asking for any other app answers 403, in the console, its API and the MCP tools alike. Flags, segments and their history stay visible: the ruleset is shared.

Results for one app are computed on demand from the analytics backend and reused for a minute. Results for every app are the ones the worker keeps up to date.

Frontends

With browser: {} in config/flags.ts, frontends read flags with remoteFlags({ endpoint: '/_flags/token' }). Turn it on in each app that has a frontend and on the control-plane:

config/flags.ts (flags server)
topology: 'control-plane',
verifyTenant,
browser: { corsOrigins: ['https://app.example.com', 'https://shop.example.com'] },
config/flags.ts (an app)
topology: 'tenant',
tenant: { url, partition: 'shop', token },
browser: {},

The app signs its users' tokens; the browser then talks to the control-plane directly:

  1. The browser calls the app's GET /_flags/token with its session cookie.
  2. The app signs the session's user with its own key. It got that key from the control-plane (POST /v1/browser-key) over the tenant connection it already has, authenticated by its tenant token. No new secret to distribute.
  3. The browser calls the control-plane with the token. The control-plane derives the app's key again from the token's app and environment, so a token cannot be moved to another app or environment, and an app can only mint tokens for itself.

The control-plane derives every app key from browser.secret, which defaults to its APP_KEY. Rotating it invalidates outstanding tokens; frontends fetch new ones on their own. Set browser.publicUrl on a tenant when browsers reach the control-plane under another address than the app does (an internal hostname, for example).

With authkit

When your app is an authkit client (it signs users in against an authkit-server, with @adonis-agora/authkit-client), the token endpoint signs that session's identity: sub, email, global roles and active organization. The authkit-server, the control-plane and the app can be three different apps. The flags server never calls the authkit-server for browsers: the app vouches for its signed-in user, the same way it already does in ctx.flags.

Since authkit gives a person the same sub in every app, a user lands in the same variant in every frontend.

Apps with their own authkit token

A mobile app or SPA that signs in to authkit itself (PKCE) has no Adonis session to ask. Let the control-plane accept its access tokens too. It needs @adonis-agora/authkit-client:

config/flags.ts (flags server)
import { userVerifiers } from '@adonis-agora/flags'

browser: {
  verifyUser: userVerifiers.authkit({
    issuer: env.get('AUTHKIT_ISSUER'),
    audience: 'https://flags.example.com',
  }),
},

Declare https://flags.example.com in authkit-server's accessTokens.resources and have the app request it. The token is checked against the keys found by discovery; its sub is the subject, its email, global roles and active organization become targeting attributes, and its client_id becomes the app on events. Map client ids to environments with environments: { 'mobile-app': 'staging' }.

OFREP: browsers, mobile and other languages

Any OpenFeature SDK with an OFREP provider can evaluate against the control-plane — web, React Native, Go, Python. Evaluation happens on the server, so the rules never leave it. Give those clients a token with the flags:ofrep:evaluate capability, and list browser origins in controlPlane.corsOrigins.

OFREP callers send their own evaluation context. Do not base security decisions on flags whose targeting a client can influence.

On this page

Partner

Your product as the official integration for Flags, right here.

Become a partner →