DevelopmentSystem Administration
Moving Our API from PHP on ECS to Go on Lambda
We rewrote our API in Go and moved it from PHP on ECS (nginx and php-fpm) to AWS Lambda, behind the same load balancer. The problem we set out to fix was the top of the hour: our customers' scheduled jobs all call the API at :00, and PHP slowed to a crawl every time. In the first five minutes of each hour, the 99th percentile response time fell from 1.46 seconds to 108 ms, and the 95th from 854 ms to 47 ms.
Why Was the Top of the Hour So Slow?
Traffic to the API is steady around the clock, with one exception. Cron jobs run on the hour, so the first minute of every hour brings about 28 times the requests of a normal minute, and most of them arrive within twenty seconds.

Nearly all of those requests were for responses we'd already cached in Redis, and they still took 0.3 to 0.5 seconds on average. PHP starts almost from scratch on every request: it loads its classes, reads its settings, opens a database connection, and checks the API key, about 35 ms of work before it can look in the cache. With hundreds of requests doing that at once, they all competed for the same CPUs.
Autoscaling was no help. Scaling on CPU reacts only after the load has stayed high for a while, and this spike is over in twenty seconds. We ended up adding containers on a schedule, a few minutes before every hour.
Why Go on Lambda?
Lambda solves the CPU problem by design. Each concurrent request runs in its own environment with its own CPU, so when the spike arrives, Lambda starts more environments and no request waits behind another. A typical top of the hour uses about nine at once, and the rest of the hour gets by on one or two.
How Do You Run Go on Lambda Without a Go Runtime?
Lambda has no Go runtime. It has managed runtimes for Java, Python, Node.js, .NET, and Ruby, and the Go one it used to have is deprecated. AWS's position is that Go doesn't need one: it compiles to a native executable, so it runs on an OS-only runtime, a plain Amazon Linux environment that starts your executable.
That makes your binary the runtime. It has to ask Lambda for the next event, run the handler, and post the result back, in a loop. AWS's aws-lambda-go library does that part, so the build is a static arm64 binary copied onto AWS's OS-only base image:
FROM golang:1.26 AS build
WORKDIR /src
COPY . .
RUN CGO_ENABLED=0 GOOS=linux GOARCH=arm64 \
go build -tags lambda.norpc -o /out/bootstrap ./cmd/api
FROM public.ecr.aws/lambda/provided:al2023
COPY --from=build /out/bootstrap /var/runtime/bootstrap
CMD [ "bootstrap" ]
The other half is HTTP. Behind a load balancer, a Lambda function receives each HTTP request as a JSON document, and returns the response as another. Our adapter builds a standard http.Request from the event, runs the API's ordinary net/http handler, and converts what the handler wrote back into the load balancer's format:
func run_lambda(api http.Handler) {
lambda.Start(func(ctx context.Context, event events.ALBTargetGroupRequest) (events.ALBTargetGroupResponse, error) {
// the load balancer's JSON event, as an *http.Request
request, err := new_request(ctx, event)
if err != nil {
return bad_request(), nil
}
// the same handler a plain HTTP server would use
recorder := httptest.NewRecorder()
api.ServeHTTP(recorder, request)
// status, headers, and body, back in the load balancer's format
return new_response(recorder), nil
})
}
Nothing in the handler knows about Lambda, so the same binary also runs as a plain HTTP server, which is how we develop and test it.
What a Go Process Keeps Between Requests
Go solves the start-up problem, and that's where most of the gain came from. A Lambda environment handles one request at a time, but it stays alive to handle the next one, and everything the Go process has set up is still there: the configuration, the secrets, and open connections to the database and Redis. We set all of it up once, when the environment starts:
func main() {
// once per environment, before the first request arrives
settings, _ := config.Load(ctx)
database, _ := store.Open(ctx, settings, max_conns)
redis := cache.Open(settings.Redis, redis_conns)
// connect now, so no request pays for the TLS handshakes
warm(ctx, database, redis)
// every request from here on reuses all of it
run_lambda(server.New(settings, database, redis))
}
The warm() call is there because the TLS handshake with Redis alone took 80 to 160 ms, and the first request in every new environment used to pay for it.
The Redis response cache is the same one PHP used, with the same 30-second lifetime. What changed is how much work stands between a request and that cache: 35 ms of bootstrap and a fight for CPU on PHP, and one or two Redis round trips on Go. During the spike, the requests that took PHP 0.3 to 0.5 seconds now take a median of 4 to 6 ms inside the function.
How Do You Run Code After a Lambda Returns Its Response?
Every API request is logged to the database, and that log feeds the usage pages in our customers' accounts. The write shouldn't hold up the response, so it has to run after the response has gone out.
PHP has a function for this: fastcgi_finish_request() sends the response to the client and lets the script carry on. Our PHP code called it, then put the log entry on an SQS queue for a second Lambda function to write to the database.
Lambda has no equivalent. Once the handler returns, Lambda can freeze the whole environment, including any goroutine still running in the background, until the next request wakes it.
What Lambda does have is extensions. It sends the response to the client as soon as the handler returns, but it won't freeze the environment until every registered extension has asked for its next event. Our binary registers itself as an internal extension, which is a goroutine in the same process, and it doesn't ask for the next event until the queued work has run:
for {
// blocks until the next invocation starts
next_event(id)
// wait for the handler to finish building its response
<-done
// the client has its response: run the queued work,
// then go back and ask for the next event
for _, work := range take_queue() {
work()
}
}
The handler queues the log write and returns. The client gets its response, the extension writes the row on a database connection that's already open, and then the environment freezes. The SQS queue and the second function are gone.
There's a price. The extension's time is billed, and the environment can't take its next request until the work is finished, which for us is about 7 ms at the 99th percentile.
The Results
These are the load balancer's own response times, over five days before the move and five days at the end of November, with about the same amount of traffic in each. The :00 rows are the first five minutes of the hour, for the median hour.
| PHP on ECS | Go on Lambda | |
|---|---|---|
| 99th percentile at :00 | 1,457 ms | 108 ms |
| 95th percentile at :00 | 854 ms | 47 ms |
| Slowest request at :00 | 3.2 s | 396 ms |
| 99th percentile, all day | 1,661 ms | 124 ms |
Cold starts cost less than I expected: fewer than 1% of requests land on a new environment, and starting one takes 0.2 to 0.35 seconds. So did the compute. Lambda bills by the millisecond, and at about 12 ms a request the bill is roughly a fortieth of what the containers cost.
Things We Ran Into
The load balancer's limits. A load balancer in front of Lambda caps the request body and the response at 1 MB each. The target group also needs multi-value headers turned on, or a response that sends the same header twice loses one of them.
New environments stalling on Redis. The first time we replayed a recorded spike against the function, several new environments hung for 5 to 13 seconds on their first request. The Redis cluster client was connecting to the cluster's reader port, which our security group blocked. It now connects only to the primaries.
Concurrency is also a database limit. Every environment holds its own database connections, so a spike in requests is a spike in connections too. Reserved concurrency caps both. With a cap of 10, the replayed spike was throttled; it's 100 now, and the real peak stays well under half of that.
Matching PHP's JSON. PHP's json_encode() escapes / and every non-ASCII character. Go's encoder does neither, and escapes <, >, and & on its own. We weren't going to bet on every customer's parser reading both the same way, so the Go API escapes exactly as PHP did.
Pros and Cons
What we gained:
- The hourly spike no longer slows anyone down.
- There's nothing to scale, and nothing to pay for ahead of the spike.
- Connections and configuration are kept between requests, so a cache hit takes a few milliseconds.
- Work after the response no longer needs a queue and a second function.
- Compute costs about a fortieth of what it did.
What it cost:
- Fewer than 1% of requests wait on a cold start.
- Work after the response needs an extension, and its time is billed.
- Requests and responses are capped at 1 MB.
- More of the code is specific to AWS.
We moved one group of endpoints at a time over three days, each one a deleted load balancer rule away from going back to PHP. We never needed it. Two months later, the spike still arrives every hour, and the API no longer notices.