Subscribe

A serverless API in Go with Lambda, API Gateway and DynamoDB

shorty, the Go URL shortener from this series, rebuilt as one Lambda function on provided.al2023 behind an API Gateway HTTP API with a DynamoDB table. Tested locally with the Lambda emulator, deployed with Terraform, and costed against ECS in Mumbai.

A serverless API in Go with Lambda, API Gateway and DynamoDB

shorty, the URL shortener this tutorial series keeps building, runs as a container with Postgres and Redis next to it. That's quite a lot of always-on machinery for an app that might get a few hundred clicks a day. So in this blog we will take the same API and run it as a Lambda function behind an API Gateway HTTP API, with a DynamoDB table instead of Postgres, and then do the sums against ECS.

Level is intermediate. You should know a bit of Go and Terraform, and it helps to have read Designing a URL shortener from requirements to scale and Building a REST API in Go with only the standard library. I used Go 1.27.3, aws-lambda-go v1.55.1, aws-sdk-go-v2 (service/dynamodb v1.74.1), Terraform 1.17.1 with AWS provider 6.73.0, and the Lambda Runtime Interface Emulator v1.38. I did not deploy this to a real account. Everything ran on my Mac, against DynamoDB Local in Docker, and the Terraform is validated only.

What changes and what stays

The endpoints stay exactly the same as the container version, so any client written for shorty keeps working.

POST   /links            create, 201 / 409 / 422 / 400
GET    /links/{code}     JSON with clicks
DELETE /links/{code}     204 / 404
GET    /{code}           302 redirect, counts a click
GET    /healthz          200

/readyz is gone. There is no load balancer asking "can you take traffic?" anymore, Lambda decides that. The env vars I kept are BASE_URL and LOG_LEVEL, and there's one new one, TABLE_NAME. DATABASE_URL, REDIS_URL, CACHE_TTL, DB_MAX_CONNS and CLICK_FLUSH_INTERVAL all disappear, and the last one is the interesting loss. I'll get to it.

I went with one function for all five routes. You can do one function per route, and some people like that because the redirect can get its own memory size and concurrency limit. For an app this small, I'd rather have one binary, one log group and one thing to deploy.

The table

The table uses generic key names, PK and SK, with a type prefix in the value. A link is one item with PK = LINK#<code> and SK = META. This is the single-table layout, and it leaves room to add daily click counters or a user's links in the same table later without a migration.

PK              SK      code     url                 clicks  created_at
LINK#golang     META    golang   https://go.dev/     2       2026-11-19T07:35:01Z

Creating a link is a PutItem with attribute_not_exists(PK), which is DynamoDB's version of a unique constraint. A taken code comes back as ConditionalCheckFailedException and the handler turns that into a 409.

The redirect is where I spent the most thought. The container shorty counts clicks in memory and writes them to Postgres every five seconds. A Lambda function can't do that. It may be frozen right after it returns, and there's no background goroutine you can trust to flush later. So every click has to be written during the request itself. I do the read and the write in one call.

// Resolve counts a click and returns the long URL in one UpdateItem call.
// The condition stops it from creating an item for an unknown code.
func (s *Store) Resolve(ctx context.Context, code string) (string, error) {
    out, err := s.db.UpdateItem(ctx, &dynamodb.UpdateItemInput{
        TableName:           aws.String(s.table),
        Key:                 key(code),
        UpdateExpression:    aws.String("ADD clicks :one"),
        ConditionExpression: aws.String("attribute_exists(PK)"),
        ExpressionAttributeValues: map[string]types.AttributeValue{
            ":one": &types.AttributeValueMemberN{Value: "1"},
        },
        ReturnValues: types.ReturnValueAllNew,
    })
    if isConditionFailed(err) {
        return "", ErrNotFound
    }
    if err != nil {
        return "", err
    }
    u, ok := out.Attributes["url"].(*types.AttributeValueMemberS)
    if !ok {
        return "", errors.New("link item has no url")
    }
    return u.Value, nil
}

