Configuration done right
Layer ASP.NET Core configuration from appsettings.json through environment variables to Systems Manager Parameter Store and AWS AppConfig, validate it at start-up, reload it safely, and roll out feature flags gradually with automatic rollback.
Assumes: .NET 10 LTS · Amazon.Extensions.Configuration.SystemsManager 7.1.1 · AWS SDK for .NET v4 (AWSSDK.AppConfigData 4.1.0.2) · AWS CLI v2 · Region us-east-1. Verified against official sources on 2026-11-18.
Learning objectives
By the end of this lesson you can:
- Decide where each kind of setting belongs:
appsettings.json, environment variables, Parameter Store, AppConfig or Secrets Manager. - Explain the ASP.NET Core configuration layering order and add Parameter Store and AppConfig as configuration sources with reload.
- Use
IOptions,IOptionsSnapshotandIOptionsMonitorcorrectly, and validate configuration at start-up so a bad value stops a deployment instead of a payment. - Design a Parameter Store hierarchy with IAM permissions per path, and know the tier, size, throughput and cost limits.
- Roll out a feature flag with an AppConfig deployment strategy, JSON-schema validation and CloudWatch-alarm rollback.
Prerequisites
- AWS SDK for .NET v4 in depth and AWS clients and dependency injection.
- One of the hosting lessons: ECS on Fargate, Elastic Beanstalk or Lambda with C#.
- Tools: .NET 10 SDK, AWS CLI v2 with
learn-sandbox.
Why this matters in banking
Three real-world failure patterns:
- Configuration baked into the image. The payments service has the sanctions-screening endpoint URL in
appsettings.Production.json. When the provider changes the URL, the bank must rebuild, re-test and redeploy the image under an emergency change. With external configuration, it is a controlled parameter change. - A typo that takes production down. Someone sets
Limits__DailyTransferGbpto5O00(letter O). The app starts, the first transfer request throws aFormatException, and every transfer fails. Validation at start-up would have stopped the new tasks from ever becoming healthy, and the deployment would have rolled back. - A feature switched on for everyone at once. A new "instant payments to new payees" flag is flipped to
trueglobally. A bug in the limit check lets through a fraud pattern. A gradual rollout with an alarm would have exposed 10% of traffic for a few minutes and rolled back automatically.
Regulators also expect change control over configuration that affects customer outcomes (limits, fees, fraud thresholds). Parameter Store versions, AppConfig deployments and CloudTrail give you the who/what/when evidence.
The idea in plain language
Configuration is everything that changes between environments or over time without changing code: table names, URLs, timeouts, limits, feature switches.
ASP.NET Core already has a great model for this: a stack of configuration sources, where later sources override earlier ones, all merged into one IConfiguration. On AWS you add two more sources at the top of the stack:
| Layer (later wins) | What goes there | Changes how |
|---|---|---|
1. appsettings.json | Safe defaults, structure, logging levels | Code change + deployment |
2. appsettings.{Environment}.json | Environment-specific defaults that are not sensitive (e.g. Development endpoints) | Code change + deployment |
| 3. User secrets (Development only) | Local secrets on a developer's machine | Developer only |
| 4. Environment variables | Per-deployment wiring: Region, table name, which parameter path to read | New task definition / environment update |
| 5. Command-line arguments | Rare: utility modes | At launch |
| 6. Parameter Store | Operational settings shared across instances: endpoints, timeouts, limits; SecureString for low-risk sensitive values | Parameter change; picked up on reload |
| 7. AppConfig | Values that need safe rollout: feature flags, operational toggles, thresholds; validated and deployed gradually with rollback | AppConfig deployment |
| Separate: Secrets Manager | Credentials and keys that need rotation, auditing and fine-grained access | Rotation (next lesson) |
Analogy: Think of a bank branch's operating manual. The printed manual (
appsettings.json) gives the standard procedures. A laminated card on each desk (environment variables) says which branch and which safe this desk uses. The head office bulletin board (Parameter Store) posts updates everyone must follow, read every morning. And major procedure changes (AppConfig) are piloted at two branches first, with the regional manager ready to call them off if complaints spike.
What problem Parameter Store and AppConfig solve
AWS Systems Manager Parameter Store is a hierarchical key-value store for configuration and simple secrets. It is versioned, integrated with IAM and KMS, and free for standard parameters.
| Standard tier | Advanced tier | |
|---|---|---|
| Parameters per account per Region | 10,000 | 100,000 |
| Maximum value size | 4 KB | 8 KB |
| Parameter policies (expiration, notifications) | No | Yes |
| Share with other accounts | No | Yes |
| Storage cost | Free | USD 0.05 per parameter per month |
| API interactions | Free at standard throughput | USD 0.05 per 10,000 |
You can raise the account's throughput setting for higher request rates; then API interactions cost USD 0.05 per 10,000 for all parameters. Standard throughput is limited (40 transactions per second for GetParameter* by default ⚠ VERIFY current quota), which matters when hundreds of tasks start at once.
AWS AppConfig (a capability of Systems Manager) is a configuration deployment service. It adds what Parameter Store lacks:
- Validators — a JSON Schema or a Lambda function checks the configuration before deployment.
- Deployment strategies — roll out to a percentage of callers over time, with a bake time.
- Automatic rollback — if a CloudWatch alarm fires during deployment or bake time.
- Feature flag profiles — a structured format for on/off flags with attributes.
- Agent — the AppConfig Agent runs as a Lambda extension or a container sidecar, caches configuration locally and serves it on
localhost.
Pricing (checked 2026-11-18): USD 0.0000002 per configuration request via API and USD 0.0008 per configuration received (charged when a client gets a new version). Polling an unchanged configuration therefore costs very little.
AppConfig's predefined deployment strategies:
| Strategy | Behaviour | Use for |
|---|---|---|
AppConfig.Linear20PercentEvery6Minutes | 20% every 6 minutes over 30 minutes, then 30 minutes of alarm monitoring | Production (AWS recommended) |
AppConfig.Canary10Percent20Minutes | Exponential growth starting at 10% over 20 minutes, 10 minutes bake | Production (AWS recommended) |
AppConfig.AllAtOnce | Everyone immediately, 10 minutes bake | Urgent changes, kill switches |
AppConfig.Linear50PercentEvery30Seconds | 50% every 30 s, 1-minute bake | Testing and demos only |
Limitations:
- Parameter Store has no rollout, no validation and no rollback; a change is visible to every reader on its next refresh.
- AppConfig rollout percentages are per caller session, not per customer, unless you use the Agent's entity-based gradual deployments.
- Both are eventually applied: your app sees changes only when its reload timer fires.
- Neither replaces Secrets Manager for credentials that must rotate.
Microsoft / Azure comparison
| You know (Microsoft/Azure) | AWS equivalent | What's different |
|---|---|---|
appsettings.json + environment variables | Same | Identical in ASP.NET Core on any host |
| Azure App Configuration (key-values) | Systems Manager Parameter Store | Hierarchy by / paths; standard tier is free; no labels-per-environment model — use separate paths per environment |
| Azure App Configuration feature manager | AWS AppConfig feature flag profiles | AppConfig adds deployment strategies and alarm rollback to flags |
| App Configuration sentinel key + refresh | reloadAfter on the configuration provider; AppConfig Agent polling | No push notifications to the app; polling interval is your choice |
| Key Vault references | SecureString parameters, or Secrets Manager | SecureString is encrypted with KMS; Secrets Manager adds rotation |
| App Service application settings | Task definition environment, Beanstalk environment properties, Lambda environment variables | Per-host mechanisms; keep them for wiring only |
Microsoft.Azure.AppConfiguration.AspNetCore | Amazon.Extensions.Configuration.SystemsManager | One NuGet package covers both Parameter Store (AddSystemsManager) and AppConfig (AddAppConfig) |
Architecture
Security-boundary view: reading configuration is an IAM permission like any other. The task or function role gets ssm:GetParametersByPath on its own path only (arn:aws:ssm:…:parameter/hl-m03/accounts-api), kms:Decrypt on the key used for SecureString values, and appconfig:StartConfigurationSession plus appconfig:GetLatestConfiguration on its own application/environment/profile. Writing configuration is a separate, more privileged permission held by the pipeline or an operations role, never by the application.
Naming the hierarchy
Use a predictable path per environment and application, and make the path segments match .NET configuration sections:
/hl/prod/accounts-api/Repository/CallTimeout = 00:00:03
/hl/prod/accounts-api/Limits/DailyTransferGbp = 5000
/hl/prod/accounts-api/Sanctions/Endpoint = https://screening.example.net/v2
/hl/prod/accounts-api/Pseudonymisation/Key = (SecureString)AddSystemsManager("/hl/prod/accounts-api/") strips the prefix and turns / into :, so the app sees Limits:DailyTransferGbp. IAM policies on parameter/hl/prod/accounts-api/* give each service exactly its own settings. The module lab uses the shorter /hl-m03/accounts-api/ path.
Step-by-step implementation
Define strongly-typed options with validation
Create one class per configuration section with data-annotation attributes (or IValidateOptions for cross-field rules). Register with ValidateDataAnnotations() and ValidateOnStart().
Add the AWS sources only when configured
Read ParameterStore:Path and AppConfig:* from the earlier layers (environment variables). If they are present, add the AWS sources. Locally, nothing is added and the app runs on appsettings.Development.json and user secrets.
Create parameters
Create standard String parameters for plain settings and a SecureString for the low-risk sensitive value, all under the service's path, tagged.
Create the AppConfig application, environment and profile
A freeform JSON profile for operational settings, with a JSON Schema validator. Optionally a separate feature-flag profile.
Deploy a configuration change gradually
Start a deployment with AppConfig.Linear50PercentEvery30Seconds in the lab (Linear20PercentEvery6Minutes in production) and an alarm on the environment.
Read and react
Consumers use IOptionsMonitor so new values apply on the next request after reload — no restart.
AWS Console instructions
- Console → Systems Manager → Application tools → Parameter Store → Create parameter. Name
/hl-m03/accounts-api/Repository/CallTimeout, tier Standard, type String, value00:00:03. Add tags. Repeat forLimits/DailyTransferGbp. ForPseudonymisation/Keychoose SecureString and KMS key source: My current account withalias/aws/ssm(lab) or a customer managed key (production). - Open a parameter → History to see versions; Labels to attach a label such as
approvedto a version. - Console → Systems Manager → Application tools → AppConfig → Create application
hl-m03-accounts-api. - Inside it: Environments → Create environment
learn. Under Monitors, optionally add a CloudWatch alarm and a role that lets AppConfig read it. - Configuration profiles and feature flags → Create. Choose Freeform configuration, name
runtime, source AWS AppConfig hosted configuration, content type JSON, paste the JSON from below. Under Validators, add the JSON Schema. - Start deployment: environment
learn, hosted version 1, strategy AppConfig.Linear50PercentEvery30Seconds. Watch the percentage progress; Stop deployment rolls back. - For feature flags: Create → Feature flag, name
release-flags, add a flagincludePendingTransactions(off), save a new version and deploy it the same way.
AWS CLI
export AWS_PROFILE=learn-sandbox AWS_REGION=us-east-1
P=/hl-m03/accounts-api
TAGS='Key=Project,Value=cea-lab Key=Lab,Value=m03-config Key=Environment,Value=learn Key=Owner,Value=you'
# ---- Parameter Store ------------------------------------------------------------------------
aws ssm put-parameter --name "$P/Repository/CallTimeout" --type String --value "00:00:03" --tags $TAGS
aws ssm put-parameter --name "$P/Limits/DailyTransferGbp" --type String --value "5000" --tags $TAGS
# SecureString with the AWS managed key (lab). Production: --key-id alias/hl-config
aws ssm put-parameter --name "$P/Pseudonymisation/Key" --type SecureString \
--value "$(openssl rand -base64 32)" --tags $TAGS
# Read everything under the path, decrypted, exactly as the .NET provider does.
aws ssm get-parameters-by-path --path "$P/" --recursive --with-decryption \
--query 'Parameters[].{Name:Name,Version:Version,Type:Type}' --output table
# Change a value (creates version 2) and label the approved version.
aws ssm put-parameter --name "$P/Limits/DailyTransferGbp" --type String --value "7500" --overwrite
aws ssm label-parameter-version --name "$P/Limits/DailyTransferGbp" --parameter-version 2 --labels approved
aws ssm get-parameter-history --name "$P/Limits/DailyTransferGbp" \
--query 'Parameters[].{v:Version,value:Value,by:LastModifiedUser,at:LastModifiedDate}' --output table
# ---- AppConfig --------------------------------------------------------------------------------
APP=$(aws appconfig create-application --name hl-m03-accounts-api --query Id --output text)
ENV=$(aws appconfig create-environment --application-id "$APP" --name learn --query Id --output text)
# JSON Schema validator: rejects a deployment whose values are the wrong type or out of range.
cat > runtime-schema.json <<'EOF'
{ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"Features": { "type": "object",
"properties": { "IncludePendingTransactions": { "type": "boolean" } },
"required": ["IncludePendingTransactions"], "additionalProperties": false },
"Limits": { "type": "object",
"properties": { "DailyTransferGbp": { "type": "number", "minimum": 0, "maximum": 50000 } } } },
"required": ["Features"] }
EOF
PROFILE_ID=$(aws appconfig create-configuration-profile --application-id "$APP" --name runtime \
--location-uri hosted --type AWS.Freeform \
--validators "[{\"Type\":\"JSON_SCHEMA\",\"Content\":$(jq -c . runtime-schema.json | jq -R .)}]" \
--query Id --output text)
echo '{"Features":{"IncludePendingTransactions":true},"Limits":{"DailyTransferGbp":5000}}' > runtime-v1.json
VERSION=$(aws appconfig create-hosted-configuration-version --application-id "$APP" \
--configuration-profile-id "$PROFILE_ID" --content-type application/json \
--content fileb://runtime-v1.json version-out.json --query VersionNumber --output text)
aws appconfig start-deployment --application-id "$APP" --environment-id "$ENV" \
--configuration-profile-id "$PROFILE_ID" --configuration-version "$VERSION" \
--deployment-strategy-id AppConfig.Linear50PercentEvery30Seconds
# Read it like a client does: start a session, then poll with the returned token.
TOKEN=$(aws appconfigdata start-configuration-session --application-identifier "$APP" \
--environment-identifier "$ENV" --configuration-profile-identifier "$PROFILE_ID" \
--query InitialConfigurationToken --output text)
aws appconfigdata get-latest-configuration --configuration-token "$TOKEN" latest.json && cat latest.json
# These environment variables tell the app where to look (set them on the host).
echo "ParameterStore__Path=$P/ AppConfig__ApplicationId=$APP AppConfig__EnvironmentId=$ENV AppConfig__ProfileId=$PROFILE_ID"A note on the validator: --validators takes a JSON list in which Content is the schema as an escaped JSON string; jq -c . | jq -R . produces exactly that. If you do not have jq, add the validator in the console instead.
Infrastructure as Code
using Amazon.CDK;
using Amazon.CDK.AWS.AppConfig;
using Amazon.CDK.AWS.SSM;
using Constructs;
public sealed class ConfigStack : Stack
{
public ConfigStack(Construct scope, string id, IStackProps props) : base(scope, id, props)
{
const string path = "/hl-m03/accounts-api";
_ = new StringParameter(this, "CallTimeout", new StringParameterProps
{
ParameterName = $"{path}/Repository/CallTimeout",
StringValue = "00:00:03",
Tier = ParameterTier.STANDARD,
});
_ = new StringParameter(this, "DailyLimit", new StringParameterProps
{
ParameterName = $"{path}/Limits/DailyTransferGbp",
StringValue = "5000",
});
// SecureString values must not be in source code: create them out of band (CLI / pipeline secret).
var app = new CfnApplication(this, "App", new CfnApplicationProps { Name = "hl-m03-accounts-api" });
var env = new CfnEnvironment(this, "Env", new CfnEnvironmentProps { ApplicationId = app.Ref, Name = "learn" });
var profile = new CfnConfigurationProfile(this, "Runtime", new CfnConfigurationProfileProps
{
ApplicationId = app.Ref,
Name = "runtime",
LocationUri = "hosted",
Type = "AWS.Freeform",
Validators = new[]
{
new CfnConfigurationProfile.ValidatorsProperty
{
Type = "JSON_SCHEMA",
Content = System.IO.File.ReadAllText("runtime-schema.json"),
},
},
});
var version = new CfnHostedConfigurationVersion(this, "RuntimeV1", new CfnHostedConfigurationVersionProps
{
ApplicationId = app.Ref,
ConfigurationProfileId = profile.Ref,
ContentType = "application/json",
Content = """{"Features":{"IncludePendingTransactions":false},"Limits":{"DailyTransferGbp":5000}}""",
});
_ = new CfnDeployment(this, "Deploy", new CfnDeploymentProps
{
ApplicationId = app.Ref,
EnvironmentId = env.Ref,
ConfigurationProfileId = profile.Ref,
ConfigurationVersion = version.Ref,
DeploymentStrategyId = "AppConfig.Linear20PercentEvery6Minutes",
});
_ = new CfnOutput(this, "AppConfigIds", new CfnOutputProps { Value = $"{app.Ref}/{env.Ref}/{profile.Ref}" });
}
}The CDK also offers higher-level AppConfig constructs (Application, Environment, HostedConfiguration); the L1 form above maps directly to the CLI and CloudFormation, which makes it easier to review.
Complete code
The lab project already wires these sources in Hosting/HostingExtensions.cs (AddAwsConfigurationSources). The code below is a self-contained version you can paste into a new Minimal API to see every piece working, including validation.
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<RootNamespace>Harbourline.ConfigDemo</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Amazon.Extensions.Configuration.SystemsManager" Version="7.1.1" />
<PackageReference Include="AWSSDK.Extensions.NETCore.Setup" Version="4.1.0.2" />
<PackageReference Include="AWSSDK.SSO" Version="4.1.0.2" />
<PackageReference Include="AWSSDK.SSOOIDC" Version="4.1.0.2" />
</ItemGroup>
</Project>using System.ComponentModel.DataAnnotations;
using Microsoft.Extensions.Options;
namespace Harbourline.ConfigDemo;
public sealed class LimitsOptions
{
public const string SectionName = "Limits";
/// <summary>Maximum outbound transfers per customer per day, in GBP. decimal, never double.</summary>
[Range(typeof(decimal), "0", "50000")]
public decimal DailyTransferGbp { get; set; }
/// <summary>Above this amount, a transfer needs step-up authentication.</summary>
[Range(typeof(decimal), "0", "50000")]
public decimal StepUpThresholdGbp { get; set; }
}
public sealed class SanctionsOptions
{
public const string SectionName = "Sanctions";
[Required, Url]
public string Endpoint { get; set; } = "";
[Range(typeof(TimeSpan), "00:00:00.100", "00:00:10")]
public TimeSpan Timeout { get; set; } = TimeSpan.FromSeconds(2);
}
public sealed class FeatureOptions
{
public const string SectionName = "Features";
public bool IncludePendingTransactions { get; set; }
}
/// <summary>Cross-field rule that attributes cannot express.</summary>
public sealed class LimitsValidator : IValidateOptions<LimitsOptions>
{
public ValidateOptionsResult Validate(string? name, LimitsOptions options) =>
options.StepUpThresholdGbp <= options.DailyTransferGbp
? ValidateOptionsResult.Success
: ValidateOptionsResult.Fail("Limits:StepUpThresholdGbp must not exceed Limits:DailyTransferGbp.");
}using Harbourline.ConfigDemo;
using Microsoft.Extensions.Options;
var builder = WebApplication.CreateBuilder(args);
// ---- 1. AWS configuration sources, added on top of appsettings + env vars ----------------------
// The *location* of the AWS configuration comes from the earlier layers (environment variables),
// so the same image works locally (no AWS sources) and in every AWS environment.
var parameterPath = builder.Configuration["ParameterStore:Path"];
if (!string.IsNullOrWhiteSpace(parameterPath))
{
// optional: false → start-up fails if the path cannot be read (missing permission, wrong Region).
builder.Configuration.AddSystemsManager(parameterPath, optional: false, reloadAfter: TimeSpan.FromMinutes(5));
}
var appConfig = builder.Configuration.GetSection("AppConfig");
if (appConfig["ApplicationId"] is { Length: > 0 } appId
&& appConfig["EnvironmentId"] is { Length: > 0 } envId
&& appConfig["ProfileId"] is { Length: > 0 } profileId)
{
// optional: true → if AppConfig is briefly unavailable at start-up, run on the lower layers.
builder.Configuration.AddAppConfig(appId, envId, profileId, optional: true, reloadAfter: TimeSpan.FromSeconds(45));
}
// ---- 2. Strongly typed, validated options --------------------------------------------------------
builder.Services.AddOptions<LimitsOptions>()
.Bind(builder.Configuration.GetSection(LimitsOptions.SectionName))
.ValidateDataAnnotations()
.ValidateOnStart();
builder.Services.AddSingleton<IValidateOptions<LimitsOptions>, LimitsValidator>();
builder.Services.AddOptions<SanctionsOptions>()
.Bind(builder.Configuration.GetSection(SanctionsOptions.SectionName))
.ValidateDataAnnotations()
.ValidateOnStart();
builder.Services.AddOptions<FeatureOptions>()
.Bind(builder.Configuration.GetSection(FeatureOptions.SectionName));
var app = builder.Build();
// ---- 3. Consumers use IOptionsMonitor so reloaded values apply without a restart ------------------
app.MapPost("/transfers/check", (TransferCheck request, IOptionsMonitor<LimitsOptions> limits) =>
{
var current = limits.CurrentValue;
if (request.AmountGbp > current.DailyTransferGbp)
{
return Results.Problem(
title: "Daily limit exceeded",
detail: $"Transfers above {current.DailyTransferGbp:N2} GBP per day are not allowed.",
statusCode: StatusCodes.Status422UnprocessableEntity);
}
return Results.Ok(new { allowed = true, stepUpRequired = request.AmountGbp > current.StepUpThresholdGbp });
});
app.MapGet("/features", (IOptionsMonitor<FeatureOptions> features) =>
Results.Ok(new { features.CurrentValue.IncludePendingTransactions }));
// Log every reload so operations can correlate behaviour changes with configuration changes.
var monitor = app.Services.GetRequiredService<IOptionsMonitor<LimitsOptions>>();
monitor.OnChange(o => app.Logger.LogInformation(
"Limits reloaded: DailyTransferGbp={Daily} StepUpThresholdGbp={StepUp}", o.DailyTransferGbp, o.StepUpThresholdGbp));
app.Run();
public sealed record TransferCheck(decimal AmountGbp);{
"AWS": { "Region": "us-east-1" },
"Limits": { "DailyTransferGbp": 5000, "StepUpThresholdGbp": 1000 },
"Sanctions": { "Endpoint": "https://screening.example.net/v2", "Timeout": "00:00:02" },
"Features": { "IncludePendingTransactions": false }
}Run it locally, then against AWS:
# Local only: no AWS sources are added.
dotnet run
# With Parameter Store: values under the path override appsettings.json.
AWS_PROFILE=learn-sandbox ParameterStore__Path=/hl-m03/accounts-api/ dotnet run
# Prove validation: a bad override stops start-up with an OptionsValidationException.
Limits__DailyTransferGbp=-1 dotnet runCode explained line by line
builder.Configuration["ParameterStore:Path"]— read from the layers already loaded (appsettings*.json, environment variables). In ECS this comes from the task definition'sParameterStore__Pathvariable.AddSystemsManager(path, optional: false, reloadAfter: 5 min)— callsGetParametersByPath(recursive, with decryption) once at start-up and then every five minutes per process.optional: falsemakes a missing permission a start-up failure, which is what you want: a task without its configuration should never become healthy.AddAppConfig(..., optional: true, reloadAfter: 45 s)— uses the AppConfig Data API (a configuration session plus polling). Optional here because the values also have safe defaults inappsettings.json. In Lambda, the package'sAddAppConfigUsingLambdaExtensionreads from the AppConfig Agent extension onlocalhostinstead.- Order matters. The provider added last wins, so AppConfig overrides Parameter Store, which overrides environment variables.
AddOptions<LimitsOptions>().Bind(...)— binds the section to a class. Binding is case-insensitive, andTimeSpan/decimalparse with invariant culture.ValidateDataAnnotations()— enforces[Range],[Required]and[Url].ValidateOnStart()— validation runs when the host starts, not on first use. Combined with ECS health checks and the circuit breaker, a bad configuration value means the new deployment never becomes healthy and rolls back automatically.IValidateOptions<LimitsOptions>— cross-field rules (step-up threshold must not exceed the daily limit). Re-runs on every reload; if a reloaded value is invalid, accessingCurrentValuethrows, so validate in AppConfig too (JSON Schema) to stop bad values before they reach the app.IOptionsMonitor<T>.CurrentValue— always the latest value.IOptions<T>is computed once and never changes;IOptionsSnapshot<T>is per request (scoped) and cannot be injected into singletons.monitor.OnChange(...)— logs every reload; the log line becomes evidence of when production behaviour changed.Results.Problem(...)— RFC 9457 ProblemDetails for a business-rule rejection.
Security considerations
⚠ Learning shortcut — not for production
The lab encrypts the SecureString with the AWS managed key alias/aws/ssm, and the app reads the whole /hl-m03/accounts-api/ path including that value. In production use a customer managed KMS key per data classification (so the key policy, not just IAM, controls who can decrypt), keep credentials that must rotate in Secrets Manager rather than SecureString, and require two-person approval for changes to limits and fraud thresholds through the pipeline rather than console edits.
- Least privilege by path. Application roles get
ssm:GetParametersByPathon their path only. A wildcard onparameter/*lets one service read another's settings. - Separate read from write. Applications never get
ssm:PutParameterorappconfig:StartDeployment. - Audit. Every
PutParameterand AppConfig deployment is in CloudTrail. Parameter history shows who changed what.GetParametercalls onSecureStringare also logged — useful for detecting unexpected readers. - No configuration endpoint in production. Never expose
/configor aIConfigurationdump. It leaks endpoints, internal hostnames and (if mis-classified) secrets. - Treat configuration as code. Limits, fees and fraud thresholds affect customer outcomes; changes go through the same review and change-ticket process as code, with the AppConfig deployment ID recorded on the ticket.
- Environment variables are visible. Anyone with
ecs:DescribeTaskDefinitionorlambda:GetFunctionConfigurationcan read them. Use them only for wiring (paths, IDs, Region).
Banking use case
Harbourline's Payments Service has three kinds of configuration:
- Wiring (table names, queue URLs, parameter path, AppConfig IDs) — environment variables in the task definition, created by CDK.
- Operational settings (sanctions endpoint, HTTP timeouts, retry counts) — Parameter Store under
/hl/prod/payments/, changed through a pipeline with peer review, reloaded every five minutes. - Risk-bearing switches (instant payments to new payees, daily limit per segment, fraud score threshold) — AppConfig, with a JSON Schema validator (types and ranges),
AppConfig.Linear20PercentEvery6Minutes, and a CloudWatch alarm on the payment-rejection rate. When a threshold change spiked rejections from 0.4% to 3% at the 20% step, AppConfig rolled back automatically and the incident record contained the deployment ID, the alarm and the timestamps — exactly the evidence the operational-resilience team needs.
Common mistakes
- Injecting
IOptions<T>and expecting reloads → values never change → useIOptionsMonitor<T>. - Adding AWS sources before environment variables → environment variables override Parameter Store unexpectedly → add AWS sources after
CreateBuilderhas loaded the defaults (as shown). - Path segment mismatch →
/limits/daily-transfer-gbpnever binds toLimits:DailyTransferGbp→ name segments like your section and property names (binding is case-insensitive, but hyphens do not match). - Very short reload intervals across many tasks → Parameter Store throttling (
ThrottlingException) → 5 minutes for Parameter Store; AppConfig for faster-changing values. optional: truefor configuration the app cannot run without → app starts with defaults in production → make essential sources required and validate on start.- Secrets in
appsettings.Production.json→ secrets in the image and in Git → Parameter StoreSecureStringor Secrets Manager. - Flipping a flag with
AllAtOncefor risky features → full blast radius → linear or canary strategies with an alarm.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
Start-up fails: AccessDeniedException ... ssm:GetParametersByPath | Task/function role lacks permission on the path | Allow ssm:GetParametersByPath on parameter/<path> (no trailing slash in the ARN) |
Start-up fails: AccessDeniedException ... kms:Decrypt | SecureString uses a key the role cannot use | Add kms:Decrypt on that key and allow the role in the key policy |
| Values from Parameter Store ignored | Path not matching sections, or a later source overrides them | Check names; log ((IConfigurationRoot)config).GetDebugView() locally (never in production) |
OptionsValidationException on start | A value is out of range or missing | Read the message — it names the property; fix the parameter |
ThrottlingException from SSM during scale-out | Many tasks loading at once at standard throughput | Increase reload interval, enable higher throughput, or move hot values to AppConfig |
AppConfig deployment ROLLED_BACK | Alarm fired during deployment or bake | Investigate the alarm; fix and redeploy |
| AppConfig deployment rejected immediately | Validator failed | Run the JSON Schema locally against the content |
| New AppConfig value not visible | Client polls every reloadAfter; deployment still at partial percentage | Wait for 100% and one poll interval |
Cost and cleanup
What this lesson costs: standard parameters and standard-throughput API calls are free. AppConfig for a lab is a fraction of a cent: USD 0.0000002 per configuration request and USD 0.0008 per configuration received. KMS: the AWS managed aws/ssm key has no monthly fee; requests within the free tier are free (customer managed keys cost about USD 1 per month ⚠ VERIFY). Label: free.
Teardown:
export AWS_PROFILE=learn-sandbox AWS_REGION=us-east-1
# Parameters
aws ssm delete-parameters --names /hl-m03/accounts-api/Repository/CallTimeout \
/hl-m03/accounts-api/Limits/DailyTransferGbp /hl-m03/accounts-api/Pseudonymisation/Key
# AppConfig: delete hosted versions, profile, environment, then application.
for v in $(aws appconfig list-hosted-configuration-versions --application-id "$APP" \
--configuration-profile-id "$PROFILE_ID" --query 'Items[].VersionNumber' --output text); do
aws appconfig delete-hosted-configuration-version --application-id "$APP" \
--configuration-profile-id "$PROFILE_ID" --version-number "$v"
done
aws appconfig delete-configuration-profile --application-id "$APP" --configuration-profile-id "$PROFILE_ID"
aws appconfig delete-environment --application-id "$APP" --environment-id "$ENV"
aws appconfig delete-application --application-id "$APP"
aws ssm get-parameters-by-path --path /hl-m03/ --recursive --query 'Parameters[].Name'Exercises
- 🟢 Guided: Create the two
Stringparameters, run the demo withParameterStore__Path, changeLimits/DailyTransferGbpand observe the reload log line within five minutes (shortenreloadAfterto 30 seconds for the test). - 🟡 Challenge: Add the AppConfig
runtimeprofile with the JSON Schema validator. Try to deploy{"Features":{"IncludePendingTransactions":"yes"}}and capture the validation error. Then deploy a valid change withAppConfig.Linear50PercentEvery30Secondsand watch/featuresflip. - 🔴 Live problem: Ticket PRB-0912: "During Monday's scale-out from 10 to 120 tasks, about a third of new Payments tasks failed to start with
ThrottlingExceptionfrom SSM, and the circuit breaker rolled back an unrelated release." Analyse and propose changes to the configuration design.
Assignment
Write a one-page configuration standard for Harbourline: the hierarchy naming rule, which layer each kind of setting belongs in, IAM rules for read/write, validation requirements, reload intervals, and which settings require AppConfig gradual rollout. Include the options classes and validator from this lesson as the reference implementation.
Solutions
With reloadAfter at 30 seconds, put-parameter --overwrite creates version 2; within 30 seconds the provider fetches the path again, IOptionsMonitor raises OnChange, the log shows the new limit, and /transfers/check uses it on the next request. Why no restart is needed: the provider triggers a configuration reload token; options bound through IOptionsMonitor recompute on that token.
create-hosted-configuration-version succeeds (validators run at deployment time), but start-deployment fails with a BadRequestException mentioning the JSON Schema validation error ("yes" is not a boolean). The valid deployment progresses 50% → 100% with a one-minute bake. Because rollout is per client session, some tasks may see the new value up to one poll interval before others. Why validate in AppConfig and in .NET: the schema stops bad values centrally before any client sees them; ValidateOnStart protects you from values coming from other layers.
Each new task calls GetParametersByPath at start-up (and the provider pages through results), so 110 tasks starting within a minute exceeded the standard-throughput limit. optional: false correctly made those tasks fail, and the circuit breaker counted them as failed tasks. Options: (1) enable higher throughput for Parameter Store (small per-call charge) — fastest fix; (2) move frequently read, shared values into AppConfig and read them through the AppConfig Agent sidecar, which caches locally; (3) add jittered retries on start-up configuration load (SDK standard retry mode already retries throttles; increase MaxErrorRetry for the SSM client); (4) reduce the number of parameters per path read, or batch into a single JSON parameter; (5) scale out in steps (target tracking already does this) rather than jumping from 10 to 120. Record the decision in an ADR.
Knowledge check
Answer: IOptionsMonitor<T>. IOptions<T> is computed once; IOptionsSnapshot<T> is scoped and cannot be injected into a singleton.
Answer: It runs validation when the host starts instead of on first access, so an invalid configuration prevents the instance from starting (and becoming healthy) rather than failing a customer request later.
Answer: Any two of: validators (JSON Schema/Lambda), gradual deployment strategies with bake time, automatic rollback on CloudWatch alarms, feature-flag profiles, the caching Agent.
Answer: 4 KB. Use an advanced parameter (8 KB, charged), split the value, or move larger configuration documents to AppConfig.
Answer: So the same image runs in every environment: the wiring (which path, which AppConfig IDs) differs per environment and is set by infrastructure code, while the values themselves live in Parameter Store/AppConfig.
Interview questions
- "How do you manage configuration for a .NET app on AWS?" — Layered
IConfiguration: defaults inappsettings.json, wiring in environment variables, operational settings in Parameter Store, risky toggles in AppConfig with gradual rollout, secrets in Secrets Manager. Strongly-typed options validated on start,IOptionsMonitorfor reloads, least-privilege IAM by path. - "Parameter Store or AppConfig?" — Parameter Store for simple, rarely changed settings and
SecureStringvalues; AppConfig when a change can hurt customers and needs validation, staged rollout and automatic rollback. - "How do you stop a bad configuration change from causing an outage?" — Validate centrally (AppConfig JSON Schema), validate in the app on start, roll out gradually with alarms and bake time, and keep a fast rollback (stop deployment, previous version).
- "Where would you not use environment variables?" — For secrets (readable via describe APIs and process listings) and for values that must change without a redeployment.
Certification practice
A team wants to turn on a new feature in a .NET application running on 40 ECS tasks. The change must reach 20% of tasks at a time and revert automatically if the 5xx error rate alarm fires. Code changes must be minimal. What should they use?
A. Update an SSM Parameter Store parameter and restart the service. B. AWS AppConfig feature flag with a linear deployment strategy and a CloudWatch alarm monitor on the environment. C. A new task definition revision with a changed environment variable and a rolling update. D. An S3 object read by the application every minute.
Answer: B. AppConfig provides gradual percentage rollout and alarm-based automatic rollback for configuration. A changes everything at once. C redeploys the whole service and only rolls back on task health failures, not on an application error-rate alarm. D has no rollout or rollback.
A .NET application must load all settings under /payments/prod/ from Parameter Store into IConfiguration at start-up, including SecureString values. Which permissions does the application role need? (Choose TWO.)
A. ssm:GetParametersByPath on the path ARN
B. ssm:PutParameter on the path ARN
C. kms:Decrypt on the KMS key used to encrypt the SecureString parameters
D. secretsmanager:GetSecretValue on all secrets
E. ssm:DescribeParameters on * only
Answer: A and C. The provider reads by path and decrypts SecureString values with KMS. B is write access, which the app must not have. D is unrelated. E lists metadata but does not return values.
An application stores 300 small configuration values (under 1 KB each) that change monthly and are read at start-up by 20 instances. The company wants the lowest cost with IAM-controlled access and version history. Which option fits best?
A. Parameter Store standard parameters B. Parameter Store advanced parameters C. Secrets Manager secrets D. A DynamoDB table with on-demand capacity
Answer: A. Standard parameters are free to store and to read at standard throughput, support IAM per path and keep version history. B costs USD 0.05 per parameter per month without needing advanced features. C costs USD 0.40 per secret per month and is meant for secrets. D works but adds cost and code for no benefit.
Completion checklist
- I can say which layer each kind of setting belongs in
- I loaded Parameter Store values into
IConfigurationand saw a reload without a restart - I made start-up fail on an invalid value with
ValidateOnStart - I deployed an AppConfig change with a strategy and saw a validator reject a bad one
- I deleted the parameters and AppConfig resources
Key takeaways
- One
IConfiguration, many layers: defaults → environment wiring → Parameter Store → AppConfig; secrets stay in Secrets Manager. - Strongly-typed options with
ValidateOnStartturn bad configuration into a failed deployment instead of failed payments. - Use
IOptionsMonitorfor values that reload; choose reload intervals that respect Parameter Store throughput. - AppConfig adds validation, gradual rollout and alarm rollback — use it for anything that can hurt customers.
- IAM by path, separate read from write, and treat configuration changes as auditable changes.
Further reading
Independent learning resource — not affiliated with, endorsed or sponsored by Amazon Web Services. AWS and related marks are trademarks of Amazon.com, Inc. or its affiliates. All banking data in examples is fictional. Sample architectures are for learning and are not automatically compliant with GDPR, PCI DSS or any banking regulation.
Lambda with C#
Write, test and deploy C# Lambda functions on the dotnet10 runtime: plain handlers, the Lambda Annotations framework, a whole ASP.NET Core API inside Lambda, Native AOT, and the real options for cold starts including SnapStart and provisioned concurrency.
Secrets in .NET on AWS
Store credentials and keys in AWS Secrets Manager, read them from .NET with client-side caching, survive rotation without outages, write a C# rotation function, and know why environment variables are the wrong place for secrets.