Skip to content

CDN Construct: A Small Infrastructure API

Why a custom CDK construct for static websites is more than saved lines: an opinionated interface over S3, CloudFront, certificates and DNS.

≈ 10 min readSoftwareAWSCloud

CDN Construct: A Small Infrastructure API

Around 280 lines of CloudFormation, spread across two stacks in two regions – that was recently the price of rolling out a static website “properly” on AWS. Fourteen resources for a handful of HTML files: an S3 bucket, a bucket policy, an origin access identity, a CloudFront distribution with cache and error behavior, an ACM certificate including DNS validation – mandatory in us-east-1, hence the second stack – plus A and AAAA alias records in Route53. None of this is difficult on its own. But all of it together is wiring that comes up again with every new project and turns out a little bit different each time.

It was exactly this repetition that made me pack the whole chain into a small AWS CDK construct of my own: cdk-cdn-construct. Static content – a single-page application or a classic static website – lands in an S3 bucket and is delivered via CloudFront as a CDN. The call in your own stack shrinks to a few lines. That is the visible gain. The more interesting gain is a different one, and that is what this article is about: a good construct is an opinionated interface. It makes decisions explicit that were previously hidden in copy-and-paste templates, and it leaves free exactly the knobs that really vary from project to project.

What actually gets wired up#

Before the abstraction holds, it is worth looking at what it encapsulates. A static website behind CloudFront consists of more parts than the sentence “S3 bucket with a CDN in front” suggests:

  • a private S3 bucket with Block Public Access fully enabled
  • an origin access identity (OAI) through which CloudFront – and only CloudFront – gets read access to the bucket
  • the matching bucket policy that allows exactly this identity s3:GetObject
  • a CloudFront distribution with enforced HTTPS, a default root object and sensible error behavior for client-side routing
  • an ACM certificate in us-east-1 including DNS validation
  • A and AAAA alias records in the Route53 zone that point to the distribution
  • the actual upload of the build output, including cache invalidation after the deployment

As a diagram, the wiring looks like this:

flowchart LR
  Browser[Browser] -->|HTTPS| CF[CloudFront distribution]
  CF -->|only via OAI| S3[S3 bucket<br/>private, Block Public Access]
  ACM[ACM certificate<br/>us-east-1] -.->|TLS| CF
  R53[Route53<br/>A/AAAA alias] -.->|resolves domain| CF
  Build[Build output<br/>e.g. ./build] -->|Upload + invalidation| S3

Each of these edges is a decision. The bucket could also be public and offer website hosting directly – then no OAI would be needed, but the bucket would be reachable bypassing the CDN, and HTTPS on your own domain would be gone. The certificate could be imported instead of DNS-validated. The error pages could point to 404.html instead of index.html. In handwritten templates, none of these decisions appear anywhere as a decision. They appear as 280 lines of YAML, and you can’t tell from them whether a deviation is intent or accident.

From template to API#

With its construct levels, the AWS CDK offers a usable vocabulary for this. L1 constructs are generated one-to-one images of the CloudFormation resources. L2 constructs are handwritten classes with defaults and helper methods – Bucket instead of CfnBucket. And L3 constructs, also called patterns in the documentation, bundle several resources into a pattern with intent. Since last year, AWS itself has maintained a whole library of such patterns with the Solutions Constructs.

My construct is such an L3 building block, technically implemented as its own stack so it can be plugged into an existing CDK app as a whole. Using it looks like this:

#!/usr/bin/env node
import { App } from '@aws-cdk/core';
import { CdkCdnConstructStack } from 'cdk-cdn-construct';

const app = new App();

// ... your own stacks ...

new CdkCdnConstructStack(app, 'MyWebsite', {
  namespace: 'my-app-namespace',
  env: {
    account: process.env.CDK_DEFAULT_ACCOUNT,
    region: process.env.CDK_DEFAULT_REGION,
  },
});

What stays configurable from outside deliberately follows a plain convention via environment variables – name, build directory, domain:

CDK_DEFAULT_REGION=eu-central-1
CDK_DEFAULT_ACCOUNT=default
CDK_CDN_NAME=your-host-and-bucket-name
CDK_CDN_PATH=./build
CDK_CDN_DOMAIN=example.com

That is the entire public surface. No switch for the distribution’s price class, none for TTLs, none for the question of whether the bucket should be public after all. That isn’t laziness but the heart of the matter. An opinionated interface says: these points are decided, and decided this way. If you need a different opinion, you shouldn’t thread it through a parameter but take a different construct – or write your own.

To be honest, the project is a work in progress, a building block from my own workshop and not a polished product. But that is exactly why it works as illustrative material: the question of which knobs an infrastructure API leaves free comes up with a small construct just as it does with a large platform – except that here, you can still discuss it during a coffee break.

A look inside#

Inside, exactly what used to be in the template happens – just once, named and with defaults you can read in a code review. With the CDK v1 building blocks, the core can be sketched like this:

const originAccessIdentity = new cloudfront.OriginAccessIdentity(this, 'WebsiteOAI');

const websiteBucket = new s3.Bucket(this, 'WebsiteBucket', {
  blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
});
websiteBucket.grantRead(originAccessIdentity);

const certificate = new acm.DnsValidatedCertificate(this, 'WebsiteCertificate', {
  domainName: props.domainName,
  hostedZone: props.hostedZone,
  region: 'us-east-1', // CloudFront accepts ACM certificates from us-east-1 only
});

