Skip to content

Zero to Zipwyn: Building a Production Ready Serverless API on AWS with Terraform

Build a serverless REST API with AWS API Gateway, Lambda, DynamoDB, CloudWatch, and IAM using Terraform. Explore Zipwyn’s architecture, security, monitoring, and local development.

Author
Navinda Chandrasiri
Published
Reading time
13 min read
Topics
AWSServerlessTerraformAPI GatewayLambdaDynamoDBCloudWatchIAMNode.js
Zero to Zipwyn: Building a Production Ready Serverless API on AWS with Terraform
On this page

Servers are a liability. Every one you run needs patching, scaling, monitoring and paying for, even at 3 a.m. when nobody is using your app. For a small service with spiky traffic, that is a lot of overhead for very little value.

So when I rebuilt the backend of Zipwyn, my short-link service, I made a rule: no servers, no clicking around the AWS console, and nothing that cannot be recreated from a Git repository.

This blog walks through exactly how I did it. You will build a serverless API with:

  • Amazon API Gateway (HTTP API) as the front door
  • AWS Lambda (Node.js) for the logic
  • Amazon DynamoDB for storage
  • Amazon CloudWatch for logs and alarms
  • AWS IAM with least-privilege roles
  • Terraform to define all of it as code

Every snippet comes from the real project, trimmed for readability. By the end you will have a pattern you can reuse for almost any small API.

What we are building#

Zipwyn turns long URLs into short links and counts every click. The API is small on purpose:

  • POST /urls creates a short link
  • GET /urls lists links, with pagination
  • GET /urls/{shortCode}/stats returns the click count
  • GET /{shortCode} redirects the visitor to the destination

The Architecture#

Here is the big picture:

Architecture diagram: Building a Production Ready Serverless API on AWS with Terraform

Notice there are two APIs, not one. The redirect endpoint is public and takes all the traffic. The management endpoints are used by my web app. Keeping them separate gives each its own domain, throttling and access logs, and it means the public domain simply does not have a route to the management functions. Less surface area, fewer surprises.

Why this stack?#

  • HTTP API over REST API. HTTP APIs are cheaper and faster, and they cover everything a Lambda-backed API needs: routes, CORS, throttling, custom domains and access logs. Choose REST APIs only if you need features such as API keys with usage plans or request validation at the gateway.
  • DynamoDB on-demand. There is no capacity to plan. You pay per request, and it scales from zero to a lot. A short-link lookup is a perfect key-value access pattern.
  • Lambda on arm64. Graviton functions are cheaper per millisecond, and plain JavaScript runs on them without changes.
  • Terraform. Declarative, reviewable infrastructure. A pull request can show you exactly what will change before it does.

Project layout#

text
zipwyn-serverless/
├── src/
│   ├── lambda/             # one file per function (the deployed handlers)
│   └── lib/                # shared code: validation, DynamoDB client, HTTP helpers
├── infra/terraform/        # all infrastructure
│   └── modules/http-api/
├── scripts/                # local dev server
└── test/                   # unit tests

Separating src/lambda (entry points) from src/lib (shared code) keeps handlers short and makes the logic easy to test.

Step 1: The DynamoDB table#

Start with the data, because everything else depends on it.

hcl
resource "aws_dynamodb_table" "urls" {
  name         = var.dynamodb_table_name
  billing_mode = "PAY_PER_REQUEST"
  hash_key     = "shortCode"
 
  attribute {
    name = "shortCode"
    type = "S"
  }
 
  point_in_time_recovery {
    enabled = true
  }
 
  deletion_protection_enabled = var.dynamodb_deletion_protection
}

A few deliberate choices here:

  • The partition key is the short code itself, so a redirect is a single-item lookup. That is the fastest, cheapest thing DynamoDB does.
  • Point-in-time recovery lets you restore the table to any second in the last 35 days. It costs very little and saves you from the worst kind of mistake.
  • Deletion protection means a careless terraform destroy cannot wipe production data.

Step 2: Write the handlers#

Before wiring anything together, let us look at the code that actually runs. The most interesting function is the redirect.

The redirect, in a single database call#

A naive implementation reads the item, redirects, then updates the click counter afterwards. That is two round trips, and if the second one is fire-and-forget, Lambda may freeze before it completes and you silently lose clicks.

