Serverless
Intent
Run code and backends without managing servers: ephemeral functions and managed services scale to demand — including to zero — and you pay per use.
When It Helps
- Traffic is bursty or unpredictable and idle servers would waste money.
- A small team wants to ship without operating runtimes, clusters, or OS patching.
- Workloads are event-triggered tasks (webhooks, file processing, scheduled jobs) rather than long-lived connections.
Structure
flowchart LR Clients --> Edge[Managed Gateway / CDN] Edge --> F1[Function: place-order] Edge --> F2[Function: get-catalog] F1 --> BaaS1[(Managed DB)] F1 -->|emits| Queue[(Managed Queue)] Queue --> F3[Function: send-receipt] F2 --> BaaS1
Deployment unit: individual functions (plus managed-backend configuration) deployed per function, not per server fleet. Communication: inbound via managed triggers (HTTP gateway, queue, timer, storage event); outbound via managed service APIs. Data ownership: state lives in managed backends (database, object store, queue) — functions themselves are stateless and own no durable data.
Rules
- Functions must be stateless — persist everything to a managed backend, never to local disk or memory across invocations.
- Keep functions small and single-purpose so cold starts stay short and permissions stay narrow.
- Design for retries and timeouts: every trigger may fire twice and every run has a maximum duration.
- Put shared logic in versioned layers or packages, not copy-pasted across dozens of functions.
Illustrative Snippet
Illustrative pseudocode — not runnable.
# sketch: function + trigger config, no servers
function place-order:
trigger: http POST /orders (via managed gateway)
timeout: 10s, memory: 512MB, concurrency: 100
env: ORDERS_TABLE (managed db reference)
steps:
- validate(request) -> save(ORDERS_TABLE) -> enqueue(receipt-queue)
function send-receipt:
trigger: receipt-queue message
steps:
- load(order) -> send_email() # idempotent on order_id
Basic Recap
Serverless systems run stateless code in provider-managed execution environments triggered by requests, events, or schedules. Durable state belongs in managed databases, queues, and object stores rather than function memory. Capacity can scale with demand and fall to zero, while billing follows consumption. The model reduces server operations but introduces provider limits, cold starts, and distributed configuration.
Complex Scenario
A document-signing product accepts webhooks, renders signed PDFs, and notifies recipients through managed functions. Rendering is CPU-heavy, while webhook acknowledgement must be fast and reliable. A queue separates ingestion from rendering, and signed files live in object storage. A customer campaign is expected to produce a sharp burst after a quiet period.
flowchart LR
Partners["Partner webhooks"] --> Gateway["Managed API gateway"]
Gateway --> Ingest["Function: ingest webhook"]
Ingest --> Queue[("Managed render queue")]
Ingest --> Meta[("Signing metadata DB")]
Queue --> Render["Function: render PDF"]
Render --> Pool["Database connection proxy"]
Pool --> Meta
Render --> Files[("Signed document storage")]
Files --> NotifyTrigger["Storage event trigger"]
NotifyTrigger --> Notify["Function: notify recipient"]
Notify --> Email["Managed email API"]
Failure walkthrough. Traffic rises tenfold after idle, so new webhook and renderer instances start together. Cold starts delay execution, queue retries multiply invocations, and hundreds of renderers open direct database connections until ingestion also fails. Mitigate by acknowledging only after durable queue storage, reserving finite renderer concurrency, reusing connections through a proxy, extending retry backoff beyond cold-start time, and keeping minimal warm capacity only for the latency-critical ingest path.
Edge cases — triggers may retry or arrive out of order, so rendering needs a deterministic signing-operation key and revision check. Concurrent completions require compare-and-swap metadata updates, and partial failure must leave retryable temporary files separate from the final signed object.
Sketch (illustrative pseudocode, not runnable):
function ingest-webhook:
timeout: 3s
reserved_concurrency: 40
minimum_warm_instances: 2
writes: queue_message{idempotency_key, document_revision}
response: accepted_only_after_queue_commit
function render-pdf:
timeout: 90s
memory: 2048MB
reserved_concurrency: 25
database: via_connection_proxy
success: atomic_publish(final_object, revision)
queue render-queue:
visibility_timeout: 120s
delivery: at_least_once
poison_policy: dead_letter_after_6_attempts
Trade-offs
- Benefit: near-effortless scaling — concurrency rises with demand and drops to zero cost when idle, with no capacity planning.
- Benefit: minimal operations — patching, availability zones, and runtime hardening shift to the provider.
- Cost: cold starts, timeouts, and runtime limits constrain long-running or latency-sensitive work.
- Cost: provider coupling and cost surprises — egress, invocations, and managed-service bills need monitoring, and deep provider features are hard to port.
When to Use / When Not to Use
Use when:
- Spiky workloads with minimal ops, event-triggered functions plus managed backends.
Avoid when:
- Long-running, stateful, or latency-critical paths with sustained load.
Anti-pattern / Failure Mode
- Misuse: Functions chained into a distributed monolith with hidden latency.
- Review signal: No idempotency on retried invocations causing duplicates.
Failure Modes / Trade-offs
- Function pinball: dozens of tiny synchronous functions add latency and make one business request difficult to trace. Group work by operational boundary, not by arbitrary code size.
- Hidden state: local caches or temporary files become required for correctness even though instances are ephemeral. Move durable workflow state to an explicit backend.
- Unbounded elasticity: functions scale faster than databases and partner APIs, shifting the outage downstream. Reserved concurrency is a backpressure tool as well as a cost control.
- Economic trade-off: idle and spiky workloads can be inexpensive, but sustained high utilization, egress, observability, and managed-service requests can exceed fleet costs.
Cold-path review. Measure initialization, dependency downloads, cold starts, and downstream connection setup separately; provisioned warmth cannot fix an oversized deployment package alone.
Permission review. Give ingest, render, and notify distinct identities and resource policies so a vulnerable parser cannot read unrelated documents or publish arbitrary events.
Cost review. Model invocation, duration, queue retention, storage, proxy, logs, and egress together under both burst and sustained-load assumptions.
- Recovery trade-off: short stateless runs simplify replacement, but workflow recovery still depends on durable checkpoints and idempotent external effects.
- Portability trade-off: ordinary language code may move easily while triggers, identity policies, queues, and observability remain deeply provider-specific.
- Consistency trade-off: queues and storage events create delays between signing and notification, so product status must reflect each completed stage.
Constraint-based use / avoid
| Constraint | Recommendation |
|---|---|
| Small team with sparse, unpredictable event traffic | Use managed triggers and scale-to-zero to minimize operations and idle spend. |
| Hard p99 latency below cold-start variance | Avoid on-demand cold paths, or budget for warm capacity and verify with production-like tests. |
| Long-running jobs beyond provider execution limits | Avoid one function per job; use a worker or explicitly checkpointed workflow. |
| Strict data residency and portability requirements | Use cautiously: select regionally compliant services and isolate provider-specific APIs behind tested boundaries. |
| Fixed monthly budget with possible viral load | Use concurrency caps, queue backpressure, and cost alarms rather than relying on infinite autoscaling. |
Related Patterns
- Event-Driven — serverless functions are usually triggered by events from queues, streams, or storage.
- Microservices — functions can serve as the smallest deployable unit, but without long-lived service processes.
- Monolithic — the opposite starting point: one always-on process you manage yourself versus zero-managed ephemeral units.
- Bounded Resource — configure timeouts and concurrency.
- Multi-Tenant SaaS — elastic bursts per tenant.