Skip to content

Feature flags in AWS Lambda and serverless functions: patterns, AppConfig and a freeze test

How to use feature flags in AWS Lambda: what the execution environment lifecycle means for flag SDKs, six patterns from in-process SDKs to the AppConfig extension and relay proxies, vendor guidance, tested Node.js handlers, and a reproducible test of stale flags after a freeze.

11 min read

Short answer: Initialize the flag SDK outside the handler so warm invocations reuse it, and prefer a source close by: a local evaluation SDK, the AWS AppConfig Lambda extension, or a relay proxy in the same region. Background refreshes pause while Lambda freezes the environment, so the first request after a pause can get old values; flush analytics before each invocation returns.

What does Lambda change for a flag SDK?

Flag SDKs are built for long-running servers. These facts from the Lambda execution environment docs matter:

Lambda behavior What it means for flags
Code outside the handler runs once per execution environment, and "is not run again" on warm invocations Create the SDK client there, not in the handler, or each invocation pays for a fresh download
On demand, Init is limited to 10 seconds; if it runs over, Lambda retries Init during the first invocation, under the function timeout A slow first flag download delays the first request; give the SDK a timeout well below 10 seconds
Lambda freezes the environment between invocations; unfinished background work resumes when it's reused Polling and streaming pause while frozen; the SDK refreshes only after an invocation thaws it
Shutdown lasts 0 ms with no extensions, 500 ms with an internal extension and 2,000 ms with external ones; the runtime only receives SIGTERM when an external extension is registered A SIGTERM handler that flushes events usually never runs; flush during each invocation instead

Lambda also replaces execution environments every few hours, and each concurrent instance has its own environment, its own SDK client and its own cache. Lambda Managed Instances don't freeze between invocations and run several invocations at once, so the freeze advice below doesn't apply to them. Sources: execution environment, AWS graceful shutdown samples.

Which pattern should I use?

Pattern How it works Good for Watch out for
SDK with local evaluation, initialized outside the handler Downloads rules once per environment, evaluates in memory Most functions First-request latency; values from before a freeze (see the test below)
Flag file bundled at deploy time flagd, GO Feature Flag or OpenFeature reads a file in the deployment package Flags that change with releases, or as a fallback Changing a flag means redeploying
AWS AppConfig Lambda extension A layer runs an agent on localhost:2772 that caches configurations and polls AppConfig every 45 seconds by default AWS-native teams; no vendor SDK in the function Each environment keeps its own cache; every new environment receives the configuration, which AppConfig bills
Relay proxy or edge server close by LaunchDarkly Relay Proxy, Unleash Edge, the GO Feature Flag relay proxy or Flagsmith's Edge Proxy in the same region or VPC Many functions or high concurrency, to protect the vendor API and cut init latency Another service to run (GO Feature Flag's relay can itself run as a Lambda); in-process SDKs polling it still refresh in the background
Shared persistent store A separate process writes flag data to Redis or DynamoDB; functions only read it Large fleets where downloading rules on every cold start is too slow LaunchDarkly daemon mode, Split consumer mode with the Split Synchronizer, Statsig data adapters; more infrastructure
Remote evaluation per check Each check calls the vendor's API or a relay Low-traffic functions, and kill switches that must apply at once A network round trip per check, and the function depends on that service being up

Sources: AppConfig Lambda extension configuration and how it works, LaunchDarkly serverless guide, GO Feature Flag relay proxy on AWS Lambda, Statsig data stores, Split on serverless.

What do the vendors recommend for Lambda?

From each vendor's documentation, checked on 15 November 2026:

Tool Guidance
LaunchDarkly Create the client at module scope and call waitForInitialization({ timeout }) in the handler; streaming is the default and recommended. For large fleets, a Redis-backed persistent store in daemon mode, or the Relay Proxy. The Node.js SDK doesn't send pending events when it closes: call flush() first
Unleash Initialize once per function lifetime (its example calls init() inside the handler, guarded so it runs once) with an in-memory storage provider; the SDK syncs in the background. Its guide flushes metrics with destroyWithFlush() on SIGTERM, which only fires when an external extension is registered. Suggests Unleash Edge to scale
PostHog "await client.flush() before returning if you reuse the client across invocations"; call shutdown() only when you're done with the client
ConfigCat Auto polling isn't a good fit for short-lived functions; use lazy loading (cache TTL, 60 seconds by default) or manual polling
GrowthBook GrowthBookClient fetches features once at initialization by default, which suits serverless; you can pass a payload loaded from your own store with init({ payload })
Flagsmith No Lambda guide; local evaluation refreshes every 60 seconds, offline mode can read a file exported with the Flagsmith CLI, and close() ends the polling thread
Statsig A blog post recommends initializing outside the handler and reading config from an external store kept current by a separate process; the SDK's data adapters read from "your own storage solution"
Split / Harness FME A 2017 post (updated 2026): SDK in consumer mode reading from Redis, kept current by the Split Synchronizer; standalone mode with one SDK object per function is "NOT recommended" because of creation latency
GO Feature Flag The relay proxy can run as a Lambda behind API Gateway or an ALB (startAsAwsLambda)
DevCycle A Lambda example with a server SDK key and initializeDevCycle(...).onClientInitialized(); no lifecycle guidance on the page
AWS AppConfig The Lambda extension, or Powertools for AWS Lambda (Python), whose feature flags utility reads AppConfig (directly or through the extension) and caches for 5 seconds by default