Instead, one conditional UpdateItem does both jobs atomically: it increments the counter and returns the destination.

js
import { UpdateCommand } from '@aws-sdk/lib-dynamodb';
 
export const handler = async (event) => {
  const shortCode = event.pathParameters?.shortCode;
 
  try {
    const { Attributes } = await docClient.send(
      new UpdateCommand({
        TableName: getTableName(),
        Key: { shortCode },
        UpdateExpression: 'SET clicks = if_not_exists(clicks, :zero) + :inc',
        ConditionExpression: 'attribute_exists(shortCode)',
        ExpressionAttributeValues: { ':inc': 1, ':zero': 0 },
        ReturnValues: 'ALL_NEW',
      }),
    );
 
    return {
      statusCode: 302,
      headers: {
        Location: Attributes.originalUrl,
        'Cache-Control': 'no-cache, no-store, must-revalidate',
      },
    };
  } catch (error) {
    if (error.name === 'ConditionalCheckFailedException') {
      return notFoundPage();
    }
    // ...fall back to a plain lookup so links keep working if counting fails
  }
};

What this buys you:

  • One round trip instead of two.
  • No lost clicks. The increment is atomic and finishes before the response is sent.
  • No ghost records. attribute_exists(shortCode) makes unknown codes fail with a 404 instead of creating an item.
  • Accurate counts. The no-store header stops browsers and proxies from caching the redirect and skipping your function.

Create: validate hard, write conditionally#

Anyone can send anything to a public endpoint, so validate on the way in. The key rule for a redirect service: only allow http and https destinations. Otherwise someone can create a link to javascript: or data: URLs.

js
export const validateTargetUrl = (value, { blockedHosts = [] } = {}) => {
  if (typeof value !== 'string' || value.trim() === '') {
    return { error: 'URL is required' };
  }
 
  let parsed;
  try {
    parsed = new URL(value.trim());
  } catch {
    return { error: 'Invalid URL format' };
  }
 
  if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
    return { error: 'Only http and https URLs are allowed' };
  }
  if (parsed.username || parsed.password) {
    return { error: 'URLs containing credentials are not allowed' };
  }
  if (blockedHosts.includes(parsed.host.toLowerCase())) {
    return { error: 'Links cannot point back to the service itself' };
  }
 
  return { url: parsed.href };
};

Then write with a condition, so two requests can never claim the same code:

js
await docClient.send(
  new PutCommand({
    TableName: getTableName(),
    Item: { shortCode, originalUrl, createdAt: Date.now(), clicks: 0 },
    ConditionExpression: 'attribute_not_exists(shortCode)',
  }),
);

For custom codes, a ConditionalCheckFailedException becomes a 409 Conflict. For random codes, the handler simply retries with a new code. Generate those codes with crypto.randomInt, not Math.random(), so they are not guessable.

Tip: The AWS SDK v3 is already included in the Lambda Node.js runtime. My deployment package is only about 17 KB with no node_modules, which makes deployments and cold starts fast.

Step 3: Least-privilege IAM#

This is the step people skip, and it matters most for security. The lazy approach gives every function one shared role with broad DynamoDB access. If any function is compromised or buggy, it can do anything.

Instead, give each function its own role with exactly the actions it needs. Describe the functions once in a map:

hcl
locals {
  functions = {
    create-url = {
      handler          = "lambda/createUrl.handler"
      api              = "management"
      route            = "POST /urls"
      dynamodb_actions = ["dynamodb:PutItem"]
    }
    list-urls = {
      handler          = "lambda/listUrls.handler"
      api              = "management"
      route            = "GET /urls"
      dynamodb_actions = ["dynamodb:Scan"]
    }
    get-stats = {
      handler          = "lambda/getStats.handler"
      api              = "management"
      route            = "GET /urls/{shortCode}/stats"
      dynamodb_actions = ["dynamodb:GetItem"]
    }
    redirect = {
      handler          = "lambda/redirect.handler"
      api              = "redirect"
      route            = "GET /{shortCode}"
      dynamodb_actions = ["dynamodb:UpdateItem", "dynamodb:GetItem"]
    }
  }
}

Then for_each over that map to build a role and policies for every function:

