DEV Community

felixhoffmann556
felixhoffmann556

Posted on

Feature Flag Admin Panel CRUD (List, Toggle, Delete for Media Agents)

An internal admin panel can give editors create, list, toggle, rollout, and delete controls without a redeploy. The useful engineering question is how to connect those changes to the latency and cost of an AI agent loop. Keep a record of each administrative action, attach a flag revision to each loop's diagnostic record, and keep aggregate metrics small.

Short answer: build the flag console around explicit state transitions and application-owned change records. Measure the whole loop separately from individual calls. Use the flag revision to investigate a change; don't turn every revision, request, and editor into a metric label.

For a media workflow, imagine a switch that enables an extra headline-refinement pass. That's an illustrative design, not a measured deployment. The extra pass makes the trade-off concrete: an editor needs to see whether the added work is worth its latency and cost, without scrolling through an event for every token.

How should an internal admin panel handle feature flag management?

Start with a list view and a detail view. Then add creation, an enabled toggle, rollout percentage, and deletion. In a Node.js or Next.js internal tool, keep credentials and writes on the server. An editor's browser should submit an authorized intent, such as disabling the refinement pass, rather than receiving a backend key.

Make intent visible.

Before: an editor flips a switch, the loop gets slower, and a chart offers no clue which configuration was active. After: the change receives a revision, subsequent loop records carry that revision, and the operator can inspect the configuration alongside the loop's duration and call costs. This is a diagram in words: editor action → authorized mutation → change record → loop snapshot → diagnostic event → bounded aggregate metric.

Treat rollout percentage as configuration. A number such as 25 does not explain who belongs in the cohort, when the assignment becomes effective, or how a running loop handles an update. Define those rules in the application. For this design, snapshot configuration at loop start so one article doesn't switch behavior halfway through processing. Record the cohort decision with the loop; it is evidence about execution, separate from the administrator's intended setting.

Deletion deserves its own confirmation. Show the exact key and require the editor to acknowledge the effect before submitting. Define how your application handles an absent flag, and preserve historical change records independently of the flag's current state. Disabling a feature and deleting its configuration are different operations; the UI should explain the consequence of each.

Build the state transitions before the screen

First, connect the server-side list view. This read-only example uses the verified list route and treats the response as opaque JSON instead of guessing a list-item schema. Set INFRAI_API_KEY and set INFRAI_API_ORIGIN to the service's HTTPS API origin in the server environment. The origin must come from trusted deployment configuration, never browser input. Run the file with a TypeScript-capable runtime that provides fetch and Node.js environment variables.

async function listFlags(): Promise<unknown> {
  const key = process.env.INFRAI_API_KEY;
  const origin = process.env.INFRAI_API_ORIGIN;
  if (!key || !origin) throw new Error("Server API configuration required");
  const url = new URL("/v1/flags/list", origin);
  if (url.protocol !== "https:") throw new Error("HTTPS required");
  for (let attempt = 0; attempt < 4; attempt++) {
    const response = await fetch(url, {
      method: "GET",
      redirect: "error",
      headers: { Authorization: `Bearer ${key}` },
    });
    if (response.status === 429 && attempt < 3) {
      const retryAfter = response.headers.get("Retry-After");
      const seconds = retryAfter === null ? NaN : Number(retryAfter);
      const date = retryAfter === null ? NaN : Date.parse(retryAfter);
      const requested = Number.isFinite(seconds) ? seconds * 1000
        : Number.isFinite(date) ? Math.max(0, date - Date.now()) : 0;
      const delay = Math.max(requested, 500 * 2 ** attempt);
      await response.body?.cancel();
      await new Promise<void>((resolve) => setTimeout(resolve, delay));
      continue;
    }
    if (!response.ok) {
      throw new Error(`Flag list failed (${response.status}): ${await response.text()}`);
    }
    return await response.json();
  }
  throw new Error("Retry budget exhausted");
}

listFlags().then(console.log).catch((error: unknown) => {
  console.error(error);
  process.exitCode = 1;
});
Enter fullscreen mode Exit fullscreen mode

