Serverless functions
What is a serverless function?
A serverless function is a small unit of application code executed by a managed platform when a request or event arrives. With Functions as a Service (FaaS), you usually supply code, dependencies, configuration and a trigger instead of administering a server yourself. Servers still exist: the platform operates their infrastructure, while you own the application behavior, permissions, data protection and costs.
Imagine Byte Books wants to prepare a receipt whenever an order is created. Rather than running a dedicated VM that waits for orders, it can connect a function to the order event source. The function validates the event and prepares receipt data. A separate component can store or deliver the receipt. This is a useful candidate when arrivals are intermittent and work is short and independent.
Follow an event through a handler
An event is a record of something that happened. A trigger connects an event source to a function. The handler is the entry point invoked by the runtime. An HTTP trigger starts work on a web request; a queue or storage trigger starts work on a message or object event. A timer can start scheduled work. The invocation is one execution attempt, not necessarily one unique business event.
Order event -> trigger -> handler -> validated receipt data | +-> external storage (separate step)An HTTP caller may wait for a response. An asynchronous producer can receive acceptance before processing finishes. Acceptance is not evidence that a receipt exists. A queue can retain work until a consumer acknowledges it; the precise acknowledgment and retry rules belong to the integration.
First function: prepare a receipt offline
The following Python 3 example is ordinary local code with a fictional event format, not a Lambda, Azure or Google deployment entry point. It expects a dictionary, checks the event type and validates a nonempty order ID and a nonnegative integer amount in cents. A Boolean is intentionally not accepted as an integer amount. Integer cents avoid rounding issues in this exercise.
def receipt(event): if event.get("type") != "order.created": return {"status": "ignored"} order_id = event.get("order_id") cents = event.get("total_cents") if (not isinstance(order_id, str) or not order_id or type(cents) is not int or cents < 0): return {"status": "invalid"} return {"status": "ready", "key": order_id, "total_cents": cents}
sample = {"type": "order.created", "order_id": "B17", "total_cents": 2500}print(receipt(sample))print(receipt({"type": "order.cancelled"}))Expected output:
{'status': 'ready', 'key': 'B17', 'total_cents': 2500}{'status': 'ignored'}The handler returns a new dictionary and does not send email or modify a database. Try a negative amount, zero amount, or a missing ID. The result is deterministic. The same valid event produces the same result each time; a real external write requires additional duplicate protection. Provider adapters must validate their actual envelope, including authentication and encoding, then translate it into the domain input.
Execution environments and cold starts
The platform prepares an execution environment containing a language runtime, dependencies and your code. A cold start includes work to initialize a new environment; a warm invocation can reuse an existing one. Reuse is an optimization, not a promise. New deployments, idle periods and scaling may create fresh environments. Initialization cost depends on runtime, dependencies, network setup and hosting plan.
Reuse immutable configuration and safe client connections when supported, but do not assume memory or temporary files survive. Multiple invocations may share an instance on some plans; never retain user-specific data in a global variable. Write durable business state to an appropriate database or storage service. Complete required work before returning; do not rely on arbitrary background tasks running after completion.
Memory, CPU, execution timeout, payload size and temporary disk are bounded. A timeout does not prove a side effect was cancelled. Set dependency deadlines below the remaining invocation time and leave room for cleanup or an explicit retry. Long-running, stateful or tightly coupled work may be better on a container platform, VM or workflow service.
Compare provider models without assuming parity
| Platform | Typical entry points | Important distinction |
|---|---|---|
| AWS Lambda Event Functions | HTTP integrations, direct invocation, service events | Standard event-function concurrency and asynchronous invocation rules differ from other Lambda execution modes. |
| Azure Functions | HTTP, timer, queue and other triggers; bindings | Hosting plan, language worker and trigger affect scaling, execution limits and retry policy. |
| Google Cloud Run functions | HTTP or event-driven functions | Current Cloud Run-based functions and first-generation functions have different concurrency and deployment characteristics. |
A binding is an integration that can simplify reading or writing data; it is not a universal transaction mechanism. Select a supported runtime and trigger, inspect regional availability, and choose a least-privilege workload identity. Do not copy one provider's handler signature, timeouts, trigger settings or billing assumptions to another. See the chapter evidence register for official documentation; exact plan/version limits require verification before deployment.
Avoid recursive events and unsafe configuration
Suppose a storage event invokes a thumbnail function. If the function writes its result into the same watched prefix, that new object can trigger another invocation. Use a distinct output location or narrowly scoped event filters, test the event graph offline, and limit concurrency and retries. Monitor invocation rate, failures, event age and unexpected costs. Configure a reviewed stop procedure for your chosen trigger and preserve pending events where appropriate.
Use a dedicated workload identity with access only to the required input and output resources. Validate untrusted input even when it came through an event service; network reachability does not establish authorization. Do not put credentials in the event or log sensitive payloads. The chapter requires no cloud credentials or live deployment.
Practice and next step
Trace a fictional order through the diagram. Predict the output for valid, ignored and malformed events. Explain where durable state would live, and why a warm environment cannot guarantee a unique receipt. Complete the linked manual exercise before moving to Function concurrency and billing, where repeated events and capacity limits are handled explicitly.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Serverless functions — knowledge check
Choose the best answer for each offline scenario.
What does a trigger do?
Why is a warm global variable unsuitable as the only receipt ledger?
What does the example return for order.created with a nonempty ID and total_cents of 0?
A storage-triggered function writes into its own watched prefix. What is the primary risk?
What does asynchronous acceptance of an order event prove?