const distribution = new cloudfront.Distribution(this, 'WebsiteDistribution', {
  defaultBehavior: {
    origin: new origins.S3Origin(websiteBucket, { originAccessIdentity }),
    viewerProtocolPolicy: cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
  },
  domainNames: [props.domainName],
  certificate,
  defaultRootObject: 'index.html',
});

new route53.ARecord(this, 'WebsiteAliasRecord', {
  zone: props.hostedZone,
  recordName: props.domainName,
  target: route53.RecordTarget.fromAlias(new targets.CloudFrontTarget(distribution)),
});

I find three details remarkable here, because they show what an L2/L3 cut actually achieves compared to raw CloudFormation.

First: websiteBucket.grantRead(originAccessIdentity) is one line. Behind it is the complete bucket policy with the OAI’s canonical principal – a piece of JSON that, back in template days, I regularly copied from the last project, including the opportunity to drag something along in the process. The method expresses the intent (“this identity may read”), not the mechanism.

Second: DnsValidatedCertificate with an explicit region: 'us-east-1'. CloudFront only accepts certificates from this one region, no matter where the rest of the stack lives. If you overlook this the first time, the deployment gives you an error message that points to the certificate but not to the cause – that happened to me back then with a certificate in eu-central-1, and the search cost half an afternoon. In the construct, this stumbling block is now a commented line. A colleague pointed at exactly that in a review and asked why the region is hardwired – and that very conversation is the point: the rule now lives in one place where you can discuss it, instead of being copied implicitly right or wrong in three projects.

Third: the alias record is created in the same go as the distribution. In the template world, DNS entries were often the manual leftover, “we’ll do that later in the console” – and three months later, nobody knew why the staging environment pointed to a deleted distribution. When the record is part of the same building block, that leftover doesn’t exist.

Defaults are opinion, not magic#

The usual objection to such building blocks is: abstraction hides what happens, and in the cloud, hidden quickly means expensive or insecure. The objection hits bad constructs, but it doesn’t hit the principle. The difference lies in whether the defaults are implicit or explicit.

A copied template has defaults too – they just aren’t called that. They are whatever the author of the first template considered right two years ago, spread across 280 lines, without a name and without a reason. A construct, on the other hand, forces a decision: What is fixed? What is a parameter? What is deliberately not provided for? Answering these three questions cleanly once cost me more time when building the construct than the actual wiring – and it was the better-invested time.

For the CDN building block, the fixed opinions are, for example: the bucket is private, always. Delivery happens exclusively via CloudFront, always over HTTPS. The certificate is validated via DNS and lives where CloudFront demands it. What stays free are the domain, the namespace and the path to the build output – exactly the things that actually distinguish two projects. Opening up everything else would only shift the repetition: if you pass twenty parameters through, you end up with CloudFormation again, just with different brackets.

There is a limit here that I underestimated at first: a construct is an API, and infrastructure APIs have stricter compatibility rules than library APIs. If I rename a class in a library, builds break. If I change the structure in a construct, the logical IDs of the resources may change – and CloudFormation then replaces things instead of changing them. With an S3 bucket that has content, that isn’t a theoretical concern. Versioning a construct therefore doesn’t just mean assigning semantic version numbers, but keeping track of which changes trigger a replacement. That isn’t in any type system, and that is exactly why it belongs in the building block’s opinion.

When a custom construct pays off#

You don’t have to build this wheel yourself. The AWS Solutions Constructs cover the “CloudFront to S3” pattern, and for many teams that is the right choice. In my view, a custom construct pays off when the opinion you want to encapsulate is more specific than that of a generic building block: your own naming conventions, a fixed deploy convention via environment variables, a specific error behavior for single-page applications, the in-house tagging requirement. In other words, whenever you notice that you readjust the generic building block in every project with the same five tweaks – then those five tweaks are the actual construct.

The process to get there follows a simple flow that you can also read as a cycle:

flowchart TD
  A[Wiring in the project<br/>typed for the second time] --> B[Name decisions:<br/>fixed, parameter, excluded]
  B --> C[Extract construct<br/>with minimal prop surface]
  C --> D[Use it in two projects]
  D --> E{Readjusted?}
  E -->|yes, always the same| B
  E -->|no| F[Opinion holds]

The order matters: first experience the repetition, then extract. A construct created before the second project doesn’t encapsulate experience but a guess – and you recognize guesses with twenty parameters by the fact that they don’t dare to commit to anything.

Conversely: not every repetition deserves an abstraction. Two similar stacks are cheaper than a bad shared construct that grows a switch with every deviation. The honest question is whether the opinion is stable. For “static website behind CloudFront”, I’m sure of that by now – the pattern hasn’t moved across several projects; only the domains and build directories have changed. That is exactly the profile where the extraction pays for itself.

The bottom line#

280 lines in two regions become one import, one constructor call and five environment variables. That calculation is real, but it isn’t the actual return. The actual return is that the infrastructure decision now has an address. When someone asks why the bucket is private, why the certificate lives in us-east-1 or why there is no TTL switch, the answer points to a place in the code – with a name, a comment and Git history. Before, it pointed to a template that was copied somewhere at some point.

For a long time, I treated infrastructure as something you describe and application code as something you design. The CDK removes this separation, and a small construct of your own is the point where you really feel it: suddenly the familiar questions of API design – what is public, what is a default, what is excluded, what breaks with a change – apply to buckets and distributions just as they do to classes and modules. Building a small infrastructure API is therefore less a DevOps topic than an entirely normal design exercise. Except that here, a bad default doesn’t end in an exception but in a bill or a public bucket.

Further reading#

Revised and translated from German with the help of AI.