Chapter 20 of 27 · Part 9: Deployment and scaling

Serverless deployment

Even on Kubernetes, FTGO still sizes, patches and pays for servers that sit idle much of the day. This chapter shows how to hand that work to the cloud by deploying code as functions, and how to decide which services belong there.

key idea / coordinator service / good path in progress / watch out problem / failure neutral

Where we are

In chapter 19 we packaged FTGO's services as container images, ran them on Kubernetes, described the infrastructure as code and released new versions safely. That left one problem open: the team still owns a cluster. Someone must size the nodes, patch them and pay for them, busy or not.

This chapter

Can FTGO run some services without managing servers at all? By the end you can explain Function as a Service, check a workload against its limits, decide how many functions make up one service, and choose between PaaS, FaaS and containers for each service.

Stop running servers: Function as a Service

Problem

Restaurant Service answers menu lookups. It is busy at lunch and dinner and almost idle at 4 a.m., but its pods and the nodes under them run all night. When a node needs an operating system patch, an FTGO engineer drains it and reschedules pods. None of that work makes a customer's order arrive faster.

Serverless does not mean there are no servers. It means you stop managing them: the cloud provider runs, patches and scales them for you. Managed databases, queues and object storage are all serverless in this sense. The best-known kind is Function as a Service (FaaS); AWS Lambda started the excitement in 2014.

Solution · Function as a Service

Deploy a function, not a server. The function sleeps until a trigger fires, runs your code, and stops. The platform starts as many copies as the load needs and none when there is no load.

Trigger, run, stop File arrives Queue message HTTP request Function your code Result write, reply, emit runs, then stops The platform starts and stops instances and runs many copies in parallel.

On AWS Lambda, four kinds of trigger can start a function:

Serverless with AWS Lambda Invoke a Lambda by HTTP via AWS API Gateway AWS events (S3, DynamoDB, Kinesis) A schedule (cron-like) A direct API call Trade-offs Benefits no sysadmin, elastic, pay per use Drawbacks cold-start latency, short tasks only

For Restaurant Service, each HTTP endpoint becomes a function. A request for GET /restaurant/1 goes through the AWS API Gateway to a FindRestaurant handler, which calls the same business code the service used before. Only the entry point changes.

Restaurant Service as Lambda functions HTTP client GET /restaurant/1 API Gateway routes request Lambda handler FindRestaurant Restaurant svc same business code One function per endpoint. The handler is a thin entry point over the service's code.
BenefitWhy
Pay for useIdle code costs nothing, which suits low or unpredictable load like Restaurant Service at 4 a.m.
Less operationsThe platform scales up and down and patches the machines
Implicit resilienceYou get some high availability without building it
Cost

FaaS runs your code on containers you cannot see or tune. You trade control for less work, and the platform sets hard rules about what a function may do.

What the platform will not let you do

Restaurant Service fits FaaS well. The next service the team tries does not.

Problem

The team moves Accounting's nightly settlement job to a function. On a busy Friday it runs past the platform's time limit and is killed halfway. The same week, the JVM-based Kitchen Service function delays the first ticket after a quiet spell, and a counter it kept in memory resets between calls.

Each of these is a documented limit. Check every one against the workload first.

LimitWhat it means
Runtime supportThe provider must support your language. Azure had the widest support at the time; custom runtimes on AWS add upkeep.
ResourcesYou mostly choose memory only; CPU and I/O follow. You may buy memory just to get more CPU.
Execution timeCapped: about 9 minutes on Google and 15 on Lambda at the time. Long jobs, like the settlement run, are a poor fit.
StatelessnessA call cannot see the previous call's memory. State lives elsewhere, and chaining functions is hard.
Cold startStarting a new instance is slow on the JVM and .NET; Go, Python, Node and Ruby start fast. Platforms keep runtimes warm, which helps.
Concurrency capsThere are hard limits on parallel runs, and fast scaling can overwhelm systems that do not scale (next section).
Cold starts and statelessness Cold start Stateless calls First call start runtime Next calls warm, fast Call 1 sets x = 5 Call 2 cannot see x put state in a database or object store worst on JVM and .NET Platforms keep runtimes warm, so the effect is often smaller than feared.
Solution · Fit the workload to the function

Move short, event-driven work that keeps its state in a database or object store. Leave long jobs on containers, or split them into short steps. Pick a fast-starting runtime where the first call must be quick.

Splitting a long job into steps means one function must coordinate others, which plain FaaS does badly. Workflow tools fill that gap. Azure Durable Functions suspends a function and resumes it later, so it can orchestrate other functions in code. AWS Step Functions wires functions together with JSON configuration, which many teams find less friendly.

WebAssembly (Wasm) is a sandboxed, lightweight code format that may one day challenge containers on the server, but it still lacks mature server platforms. Treat it as something to watch.
Cost

Each limit pushes work out of the function: state into a database, long jobs into containers, chains into a workflow tool. And automatic scaling creates a new problem for everything the functions call.

Functions scale faster than what they call

Automatic scaling removes capacity planning for the functions. It does not remove it for anything behind them.

Problem

At 12:00 on Saturday a thousand menu requests arrive within seconds. The platform starts hundreds of Restaurant Service function instances, and each opens its own connection to the restaurant database. The database has a fixed size and a connection limit. It slows down, then rejects connections, and the menu page fails for everyone.