Sources: LaunchDarkly serverless and shutdown, Unleash AWS Lambda guide, PostHog Node.js, ConfigCat Node.js, GrowthBook Node.js, Flagsmith server-side SDKs, Statsig, Split on serverless, GO Feature Flag on Lambda, DevCycle Lambda, Powertools feature flags. Powertools for TypeScript has no feature flags utility; its Parameters utility can fetch AppConfig data.

How do I initialize a flag SDK in a Lambda function?

Start initialization at module scope and await it in the handler. We ran this in AWS's Lambda Node.js 22 base image with its Runtime Interface Emulator, using @openfeature/server-sdk 1.23.0 and the flagd provider 0.18.0 reading a flags.json bundled with the function:

import { OpenFeature } from '@openfeature/server-sdk'
import { FlagdProvider } from '@openfeature/flagd-provider'

// Runs once per execution environment, during Init
const ready = OpenFeature.setProviderAndWait(
  new FlagdProvider({ resolverType: 'in-process', offlineFlagSourcePath: './flags.json' }),
).catch((err) => console.error('Flag provider failed to start; serving defaults', err))
const client = OpenFeature.getClient()

export const handler = async (event) => {
  await ready
  const enabled = await client.getBooleanValue('new-checkout', false, {
    targetingKey: event.userId ?? 'anonymous',
    plan: event.plan ?? 'free',
  })
  return { checkout: enabled ? 'new' : 'old' }
}

With a rule turning new-checkout on for plan equal to pro, the pro event returned new and the free event old; warm invocations took under 1 ms in the emulator. Pointing it at a missing file logged the error and served the default, instead of failing the environment. Swap the provider for your vendor's and the structure stays the same. Choices to make:

  • Catch the startup promise. Without the .catch, a provider that fails during Init leaves a rejected promise no one is waiting on, and Node.js treats an unhandled rejection as fatal.
  • Where to wait. Awaiting in the handler, as above, lets Init finish quickly and makes the first invocation wait. Awaiting at module top level (ES modules) makes Init wait instead; prefer that with provisioned concurrency, where the environment is initialized and then frozen, possibly long before its first request, and a download left in flight would be frozen with it.
  • Provisioned concurrency means older values. Rules downloaded when the environment was provisioned can be hours old at the first request; the SDK refreshes after that request thaws it.
  • Keep the SDK key secret. Use a server-side key from Secrets Manager or Parameter Store rather than plain environment variables, and never a client-side key.

How do I read flags from the AppConfig Lambda extension?

The extension exposes AppConfig on localhost:2772; add ?flag= to get one flag from a feature flag configuration. We tested the same HTTP API with the AppConfig Agent container (public.ecr.aws/aws-appconfig/aws-appconfig-agent:2.x, agent 2.0.245001) in local development mode, which serves files named application:environment:configuration instead of calling AWS, and this handler in the Lambda Node.js 22 image:

const AGENT = process.env.APPCONFIG_AGENT ?? 'http://localhost:2772'
const PATH = '/applications/shop/environments/prod/configurations/flags'

async function flag(name) {
  const res = await fetch(`${AGENT}${PATH}?flag=${encodeURIComponent(name)}`)
  if (!res.ok) return { enabled: false }
  return res.json()
}

export const handler = async () => {
  const { enabled } = await flag('new-checkout')
  return { checkout: enabled ? 'new' : 'old' }
}

