Skip to Content
Cloud Engineering Academy
3. .NET Application Development on AWS

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.

intermediate⏱ 1 h 40 min🟢 FreeDVA-C03SAA-C03

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, IOptionsSnapshot and IOptionsMonitor correctly, 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

Why this matters in banking

Three real-world failure patterns:

  1. 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.
  2. A typo that takes production down. Someone sets Limits__DailyTransferGbp to 5O00 (letter O). The app starts, the first transfer request throws a FormatException, 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.
  3. A feature switched on for everyone at once. A new "instant payments to new payees" flag is flipped to true globally. 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 thereChanges how
1. appsettings.jsonSafe defaults, structure, logging levelsCode change + deployment
2. appsettings.{Environment}.jsonEnvironment-specific defaults that are not sensitive (e.g. Development endpoints)Code change + deployment
3. User secrets (Development only)Local secrets on a developer's machineDeveloper only
4. Environment variablesPer-deployment wiring: Region, table name, which parameter path to readNew task definition / environment update
5. Command-line argumentsRare: utility modesAt launch
6. Parameter StoreOperational settings shared across instances: endpoints, timeouts, limits; SecureString for low-risk sensitive valuesParameter change; picked up on reload
7. AppConfigValues that need safe rollout: feature flags, operational toggles, thresholds; validated and deployed gradually with rollbackAppConfig deployment
Separate: Secrets ManagerCredentials and keys that need rotation, auditing and fine-grained accessRotation (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 tierAdvanced tier
Parameters per account per Region10,000100,000
Maximum value size4 KB8 KB
Parameter policies (expiration, notifications)NoYes
Share with other accountsNoYes
Storage costFreeUSD 0.05 per parameter per month
API interactionsFree at standard throughputUSD 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:

StrategyBehaviourUse for
AppConfig.Linear20PercentEvery6Minutes20% every 6 minutes over 30 minutes, then 30 minutes of alarm monitoringProduction (AWS recommended)
AppConfig.Canary10Percent20MinutesExponential growth starting at 10% over 20 minutes, 10 minutes bakeProduction (AWS recommended)
AppConfig.AllAtOnceEveryone immediately, 10 minutes bakeUrgent changes, kill switches
AppConfig.Linear50PercentEvery30Seconds50% every 30 s, 1-minute bakeTesting 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 equivalentWhat's different
appsettings.json + environment variablesSameIdentical in ASP.NET Core on any host
Azure App Configuration (key-values)Systems Manager Parameter StoreHierarchy by / paths; standard tier is free; no labels-per-environment model — use separate paths per environment
Azure App Configuration feature managerAWS AppConfig feature flag profilesAppConfig adds deployment strategies and alarm rollback to flags
App Configuration sentinel key + refreshreloadAfter on the configuration provider; AppConfig Agent pollingNo push notifications to the app; polling interval is your choice
Key Vault referencesSecureString parameters, or Secrets ManagerSecureString is encrypted with KMS; Secrets Manager adds rotation
App Service application settingsTask definition environment, Beanstalk environment properties, Lambda environment variablesPer-host mechanisms; keep them for wiring only
Microsoft.Azure.AppConfiguration.AspNetCoreAmazon.Extensions.Configuration.SystemsManagerOne 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

  1. Console → Systems Manager → Application tools → Parameter Store → Create parameter. Name /hl-m03/accounts-api/Repository/CallTimeout, tier Standard, type String, value 00:00:03. Add tags. Repeat for Limits/DailyTransferGbp. For Pseudonymisation/Key choose SecureString and KMS key source: My current account with alias/aws/ssm (lab) or a customer managed key (production).
  2. Open a parameter → History to see versions; Labels to attach a label such as approved to a version.
  3. Console → Systems Manager → Application tools → AppConfig → Create application hl-m03-accounts-api.
  4. Inside it: Environments → Create environment learn. Under Monitors, optionally add a CloudWatch alarm and a role that lets AppConfig read it.
  5. 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.
  6. Start deployment: environment learn, hosted version 1, strategy AppConfig.Linear50PercentEvery30Seconds. Watch the percentage progress; Stop deployment rolls back.
  7. For feature flags: Create → Feature flag, name release-flags, add a flag includePendingTransactions (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

ConfigStack.cs
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.

Harbourline.ConfigDemo.csproj
<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>
Options.cs
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.");
}
Program.cs
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);
appsettings.json
{
  "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 run

Code explained line by line

  1. builder.Configuration["ParameterStore:Path"] — read from the layers already loaded (appsettings*.json, environment variables). In ECS this comes from the task definition's ParameterStore__Path variable.
  2. AddSystemsManager(path, optional: false, reloadAfter: 5 min) — calls GetParametersByPath (recursive, with decryption) once at start-up and then every five minutes per process. optional: false makes a missing permission a start-up failure, which is what you want: a task without its configuration should never become healthy.
  3. 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 in appsettings.json. In Lambda, the package's AddAppConfigUsingLambdaExtension reads from the AppConfig Agent extension on localhost instead.
  4. Order matters. The provider added last wins, so AppConfig overrides Parameter Store, which overrides environment variables.
  5. AddOptions<LimitsOptions>().Bind(...) — binds the section to a class. Binding is case-insensitive, and TimeSpan/decimal parse with invariant culture.
  6. ValidateDataAnnotations() — enforces [Range], [Required] and [Url].
  7. 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.
  8. 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, accessing CurrentValue throws, so validate in AppConfig too (JSON Schema) to stop bad values before they reach the app.
  9. 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.
  10. monitor.OnChange(...) — logs every reload; the log line becomes evidence of when production behaviour changed.
  11. 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:GetParametersByPath on their path only. A wildcard on parameter/* lets one service read another's settings.
  • Separate read from write. Applications never get ssm:PutParameter or appconfig:StartDeployment.
  • Audit. Every PutParameter and AppConfig deployment is in CloudTrail. Parameter history shows who changed what. GetParameter calls on SecureString are also logged — useful for detecting unexpected readers.
  • No configuration endpoint in production. Never expose /config or a IConfiguration dump. 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:DescribeTaskDefinition or lambda:GetFunctionConfiguration can 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 → use IOptionsMonitor<T>.
  • Adding AWS sources before environment variables → environment variables override Parameter Store unexpectedly → add AWS sources after CreateBuilder has loaded the defaults (as shown).
  • Path segment mismatch → /limits/daily-transfer-gbp never binds to Limits: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: true for 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 Store SecureString or Secrets Manager.
  • Flipping a flag with AllAtOnce for risky features → full blast radius → linear or canary strategies with an alarm.

Troubleshooting

SymptomLikely causeFix
Start-up fails: AccessDeniedException ... ssm:GetParametersByPathTask/function role lacks permission on the pathAllow ssm:GetParametersByPath on parameter/<path> (no trailing slash in the ARN)
Start-up fails: AccessDeniedException ... kms:DecryptSecureString uses a key the role cannot useAdd kms:Decrypt on that key and allow the role in the key policy
Values from Parameter Store ignoredPath not matching sections, or a later source overrides themCheck names; log ((IConfigurationRoot)config).GetDebugView() locally (never in production)
OptionsValidationException on startA value is out of range or missingRead the message — it names the property; fix the parameter
ThrottlingException from SSM during scale-outMany tasks loading at once at standard throughputIncrease reload interval, enable higher throughput, or move hot values to AppConfig
AppConfig deployment ROLLED_BACKAlarm fired during deployment or bakeInvestigate the alarm; fix and redeploy
AppConfig deployment rejected immediatelyValidator failedRun the JSON Schema locally against the content
New AppConfig value not visibleClient polls every reloadAfter; deployment still at partial percentageWait 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 String parameters, run the demo with ParameterStore__Path, change Limits/DailyTransferGbp and observe the reload log line within five minutes (shorten reloadAfter to 30 seconds for the test).
  • 🟡 Challenge: Add the AppConfig runtime profile with the JSON Schema validator. Try to deploy {"Features":{"IncludePendingTransactions":"yes"}} and capture the validation error. Then deploy a valid change with AppConfig.Linear50PercentEvery30Seconds and watch /features flip.
  • 🔴 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 ThrottlingException from 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

Knowledge check

Interview questions

  • "How do you manage configuration for a .NET app on AWS?" — Layered IConfiguration: defaults in appsettings.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, IOptionsMonitor for reloads, least-privilege IAM by path.
  • "Parameter Store or AppConfig?" — Parameter Store for simple, rarely changed settings and SecureString values; 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

Completion checklist

  • I can say which layer each kind of setting belongs in
  • I loaded Parameter Store values into IConfiguration and 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 ValidateOnStart turn bad configuration into a failed deployment instead of failed payments.
  • Use IOptionsMonitor for 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.

On this page