ReturnValues: ALL_NEW hands back the whole item after the update, so the URL comes for free. Without the condition, ADD on a code that doesn't exist would happily create a new item with only clicks = 1 in it, and that junk item would then make the code look taken. The store test checks that a Get on unknown code is still a 404 after resolving it.

My first draft of this function also had an ExpressionAttributeNames entry for url that nothing used. DynamoDB rejects a request with an unused name, so I took it out before it ever ran. Small thing, but it's an error you only see at runtime.

The handler

API Gateway sends payload format 2.0 events. The handy field is RouteKey, it holds the route that matched, like GET /links/{code}, and the path parameter is already pulled out. So there's no router in the Go code at all, just a switch.

func (h *Handler) Handle(ctx context.Context, req Request) (Response, error) {
    code := req.PathParameters["code"]
    switch req.RouteKey {
    case "GET /healthz":
        return jsonResp(http.StatusOK, map[string]string{"status": "ok"}), nil
    case "POST /links":
        return h.create(ctx, req), nil
    case "GET /links/{code}":
        l, err := h.Links.Get(ctx, code)
        if err != nil {
            return h.fail(ctx, err), nil
        }
        return jsonResp(http.StatusOK, h.toResponse(req, l)), nil
    case "DELETE /links/{code}":
        if err := h.Links.Delete(ctx, code); err != nil {
            return h.fail(ctx, err), nil
        }
        return Response{StatusCode: http.StatusNoContent}, nil
    case "GET /{code}":
        target, err := h.Links.Resolve(ctx, code)
        if err != nil {
            return h.fail(ctx, err), nil
        }
        return Response{StatusCode: http.StatusFound, Headers: map[string]string{
            "Location":      target,
            "Cache-Control": "private, max-age=0",
        }}, nil
    }
    return errResp(http.StatusNotFound, "no such route"), nil
}

Notice the handler never returns a Go error. If it did, API Gateway would answer with a bare 500 and the client would never see the JSON error body. Errors become responses here, and only real failures get logged.

The code validation (3 to 32 characters, reserved words like links and healthz) is shorty's shortcode package copied over. I couldn't import it, it lives under internal/ in another module, and Go doesn't allow that.

main does the expensive work once, outside the handler.

func main() {
    level := slog.LevelInfo
    _ = level.UnmarshalText([]byte(os.Getenv("LOG_LEVEL")))
    log := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: level}))

    // Everything here runs once per cold start (the INIT phase).
    // Warm invocations reuse the client and its connections.
    cfg, err := config.LoadDefaultConfig(context.Background())
    if err != nil {
        log.Error("aws config", "err", err)
        os.Exit(1)
    }
    db := dynamodb.NewFromConfig(cfg, func(o *dynamodb.Options) {
        if ep := os.Getenv("DDB_ENDPOINT"); ep != "" { // dynamodb-local, for testing only
            o.BaseEndpoint = aws.String(ep)
        }
    })

    h := &api.Handler{
        Links:   store.New(db, os.Getenv("TABLE_NAME")),
        BaseURL: os.Getenv("BASE_URL"),
        Log:     log,
        Now:     time.Now,
    }
    lambda.Start(h.Handle)
}

Building for provided.al2023

There's no Go managed runtime anymore, Go functions run on the OS-only runtime provided.al2023. Lambda runs a file called bootstrap from the zip, and that's your binary.

GOOS=linux GOARCH=arm64 CGO_ENABLED=0 \
  go build -tags lambda.norpc -trimpath -ldflags="-s -w" \
  -o build/bootstrap ./cmd/shorty-lambda
cd build && zip shorty.zip bootstrap

The lambda.norpc tag drops the old RPC mode that only the retired go1.x runtime needed. Without the strip flags the binary was 21 MB. With them it was 10.3 MB, and 3.8 MB zipped. Smaller zip, less to download on cold start.

Running it locally with the emulator

Unit tests run the handler against an in-memory fake, and one store test runs against DynamoDB Local. Both passed. But I wanted to see the real bootstrap binary talk the Lambda runtime API, so I ran it under the Runtime Interface Emulator inside a plain debian:trixie-slim container. The RIE is a single static binary from AWS's GitHub releases, so there's no special image to pull.

