Invalidating CloudFront from C#: Make the Deployment Intent Traceable

Editorial illustration.

Originally published 16 June 2023; rewritten and reviewed on 15 October 2026.

You push a new build to S3, the CI pipeline goes green, and then you open the site—only to see yesterday’s JavaScript bundle still running from the CloudFront edge in Kuala Lumpur or Singapore. The kneejerk reaction is to fire off a /* invalidation across the whole distribution. That works in an emergency, but doing it on every release burns through your free monthly invalidation quota and forces CloudFront to re-fetch assets that never changed.

Before writing the C# invalidation code, it helps to separate what actually needs invalidating from what should be versioned instead.

Versioned filenames vs cache invalidation

If you build front-end assets with Vite, Webpack, or Esbuild, let the bundler put a content hash in the filename (for example, app.8f3a1c.js). Serve those hashed files with Cache-Control: public, max-age=31536000, immutable. When you deploy a new version, the HTML points to a brand-new filename, so CloudFront never has a stale object to serve and you do not need an invalidation at all.

Cache invalidation is for unversioned, stable paths that must change in place: index.html, /sitemap.xml, a media file in Kentico that kept the same URL after an editor replaced it, or a JSON config endpoint.

Keep the paths as narrow as possible. AWS includes the first 1,000 invalidation paths per month at no charge, and each entry in Items counts as one path (including a wildcard like /assets/*). Over-broad wildcards wipe out warm cache hits for users who did not need the update.

Creating an invalidation with the AWS SDK for .NET

Install the AWSSDK.CloudFront NuGet package and use AmazonCloudFrontClient. The key field people overlook is CallerReference:

using Amazon.CloudFront;
using Amazon.CloudFront.Model;

public async Task<string> InvalidatePathsAsync(
    IAmazonCloudFront cloudFront,
    string distributionId,
    string deploymentOperationId,
    IReadOnlyList<string> paths,
    CancellationToken cancellationToken = default)
{
    var request = new CreateInvalidationRequest
    {
        DistributionId = distributionId,
        InvalidationBatch = new InvalidationBatch
        {
            CallerReference = deploymentOperationId,
            Paths = new Paths
            {
                Quantity = paths.Count,
                Items = new List<string>(paths)
            }
        }
    };

    CreateInvalidationResponse response =
        await cloudFront.CreateInvalidationAsync(request, cancellationToken);

    return response.Invalidation.Id;
}

A few practical details make this safe in production:

  • Use a deterministic CallerReference: Pass your CI/CD build number, commit SHA, or a specific operation ID (for example, deploy-20261015-042). If a network blip causes your deployment step to retry, CloudFront treats the same CallerReference with the same paths as idempotent instead of charging you for a duplicate invalidation.
  • Leading slashes are mandatory: CloudFront expects paths like "/index.html" or "/media/brochure.pdf". Passing "index.html" without a leading / will throw an InvalidArgument exception.
  • Scope IAM credentials tightly: Do not embed AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY in appsettings.json. Use an IAM role (EC2/ECS/Lambda), OIDC in GitHub Actions, or environment credentials, and restrict the policy to cloudfront:CreateInvalidation and cloudfront:GetInvalidation on that specific distribution ARN.

Wait for completion and verify the edge response

CreateInvalidationAsync returns as soon as AWS accepts the request—typically with Status = "InProgress". It does not mean every edge location has already dropped the old object. If your smoke test runs immediately after CreateInvalidationAsync returns, it might still hit a stale response.

Return and log the Invalidation.Id so you can poll GetInvalidationAsync until Status becomes "Completed" (usually within 30 to 90 seconds):

var statusResponse = await cloudFront.GetInvalidationAsync(new GetInvalidationRequest
{
    DistributionId = distributionId,
    Id = invalidationId
}, cancellationToken);

Once it completes, verify the live URL with curl -I https://example.com/index.html and inspect the x-cache and age headers. Seeing x-cache: RefreshHit from cloudfront or Miss from cloudfront followed by a fresh etag or last-modified timestamp confirms the edge actually picked up your new deployment.