DEV Community

Cover image for feature-flags: a small self-hosted feature-flag server with a Go SDK
Abdeldjalil Chougui
Abdeldjalil Chougui

Posted on Originally published at abdeldjalilchougui.biz

feature-flags: a small self-hosted feature-flag server with a Go SDK

Feature flags separate two things that are usually tied together: deploying code and turning it on. With a flag, the new checkout can be merged and deployed while it is still off, enabled for the team first, then for 10% of users, then for everyone, and switched off in seconds if something goes wrong.

The idea is simple, but a flag system that works needs more than an if and a config file. The same user must get the same answer on every request and on every server. A rollout that grows from 10% to 20% must keep the first 10%. Changes must reach running instances without a redeploy. And checking a flag must not add a network call to every request.

feature-flags is a small self-hosted server that does this, with a Go SDK. The README describes who it is for: teams that want trunk-based development and gradual rollouts without a SaaS bill. It is a single binary and a JSON file, which the README says is enough for dozens of flags and many app instances.

What it does

Flags with variants. A flag is not only on or off. Its variants can be booleans, strings, numbers or any JSON value.

Environments. Development, production and any others you create. Each environment has its own SDK key and its own configuration for every flag.

Targeting rules. Rules match on context attributes with these operators: eq, in, not_in, contains, starts_with, ends_with, matches, and gt/gte/lt/lte. A list attribute matches if any of its elements does.

Percentage rollouts with consistent hashing. A user keeps their variant, and widening 10% to 20% keeps the first 10%.

Live updates. A REST API for management, Server-Sent Events that push every change to SDKs, and an htmx admin UI embedded in the binary, with no build step.

A Go SDK that evaluates locally. The SDK keeps the configuration in a cache and evaluates flags in process. There is no network call per check, and it keeps working on the last known config if the server goes down.

How to use it

Install the flagd server with Go, and add the SDK to your module:

go install github.com/AbdeldjalilChougui/feature-flags/cmd/flagd@latest
go get github.com/AbdeldjalilChougui/feature-flags/sdk@latest
Enter fullscreen mode Exit fullscreen mode

Or build from a checkout and start the server:

go build -o flagd ./cmd/flagd
FLAGS_ADMIN_TOKEN=change-me ./flagd -addr :8080 -data flags.json
# prints one SDK key per environment
open http://localhost:8080/admin          # Basic auth: any user, the admin token as password
Enter fullscreen mode Exit fullscreen mode

Create a flag through the API. This one turns the new checkout on for the pro and team plans, and for 10% of everyone else:

curl -H "Authorization: Bearer change-me" localhost:8080/api/flags -d '{
  "key": "new-checkout",
  "variants": {"on": true, "off": false},
  "environments": {
    "production": {
      "enabled": true,
      "off_variant": "off",
      "rules": [
        {"clauses": [{"attribute": "plan", "op": "in", "values": ["pro", "team"]}], "serve": {"variant": "on"}}
      ],
      "default": {"rollout": [{"variant": "on", "weight": 1000}, {"variant": "off", "weight": 9000}]}
    }
  }
}'
Enter fullscreen mode Exit fullscreen mode

Weights are in basis points, so 1000 is 10%. Then use the flag from Go:

c := sdk.New("http://localhost:8080", os.Getenv("FLAGS_SDK_KEY"))
go c.Start(ctx)
c.WaitReady(ctx)
if c.Bool("new-checkout", flag.Context{"key": user.ID, "plan": user.Plan}, false) {
    // new code path
}
Enter fullscreen mode Exit fullscreen mode

The last argument of c.Bool is the fallback value. The context is a map of attributes: key identifies the user for rollouts, and the other attributes feed the targeting rules.

The API also has a kill switch at POST /api/flags/{key}/environments/{env}/toggle, an admin POST /api/evaluate that returns the result with its reason, and three SDK endpoints: GET /sdk/flags for the full config of the key's environment, GET /sdk/stream for SSE, and POST /sdk/evaluate for server-side evaluation by clients that are not written in Go. SDK keys go in Authorization: Bearer …, or in ?sdk_key= for the browser's EventSource, which cannot set headers.