Scaling mismatch Spike 1000 events Functions scale out fast Redis / DB fixed capacity Overload One part scales dynamically, another does not: the mismatch hurts (a team at Bustle hit this).

A team at the media company Bustle hit exactly this. Whenever one part scales on its own and the next part does not, the slower part becomes the bottleneck.

Solution · Match the scaling of each hop

Cap the function's concurrency to what the downstream system can take, buffer bursts in a queue so functions drain it at a steady rate, or scale the downstream system too, for example with a serverless database.

Cost

A concurrency cap or a queue gives back some of the elasticity you moved to FaaS for, and requests may wait. Scaling the database costs money. And once each endpoint is its own function, a new question appears: how many functions should one service become?

How many functions make one service?

With containers, one service was one deployable unit. With FaaS that link gets fuzzy.

Problem

The Restaurant Service team wants one function for every endpoint, then one for every state change of a restaurant. Soon they manage dozens of functions, each deployed on its own, and the rules that keep a restaurant consistent are spread across all of them.

A side example makes the options clear. Take an Expenses service with three endpoints: upload a receipt, submit a claim, and produce a report.

Two mappings Function per microservice Expenses function: one entry point /receipt /claim /report Function per aggregate Receipt fn Claim fn Report fn Shared or separate database Both keep one coarse "Expenses" API for callers.
Solution · Function per service, then per aggregate

Start with one function per microservice: a single entry point that dispatches by path. Split into one function per aggregate only when you have a reason, and never go finer than the aggregate.

Cost

A coarse function gives up some per-endpoint tuning; a split one adds units to deploy and watch. And FTGO still has to decide which of its services should use FaaS at all.

Pick a platform per service: PaaS, FaaS or containers

FaaS is the far end of a range of platforms. Each step along the range takes away work and control together.

Problem

One engineer proposes moving every FTGO service to FaaS, though Accounting's settlement job breaks the time limit and the rest run fine on Kubernetes. Another wants to avoid FaaS entirely to prevent lock-in.

A Platform as a Service (PaaS), with Heroku as the benchmark, sits between containers and FaaS. You push a technology-specific artifact and the platform runs it, often with scaling and databases included. It works well until you need to get under the hood, and the smarter its autoscaling tries to be, the more it can go wrong for unusual apps. Public cloud serverless products now fill much of the same need with managed pieces (brokers, databases, storage) that you assemble yourself.

The control-versus-effort spectrum More control, more work Less control, less work Physical / VM you run everything Containers you orchestrate PaaS push an artifact FaaS push a function Stay as far right as your workload and comfort with limits allow.
PaaSFaaSContainers (Kubernetes)
You supplyLanguage artifactA functionContainer image
ScalingPlatform, sometimes tunableAutomatic, with concurrency capsYou configure it
Watch outLittle control when it misbehavesTime, state and cold-start limitsReal operational complexity
Good fitStandard web appsSpiky or low load; event reactionsBroad workloads needing control
Solution · Highest-level platform that fits, per service

Choose per service, not for the whole system. Evaluate in this order: serverless first, then containers, then VMs, then plain language packages, and stop at the first one the workload fits.

Rules of thumb:

For FTGO, that might mean Restaurant Service's menu lookups and image uploads on FaaS, and Order, Kitchen and Accounting, with their long jobs and steady load, staying on the Kubernetes cluster from chapter 19.

Mix, do not choose one. The BBC uses Lambda for part of its News site and EC2 virtual machines where per-invocation cost would be too high. For Kubernetes users, Knative aims to bring a FaaS workflow to Kubernetes, but it needs a service mesh (Istio, in practice) and was still maturing. More cautious teams can look at OpenFaaS.
Cost

A mix means two or three platforms to learn, secure and observe. And whichever platform a service runs on, its code still needs a reliable, repeatable path from a developer's commit to production.

Patterns in this chapter

PatternProblem it solvesWhat it costs
Function as a ServiceServers to size, patch and pay for while idleLess control; limits on runtime, resources, time, state and concurrency
Fit the workload to the functionLong jobs killed, slow cold starts, lost in-memory stateState and long jobs move elsewhere; chains need a workflow tool
Concurrency caps and queue bufferingFunctions scale out and overload a fixed-size downstream systemSome elasticity lost; requests may wait
Function per microservice, then per aggregateToo many tiny functions and scattered aggregate rulesLess per-endpoint tuning; splits add units to manage
Highest-level platform that fits, per serviceOne platform forced on every service, or fashion-driven movesSeveral platforms to run, secure and observe

Recap

Quick check

FTGO moves menu lookups to functions. During the Saturday lunch spike the restaurant database starts rejecting connections. What went wrong, and what helps?
Show answer

A scaling mismatch: the functions scaled out much faster than the fixed-size database, and each instance opened its own connections. Cap the function's concurrency to what the database can take, put a queue in front to smooth the burst, or move to a database that scales with the load.

Accounting's nightly settlement job takes 40 minutes. Should it move to FaaS?
Show answer

Not as it is. Execution time is capped (about 15 minutes on Lambda at the time), so the job would be killed. Keep it on containers, or split it into short steps coordinated by a workflow tool such as Durable Functions or Step Functions.

Still open

FTGO now knows where each service should run: functions, a PaaS or the Kubernetes cluster. But on any platform, code still has to travel from a developer's commit to production through builds and tests that everyone trusts.

Next: 21 Continuous integration and delivery pipelines →