Function Lifecycle and Context
You'll learn: How serverless functions are born, execute, and die—and what context they carry during their lifetime.
The Lifecycle Journey
Every serverless function moves through three distinct phases:
1. Initialization (Bootstrap)
When a function is first invoked or after being idle, the platform provisions an execution environment. This includes loading your code, initializing runtime dependencies, and setting up any global variables or connections outside your handler function. This happens during a cold start.
2. Invocation (Execution)
The handler function runs with the incoming event data. The platform passes two key items: the event (trigger data like an API request or file upload) and the context (metadata about the execution itself—request ID, remaining time, function name, memory limit).
3. Termination (Shutdown)
After execution completes, the environment may stay "warm" for reuse or be terminated. Any cleanup code runs, connections close, and resources are released.
What Is Context?
Think of context as the function's "ID badge and rulebook." It tells your code:
- Who it is (function name, version)
- How long it can run (timeout remaining)
- Where to log (log stream identifiers)
- Request tracing information
You can use context to make runtime decisions—like gracefully exiting before timeout or logging request IDs for debugging.
Example Flow
Imagine a function triggered by a new image upload. The platform initializes (loads image processing libraries), invokes your handler with the event (file location) and context (timeout: 30s remaining), processes the image, then either stays warm for the next upload or terminates after 15 minutes of inactivity.
Key Takeaway: Functions follow an initialize → invoke → terminate lifecycle, with context providing runtime metadata that helps your code adapt to execution constraints and environment details.