A request for ?flag=new-checkout returned { "enabled": true }, repeating flag returned several flags, and an unknown flag returned HTTP 400 (NoSuchFlag), which the handler treats as off. Warm invocations took about 2 to 3 ms, mostly the local HTTP call. Notes:

  • When changes arrive. The extension keeps a cache per execution environment; when an invocation arrives after the poll interval (45 seconds by default, AWS_APPCONFIG_EXTENSION_POLL_INTERVAL_SECONDS), it checks AppConfig for new data. How fast a change reaches every function also depends on the AppConfig deployment strategy you use.
  • Prefetching. AWS_APPCONFIG_EXTENSION_PREFETCH_LIST fetches configurations before your function's Init starts.
  • Cost. AppConfig charges $0.0000002 per configuration request and $0.0008 per configuration received (checked on 15 November 2026). Receiving costs 4,000 times more than a request, and every new execution environment receives the configuration, so cold starts and deployments drive the bill more than the poll interval does (pricing).
  • Targeting. AppConfig also has multi-variant flags with rules; the agent evaluates them from Context request headers (retrieving feature flags). In Python, Powertools' feature flags utility evaluates its own rule format from an AppConfig document.
  • Shutdown. The AppConfig layer is an external extension, so functions using it do receive SIGTERM at shutdown.
  • Local development mode is for development only; AWS says not to use it in production.

How stale are flags after a freeze?

To see what a freeze does to background refreshes, we paused the function's container with docker pause, changed a flag while it was frozen, then sent an invocation while it was still paused and unpaused it, so the request was handled as soon as the environment thawed, as in Lambda. The function used the GO Feature Flag OpenFeature provider in in-process mode, polling a relay proxy every 5 seconds through a proxy that added latency, in the Lambda Node.js 22 image. Five runs per latency, on 15 November 2026:

Added latency to the flag server Invocation sent while frozen Next invocation, 0.2 s later 1.2 s later
None (same Docker network) Old value, 5 of 5 New value, 5 of 5 New value, 5 of 5
20 ms Old value, 5 of 5 New value, 5 of 5 New value, 5 of 5
300 ms Old value, 5 of 5 Old value, 5 of 5 New value, 5 of 5

When the environment thaws, the overdue poll starts at once, but the waiting invocation is handled before the response arrives, even on a local network. The first invocation after a freeze used the values from before it in every run. The script and raw results (no delay, 20 ms, 300 ms) are published; it needs Docker and Node.js.

Treat this as a best case:

  • It's a simulation. docker pause uses the Linux cgroup freezer, not Lambda's own freeze, and the emulator doesn't freeze between invocations on its own. Our freezes lasted 12 seconds; real ones can last minutes or hours, and connections may be dropped in that time.
  • The poll was already due. We polled every 5 seconds, so a poll was overdue at every thaw. With common defaults (GO Feature Flag's provider polls every 120 seconds, ConfigCat and Flagsmith every 60, the AppConfig extension every 45), a value can be up to one poll interval plus a round trip old, freeze or not.
  • Timer behavior in Lambda isn't documented. If time spent frozen doesn't count toward a timer, refreshes come later than in our test.

What to do about it:

  • Kill switches that must apply at once need a check that waits for fresh data: remote evaluation per check, or a cache that refreshes on read with a short TTL, so an expired value is fetched before the check returns (ConfigCat's lazy loading, or Powertools' 5-second cache). Background polling, in an SDK or the AppConfig extension, can't promise that.
  • For everything else, size the lag: about one poll interval, plus one invocation after a freeze.
  • Streaming is a trade-off. LaunchDarkly recommends streaming, and it updates warm environments quickly, but a connection that died during a long freeze may not be noticed until the SDK times it out.

How do I send flag analytics from Lambda?

SDKs batch evaluation events and experiment exposures in the background, and a frozen environment that's later recycled never sends them. Flush before the handler returns: PostHog's await client.flush(), LaunchDarkly's flush() (its Node.js SDK doesn't send pending events on close()), or your SDK's equivalent. Flushing adds a network call to each invocation; flushing only every few invocations risks losing the unsent events, and an external extension can send them after the response instead. Don't rely on a SIGTERM handler unless an external extension is registered.

What about SnapStart and Lambda@Edge?

Lambda SnapStart (Java 11+, Python 3.12+, .NET 8+) snapshots the environment after Init and restores it for new environments. A flag SDK initialized during Init is part of the snapshot, so:

  • Values can be old on restore: the snapshot holds whatever rules were downloaded when it was taken. Refresh flags in an after-restore runtime hook, or in the first invocation.
  • Connections aren't guaranteed after restore, per AWS; streaming SDKs must reconnect.
  • Unique values must be generated after restore, for example random IDs an SDK creates at startup.

Lambda@Edge supports neither layers nor container images (the ways extensions are added), nor environment variables, so the AppConfig extension isn't available there (Lambda@Edge restrictions); use a bundled flag file or a fast remote check, as in edge feature flags.

For Node.js servers, see feature flags in Node.js. For timing data, see local vs remote evaluation, and for relay proxies and self-hosting, self-hosted vs SaaS. All tools are in the directory.