curl -sLo aws-lambda-rie-arm64 \
  https://github.com/aws/aws-lambda-runtime-interface-emulator/releases/download/v1.38/aws-lambda-rie-arm64
chmod +x aws-lambda-rie-arm64

docker network create shorty-net
docker run -d --rm --name ddb --network shorty-net -p 127.0.0.1:18011:8000 \
  amazon/dynamodb-local:latest -jar DynamoDBLocal.jar -inMemory
DDB_ENDPOINT=http://127.0.0.1:18011 TABLE_NAME=shorty go run ./cmd/localtable

docker run -d --rm --name rie --network shorty-net -p 127.0.0.1:19011:8080 \
  -v "$PWD/aws-lambda-rie-arm64:/usr/local/bin/aws-lambda-rie:ro" \
  -v "$PWD/build/bootstrap:/var/runtime/bootstrap:ro" \
  -e TABLE_NAME=shorty -e DDB_ENDPOINT=http://ddb:8000 -e AWS_REGION=ap-south-1 \
  -e AWS_ACCESS_KEY_ID=local -e AWS_SECRET_ACCESS_KEY=local \
  debian:trixie-slim /usr/local/bin/aws-lambda-rie /var/runtime/bootstrap

The fake keys are for DynamoDB Local only, it accepts anything. Then I posted sample HTTP API events at it. The events/ folder in the code has one per route.

curl -s -d @events/post-links.json \
  http://127.0.0.1:19011/2015-03-31/functions/function/invocations
{"statusCode":201,"headers":{"Content-Type":"application/json","Location":"/links/golang"},...}
{"statusCode":302,"headers":{"Cache-Control":"private, max-age=0","Location":"https://go.dev/"},...}
{"statusCode":302,...}
{"statusCode":200,...,"body":"{\"code\":\"golang\",...,\"clicks\":2,...}"}
{"statusCode":409,...,"body":"{\"error\":\"code already taken\"}"}

Two redirects, two clicks, and the second create of golang got its 409. And the emulator log had the part I actually wanted.

INIT REPORT(durationMs: 21.659000)
REPORT ... Duration: 20.86 ms  Billed Duration: 21 ms  Memory Size: 3008 MB
REPORT ... Duration: 9.01 ms   Billed Duration: 10 ms
REPORT ... Duration: 3.55 ms   Billed Duration: 4 ms

Don't read too much into these. It's my laptop, DynamoDB is a container next door, and the emulator reports 3008 MB because it doesn't limit memory at all. But the shape is right: one init, a slower first call while connections open, then warm calls in single digit milliseconds.

Cold starts

A cold start is Lambda creating a new execution environment: download the zip, start the binary, run everything in main before lambda.Start. Go is one of the cheaper runtimes here since there's no VM or interpreter to boot, it's just a static binary. What you control is basically what runs in main. Keep it to building clients. No network calls, no loading a big config file from S3 on every cold start.

You'll see real numbers as Init Duration on the REPORT line in CloudWatch Logs, only on cold invocations. I can't give you numbers from AWS since I didn't deploy this, and I'd rather not quote someone else's benchmark as mine.

On cost: custom runtimes like provided.al2023 were always billed for the INIT phase, and since August 2025 AWS bills it for managed runtimes too. So a slow init now costs money on every runtime, not just latency. If cold starts really hurt, provisioned concurrency removes them, but you pay for it by the hour, which brings back exactly the always-on cost we left ECS to avoid.

The Terraform

The full file is about 150 lines, here are the parts that matter.

resource "aws_lambda_function" "shorty" {
  function_name    = local.name
  role             = aws_iam_role.lambda.arn
  runtime          = "provided.al2023"
  handler          = "bootstrap"
  architectures    = ["arm64"]
  filename         = data.archive_file.shorty.output_path
  source_code_hash = data.archive_file.shorty.output_base64sha256
  memory_size      = 256
  timeout          = 5

  environment {
    variables = {
      TABLE_NAME = aws_dynamodb_table.shorty.name
      BASE_URL   = aws_apigatewayv2_api.shorty.api_endpoint
      LOG_LEVEL  = "info"
    }
  }
}