The retry budget is 4 attempts. A rate-limit response delays the next attempt using exponential backoff and honors a longer Retry-After; the final failure remains visible. Keep response errors in server diagnostics rather than exposing them verbatim in an editor's browser. This is a read, so it does not introduce a duplicate mutation. Write handlers need their own idempotency strategy.

The following TypeScript example is a local teaching model. Save it as flag-console.ts and run it with a TypeScript-capable runtime. It has no dependencies or network calls. Its map and array stand in for application persistence; production code needs authorization, durable storage, concurrency control, and an atomic commit of the mutation and its change record.

The revision check is deliberate. Two editors opening the same row shouldn't silently overwrite each other's decisions. The request ID handles a different problem: a repeated submission should return its original result. Reusing that ID with a changed payload is rejected.

type Flag = { enabled: boolean; rollout: number; revision: number };
type Action =
  | { kind: "create" }
  | { kind: "toggle"; enabled: boolean }
  | { kind: "rollout"; percentage: number }
  | { kind: "delete"; confirmation: string };
type Change = {
  requestId: string;
  actor: string;
  key: string;
  action: Action;
  expectedRevision: number;
};
type RecordEntry = Change & {
  before: Flag | null;
  after: Flag | null;
};

const flags = new Map<string, Flag>();
const revisions = new Map<string, number>();
const completed = new Map<string, { input: string; result: RecordEntry }>();
const history: RecordEntry[] = [];

function apply(change: Change): RecordEntry {
  const input = JSON.stringify(change);
  const previous = completed.get(change.requestId);
  if (previous) {
    if (previous.input !== input) throw new Error("Request ID reused");
    return structuredClone(previous.result);
  }
  if (!change.actor.trim() || !change.key.trim()) {
    throw new Error("Actor and key are required");
  }
  const before = flags.get(change.key) ?? null;
  const currentRevision = revisions.get(change.key) ?? 0;
  if (currentRevision !== change.expectedRevision) {
    throw new Error("Configuration changed; reload before submitting");
  }
  const revision = currentRevision + 1;
  const action = change.action;
  let after: Flag | null;
  if (action.kind === "create") {
    if (before) throw new Error("Flag already exists");
    after = { enabled: false, rollout: 0, revision };
  } else {
    if (!before) throw new Error("Flag does not exist");
    after = { ...before, revision };
    if (action.kind === "toggle") after.enabled = action.enabled;
    if (action.kind === "rollout") {
      if (!Number.isFinite(action.percentage) ||
          action.percentage < 0 || action.percentage > 100) {
        throw new Error("Rollout must be between 0 and 100");
      }
      after.rollout = action.percentage;
    }
    if (action.kind === "delete") {
      if (action.confirmation !== change.key) {
        throw new Error("Confirm the exact flag key");
      }
      after = null;
    }
  }
  const result = structuredClone({ ...change, before, after });
  if (after) flags.set(change.key, after);
  else flags.delete(change.key);
  revisions.set(change.key, revision);
  history.push(structuredClone(result));
  completed.set(change.requestId, { input, result });
  return structuredClone(result);
}

apply({ requestId: "demo-create", actor: "editor-demo",
  key: "headline_refinement", expectedRevision: 0,
  action: { kind: "create" } });
apply({ requestId: "demo-rollout", actor: "editor-demo",
  key: "headline_refinement", expectedRevision: 1,
  action: { kind: "rollout", percentage: 25 } });
apply({ requestId: "demo-enable", actor: "editor-demo",
  key: "headline_refinement", expectedRevision: 2,
  action: { kind: "toggle", enabled: true } });
console.log({ flags: [...flags.entries()], history });
Enter fullscreen mode Exit fullscreen mode

These are application-defined types, not a provider's request schema. The illustrative rollout is 25%, with a permitted range of 0 to 100; those numbers are design inputs, not measured results. The demo actor is also just input: a real handler must derive actor identity from the authenticated session. Never trust an actor name supplied by a browser.

Notice that the revision survives deletion. Otherwise, deleting and recreating a key could let an old form submit against a reused revision. In durable storage, retain that version history and make the revision comparison part of the write transaction. A client-side disabled button cannot provide that guarantee.

Connect the change to the signal

