Function Initialization and Handler Code
You'll learn how to structure your serverless function code to separate one-time setup from per-request processing for better performance and efficiency.
The Core Idea
When a function executes, not all code needs to run every time. Initialization code runs once when the function container first starts (cold start), while handler code runs on every invocation. Separating these concerns optimizes execution patterns, reduces latency, and lowers costs.
Think of it like a restaurant kitchen: You don't re-stock the entire kitchen for each order (initialization). Instead, you prepare your station once at the start of your shift (cold start), then quickly use those ready ingredients for each order (handler invocations).
Why Separate Initialization from Handler?
When you place code outside your handler function, it runs during initialization and persists in the execution context between invocations (during warm starts). This is perfect for:
- Database connection setup
- SDK client initialization
- Loading configuration or credentials
- Reading environment variables
- Importing libraries
When you place code inside your handler, it runs on every single invocation, which wastes time and resources if it doesn't need to change between requests.
Structure Pattern
Put expensive, reusable operations outside the handler. Put request-specific logic inside:
[Initialization: runs once]
↓ Import libraries
↓ Create database client
↓ Load configuration
↓
[Handler: runs per invocation]
↓ Process event data
↓ Execute business logic
↓ Return response
This leverages execution context reuse from the earlier lesson, ensuring warm starts benefit from already-initialized resources.
Key Takeaway: Separate initialization code (outside handler) from per-request code (inside handler) to maximize function performance by reusing expensive setup operations across multiple invocations.