resource "aws_apigatewayv2_integration" "shorty" {
  api_id                 = aws_apigatewayv2_api.shorty.id
  integration_type       = "AWS_PROXY"
  integration_uri        = aws_lambda_function.shorty.invoke_arn
  payload_format_version = "2.0"
}

resource "aws_apigatewayv2_route" "shorty" {
  for_each = toset([
    "GET /healthz",
    "POST /links",
    "GET /links/{code}",
    "DELETE /links/{code}",
    "GET /{code}",
  ])
  api_id    = aws_apigatewayv2_api.shorty.id
  route_key = each.value
  target    = "integrations/${aws_apigatewayv2_integration.shorty.id}"
}

resource "aws_apigatewayv2_stage" "default" {
  api_id      = aws_apigatewayv2_api.shorty.id
  name        = "$default"
  auto_deploy = true

  default_route_settings {
    throttling_burst_limit = 100
    throttling_rate_limit  = 50
  }
}

resource "aws_lambda_permission" "apigw" {
  statement_id  = "AllowHttpApiInvoke"
  action        = "lambda:InvokeFunction"
  function_name = aws_lambda_function.shorty.function_name
  principal     = "apigateway.amazonaws.com"
  source_arn    = "${aws_apigatewayv2_api.shorty.execution_arn}/*/*"
}

I was half expecting a dependency cycle from putting the API endpoint into the function's environment. There isn't one, the API resource doesn't depend on the function, only the integration does. terraform validate was happy. The throttling limits on the stage are there on purpose. A public URL shortener is an easy target, and on Lambda a flood of requests is a flood on your bill. With the stage limit, API Gateway answers 429 before any of it reaches the function.

The IAM role only gets GetItem, PutItem, UpdateItem and DeleteItem on the one table, and log writes. If you're not sure how to read a policy like that, IAM explained by writing policies walks through it.

Cost compared with ECS

Prices are from the AWS price list for Asia Pacific (Mumbai, ap-south-1), checked on 19 November 2026, on-demand, without free tier.

Item Price
HTTP API $1.05 per million requests
Lambda requests $0.20 per million
Lambda arm64 compute $0.0000133334 per GB-second
DynamoDB on-demand writes $0.71 per million write units
DynamoDB on-demand reads $0.1425 per million read units
Fargate arm64 $0.02383 per vCPU-hour, $0.00261 per GB-hour
Application Load Balancer $0.0239 per hour plus $0.008 per LCU-hour

For a million redirects a month on Lambda: $1.05 for API Gateway, $0.20 for requests, about $0.05 of compute (256 MB at around 15 ms each, my guess for a warm call in-region), and $0.71 because every redirect is one DynamoDB write. That's roughly $2 a month. See, the biggest line after API Gateway is the click counter. Each click is a write, and writes cost five times reads.

The smallest sensible ECS setup is two Fargate tasks of 0.25 vCPU and 0.5 GB on arm64 (two, so one can die) behind an ALB. That's about $10.60 for the tasks and $17.45 for the ALB hours, before LCUs, so call it $29 a month at zero traffic. And that's without Postgres and Redis, which the container shorty also needs.

Lambda and API Gateway together cost about $1.30 per million requests. So they break even with that ECS floor somewhere above 20 million requests a month, roughly 8 requests a second on average, all day. Two small Fargate tasks can serve a lot more than 8 a second, so past that point ECS gets cheaper fast. Below it, which is where most side projects live, Lambda wins easily.

I run my own blog on one t3.small, and for something with steady traffic that is still the cheapest thing. Serverless shines for spiky or tiny traffic, and for things you don't want to patch. If you want the container route instead, ECS explained is where to start.

Running the tests

go vet ./...
go test ./...
DDB_ENDPOINT=http://127.0.0.1:18011 go test -count=1 ./internal/store/
cd terraform && terraform init -backend=false && terraform validate

One last tip. Put an AWS Budgets alert on the account before you make any public Lambda URL, the way I described in Setting up a new AWS account safely. The stage throttle is a good fence, the budget alert is how you find out someone is leaning on it.