Zero-Cost API on Lambda
This page puts an HTTP API on the internet that costs nothing while nobody is calling it. Your code runs as a Lambda function, CloudFront serves it over HTTPS, and a DynamoDB table holds its data. Each of the three bills per request, so a quiet week costs you nothing beyond the few cents ECR charges to store the image.
The API here is a small orders service for a shop, with one route to save an order and one to read it back. Your own API takes its place without changing anything else on the page.
Nothing in that picture runs while it waits. There is no load balancer billing by the hour, no NAT gateway, and no container kept warm. The function URL answers only requests CloudFront has signed, so the distribution is the one way in.
The code
The function is an ordinary HTTP server in a container image. The Lambda Web Adapter sits in the image and turns each Lambda invocation into a request to that server, so the same image runs anywhere a container does.
Start a project, and put the API in a folder of its own beside octo.yaml:
npx @quadnix/octo-build create-app -n shop-api
cd shop-api
mkdir api
import { createServer } from 'node:http';
import { DynamoDBClient, GetItemCommand, PutItemCommand } from '@aws-sdk/client-dynamodb';
const client = new DynamoDBClient({});
const TableName = process.env.TABLE_NAME;
createServer(async (request, response) => {
const [, resource, orderId] = request.url.split('/');
if (resource !== 'orders' || !orderId) {
response.writeHead(404).end();
return;
}
if (request.method === 'PUT') {
let body = '';
for await (const chunk of request) body += chunk;
await client.send(new PutItemCommand({ Item: { Body: { S: body }, OrderId: { S: orderId } }, TableName }));
response.writeHead(204).end();
return;
}
const { Item } = await client.send(new GetItemCommand({ Key: { OrderId: { S: orderId } }, TableName }));
response.writeHead(Item ? 200 : 404, { 'content-type': 'application/json' }).end(Item?.Body.S ?? '');
}).listen(8080);
FROM public.ecr.aws/docker/library/node:22-alpine
COPY --from=public.ecr.aws/awsguru/aws-lambda-adapter:0.9.1 /lambda-adapter /opt/extensions/lambda-adapter
WORKDIR /app
RUN npm install --no-save @aws-sdk/client-dynamodb
COPY server.mjs ./
CMD ["node", "server.mjs"]
The code never names a credential. It runs as the function's role, and Octo gives that role exactly the access to the table you ask for below.
The definition file
Replace octo.yaml with this. The comments mark the three values that are yours.
version: 1
env:
- key: AWS_ACCOUNT_ID
kind: string
value: "123456789012" # your AWS account number
terraform:
requiredVersion: "1.6.0"
requiredProviders:
aws:
source: hashicorp/aws
minVersion: "6.28.0"
providers:
- providerType: aws
accountId: "${env.AWS_ACCOUNT_ID}"
regionId: us-east-1
spec:
profile: default # your profile in ~/.aws/credentials
settings:
listeners:
- type: JournalEventListener
- type: LoggingEventListener
stateProvider:
type: LocalStateProvider
statePath: .octo
imports:
- className: SimpleAppModule
importPath: "@quadnix/octo-aws-cdk/modules/app/simple-app"
- className: AwsIniAccountModule
importPath: "@quadnix/octo-aws-cdk/modules/account/aws-ini-account"
- className: AwsServerlessRegionModule
importPath: "@quadnix/octo-aws-cdk/modules/region/aws-serverless-region"
- className: AwsServerlessEnvironmentModule
importPath: "@quadnix/octo-aws-cdk/modules/environment/aws-serverless-environment"
- className: AwsServerlessSubnetModule
importPath: "@quadnix/octo-aws-cdk/modules/subnet/aws-serverless-subnet"
- className: AwsEcrImageModule
importPath: "@quadnix/octo-aws-cdk/modules/image/aws-ecr-image"
- className: AwsEcrImageTagModule
importPath: "@quadnix/octo-aws-cdk/modules/image/aws-ecr-image-tag"
- className: AwsDynamoDBServiceModule
importPath: "@quadnix/octo-aws-cdk/modules/service/aws-dynamodb-service"
- className: AwsServerModule
importPath: "@quadnix/octo-aws-cdk/modules/server/aws-server"
- className: AwsDeploymentModule
importPath: "@quadnix/octo-aws-cdk/modules/deployment/aws-deployment"
- className: AwsLambdaExecutionModule
importPath: "@quadnix/octo-aws-cdk/modules/execution/aws-lambda-execution"
- className: AwsCloudFrontServiceModule
importPath: "@quadnix/octo-aws-cdk/modules/service/aws-cloudfront-service"
modules:
# Where everything goes: an app, the account it deploys into, and a region with no network.
- moduleId: app-module
moduleClass: SimpleAppModule
moduleInputs:
name: shop-api
- moduleId: account-module
moduleClass: AwsIniAccountModule
moduleInputs:
accountId: "${env.AWS_ACCOUNT_ID}"
app: "${{app-module.model.app}}"
- moduleId: region-module
moduleClass: AwsServerlessRegionModule
moduleInputs:
account: "${{account-module.model.account}}"
name: api-region
regionId: aws-us-east-1
- moduleId: environment-module
moduleClass: AwsServerlessEnvironmentModule
moduleInputs:
environmentName: production
region: "${{region-module.model.region}}"
- moduleId: subnet-module
moduleClass: AwsServerlessSubnetModule
moduleInputs:
region: "${{region-module.model.region}}"
# The image: a repository, and the version of the code to build into it.
- moduleId: image-module
moduleClass: AwsEcrImageModule
moduleInputs:
imageFamily: shop
imageName: orders-api
regions:
- "${{region-module.model.region}}"
- moduleId: image-tag-module
moduleClass: AwsEcrImageTagModule
moduleInputs:
architecture: arm64
dockerfileDirectory: api
image: "${{image-module.model.image}}"
imageTag: "0.0.1"
# The data.
- moduleId: orders-table-module
moduleClass: AwsDynamoDBServiceModule
moduleInputs:
region: "${{region-module.model.region}}"
TableName: shop-orders
AttributeDefinitions:
- AttributeName: OrderId
AttributeType: S
KeySchema:
- AttributeName: OrderId
KeyType: HASH
billingMode:
type: PAY_PER_REQUEST
settings: {}
# The service: what it may reach, which code it runs, and where that code runs.
- moduleId: orders-server-module
moduleClass: AwsServerModule
moduleInputs:
account: "${{account-module.model.account}}"
serverKey: orders
dynamodb:
- access: READ_WRITE
service: "${{orders-table-module.model.service}}"
- moduleId: orders-deployment-module
moduleClass: AwsDeploymentModule
moduleInputs:
server: "${{orders-server-module.model.server}}"
deploymentTag: v1
image: "${{image-module.model.image}}"
imageTag: "0.0.1"
command: [node, server.mjs]
ports:
- containerPort: 8080
protocol: tcp
memory: 512
timeoutInSeconds: 30
- moduleId: orders-execution-module
moduleClass: AwsLambdaExecutionModule
moduleInputs:
executionId: shop-orders-api
deployment: "${{orders-deployment-module.model.deployment}}"
environment: "${{environment-module.model.environment}}"
subnet: "${{subnet-module.model.subnet}}"
environmentVariables:
TABLE_NAME: shop-orders
# The front door.
- moduleId: distribution-module
moduleClass: AwsCloudFrontServiceModule
moduleInputs:
account: "${{account-module.model.account}}"
distributionName: shop-orders-api
priceClass: PriceClass_100
origins:
- originId: orders
source: "${{orders-execution-module.model.execution}}"
routes:
- originId: orders
Most of the file reads the way you would describe the system out loud. The server is the orders service and says what it may reach, in this case read and write on one table. The deployment is one version of its code, naming the image and the port the server listens on. The execution runs that deployment as a function, and the distribution sends every request to it.
A serverless region creates nothing and has no network. It says which AWS region the table, the
image and the function go in, and it accepts a short list of regions, of which aws-us-east-1 is
one. The environment and the subnet create nothing either; they are there because an execution
always runs in an environment and a subnet.
The function name, the table name and the image name are unique in your account, and the provider
floor of 6.28.0 is the first AWS provider that can express the permissions on a function URL.
Deploy it
Docker has to be running, because the apply builds your image and pushes it to ECR.
npm run octo:generate
npm run octo:validate
npm run octo:lock
npm run octo:apply
npm run octo:commit
The report from validate lists one card per piece of intent: the table, the image, the function
with its role, URL and log group, and the distribution. The apply takes a few minutes, nearly all of
it CloudFront creating the distribution.
Find the address the distribution answers on, and call it:
aws cloudfront list-distributions --query "DistributionList.Items[].DomainName" --output text
API=https://d111111abcdef8.cloudfront.net # the domain the command above printed
BODY='{"items":["receipt-printer"]}'
curl -X PUT "$API/orders/1001" \
-H "x-amz-content-sha256: $(printf '%s' "$BODY" | sha256sum | cut -d' ' -f1)" \
--data "$BODY"
curl "$API/orders/1001"
The header on the PUT is the one thing a client of this architecture has to know. CloudFront signs
every request it forwards to the function URL, and the signature covers the body, so a request with
a body has to carry the body's SHA-256 in hex. Without it the function URL answers 403. A request
with no body, such as the GET, needs nothing.
Ship a new version
A new version of the code is a new image tag. Change imageTag in both image-tag-module and
orders-deployment-module, to 0.0.2, and run the same five commands. The apply builds and pushes
the new image before it points the function at it, so the function never names an image that does
not exist yet.
The old image stays in the repository. Each repository keeps its five newest images, and ECR
expires the older ones; imageTagsToKeep on the image module changes how many. Rolling back is
changing the tag back to 0.0.1, and since that image is still there, the apply builds nothing and
points the function at it again.
What Octo did for you
Written by hand, this stack spreads across six AWS services, and several of its pieces are easy to get subtly wrong. These are the ones Octo derived from the file above.
- The table grant.
READ_WRITEon the table became a policy on the function's role that covers the table and its indexes. A query on a global secondary index needs its own ARN,table/<name>/index/*, and is refused without it; the grant includes it, so adding an index later needs no change to the server. - The function URL's permissions. The URL requires a signed request, and the distribution signs
with an origin access control. The function admits only that distribution, through both
lambda:InvokeFunctionUrlandlambda:InvokeFunction, which AWS now requires together for a call through a URL. - The adapter's settings. The port the Web Adapter forwards to comes from the deployment's
ports, and the processor the function runs on comes from the image'sarchitecture, so the two can never disagree with the image itself. - The build and the order. The image is built and pushed as part of the apply, and the function waits for it. One run can publish a version and start the code that runs it.
- The logs. The function writes to a log group of its own,
/aws/lambda/shop-orders-api, kept for 30 days, and its role may write to that group and create no other. - The account guard. Every generated provider block carries
allowed_account_ids, so credentials for the wrong account fail the plan rather than deploying somewhere unexpected.
The report that summed it up was one card per piece of intent rather than a plan per folder, and each card holds the Terraform changes underneath it for whoever wants to read them.
Limits
A few limits come with the architecture rather than with Octo, and each one is checked before anything is created where Octo can check it.
A request through a function URL carries a body of at most 6 MB, and a response is returned whole,
up to 6 MB. Setting invokeMode: RESPONSE_STREAM on the execution streams the response instead,
which lifts that to 200 MB. CloudFront waits 60 seconds for the function to answer, so a deployment
with a longer timeoutInSeconds is refused.
A brand new account may have a Lambda concurrency limit of 10, which leaves nothing to reserve. That
only matters if you set reservedConcurrency; leave it out and nothing is reserved or capped.
Tear it down
Comment out every module after account-module, then run the lifecycle with --auto-approve on the
apply, as Destroying Infrastructure
describes. The table is listed as losing its data, because it does.