How it works

Evaluation lives in the package flag and is shared by the server and the SDK, so both give the same answer. If the flag is disabled, the result is off_variant. Otherwise the rules are tried in order, and the first rule whose clauses all match serves its variant or rollout. Everyone else gets default. Each result carries a reason: OFF, RULE_MATCH with the rule index, DEFAULT or ERROR, and whether a rollout picked the variant.

One detail is worth knowing before you write rules. A clause on a missing attribute never matches, not even neq or not_in. A rule therefore cannot accidentally target users you know nothing about.

Rollouts use this formula: bucket = sha256(flagKey + "." + salt + "." + id) mod 10000. Variants take consecutive bucket ranges in the order listed, so increasing the first variant's weight only adds users. The salt is random per flag, which means different flags bucket users independently: being in the 10% of one flag says nothing about another. bucket_by can split by another attribute, such as org, so a whole organisation gets the same variant.

The server holds its state (version, environments, flags) in memory and writes it to one JSON file atomically on every change. The version counter increases on every change. SSE subscribers get a coalescing signal and re-send the full payload, so a slow client cannot make the server queue stale diffs.

The SDK holds one SSE connection with a watchdog. If nothing arrives for 60 seconds, not even a ping, it reconnects. When streaming fails, which happens behind proxies that buffer or block SSE, it polls /sdk/flags between reconnect attempts with exponential backoff, so updates still arrive. Payloads with an older version are ignored.

The admin UI is server-rendered html/template plus htmx 1.9.12, embedded in the binary. Toggles swap a single table row. The config editor is a JSON textarea with server-side validation, and a "try it" box evaluates any context. Writes require htmx's HX-Request header. A cross-site form cannot send custom headers, so this blocks CSRF even though Basic-auth credentials are sent automatically.

Things to know

  • Storage is a single JSON file. The README says that is fine for one server instance and hundreds of flags. It does not support multiple replicas, which would need shared storage and fan-out of changes.
  • No audit log, no accounts, no schedules. There are no per-user accounts or roles, and no scheduled changes.
  • No segments. There are no reusable user lists, and no semver or date operators.
  • The SDK fetches the whole environment. That is fine for server-side use. Do not ship an environment's full rules to browsers if they contain sensitive targeting data.
  • Only a Go SDK. Other languages can call /sdk/evaluate, or reimplement the evaluation rules described above.
  • What was tested. go test -race ./... covers three packages. For flag: off and default, every operator, number types (Go int versus JSON float64), list attributes, missing attributes, a 20% rollout over 20k users within ±1.5%, stickiness when widening to 50%, independence across flags, bucket_by, validation messages and a JSON round trip. For server: CRUD and validation, toggle, evaluate, reload from disk, admin and SDK auth, the SSE stream, and the htmx endpoints including the CSRF guard. For sdk, against a real server in-process: readiness, local evaluation, an update pushed after a toggle, the cache surviving server shutdown, falling back to polling behind a proxy that rejects SSE, and a bad SDK key.

Why I built it

The README states the need in one line: trunk-based development and gradual rollouts without a SaaS bill. A team that merges small changes to the main branch every day needs a way to keep unfinished work switched off in production, and a way to release it to a few users first. Hosted flag services do this well, but they are one more subscription and one more external dependency in the request path.

For a team with dozens of flags, the core is small enough to own. What I wanted to get right were the parts that are easy to get subtly wrong: bucketing that stays sticky when a rollout widens, flags that bucket independently, a rule engine that does not match users with missing data, and an SDK that keeps answering from its cache when the flag server is down. A flag check that can fail or block defeats the point, so the server being unavailable has to be a non-event for the application.

Sharing one evaluation package between the server and the SDK follows from that. The "try it" box in the admin UI and the code running in the application cannot disagree, because they run the same function.

Get the code

The server, the SDK, the admin UI and the tests are on GitHub: https://github.com/AbdeldjalilChougui/feature-flags. It is MIT licensed. The embedded htmx is © Big Sky Software, under the 0BSD license. Issues and pull requests are welcome.


Originally published at abdeldjalilchougui.biz.

Top comments (0)