Distributed systems

Serverless Isn't Magic: Cold Starts and the Distributed Monolith

Most serverless trouble, from cold starts to the distributed monolith, comes from too much synchronous work and treating each function as its own service.

Matt Kindy · · 7 min read

Serverless platforms such as AWS Lambda run your functions on demand, scale them up and down without anyone managing servers, and charge for the requests and the time the code runs. What they don’t do is decide how the system should be divided into services, or which work has to happen while a user waits. Those decisions matter as much as they did on servers.

I think most of the trouble teams have with serverless comes from two habits: putting too much work on the path where a user is waiting, and treating each function as its own service. Cold starts, the distributed monolith and services cut too small all follow from those habits, and the fixes have more to do with design than with tuning.

Cold starts

When a request arrives and no execution environment is free, Lambda has to create one. It downloads the function’s code, starts the runtime, and runs the initialization code outside the handler before the handler itself runs. That delay is a cold start. AWS says cold starts typically affect under 1 percent of invocations in production workloads. That’s a small share, but each cold start lands on a request someone may be waiting for, and a request that passes through several functions has several chances to hit one.

You can make cold starts rarer or shorter. Provisioned concurrency keeps a set number of pre-initialized execution environments ready, so requests that land on them skip the cold start, at an extra charge. AWS recommends it mainly for interactive workloads such as web and mobile backends, and notes that asynchronous work usually doesn’t need it. Scheduled pings that keep a function warm are an older workaround, and AWS says they aren’t a reliable way to prevent cold starts, because Lambda still creates new environments as it scales and replaces old ones.

Shortening the cold start comes down to doing less during initialization. The size of the package and its dependencies affects how long a cold start takes, so a function should import only what it uses. In one AWS example, importing only the DynamoDB client instead of the whole SDK made the cold start 125 milliseconds faster. Memory matters too, because Lambda gives a function CPU in proportion to its memory, so a function with more memory can get through CPU-heavy initialization faster.

Setup the function always needs, such as an SDK client or a database connection, still belongs outside the handler. AWS’s best practices recommend that, because the setup then runs once per environment and every later request in that environment reuses it. Things the function only sometimes uses are different, and AWS suggests loading those lazily, inside the code path that needs them.

The option I’d reach for first is taking the cold start off the user’s path. If the work doesn’t have to finish while the user waits, the API can accept the request, put the work on a queue, and return right away. The worker that picks up the message a moment later may still hit a cold start, but nobody is waiting on it.

The distributed monolith

A request that passes through several functions has more to worry about than cold starts, because a system split into many functions can still behave like one program. Picture a hypothetical API built on Lambda, where a request comes in through API Gateway to service A. Service A is a Lambda function that makes a synchronous HTTP call to service B, B calls service C, and C queries the database before the response unwinds back up the chain. If B slows down or fails, the whole request slows down or fails with it, and every hop is another chance for a cold start. The functions are deployed separately, but they fail together, which is why this arrangement gets called a distributed monolith.

The distributed monolith. A request comes in through API Gateway to Service A, a Lambda, which makes a synchronous HTTP call to Service B, another Lambda, which calls Service C, another Lambda, which talks to the database. The response then unwinds back up the chain. Service B is highlighted: if it fails or slows down, the whole request fails or hangs. API Gateway Service A (Lambda) Service B (Lambda) Service C (Lambda) Database sync HTTP call calls talks to unwinds If Service B fails or slows down, the whole request fails or hangs.
Every hop waits on the next one, so the whole chain behaves like one process.

The chain also costs more than it looks. AWS’s guidance on Lambda anti-patterns points out that you pay for every function in the chain while it waits on the one below it, that every function in the chain needs the same concurrency, and that errors have to be passed back up through each caller.

The fix is to stop making functions wait on each other. If one step only needs to hand work to the next, a queue such as Amazon SQS between them lets the downstream function work at its own pace, and failed messages are retried or moved to a dead-letter queue. Several parts of the system that react to the same fact, such as an order being created, can each subscribe to an event on EventBridge or a topic on SNS, and the publisher doesn’t need to know who they are. A workflow with steps, waits and error paths can run in Step Functions, which handles the retries and failures so that the functions contain only business logic. The orchestrated saga in the distributed systems patterns post is that kind of workflow. Whichever one you use, queues and event sources can deliver the same message more than once, so every consumer has to cope with a repeat, and AWS recommends writing Lambda functions to be idempotent for that reason.

Moving work off the request path raises the question of what the user gets in the meantime. Often what they need right away is confirmation that the request was received, such as “we’ve got your order,” while the processing happens in the background. Tracking that processing means giving each request a correlation ID that’s included in every message and event, and having the workers record their progress in a database or publish an event when they finish. The UI can learn the result over a WebSocket, through server-sent events, or by polling a status endpoint. I’d keep a call synchronous only when the user can’t do anything useful until it returns.

Services cut too small

Treating each function as its own service also leads teams to cut services too small. Some read “micro” as “tiny” and write a separate function for every database query or API operation. The result is hundreds of small functions, each with its own deployment, monitoring and cold starts, and a request path that’s hard to follow because it bounces between them. Thoughtworks put this pattern, which it calls Lambda pinball, in the Hold ring of its Technology Radar in November 2019, and again in April 2023. It said the domain logic gets lost as requests move between functions, queues and buckets, and that teams find these systems hard to test and maintain.

The mistake is treating a function as the unit of design. Service boundaries belong around business capabilities instead, such as ordering, inventory, payments and shipping. Domain-driven design calls these bounded contexts, and they make good service boundaries. The Radar entry recommends something close to this, with domain boundaries and published interfaces. A service then owns everything its capability needs: its API routes, which may be several Lambda functions behind one API Gateway, the workers its queues and events trigger, and its tables. The functions become a detail inside the service, and other services talk to it through its API and its events. A few services cut that way are easier to understand and change than a few hundred functions.

Following a request across functions and queues

Moving work onto queues and events makes the system asynchronous, and asynchronous systems are harder to debug, because a request no longer shows up as one call stack. Following one means passing its correlation ID through every invocation, message and event, writing it into structured logs, and using distributed tracing, such as AWS X-Ray on Lambda, to see the hops. The same visibility helps with the earlier problems. A trace shows whether a slow request hit a cold start or a slow synchronous call, and which functions run together on the same request. If the same few functions run together on every request, and the version history shows them changing together too, that’s a sign they belong in the same service.

Serverless moved the work of running servers to the provider. The work of knowing how the functions, queues and events connect stays with the team, and it grows with every piece added, since no single deployment shows a whole request anymore. I’d plan for that part of serverless from the start, before the number of functions makes it hard to see.

Get the next essay

Follow the RSS feed to see each new essay when it goes up.