- Subject
- Software
- Date
- Read
- 10 min
Feature flags on AWS: switch it off without a deploy
Keeping flags out of business logic, why AWS AppConfig is a good home for flags and configuration, validating and rolling out changes safely, reading flags from Lambda and ECS, and cleaning flags up.
Contents
A feature flag is a switch in your code that you can flip without shipping new code. Turn a new feature on for a few users, turn a broken one off, or stop calling a system you know is down. The whole point is speed: when something goes wrong, the fix is a toggle, not a deploy.
That rules out a lot of what people call flags. A constant in the code, or an environment variable, is a static flag: changing it means a deploy or at least a restart, which is the slow path the flag was supposed to avoid. Static values are fine for things that rarely change. For anything you might need to switch quickly, the value has to live outside the code and be read while it runs.
On AWS, I use AWS AppConfig for that. This post covers how I structure flags, how AppConfig validates and rolls them out, how to read them from Lambda and ECS, and how to clean them up.
Keep flags out of the business logic
This is the part that matters most, and it doesn’t depend on any tool.
A flag check buried deep in your logic is hard to find, hard to test and hard to remove. Worse,
it spreads: one if (flags.newPricing) in the pricing code becomes three more in the code that
calls it, and soon you can’t read the logic without knowing the state of every flag.
Instead, read the flags once, at the edge (the handler or the request entry point), and use them to choose what runs. The business logic never knows a flag exists:
// The handler reads the flag and picks an implementation.
export const handler = async (event: OrderEvent) => {
const flags = await getFlags();
const priceOrder = flags.newPricing ? priceOrderV2 : priceOrderV1;
return priceOrder(event.order);
};
// Pure business logic. No flags, easy to test, and V1 is deleted cleanly later.
function priceOrderV1(order: Order): Price { /* ... */ }
function priceOrderV2(order: Order): Price { /* ... */ }
Each version can be tested on its own. Switching is one line. And when the flag is retired, you delete the old function and the one-line choice, and nothing else changes.
The same goes for configuration values. Pass the timeout or the limit into the code that needs it, instead of having that code look it up.
Flags and configuration, in one place
AppConfig handles two kinds of data, and both are worth moving out of your code:
- Feature flags: on or off, optionally with attributes (a percentage, a list of allowed customers). AppConfig has a feature flag profile type built for these.
- Configuration: values you want to change without a deploy, like timeouts, limits, retry counts or which model to call. These go in a freeform profile, usually JSON.
It’s organized in three levels:
- An application, which AWS describes as a namespace: a folder for one unit of code, like a service.
- Environments under it, like
preprodandprod. - Configuration profiles: the flags and config themselves.
That middle level is what ties a value to an environment. You don’t deploy a flag in general; you
deploy a version of it to an environment. So the same flags profile can have the new
feature on in preprod and off in prod, and promoting it is just deploying the same change to
the next environment.
Region matters just as much. AppConfig is regional: each region has its own copy of the
application, environments and profiles, and the agent reads from the region it runs in. If you’re
deployed to more than one region, that’s a feature, not a chore. When something breaks only in
us-east-1, you can turn the flag off in prod in us-east-1 and leave every other region alone.
So the repo holds a file per environment and region, plus one mapping that says where each environment lives:
orders-service/
preprod/us-east-1/flags.json
prod/us-east-1/flags.json
prod/us-west-2/flags.json
targets.json
{
"preprod": { "account": "<preprod account ID>", "regions": ["us-east-1"] },
"prod": { "account": "<prod account ID>", "regions": ["us-east-1", "us-west-2"] }
}
The pipeline reads the mapping and deploys each file to the right account, environment and region. Adding a region means adding a folder and one entry, not changing any code.
The code doesn’t decide any of this. The infrastructure sets the environment once, as an
environment variable on the function or container, and the agent already knows its region.
Nothing in the code should ever say prod or us-east-1.
My suggestion is one package for the whole team or product, with each service as its own AppConfig application. Every service gets its own flags and config, separated by namespace, but they’re all managed, reviewed and deployed in one place.
Store them in a repo, and validate twice
Flags and config should live in their own code repository, separate from the services. A flag change then gets what a code change gets: a pull request, a review, a history of who changed what and when. But it doesn’t need a service deploy, so it can still move fast.
Then validate, in two places:
- In the repo’s pipeline. Check that every file parses, every value has the right type, and every required flag exists, before anything is deployed.
- In AppConfig, built in. AppConfig checks feature flag profiles against its own schema automatically. For freeform config, you attach a JSON Schema validator, or a Lambda validator for rules a schema can’t express (like “this limit must be below that one”). AppConfig runs them when a deployment starts, and a failed check stops the deployment.
A typo in a config file shouldn’t be able to reach production. Two checks make that much harder.
Roll out like code: fast in pre-prod, gradual in prod
AppConfig deploys a configuration using a deployment strategy, and there’s no reason to use the same one everywhere:
- Pre-prod: all at once.
AppConfig.AllAtOncedeploys immediately. You want fast feedback, and nobody’s harmed if it’s wrong. - Prod: gradually, with an alarm.
AppConfig.Linear20PercentEvery6Minutesreaches 20% of targets every six minutes over 30 minutes, then watches for 30 more (the bake time).AppConfig.Canary10Percent20Minutesis a faster option. Both are AWS-recommended for production.
The alarm is what makes gradual safe. Link the environment to a CloudWatch alarm (error rate, latency, failed orders), and if it fires during the rollout or the bake time, AppConfig rolls the change back on its own. A bad flag reaches a fraction of traffic for a few minutes instead of everyone until someone notices.
One exception: when you’re turning something off in an emergency, like a kill switch during
an outage, waiting 30 minutes defeats the purpose. Go straight to the AWS console, change the
flag, and deploy it to prod immediately with AppConfig.AllAtOnce, in just the region that’s
having the problem if that’s all it is. No pull request, no pipeline, no waiting. The point of the switch is to be fast.
Afterward, make the same change in the repo. Otherwise the next normal deployment from the repo quietly turns the broken feature back on.
Reading flags: Lambda vs ECS
Calling the AppConfig API on every request would be slow and would cost money on every call.
The AppConfig Agent solves that in both places: it fetches the configuration, caches it
locally, and checks for updates in the background. Your code reads from it over
localhost:2772.
In Lambda, the agent runs as a Lambda extension, added as a layer. It checks for updates
every 45 seconds by default (AWS_APPCONFIG_EXTENSION_POLL_INTERVAL_SECONDS), and only while the
function is being invoked. Each Lambda instance keeps its own cache. Set
AWS_APPCONFIG_EXTENSION_PREFETCH_LIST to load your profiles before the function starts, so the
first request after a cold start doesn’t wait for them.
In ECS, the agent runs as a sidecar container in the same task as your service. It polls
in the background (also every 45 seconds by default, set with POLL_INTERVAL) and serves the
same localhost:2772 endpoint.
The good news: your code is the same in both. It makes a local HTTP call either way, so one small module works everywhere:
// flags.ts: the only file that knows where flags come from.
const APP = 'orders-service';
const ENV = process.env.APPCONFIG_ENV ?? 'preprod';
const URL = `http://localhost:2772/applications/${APP}/environments/${ENV}/configurations/flags`;
// Safe defaults if the agent can't be reached: the old behavior, not the new one.
const DEFAULTS: Flags = { newPricing: false };
export async function getFlags(): Promise<Flags> {
try {
const res = await fetch(URL);
if (!res.ok) return DEFAULTS;
const data = await res.json();
return { newPricing: data.newPricing?.enabled ?? DEFAULTS.newPricing };
} catch {
return DEFAULTS;
}
}
The environment comes from APPCONFIG_ENV, which the infrastructure sets, so the same code reads
preprod flags in pre-prod and prod flags in prod.
Two more details are worth copying. Every flag has a default for when the agent isn’t reachable, and the default is the safe behavior, usually the old path. And it’s the only file that knows about AppConfig, so if you ever change tools, it’s the only file that changes.
How long does a change take to arrive? The deployment strategy’s timing, plus up to one poll interval for each running copy of your code to notice. For an emergency switch-off with the all-at-once strategy and the default poll, that’s roughly a minute. If you need it faster, lower the poll interval, but every poll is a call AppConfig charges for.
Clean them up
Every flag is a second path through your code. A few are fine. Dozens of old ones, some of which nobody remembers the purpose of, make the code harder to read and every change riskier, because nobody’s sure which paths are still live.
Not every flag is temporary, so sort them when you create them:
- Release flags exist to ship something safely. Once it’s fully on and stable, they should go.
- Kill switches stay. Their whole value is being there on the day you need them.
- Configuration stays too. It isn’t a flag; it’s a setting.
For the temporary ones, AppConfig lets you mark a flag as short-term with a date it should be removed, and labels it overdue once the date passes. It doesn’t remove anything for you, so make removal part of the work: when a release flag is created, the ticket to delete it is created too. Remove the code path first, deploy, then delete the flag.
Keeping flags out of the business logic pays off here. If the flag only picks an implementation at the edge, removing it means deleting one function and one line.
The takeaway
- A flag you can’t flip without a deploy isn’t a flag. Keep the values outside the code.
- Keep flags out of business logic. Read them at the edge and use them to choose what runs.
- Use AppConfig for flags and configuration, one package for the team, one application per service.
- Keep them in a repo and validate twice: in the pipeline and in AppConfig.
- Tie values to environment and region, with one file each in the repo and a mapping to accounts and regions. Then you can switch off one region without touching the others.
- Deploy all at once in pre-prod, gradually with an alarm in prod. In an emergency, switch off from the console immediately, then update the repo.
- Read them through the AppConfig Agent, a Lambda extension or an ECS sidecar, with safe defaults.
- Clean up release flags. Keep kill switches.
Test yourself
1. A feature's on/off value is an environment variable on a Lambda function. Is that a feature flag?
Not a useful one. Changing it updates the function’s configuration, which creates new instances and is effectively a deploy. It can’t be flipped in seconds, and it can’t roll out gradually or roll back on an alarm.
2. A new flag is checked in five places across the pricing code. What's the problem, and the fix?
The logic now has two versions tangled together, and removing the flag means finding and editing all five places correctly. Read the flag once at the handler, and use it to choose between two clean implementations.
3. Prod is down because of a new feature, and the flag's environment uses a 30-minute linear rollout. What do you do?
Turn the flag off in the AWS console and deploy it immediately with the all-at-once strategy, not the slow one. Gradual rollouts protect you when turning something on. When you’re switching off to stop an outage, speed is the point. Then update the repo to match, so the next deployment doesn’t turn it back on.
4. The AppConfig Agent is unreachable when your code reads a flag. What should happen?
Fall back to a default, and make the default the safe behavior, usually the old code path. The request should still work, and nothing new should turn on by accident.