AWS Cloud Architecture•Part 3: Compute, Containers & Serverless (21 - 35)
AWS Lambda Execution Model & Firecracker.
In Simple Words: Lambda runs code in lightweight microVMs powered by Firecracker (open-source Rust virtualization). Lifecycle Phases:
- Init: Downloads code, starts runtime, runs code outside the handler function.
- Invoke: Executes the handler function with the incoming event payload.
- Shutdown: Reaps the execution environment when idle.
typescript
// Reusing database client across invokes in Lambda:
import { Client } from 'pg';
// Initialized during INIT phase (outside handler) -> reused on warm invocations!
const dbClient = new Client({ connectionString: process.env.DB_URL });
const connectionPromise = dbClient.connect();
export const handler = async (event: any) => {
await connectionPromise; // Instant on warm calls!
const res = await dbClient.query('SELECT NOW()');
return { statusCode: 200, body: JSON.stringify(res.rows[0]) };
};