No. 30Architecture9 min read2,319 words
Feature flags without a platform: a simple Postgres setup
How to build feature flags without a paid platform: a Postgres table, a cached typed helper, stable percentage rollouts, kill switches, and when to buy instead.
- Written by
- Lazy Devs
- Published
- Updated
- Sources
- Cited inline

Key takeaways ยท 05
The short version
- 01A feature flag is a function that takes a flag name and some context and returns true or false. A small team can build that function with one Postgres table and about fifty lines of TypeScript.
- 02Cache flag reads in memory with a short, deliberate TTL (30 to 60 seconds). That TTL is how long a flipped kill switch takes to reach every server, so everyone should know it.
- 03Use a deterministic hash of flag key plus user ID for percentage rollouts, so a user who sees a feature at 10 percent keeps seeing it at 40 percent.
- 04Decide each flag's safe default for when the flag store is unreachable, and keep serving the last known values instead of silently switching everything off.
- 05Buy a flag platform when you need audit trails, rich targeting, experiments with statistics, approvals, or one source of truth across many services and languages.
On this page ยท 10
You can run feature flags without a paid platform by storing flags in a database table you already have, reading them through a small cached helper, and using a deterministic hash for percentage rollouts. For a team with a handful of engineers and a handful of flags, that covers releases, gradual rollouts and kill switches for almost nothing. Buy a platform when you need audit trails, rich targeting, experiments or approvals, not before.
Every so often a team asks us to wire up a feature flag platform, and often we suggest waiting. Not because the platforms are bad, but because they answer questions the team has not asked yet. This post is the version we wish someone had handed us years ago: how to build feature flags yourself, the parts people get wrong, and the exact signals that mean it is time to pay for a real platform.
What a feature flag actually is
Strip away the marketing and a feature flag is a function. Given a flag name and some context (a user, a request, an environment), it returns true or false. Everything else (dashboards, audit logs, targeting rules, experiment statistics) is convenience built on top of that function.
Martin Fowler's article on feature toggles splits flags into categories that are worth knowing, because each has a different lifespan:
| Flag type | Purpose | Typical lifespan | Example |
|---|---|---|---|
| Release | Ship unfinished or risky code dark, then turn it on | Days to weeks | New checkout flow |
| Ops / kill switch | Turn off an expensive or fragile feature under load | Long-lived | Disable recommendations during a spike |
| Experiment | Show variants to compare outcomes | Weeks | Two pricing page layouts |
| Permission | Give specific users or plans access | Long-lived | Beta features for selected accounts |
A home-grown setup handles release flags and kill switches very well, and simple permission flags reasonably well. Experiments are where it runs out of road, because the hard part there is the statistics, not the switch.
The trap is reaching for the convenience before you need it. A SaaS flag platform usually bills by seats or usage, adds an SDK and a network dependency, and becomes one more thing that can page you. For a small team shipping a few features a quarter, that is a lot of ceremony for a yes-or-no question.
The simplest thing that works: one Postgres table
Put your flags in the database you already run. One table, one row per flag:
create table feature_flags (
key text primary key,
enabled boolean not null default false,
description text not null,
owner text not null,
-- 0 to 100, only consulted when enabled is true
rollout_pct smallint not null default 100
check (rollout_pct between 0 and 100),
expires_on date,
updated_at timestamptz not null default now()
);The owner and expires_on columns are not decoration. They are what turns your flag table into a to-do list instead of a graveyard, which we come back to below.
A typed, cached helper in TypeScript
Now a helper to read it. The important details are caching (you do not want a database query on every check, and you do not want a flag change to need a deploy) and failure behaviour (a database blip must not silently flip every flag).
// lib/flags.ts
import "server-only";
import { db } from "@/lib/db";
// One union type means a typo in a flag name is a compile error.
export type FlagKey = "new-checkout" | "ai-summaries" | "recommendations";
type FlagRow = { enabled: boolean; rollout_pct: number };
const CACHE_TTL_MS = 30_000;
let cache: { rows: Map<string, FlagRow>; expires: number } | null = null;
async function loadFlags(): Promise<Map<string, FlagRow> | null> {
if (cache && cache.expires > Date.now()) return cache.rows;
try {
const result = await db.query<{ key: string } & FlagRow>(
"select key, enabled, rollout_pct from feature_flags",
);
const rows = new Map(result.rows.map((r) => [r.key, r]));
cache = { rows, expires: Date.now() + CACHE_TTL_MS };
return rows;
} catch (err) {
console.error("flag load failed, using last known values", err);
if (!cache) return null; // never loaded: callers fall back to defaults
cache.expires = Date.now() + 5_000; // keep last known values, retry soon
return cache.rows;
}
}
// FNV-1a hash: the same user always lands in the same bucket for a flag.
function bucket(key: string, id: string): number {
let h = 2166136261;
for (const ch of `${key}:${id}`) {
h ^= ch.charCodeAt(0);
h = Math.imul(h, 16777619);
}
return (h >>> 0) % 100;
}
export async function isEnabled(
key: FlagKey,
ctx: { userId?: string } = {},
fallback = false,
): Promise<boolean> {
const flags = await loadFlags();
const flag = flags?.get(key);
if (!flag) return fallback;
if (!flag.enabled) return false;
if (flag.rollout_pct >= 100) return true;
if (!ctx.userId) return false; // no identity, no partial rollout
return bucket(key, ctx.userId) < flag.rollout_pct;
}That is the whole engine. Three details do most of the work.
The hash makes rollouts stable. Because bucket is deterministic, a user who sees the feature at 10 percent still sees it at 40 percent. Including the flag key in the hash means the same users are not always first in line for every feature. Without this, users flicker in and out of a feature between requests, which is the bug that makes home-grown flags feel unreliable.
The union type catches typos. isEnabled("new-chekout") fails to compile instead of silently returning false in production.
server-only keeps it on the server. Importing this module from a client component becomes a build error, so flag rules and unreleased feature names never ship in the browser bundle.
Using it in a React Server Component reads exactly how you would hope:
// app/checkout/page.tsx
import { isEnabled } from "@/lib/flags";
import { getSession } from "@/lib/auth";
export default async function CheckoutPage() {
const session = await getSession();
const newCheckout = await isEnabled("new-checkout", { userId: session.userId });
return newCheckout ? <NewCheckout /> : <LegacyCheckout />;
}Because the decision happens on the server, there is no flash of the old UI and no client-side flag SDK. If a client component needs to know, pass it the resulting boolean as a prop.
The parts people get wrong
The naive version works in a demo and bites you in production. Three things separate a toy from something you can trust.
The cache TTL is your kill-switch delay
A per-request database read for every flag adds latency and load you do not need. An unbounded cache is worse: flipping a flag off during an incident does nothing for an unknown amount of time. Pick a deliberate TTL (30 to 60 seconds is sensible) and make sure everyone knows that is how long a change takes to reach every server.
On serverless platforms, the in-memory cache only lives as long as a warm instance, so each new instance pays one query. That is usually fine. If it is not, move flags to a shared store designed for fast reads, such as Redis or Vercel Global Config (formerly Edge Config), and keep the same TTL idea.
Decide what happens when the flag store is down
When the database read fails, what should isEnabled return? If the answer is "false for everything", an outage silently turns off every gated feature, including ones that have been fully live for months. That is often worse than the original problem.
The helper above avoids that in two ways. It keeps serving the last values it successfully loaded, and when it has never loaded, each call site chooses its own fallback. A kill switch for an expensive feature might fall back to off. A flag guarding a feature that is already live for everyone should fall back to on, or better, be removed.
Flags are debt, so give them an expiry
The real cost of flags is not the code, it is the flags you never delete. Every release flag is a live if branch, a second code path to test and a small tax on every future change to that file. That is classic technical debt: fine when taken on deliberately, expensive when forgotten.
Write the cleanup ticket the same day you add the flag, and set expires_on. A release flag that has been at 100 percent for a few weeks should be ripped out. A quick query turns the table into a to-do list:
select key, owner, rollout_pct, expires_on
from feature_flags
where expires_on < current_date
or (enabled and rollout_pct = 100 and updated_at < now() - interval '30 days')
order by expires_on nulls last;A safe rollout, step by step
Here is how we roll out a risky feature with this setup:
- Merge the code dark. The flag exists with
enabled = false. Production runs the old path, and the new code is deployed but unreachable. Our guide to CI/CD that small teams maintain explains why decoupling deploy from release makes every deploy less scary. - Turn it on for the team. Use a permission check or a test account so you see the feature in production first.
- Roll out to a small percentage. Start at 5 or 10 percent and watch error rates and latency for the flagged path. Tag logs and traces with the flag state so you can compare the two paths, as described in our observability basics.
- Ramp up in steps. 25, 50, 100 percent, pausing at each step long enough to see real traffic.
- Clean up. Once it has been stable at 100 percent, delete the flag and the old code path in one pull request.
If something goes wrong at any step, set enabled = false and wait one TTL. No deploy, no revert.
Giving non-engineers a switch
A table works until a product manager needs to flip a flag at 9 p.m. and you are the only one with a database client. You do not need a full UI. A small admin route guarded by your existing auth, the kind of plumbing that falls squarely under API and backend engineering, covers it, and it can write a basic audit trail at the same time:
// app/api/admin/flags/route.ts
import { db } from "@/lib/db";
import { requireAdmin } from "@/lib/auth";
export async function POST(req: Request) {
const admin = await requireAdmin(req); // your existing auth
const { key, enabled, rolloutPct = 100 } = await req.json();
if (typeof key !== "string" || typeof enabled !== "boolean" ||
!Number.isInteger(rolloutPct) || rolloutPct < 0 || rolloutPct > 100) {
return Response.json({ error: "invalid_input" }, { status: 400 });
}
// Only update existing flags; new flags are created in code review.
const result = await db.query(
`update feature_flags
set enabled = $2, rollout_pct = $3, updated_at = now()
where key = $1`,
[key, enabled, rolloutPct],
);
if (result.rowCount === 0) {
return Response.json({ error: "unknown_flag" }, { status: 404 });
}
await db.query(
`insert into feature_flag_changes (key, enabled, rollout_pct, changed_by)
values ($1, $2, $3, $4)`,
[key, enabled, rolloutPct, admin.email],
);
return Response.json({ ok: true });
}Two deliberate choices here. The route only updates flags that already exist, so new flags are created through a migration that goes through code review, with an owner and an expiry. And every change is written to a feature_flag_changes table, which gives you a basic "who flipped what, when" history for incident reviews:
create table feature_flag_changes (
id bigserial primary key,
key text not null references feature_flags(key),
enabled boolean not null,
rollout_pct smallint not null,
changed_by text not null,
changed_at timestamptz not null default now()
);Postgres also supports INSERT ... ON CONFLICT if you prefer an upsert, but for flags we like the stricter version.
Put a small form in your admin area against that route, and product can toggle flags without touching code or pinging an engineer. That single endpoint removes most of the day-to-day reasons teams give for buying a platform.
Testing code behind flags
Every flag doubles the paths through a piece of code, so test both. Keep it cheap: make the flag helper easy to stub in tests, write tests for the on and off paths of each active flag, and delete the off-path tests when you delete the flag. Do not try to test every combination of every flag. If two flags interact in complicated ways, that is a sign one of them should be removed.
When to buy a feature flag platform instead
This approach has a ceiling, and pretending otherwise is how teams get burned. Pay for a real platform when you hit any of these:
| Signal | Why home-grown struggles |
|---|---|
| You need a full audit trail with approvals for compliance | A changes table helps, but approvals, reviews and retention policies are real product work |
| You want targeting rules non-engineers can edit safely (plan, region, account, AND/OR logic) | Rule editors with validation are a product in themselves |
| You run experiments and need statistical results | The switch is easy; trustworthy experiment analysis is not |
| You have many services in different languages | Reimplementing and keeping isEnabled consistent five times is error-prone |
| Flag changes need scheduling and instant, guaranteed propagation | A polling cache gives you "within a TTL", not "now, everywhere" |
When you get there, consider coding against OpenFeature, a vendor-neutral standard API for flag evaluation. Your call sites stay the same and the provider underneath can be your Postgres table today and a commercial platform later. If you are on Next.js and Vercel, the Flags SDK is another option that keeps evaluation on the server.
Start with the function, grow when it hurts
Feature flags are a function that returns a boolean. A Postgres table, a cached and typed helper, a stable hash for rollouts and a small admin route give you that function for almost nothing, and they go further than most teams expect. Set a deliberate cache TTL, decide how each flag fails, and treat every release flag as debt with an expiry date. When you genuinely need audit logs, targeting or experiments, buy the platform with a clear conscience.
Flags are also one of the cheapest ways to make launches safer, alongside the steps in our guide to scaling a web app when traffic spikes. If you want help setting up safer releases, or deciding whether your team has outgrown a home-grown setup, talk to us.
FAQ ยท 05 questions
Frequently asked questions
What is a feature flag?
A feature flag, also called a feature toggle, is a switch in your code that turns a behaviour on or off at runtime without a new deploy. Teams use flags to release features gradually, test with a subset of users, hide unfinished work in production, and switch off a misbehaving feature instantly.
Do I need LaunchDarkly or another platform for feature flags?
Not when you are starting out. A small team with a handful of flags can store them in its existing database and evaluate them with a small helper. Paid platforms earn their cost when you need audit logs, targeting rules non-engineers can edit safely, experimentation statistics, approvals, or consistent SDKs across many services.
How do percentage rollouts work?
Each user is assigned a stable bucket from 0 to 99 by hashing their user ID together with the flag name. If the rollout is set to 20 percent, users in buckets 0 to 19 see the feature. Because the hash is deterministic, users keep their bucket on every request, and raising the percentage only adds new users.
Are feature flags technical debt?
Release flags are temporary debt by design, because each one keeps two code paths alive. Remove a release flag once its feature has been fully rolled out and stable for a short period. Operational kill switches and permission flags can be long-lived, but they should be documented as such.
Should feature flags be evaluated on the server or the client?
Evaluate them on the server where you can. Server-side evaluation keeps flag rules and unreleased feature names out of the browser bundle, avoids a flash of the wrong UI, and works naturally with React Server Components. Pass only the resulting boolean to client components that need it.