hcl
resource "aws_iam_role" "lambda" {
  for_each = local.functions
 
  name               = "${local.name_prefix}-${each.key}-role"
  assume_role_policy = data.aws_iam_policy_document.lambda_assume.json
}
 
resource "aws_iam_role_policy" "dynamodb" {
  for_each = local.functions
 
  name = "dynamodb-access"
  role = aws_iam_role.lambda[each.key].id
 
  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Effect   = "Allow"
      Action   = each.value.dynamodb_actions
      Resource = aws_dynamodb_table.urls.arn
    }]
  })
}

The create-url function can only PutItem. The list-urls function can only Scan. Neither can delete anything, and neither can touch any other table. Adding a new function later is one entry in the map.

Logging permissions are scoped the same way: each function may write only to its own log group, which brings us to the functions themselves.

Step 4: Lambda functions and CloudWatch logs#

One zip file contains all handlers, and every function points at a different handler inside it:

hcl
data "archive_file" "lambda" {
  type        = "zip"
  source_dir  = "${path.module}/../../src"
  output_path = "${path.module}/zipwyn-lambda.zip"
}
 
resource "aws_cloudwatch_log_group" "lambda" {
  for_each = local.functions
 
  name              = "/aws/lambda/${local.name_prefix}-${each.key}"
  retention_in_days = var.log_retention_days
}
 
resource "aws_lambda_function" "this" {
  for_each = local.functions
 
  function_name    = "${local.name_prefix}-${each.key}"
  role             = aws_iam_role.lambda[each.key].arn
  runtime          = "nodejs24.x"
  architectures    = ["arm64"]
  handler          = each.value.handler
  filename         = data.archive_file.lambda.output_path
  source_code_hash = data.archive_file.lambda.output_base64sha256
  memory_size      = 256
  timeout          = 10
 
  environment {
    variables = {
      URLS_TABLE = aws_dynamodb_table.urls.name
      BASE_URL   = local.base_url
    }
  }
 
  logging_config {
    log_format = "JSON"
    log_group  = aws_cloudwatch_log_group.lambda[each.key].name
  }
}

Two details worth copying:

  1. Create the log groups yourself. If you let Lambda create them, they never expire and cost grows quietly forever. Owning them in Terraform means you set retention (30 days here) and you can scope IAM to the exact group.
  2. Use JSON logging. With log_format = "JSON", console.log and console.error output becomes structured records you can filter in CloudWatch Logs Insights.

When the zip contents change, source_code_hash changes, and Terraform updates the functions. Deploying code is just terraform apply.

Step 5: API Gateway as a reusable module#

Because I have two APIs with the same shape, I wrote the HTTP API once as a module and called it twice. The core of it:

hcl
resource "aws_apigatewayv2_api" "this" {
  name          = var.name
  protocol_type = "HTTP"
 
  dynamic "cors_configuration" {
    for_each = var.cors == null ? [] : [var.cors]
    content {
      allow_origins = cors_configuration.value.allow_origins
      allow_methods = cors_configuration.value.allow_methods
      allow_headers = cors_configuration.value.allow_headers
    }
  }
}
 
resource "aws_apigatewayv2_integration" "this" {
  for_each = var.routes
 
  api_id                 = aws_apigatewayv2_api.this.id
  integration_type       = "AWS_PROXY"
  integration_uri        = each.value.lambda_invoke_arn
  payload_format_version = "2.0"
}
 
resource "aws_apigatewayv2_route" "this" {
  for_each = var.routes
 
  api_id    = aws_apigatewayv2_api.this.id
  route_key = each.value.route_key
  target    = "integrations/${aws_apigatewayv2_integration.this[each.key].id}"
}
 
resource "aws_lambda_permission" "invoke" {
  for_each = var.routes
 
  statement_id  = "AllowInvokeFromHttpApi-${each.key}"
  action        = "lambda:InvokeFunction"
  function_name = each.value.lambda_name
  principal     = "apigateway.amazonaws.com"
  source_arn    = "${aws_apigatewayv2_api.this.execution_arn}/*/*"
}

The aws_lambda_permission is the piece beginners forget. Without it, API Gateway has the route and the integration but is not allowed to invoke your function, and you get a confusing 500 or Internal Server Error.

The stage adds throttling and access logs, which protect you from abuse and runaway bills:

hcl
resource "aws_apigatewayv2_stage" "default" {
  api_id      = aws_apigatewayv2_api.this.id
  name        = "$default"
  auto_deploy = true
 
  default_route_settings {
    throttling_rate_limit  = var.throttling_rate_limit
    throttling_burst_limit = var.throttling_burst_limit
  }
 
  access_log_settings {
    destination_arn = aws_cloudwatch_log_group.access.arn
    format = jsonencode({
      requestId = "$context.requestId"
      routeKey  = "$context.routeKey"
      status    = "$context.status"
      latency   = "$context.responseLatency"
    })
  }
}

Handle CORS at the gateway, not in your Lambda code. API Gateway answers preflight requests itself, so your functions stay focused on business logic.

Step 6: A custom domain with ACM (even when DNS is manual)#

Nobody wants to share an execute-api URL. For a custom domain you need an ACM certificate and an API Gateway domain name. The catch: my DNS lives at a registrar (Name.com) that Terraform cannot manage. With Route 53 this is fully automatic, but with an external DNS provider, you have to pause for a manual step.

I handle that with a simple two-phase flag:

hcl
resource "aws_acm_certificate" "this" {
  domain_name               = local.certificate_domains[0]
  subject_alternative_names = slice(local.certificate_domains, 1, length(local.certificate_domains))
  validation_method         = "DNS"
 
  lifecycle {
    create_before_destroy = true
  }
}
 
resource "aws_acm_certificate_validation" "this" {
  count = var.enable_custom_domains ? 1 : 0
 
  certificate_arn = aws_acm_certificate.this.arn
}

The workflow:

  1. Apply with enable_custom_domains = false. Terraform creates everything and requests the certificate.
  2. Add the validation CNAMEs at your DNS provider. A Terraform output prints them, ready to copy.
  3. Set enable_custom_domains = true and apply again. Terraform waits for the certificate to be issued, then creates the custom domains.
  4. Add two more CNAMEs pointing your subdomains at the API Gateway domain names, which another output prints.

Four DNS records, two applies, and no clicking in the console. One gotcha: for a regional API Gateway domain, the certificate must live in the same region as the API, unlike CloudFront, which needs us-east-1.

Step 7: Know when it breaks, with CloudWatch alarms#

Logs are for debugging. Alarms are for knowing you need to. Here is a pair that covers most failures:

hcl
resource "aws_cloudwatch_metric_alarm" "lambda_errors" {
  for_each = local.functions
 
  alarm_name          = "${local.name_prefix}-${each.key}-errors"
  namespace           = "AWS/Lambda"
  metric_name         = "Errors"
  statistic           = "Sum"
  period              = 300
  evaluation_periods  = 1
  threshold           = 1
  comparison_operator = "GreaterThanOrEqualToThreshold"
  treat_missing_data  = "notBreaching"
  alarm_actions       = [aws_sns_topic.alarms.arn]
 
  dimensions = {
    FunctionName = aws_lambda_function.this[each.key].function_name
  }
}

Alongside it sits an alarm on the API's 5xx metric. You need both, and here is why: my handlers catch their own errors and return a clean 500 response. From Lambda's point of view that is a success, so the Errors metric stays at zero. The API Gateway 5xx alarm catches exactly those handled failures.

I made alarms optional behind an alarm_email variable. Remember to confirm the SNS subscription email, or you will never be notified.

Run it locally, with the same code#

Deploying to test every change is slow. I wanted pnpm run dev and a working API on my laptop, using the exact same handlers that ship to AWS.

The trick: a Lambda handler is just a function that receives an event object. API Gateway HTTP APIs send a predictable event shape (payload format 2.0), so a small Node server can build that event from an incoming HTTP request, call the handler, and turn the returned object into a response.

Pair it with DynamoDB Local in Docker:

yaml
services:
  dynamodb-local:
    image: amazon/dynamodb-local:latest
    command: ["-jar", "DynamoDBLocal.jar", "-sharedDb", "-dbPath", "/home/dynamodblocal/data"]
    user: root
    ports:
      - "8000:8000"
    volumes:
      - zipwyn-dynamodb-data:/home/dynamodblocal/data

The only code difference between local and AWS is one environment variable in the DynamoDB client:

js
const endpoint = process.env.DYNAMODB_ENDPOINT;
 
export const dynamoClient = new DynamoDBClient(endpoint ? { endpoint } : {});

Then:

bash
pnpm run db:start   # DynamoDB Local
pnpm run dev        # API on http://localhost:3001
 
curl -X POST http://localhost:3001/urls \
  -H "Content-Type: application/json" \
  -d '{"url": "https://example.com/a/very/long/path", "customCode": "docs"}'
 
curl -i http://localhost:3001/docs   # 302 redirect

The dev server also creates the tables on startup and mimics CORS, so a frontend running on localhost:3000 just works.

Test without AWS#

Handlers import a shared docClient, so tests can swap its send method for an in-memory fake and check real behaviour: redirects increment the counter once, unknown codes create nothing, duplicate custom codes return 409, bad schemes return 400. Node's built-in node:test runner is enough. No extra frameworks.

Deploying it#

With the pieces in place, the whole deployment is a few commands:

bash
cd infra/terraform
 
terraform init -backend-config=backend.hcl   # remote state in S3
terraform plan -out=tfplan                   # review exactly what will change
terraform apply tfplan

Store state in an S3 bucket with versioning and encryption turned on, and enable native state locking. State is the one thing you cannot afford to lose or corrupt.

Lessons learned and gotchas#

A few things worth knowing before you build your own:

  • Secrets and for_each do not mix. Terraform refuses to use a map containing sensitive values as a for_each source. Keep the secret out of the map and inject it inside the resource body instead.
  • Own your log groups. Pre-create them with a retention period, and scope IAM to them.
  • Never cache a counting redirect. Cache-Control: no-store is what keeps the click counter honest.
  • Separate public and private surfaces. Two small APIs beat one big API with careful routing.
  • Use terraform plan as a code review. Read the plan every time, especially anything marked "must be replaced".
  • Validate Terraform in CI. terraform fmt -check and terraform validate on every pull request catch most mistakes early.
  • Know the cost shape. There is no idle server, so a quiet service costs close to nothing. Throttling on the API is your safety net against surprise bills. Always check current AWS pricing for your region.

What I would add next#

This is a solid foundation, but a real product keeps growing. On my list:

  • A per-user index so listing links is a query instead of a table scan
  • JWT or IAM authorization instead of a shared key
  • AWS WAF in front of the public API
  • CI/CD deploys from GitHub Actions using OIDC, so there are no long-lived AWS keys anywhere
  • Richer analytics, such as referrer and country per click, streamed rather than counted inline

Wrapping up#

A serverless API is not just "a Lambda behind a URL". The difference between a demo and something you can trust is everything around the function: least-privilege roles, structured logs, throttling, alarms, backups, repeatable infrastructure and a fast local loop.

The good news is that once you have this skeleton, it barely changes between projects. Swap the handlers and the table schema, and you have your next API.

If you build something with this pattern, I would love to hear about it. And if something here is unclear, reach out and I will happily improve the blog.

Happy building!

Portrait of Navinda Chandrasiri

Written by Navinda Chandrasiri

Senior Software Engineer in Colombo, Sri Lanka, building cloud-native web applications and AI systems.

See my portfolio

ShareLinkedInX

  1. Before the First Server: Designing a Production Ready AWS VPC from Scratch with Terraform

    Build a production ready AWS VPC with Terraform, covering multi-AZ subnets, route tables, NAT and internet gateways, security groups, NACLs, VPC endpoints, and flow logs.

    AWSVPCTerraformNetworking

    20 min read
  2. From git push to Global CDN: Hosting a Secure Next.js Static Site on S3 and CloudFront with Terraform and CodePipeline

    Learn to host a Next.js static export on a private S3 bucket with CloudFront, a custom domain, HTTPS, security headers, and automated GitHub to CodePipeline deployments using Terraform.

    AWSTerraformCloudFrontS3

    12 min read
  3. Zero Servers, One Bucket: Deploying a Next.js Static Site to Amazon S3 with Terraform and CodePipeline

    Host a Next.js static export on Amazon S3 website hosting and automate every deployment from GitHub using AWS CodePipeline, CodeBuild, and Terraform, with the trade-offs explained honestly.

    AWSTerraformS3CodePipeline

    12 min read