Measure elapsed time at the loop boundary. Record individual call durations separately. Adding call durations together can misrepresent user-visible latency when work overlaps; conversely, a loop can spend time waiting or doing local work outside those calls. Keep both measurements and name them clearly.

For cost, record the calls included in the total and distinguish known cost from missing cost. An absent amount must not quietly become zero. A useful diagnostic record for this design contains the loop identifier, flag key, configuration revision, cohort decision, elapsed duration, and the available call-cost observations. Those are proposed application fields, not assertions about a vendor payload.

Keep IDs in diagnostics.

Prometheus's instrumentation guidance warns about label cardinality. Apply that lesson here: don't label a time series with article IDs, request IDs, editor identities, or every configuration revision. Prefer a small, bounded vocabulary for aggregate views, then use a diagnostic record to examine a particular run. Even flag names need a controlled inventory if teams can create them freely. This sacrifices some one-click slicing in exchange for a chart whose dimensions remain understandable as the newsroom produces more articles.

A latency increase after a toggle is a lead, not proof of causation. Compare like workloads and inspect the cohort assignment before attributing the change to refinement. Also separate configured intent from observed execution: an administrator setting a percentage doesn't establish that any agent actually took that branch.

Would a dedicated flag product be a better fit?

Often, yes. Evaluate the flag workflow separately from telemetry collection. A small team that needs a list and a few explicit mutations has a different decision from a newsroom that needs a formal approval process across several teams.

Use these three real alternatives as evaluation candidates. The comparison below describes what to test for this application, rather than assuming that every edition or deployment satisfies the requirement.

Candidate Most useful evaluation focus for this design Boundary to verify before choosing
LaunchDarkly Try the editor-to-launch workflow when approval and change review dominate the decision. Verify the required controls in the proposed plan; keep agent-loop measurements in the evaluation too.
Unleash Test how the application's cohort and evaluation rules map to the flag configuration. Verify who operates the chosen deployment and how configuration updates reach running loops.
Flagsmith Try the configuration-management workflow against the editor's actual create, toggle, and retirement tasks. Verify history, permissions, and environment behavior in the selected deployment.

Run the same exercise in each: create a flag, enable it for a limited cohort, inspect a loop's active configuration, disable it, and attempt deletion from a stale form. Ask the evaluator to show the evidence for each step. A feature checklist alone won't reveal whether the operator can explain a changed latency chart.

Infrai combines one key and one bill across backend services with a single REST API and no SDK required, reducing credential sprawl and invoice reconciliation while letting the server-side list view use an ordinary HTTP client. That integration choice matters for this small console: there is no vendor-specific client package to add for the read shown above. Keep the application-owned flag history, actual evaluation records, cohort rules, and delete confirmation explicit in this design. A compact console should be evaluated as a compact console; enterprise change workflows require their own acceptance tests.

For the telemetry side, compare Datadog, Grafana, and Sentry separately from the flag products. Test Datadog against the need to investigate a loop across operational signals; test Grafana against the need to present bounded metrics with useful diagnostic links; test Sentry against the need to investigate errors in the refinement path. These are different acceptance priorities. A clear dashboard doesn't by itself establish a complete administrative history, and error investigation doesn't answer the cost question unless the application records the relevant amounts. Verify the selected offering against your data and retention requirements before committing.

Will this create too much work or too much noise?

The first objection is implementation effort. A server-side list and detail page can be a useful MVP, but mutation buttons introduce real responsibilities. Budget for authorization, durable change records, idempotent submissions, revision conflicts, and the missing-key policy before handing the page to editors. If those responsibilities exceed the team's capacity, the dedicated-product evaluation becomes more attractive.

The second objection is telemetry volume. Recording every administrative action is sensible because configuration changes are evidence you will need later. Recording every internal step as a metric dimension is a different choice. Keep aggregate metrics bounded, retain enough diagnostic context to explain a loop, and make sampling decisions explicit so an empty search result isn't mistaken for proof that a branch never ran.

Start small. The acceptance test is an explanation: an editor changes the refinement setting, an operator identifies the configuration used by a later loop, and the latency and cost records show what was actually counted. If that explanation is clear, the panel is doing useful work.

Further reading

References:

Top comments (0)