Course outline · 0% complete

0/27 lessons0%

Course overview →

Functions instead of servers

lesson 7-1 · ~9 min · 19/27

Lesson 3-1 covered what EC2 bills you for while your app waits idle for the next request at 4 a.m.

The full per-hour price. An instance costs the same busy or idle, because an EC2 instance is a rented machine and the meter runs while it exists rather than while it works.

Hold that thought, because it is exactly the deal Lambda changes.

Lambda

Lambda is AWS's serverless compute service. Servers still exist (everything runs on the machines from unit 1), but they stop being your concern: no instance, no SSH, no patching, no security group to babysit for the compute itself.

The unit of deployment shrinks from a machine to a function: one piece of code with an entry point called a handler. You upload the code (a zip, or a container image, familiar territory), and AWS runs one copy of it per event, billing you per invocation and per millisecond of runtime. A handler receives an event, a JSON description of whatever happened, does its work, and returns.

Zero traffic costs zero dollars. A thousand simultaneous events means AWS spins up as many copies as needed. That is elasticity from lesson 1-3 taken to its limit, and it is why serverless fits spiky and occasional workloads so well.

A handler in miniature

A Lambda handler wakes up, reads its event, does its job, and exits. This script is that lifecycle, with the event fed in on standard input.

read event
echo "handler invoked"
echo "event received: $event"
echo "done in 12ms"

Input

user.signup

Output

handler invoked
event received: user.signup
done in 12ms

The shape is the whole idea. There is no listening socket, no request loop, and no startup code that runs once and stays resident. The function exists for the duration of one event.

That is also what the billing follows. A run of 12 ms is billed as 12 ms of compute plus one invocation, and the next 4 a.m. hour with no events costs nothing at all.

A handler that returns an HTTP response

This handler reads a name and prints an HTTP-style response with a status code and a body.

read name
echo "{\"statusCode\": 200, \"body\": \"Hello, $name\"}"

Input

Ada

Output

{"statusCode": 200, "body": "Hello, Ada"}

Reading the escaping and the shape

  • The output needs literal double quotes inside a double-quoted string, so each one is escaped as \" in the echo. The $name expansion still happens, because escaping the quotes does not disable expansion.
  • Real Lambda handlers behind an API return exactly this shape: a statusCode plus a body. API Gateway reads those fields and turns them into an actual HTTP response.
  • Returning a bare string instead would produce a 200 with the string JSON-encoded in the body, which is a common first surprise. The response format is a contract, not a suggestion.